agentic-flow 2.0.6 → 2.0.8

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 (316) hide show
  1. package/.claude/settings.json +133 -9
  2. package/.claude/skills/agentic-flow-quickstart/skill.md +69 -0
  3. package/.claude/skills/hooks-automation/skill.md +155 -0
  4. package/.claude/skills/memory-patterns/skill.md +110 -0
  5. package/.claude/skills/sparc-methodology/skill.md +137 -0
  6. package/.claude/skills/swarm-coordination/skill.md +94 -0
  7. package/.claude/skills/worker-benchmarks/skill.md +135 -0
  8. package/.claude/skills/worker-integration/skill.md +154 -0
  9. package/.claude/statusline.mjs +109 -0
  10. package/.claude/statusline.sh +71 -0
  11. package/README.md +1797 -624
  12. package/dist/.tsbuildinfo +1 -1
  13. package/dist/agentdb/index.d.ts +2 -0
  14. package/dist/agentdb/index.d.ts.map +1 -1
  15. package/dist/agentdb/index.js +5 -0
  16. package/dist/agentdb/index.js.map +1 -1
  17. package/dist/agentdb/prerequisites.d.ts +25 -0
  18. package/dist/agentdb/prerequisites.d.ts.map +1 -0
  19. package/dist/agentdb/prerequisites.js +180 -0
  20. package/dist/agentdb/prerequisites.js.map +1 -0
  21. package/dist/benchmarks/embeddings-benchmark.d.ts +38 -0
  22. package/dist/benchmarks/embeddings-benchmark.d.ts.map +1 -0
  23. package/dist/benchmarks/embeddings-benchmark.js +282 -0
  24. package/dist/benchmarks/embeddings-benchmark.js.map +1 -0
  25. package/dist/billing/mcp/tools.js +1 -0
  26. package/dist/billing/mcp/tools.js.map +1 -1
  27. package/dist/cli/commands/embeddings.d.ts +12 -0
  28. package/dist/cli/commands/embeddings.d.ts.map +1 -0
  29. package/dist/cli/commands/embeddings.js +386 -0
  30. package/dist/cli/commands/embeddings.js.map +1 -0
  31. package/dist/cli/commands/hooks.d.ts.map +1 -1
  32. package/dist/cli/commands/hooks.js +79 -4
  33. package/dist/cli/commands/hooks.js.map +1 -1
  34. package/dist/cli/commands/init.d.ts +8 -0
  35. package/dist/cli/commands/init.d.ts.map +1 -0
  36. package/dist/cli/commands/init.js +514 -0
  37. package/dist/cli/commands/init.js.map +1 -0
  38. package/dist/cli/commands/workers.d.ts +9 -0
  39. package/dist/cli/commands/workers.d.ts.map +1 -0
  40. package/dist/cli/commands/workers.js +991 -0
  41. package/dist/cli/commands/workers.js.map +1 -0
  42. package/dist/cli/config-wizard.d.ts.map +1 -1
  43. package/dist/cli/config-wizard.js +47 -25
  44. package/dist/cli/config-wizard.js.map +1 -1
  45. package/dist/cli-proxy.js +89 -1
  46. package/dist/cli-proxy.js.map +1 -1
  47. package/dist/core/agentdb-fast.js +3 -3
  48. package/dist/core/agentdb-fast.js.map +1 -1
  49. package/dist/core/agentdb-wrapper-enhanced.d.ts.map +1 -1
  50. package/dist/core/agentdb-wrapper-enhanced.js +37 -11
  51. package/dist/core/agentdb-wrapper-enhanced.js.map +1 -1
  52. package/dist/core/agentdb-wrapper.d.ts +3 -2
  53. package/dist/core/agentdb-wrapper.d.ts.map +1 -1
  54. package/dist/core/agentdb-wrapper.js +15 -1
  55. package/dist/core/agentdb-wrapper.js.map +1 -1
  56. package/dist/core/attention-native.d.ts +4 -0
  57. package/dist/core/attention-native.d.ts.map +1 -1
  58. package/dist/core/attention-native.js +14 -2
  59. package/dist/core/attention-native.js.map +1 -1
  60. package/dist/core/gnn-wrapper.d.ts.map +1 -1
  61. package/dist/core/gnn-wrapper.js +14 -0
  62. package/dist/core/gnn-wrapper.js.map +1 -1
  63. package/dist/embeddings/index.d.ts +17 -0
  64. package/dist/embeddings/index.d.ts.map +1 -0
  65. package/dist/embeddings/index.js +17 -0
  66. package/dist/embeddings/index.js.map +1 -0
  67. package/dist/embeddings/neural-substrate.d.ts +206 -0
  68. package/dist/embeddings/neural-substrate.d.ts.map +1 -0
  69. package/dist/embeddings/neural-substrate.js +629 -0
  70. package/dist/embeddings/neural-substrate.js.map +1 -0
  71. package/dist/embeddings/optimized-embedder.d.ts +103 -0
  72. package/dist/embeddings/optimized-embedder.d.ts.map +1 -0
  73. package/dist/embeddings/optimized-embedder.js +730 -0
  74. package/dist/embeddings/optimized-embedder.js.map +1 -0
  75. package/dist/examples/embedding-geometry.d.ts +105 -0
  76. package/dist/examples/embedding-geometry.d.ts.map +1 -0
  77. package/dist/examples/embedding-geometry.js +528 -0
  78. package/dist/examples/embedding-geometry.js.map +1 -0
  79. package/dist/federation/SecurityManager.d.ts +11 -2
  80. package/dist/federation/SecurityManager.d.ts.map +1 -1
  81. package/dist/federation/SecurityManager.js +50 -17
  82. package/dist/federation/SecurityManager.js.map +1 -1
  83. package/dist/federation/integrations/supabase-adapter-debug.js +3 -3
  84. package/dist/federation/integrations/supabase-adapter-debug.js.map +1 -1
  85. package/dist/hooks/swarm-learning-optimizer.js +5 -5
  86. package/dist/hooks/swarm-learning-optimizer.js.map +1 -1
  87. package/dist/index.d.ts +5 -3
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.js +89 -51
  90. package/dist/index.js.map +1 -1
  91. package/dist/intelligence/IntelligenceStore.d.ts +35 -26
  92. package/dist/intelligence/IntelligenceStore.d.ts.map +1 -1
  93. package/dist/intelligence/IntelligenceStore.js +308 -123
  94. package/dist/intelligence/IntelligenceStore.js.map +1 -1
  95. package/dist/intelligence/RuVectorIntelligence.d.ts +26 -1
  96. package/dist/intelligence/RuVectorIntelligence.d.ts.map +1 -1
  97. package/dist/intelligence/RuVectorIntelligence.js +49 -10
  98. package/dist/intelligence/RuVectorIntelligence.js.map +1 -1
  99. package/dist/intelligence/agent-booster-enhanced.d.ts +1 -0
  100. package/dist/intelligence/agent-booster-enhanced.d.ts.map +1 -1
  101. package/dist/intelligence/agent-booster-enhanced.js +24 -3
  102. package/dist/intelligence/agent-booster-enhanced.js.map +1 -1
  103. package/dist/intelligence/index.d.ts +29 -3
  104. package/dist/intelligence/index.d.ts.map +1 -1
  105. package/dist/intelligence/index.js +13 -3
  106. package/dist/intelligence/index.js.map +1 -1
  107. package/dist/mcp/claudeFlowSdkServer.d.ts.map +1 -1
  108. package/dist/mcp/claudeFlowSdkServer.js +162 -115
  109. package/dist/mcp/claudeFlowSdkServer.js.map +1 -1
  110. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js +5 -5
  111. package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js.map +1 -1
  112. package/dist/mcp/fastmcp/tools/swarm/init.d.ts.map +1 -1
  113. package/dist/mcp/fastmcp/tools/swarm/init.js +36 -7
  114. package/dist/mcp/fastmcp/tools/swarm/init.js.map +1 -1
  115. package/dist/mcp/fastmcp/tools/swarm/spawn.d.ts.map +1 -1
  116. package/dist/mcp/fastmcp/tools/swarm/spawn.js +47 -8
  117. package/dist/mcp/fastmcp/tools/swarm/spawn.js.map +1 -1
  118. package/dist/mcp/tools/agent-booster-tools.d.ts +15 -1
  119. package/dist/mcp/tools/agent-booster-tools.d.ts.map +1 -1
  120. package/dist/mcp/tools/agent-booster-tools.js +79 -63
  121. package/dist/mcp/tools/agent-booster-tools.js.map +1 -1
  122. package/dist/mcp/tools/sona-tools.d.ts.map +1 -1
  123. package/dist/mcp/tools/sona-tools.js +6 -0
  124. package/dist/mcp/tools/sona-tools.js.map +1 -1
  125. package/dist/memory/SharedMemoryPool.d.ts +103 -0
  126. package/dist/memory/SharedMemoryPool.d.ts.map +1 -0
  127. package/dist/memory/SharedMemoryPool.js +263 -0
  128. package/dist/memory/SharedMemoryPool.js.map +1 -0
  129. package/dist/optimizations/agent-booster-migration.d.ts +2 -1
  130. package/dist/optimizations/agent-booster-migration.d.ts.map +1 -1
  131. package/dist/optimizations/agent-booster-migration.js +69 -45
  132. package/dist/optimizations/agent-booster-migration.js.map +1 -1
  133. package/dist/orchestration/index.d.ts +11 -0
  134. package/dist/orchestration/index.d.ts.map +1 -0
  135. package/dist/orchestration/index.js +10 -0
  136. package/dist/orchestration/index.js.map +1 -0
  137. package/dist/orchestration/memory-plane-types.d.ts +23 -0
  138. package/dist/orchestration/memory-plane-types.d.ts.map +1 -0
  139. package/dist/orchestration/memory-plane-types.js +5 -0
  140. package/dist/orchestration/memory-plane-types.js.map +1 -0
  141. package/dist/orchestration/memory-plane.d.ts +41 -0
  142. package/dist/orchestration/memory-plane.d.ts.map +1 -0
  143. package/dist/orchestration/memory-plane.js +84 -0
  144. package/dist/orchestration/memory-plane.js.map +1 -0
  145. package/dist/orchestration/orchestration-client.d.ts +104 -0
  146. package/dist/orchestration/orchestration-client.d.ts.map +1 -0
  147. package/dist/orchestration/orchestration-client.js +94 -0
  148. package/dist/orchestration/orchestration-client.js.map +1 -0
  149. package/dist/orchestration/orchestration-runtime.d.ts +26 -0
  150. package/dist/orchestration/orchestration-runtime.d.ts.map +1 -0
  151. package/dist/orchestration/orchestration-runtime.js +78 -0
  152. package/dist/orchestration/orchestration-runtime.js.map +1 -0
  153. package/dist/orchestration/orchestration-types.d.ts +124 -0
  154. package/dist/orchestration/orchestration-types.d.ts.map +1 -0
  155. package/dist/orchestration/orchestration-types.js +7 -0
  156. package/dist/orchestration/orchestration-types.js.map +1 -0
  157. package/dist/proxy/anthropic-to-openrouter.js.map +1 -1
  158. package/dist/proxy/anthropic-to-requesty.js.map +1 -1
  159. package/dist/proxy/quic-proxy.d.ts +0 -1
  160. package/dist/proxy/quic-proxy.d.ts.map +1 -1
  161. package/dist/proxy/quic-proxy.js +2 -2
  162. package/dist/proxy/quic-proxy.js.map +1 -1
  163. package/dist/reasoningbank/AdvancedMemory.js +1 -1
  164. package/dist/reasoningbank/AdvancedMemory.js.map +1 -1
  165. package/dist/reasoningbank/HybridBackend.d.ts.map +1 -1
  166. package/dist/reasoningbank/HybridBackend.js +2 -5
  167. package/dist/reasoningbank/HybridBackend.js.map +1 -1
  168. package/dist/reasoningbank/backend-selector.d.ts +10 -0
  169. package/dist/reasoningbank/backend-selector.d.ts.map +1 -1
  170. package/dist/reasoningbank/backend-selector.js +45 -5
  171. package/dist/reasoningbank/backend-selector.js.map +1 -1
  172. package/dist/reasoningbank/core/consolidate.d.ts.map +1 -1
  173. package/dist/reasoningbank/core/consolidate.js +113 -45
  174. package/dist/reasoningbank/core/consolidate.js.map +1 -1
  175. package/dist/reasoningbank/index-new.d.ts +1 -6
  176. package/dist/reasoningbank/index-new.d.ts.map +1 -1
  177. package/dist/reasoningbank/index-new.js +1 -6
  178. package/dist/reasoningbank/index-new.js.map +1 -1
  179. package/dist/reasoningbank/index.d.ts +6 -0
  180. package/dist/reasoningbank/index.d.ts.map +1 -1
  181. package/dist/reasoningbank/index.js +6 -13
  182. package/dist/reasoningbank/index.js.map +1 -1
  183. package/dist/reasoningbank/utils/embeddings.d.ts +1 -0
  184. package/dist/reasoningbank/utils/embeddings.d.ts.map +1 -1
  185. package/dist/reasoningbank/utils/embeddings.js +53 -26
  186. package/dist/reasoningbank/utils/embeddings.js.map +1 -1
  187. package/dist/router/index.d.ts +2 -1
  188. package/dist/router/index.d.ts.map +1 -1
  189. package/dist/router/index.js +1 -0
  190. package/dist/router/index.js.map +1 -1
  191. package/dist/router/providers/ollama.d.ts +20 -0
  192. package/dist/router/providers/ollama.d.ts.map +1 -0
  193. package/dist/router/providers/ollama.js +242 -0
  194. package/dist/router/providers/ollama.js.map +1 -0
  195. package/dist/router/providers/onnx-local-optimized.d.ts +2 -0
  196. package/dist/router/providers/onnx-local-optimized.d.ts.map +1 -1
  197. package/dist/router/providers/onnx-local-optimized.js +10 -0
  198. package/dist/router/providers/onnx-local-optimized.js.map +1 -1
  199. package/dist/router/providers/onnx-local.d.ts +1 -0
  200. package/dist/router/providers/onnx-local.d.ts.map +1 -1
  201. package/dist/router/providers/onnx-local.js +22 -5
  202. package/dist/router/providers/onnx-local.js.map +1 -1
  203. package/dist/router/router.d.ts.map +1 -1
  204. package/dist/router/router.js +39 -23
  205. package/dist/router/router.js.map +1 -1
  206. package/dist/sdk/index.d.ts +2 -1
  207. package/dist/sdk/index.d.ts.map +1 -1
  208. package/dist/sdk/index.js +3 -1
  209. package/dist/sdk/index.js.map +1 -1
  210. package/dist/services/embedding-service.js.map +1 -1
  211. package/dist/services/sona-agent-training.d.ts +1 -0
  212. package/dist/services/sona-agent-training.d.ts.map +1 -1
  213. package/dist/services/sona-agent-training.js.map +1 -1
  214. package/dist/services/sona-agentdb-integration.d.ts.map +1 -1
  215. package/dist/services/sona-agentdb-integration.js +9 -6
  216. package/dist/services/sona-agentdb-integration.js.map +1 -1
  217. package/dist/services/sona-service.d.ts.map +1 -1
  218. package/dist/services/sona-service.js +6 -5
  219. package/dist/services/sona-service.js.map +1 -1
  220. package/dist/utils/cli.d.ts +1 -1
  221. package/dist/utils/cli.d.ts.map +1 -1
  222. package/dist/utils/cli.js +21 -0
  223. package/dist/utils/cli.js.map +1 -1
  224. package/dist/utils/index.d.ts +6 -0
  225. package/dist/utils/index.d.ts.map +1 -0
  226. package/dist/utils/index.js +6 -0
  227. package/dist/utils/index.js.map +1 -0
  228. package/dist/utils/model-cache.d.ts +61 -0
  229. package/dist/utils/model-cache.d.ts.map +1 -0
  230. package/dist/utils/model-cache.js +176 -0
  231. package/dist/utils/model-cache.js.map +1 -0
  232. package/dist/utils/suppress-warnings.d.ts +19 -0
  233. package/dist/utils/suppress-warnings.d.ts.map +1 -0
  234. package/dist/utils/suppress-warnings.js +59 -0
  235. package/dist/utils/suppress-warnings.js.map +1 -0
  236. package/dist/workers/consolidated-phases.d.ts +40 -0
  237. package/dist/workers/consolidated-phases.d.ts.map +1 -0
  238. package/dist/workers/consolidated-phases.js +497 -0
  239. package/dist/workers/consolidated-phases.js.map +1 -0
  240. package/dist/workers/custom-worker-config.d.ts +133 -0
  241. package/dist/workers/custom-worker-config.d.ts.map +1 -0
  242. package/dist/workers/custom-worker-config.js +215 -0
  243. package/dist/workers/custom-worker-config.js.map +1 -0
  244. package/dist/workers/custom-worker-factory.d.ts +89 -0
  245. package/dist/workers/custom-worker-factory.d.ts.map +1 -0
  246. package/dist/workers/custom-worker-factory.js +404 -0
  247. package/dist/workers/custom-worker-factory.js.map +1 -0
  248. package/dist/workers/dispatch-service.d.ts +123 -0
  249. package/dist/workers/dispatch-service.d.ts.map +1 -0
  250. package/dist/workers/dispatch-service.js +1024 -0
  251. package/dist/workers/dispatch-service.js.map +1 -0
  252. package/dist/workers/hooks-integration.d.ts +79 -0
  253. package/dist/workers/hooks-integration.d.ts.map +1 -0
  254. package/dist/workers/hooks-integration.js +286 -0
  255. package/dist/workers/hooks-integration.js.map +1 -0
  256. package/dist/workers/index.d.ts +42 -0
  257. package/dist/workers/index.d.ts.map +1 -0
  258. package/dist/workers/index.js +52 -0
  259. package/dist/workers/index.js.map +1 -0
  260. package/dist/workers/mcp-tools.d.ts +56 -0
  261. package/dist/workers/mcp-tools.d.ts.map +1 -0
  262. package/dist/workers/mcp-tools.js +359 -0
  263. package/dist/workers/mcp-tools.js.map +1 -0
  264. package/dist/workers/phase-executors.d.ts +22 -0
  265. package/dist/workers/phase-executors.d.ts.map +1 -0
  266. package/dist/workers/phase-executors.js +445 -0
  267. package/dist/workers/phase-executors.js.map +1 -0
  268. package/dist/workers/resource-governor.d.ts +75 -0
  269. package/dist/workers/resource-governor.d.ts.map +1 -0
  270. package/dist/workers/resource-governor.js +187 -0
  271. package/dist/workers/resource-governor.js.map +1 -0
  272. package/dist/workers/ruvector-integration.d.ts +163 -0
  273. package/dist/workers/ruvector-integration.d.ts.map +1 -0
  274. package/dist/workers/ruvector-integration.js +543 -0
  275. package/dist/workers/ruvector-integration.js.map +1 -0
  276. package/dist/workers/ruvector-native-integration.d.ts +91 -0
  277. package/dist/workers/ruvector-native-integration.d.ts.map +1 -0
  278. package/dist/workers/ruvector-native-integration.js +254 -0
  279. package/dist/workers/ruvector-native-integration.js.map +1 -0
  280. package/dist/workers/trigger-detector.d.ts +68 -0
  281. package/dist/workers/trigger-detector.d.ts.map +1 -0
  282. package/dist/workers/trigger-detector.js +281 -0
  283. package/dist/workers/trigger-detector.js.map +1 -0
  284. package/dist/workers/types.d.ts +145 -0
  285. package/dist/workers/types.d.ts.map +1 -0
  286. package/dist/workers/types.js +6 -0
  287. package/dist/workers/types.js.map +1 -0
  288. package/dist/workers/worker-agent-integration.d.ts +140 -0
  289. package/dist/workers/worker-agent-integration.d.ts.map +1 -0
  290. package/dist/workers/worker-agent-integration.js +471 -0
  291. package/dist/workers/worker-agent-integration.js.map +1 -0
  292. package/dist/workers/worker-benchmarks.d.ts +88 -0
  293. package/dist/workers/worker-benchmarks.d.ts.map +1 -0
  294. package/dist/workers/worker-benchmarks.js +452 -0
  295. package/dist/workers/worker-benchmarks.js.map +1 -0
  296. package/dist/workers/worker-registry.d.ts +85 -0
  297. package/dist/workers/worker-registry.d.ts.map +1 -0
  298. package/dist/workers/worker-registry.js +547 -0
  299. package/dist/workers/worker-registry.js.map +1 -0
  300. package/docs/embeddings/EMBEDDING_GEOMETRY.md +935 -0
  301. package/package.json +26 -8
  302. package/scripts/postinstall.js +45 -4
  303. package/wasm/reasoningbank/reasoningbank_wasm.js +1 -1
  304. package/wasm/reasoningbank/reasoningbank_wasm_bg.js +54 -54
  305. package/wasm/reasoningbank/reasoningbank_wasm_bg.wasm +0 -0
  306. package/wasm/reasoningbank/reasoningbank_wasm_bg.wasm.d.ts +4 -3
  307. package/.claude/agents/test-neural.md +0 -14
  308. /package/.claude/agents/analysis/{code-review/analyze-code-quality.md → analyze-code-quality.md} +0 -0
  309. /package/.claude/agents/architecture/{system-design/arch-system-design.md → arch-system-design.md} +0 -0
  310. /package/.claude/agents/data/{ml/data-ml-model.md → data-ml-model.md} +0 -0
  311. /package/.claude/agents/development/{backend/dev-backend-api.md → dev-backend-api.md} +0 -0
  312. /package/.claude/agents/devops/{ci-cd/ops-cicd-github.md → ops-cicd-github.md} +0 -0
  313. /package/.claude/agents/documentation/{api-docs/docs-api-openapi.md → docs-api-openapi.md} +0 -0
  314. /package/.claude/agents/specialized/{mobile/spec-mobile-react-native.md → spec-mobile-react-native.md} +0 -0
  315. /package/.claude/agents/testing/{validation/production-validator.md → production-validator.md} +0 -0
  316. /package/.claude/agents/testing/{unit/tdd-london-swarm.md → tdd-london-swarm.md} +0 -0
@@ -0,0 +1,629 @@
1
+ /**
2
+ * Neural Embedding Substrate Integration
3
+ *
4
+ * Wraps ruvector's NeuralSubstrate for agentic-flow agents
5
+ * treating embeddings as a synthetic nervous system.
6
+ *
7
+ * Based on ruvector@0.1.85 neural-embeddings.ts
8
+ */
9
+ import { getOptimizedEmbedder, cosineSimilarity, euclideanDistance } from './optimized-embedder.js';
10
+ // ============================================================================
11
+ // Security Constants
12
+ // ============================================================================
13
+ const MAX_TEXT_LENGTH = 10000; // Maximum input text length
14
+ const MAX_MEMORIES = 10000; // Maximum memories in MemoryPhysics
15
+ const MAX_AGENTS = 1000; // Maximum agents in swarm
16
+ const MAX_BASELINE_SAMPLES = 1000; // Maximum calibration samples
17
+ const MAX_HISTORY_SIZE = 100; // Maximum drift history
18
+ const VALID_ID_PATTERN = /^[a-zA-Z0-9_-]{1,256}$/;
19
+ // ============================================================================
20
+ // Security Validation Functions
21
+ // ============================================================================
22
+ /**
23
+ * Validate text input length
24
+ */
25
+ function validateTextInput(text, context) {
26
+ if (!text || typeof text !== 'string') {
27
+ throw new Error(`${context}: Input must be a non-empty string`);
28
+ }
29
+ if (text.length > MAX_TEXT_LENGTH) {
30
+ throw new Error(`${context}: Text exceeds maximum length of ${MAX_TEXT_LENGTH} characters`);
31
+ }
32
+ }
33
+ /**
34
+ * Validate ID format
35
+ */
36
+ function validateId(id, context) {
37
+ if (!id || typeof id !== 'string') {
38
+ throw new Error(`${context}: ID must be a non-empty string`);
39
+ }
40
+ if (!VALID_ID_PATTERN.test(id)) {
41
+ throw new Error(`${context}: Invalid ID format. Use 1-256 alphanumeric characters, underscores, or hyphens`);
42
+ }
43
+ }
44
+ /**
45
+ * Validate array is not null and has expected dimension
46
+ */
47
+ function validateEmbedding(arr, context) {
48
+ if (!arr) {
49
+ throw new Error(`${context}: Not initialized. Call the appropriate setup method first.`);
50
+ }
51
+ }
52
+ /**
53
+ * Semantic Drift Detector
54
+ * Monitors semantic movement and triggers reflexes
55
+ * Optimized with pre-allocated buffers (80-95% less GC pressure)
56
+ */
57
+ export class SemanticDriftDetector {
58
+ driftThreshold;
59
+ escalationThreshold;
60
+ historySize;
61
+ embedder = getOptimizedEmbedder();
62
+ baseline = null;
63
+ history = [];
64
+ velocity = null;
65
+ acceleration = null;
66
+ dimension = 0;
67
+ // Pre-allocated buffer for velocity calculation (reused each detect call)
68
+ tempVelocityBuffer = null;
69
+ constructor(driftThreshold = 0.15, escalationThreshold = 0.30, historySize = 20) {
70
+ this.driftThreshold = driftThreshold;
71
+ this.escalationThreshold = escalationThreshold;
72
+ this.historySize = historySize;
73
+ }
74
+ async init() {
75
+ await this.embedder.init();
76
+ }
77
+ async setBaseline(context) {
78
+ validateTextInput(context, 'SemanticDriftDetector.setBaseline');
79
+ this.baseline = await this.embedder.embed(context);
80
+ this.dimension = this.baseline.length;
81
+ this.history = [{ embedding: this.baseline, timestamp: Date.now() }];
82
+ // Pre-allocate buffers once (reused for all subsequent detect calls)
83
+ if (!this.velocity || this.velocity.length !== this.dimension) {
84
+ this.velocity = new Float32Array(this.dimension);
85
+ this.acceleration = new Float32Array(this.dimension);
86
+ this.tempVelocityBuffer = new Float32Array(this.dimension);
87
+ }
88
+ else {
89
+ // Zero out existing buffers
90
+ this.velocity.fill(0);
91
+ this.acceleration.fill(0);
92
+ }
93
+ }
94
+ async detect(input) {
95
+ validateTextInput(input, 'SemanticDriftDetector.detect');
96
+ validateEmbedding(this.baseline, 'SemanticDriftDetector.detect');
97
+ const current = await this.embedder.embed(input);
98
+ const distance = 1 - cosineSimilarity(this.baseline, current);
99
+ // Calculate velocity using pre-allocated buffer (no new allocation!)
100
+ const prev = this.history[this.history.length - 1]?.embedding || this.baseline;
101
+ const newVelocity = this.tempVelocityBuffer;
102
+ const dim = this.dimension;
103
+ // 8x unrolled velocity calculation
104
+ const unrolledLen = dim - (dim % 8);
105
+ let i = 0;
106
+ for (; i < unrolledLen; i += 8) {
107
+ newVelocity[i] = current[i] - prev[i];
108
+ newVelocity[i + 1] = current[i + 1] - prev[i + 1];
109
+ newVelocity[i + 2] = current[i + 2] - prev[i + 2];
110
+ newVelocity[i + 3] = current[i + 3] - prev[i + 3];
111
+ newVelocity[i + 4] = current[i + 4] - prev[i + 4];
112
+ newVelocity[i + 5] = current[i + 5] - prev[i + 5];
113
+ newVelocity[i + 6] = current[i + 6] - prev[i + 6];
114
+ newVelocity[i + 7] = current[i + 7] - prev[i + 7];
115
+ }
116
+ for (; i < dim; i++) {
117
+ newVelocity[i] = current[i] - prev[i];
118
+ }
119
+ // Calculate acceleration and update velocity in-place
120
+ let velocityMagSq = 0;
121
+ let accelerationMagSq = 0;
122
+ for (i = 0; i < dim; i++) {
123
+ const oldVel = this.velocity[i];
124
+ const newVel = newVelocity[i];
125
+ this.acceleration[i] = newVel - oldVel;
126
+ this.velocity[i] = newVel;
127
+ velocityMagSq += newVel * newVel;
128
+ accelerationMagSq += this.acceleration[i] * this.acceleration[i];
129
+ }
130
+ const velocityMag = Math.sqrt(velocityMagSq);
131
+ const accelerationMag = Math.sqrt(accelerationMagSq);
132
+ // Update history
133
+ this.history.push({ embedding: current, timestamp: Date.now() });
134
+ if (this.history.length > this.historySize)
135
+ this.history.shift();
136
+ // Determine trend
137
+ let trend = 'stable';
138
+ if (accelerationMag > 0.01)
139
+ trend = 'accelerating';
140
+ else if (velocityMag > 0.05)
141
+ trend = 'drifting';
142
+ else if (distance < this.driftThreshold * 0.5 && velocityMag < 0.02)
143
+ trend = 'recovering';
144
+ return {
145
+ distance,
146
+ velocity: velocityMag,
147
+ acceleration: accelerationMag,
148
+ trend,
149
+ shouldEscalate: distance > this.driftThreshold,
150
+ shouldTriggerReasoning: distance > this.escalationThreshold
151
+ };
152
+ }
153
+ getStats() {
154
+ if (!this.baseline || this.history.length < 2) {
155
+ return { avgDrift: 0, maxDrift: 0, driftEvents: 0 };
156
+ }
157
+ const drifts = this.history.map(h => 1 - cosineSimilarity(this.baseline, h.embedding));
158
+ const avgDrift = drifts.reduce((a, b) => a + b, 0) / drifts.length;
159
+ const maxDrift = Math.max(...drifts);
160
+ const driftEvents = drifts.filter(d => d > this.driftThreshold).length;
161
+ return { avgDrift, maxDrift, driftEvents };
162
+ }
163
+ }
164
+ /**
165
+ * Memory Physics
166
+ * Hippocampal-like dynamics: decay, interference, consolidation
167
+ */
168
+ export class MemoryPhysics {
169
+ decayRate;
170
+ interferenceRadius;
171
+ forgettingThreshold;
172
+ embedder = getOptimizedEmbedder();
173
+ memories = new Map();
174
+ lastConsolidation = Date.now();
175
+ constructor(decayRate = 0.01, interferenceRadius = 0.3, forgettingThreshold = 0.1) {
176
+ this.decayRate = decayRate;
177
+ this.interferenceRadius = interferenceRadius;
178
+ this.forgettingThreshold = forgettingThreshold;
179
+ }
180
+ async init() {
181
+ await this.embedder.init();
182
+ }
183
+ async store(id, content) {
184
+ validateId(id, 'MemoryPhysics.store');
185
+ validateTextInput(content, 'MemoryPhysics.store');
186
+ // Security: Enforce memory limit
187
+ if (this.memories.size >= MAX_MEMORIES && !this.memories.has(id)) {
188
+ throw new Error(`Memory capacity exceeded (max: ${MAX_MEMORIES}). Call consolidate() to free space.`);
189
+ }
190
+ const embedding = await this.embedder.embed(content);
191
+ const interference = [];
192
+ // Check interference with existing memories
193
+ for (const [memId, mem] of this.memories) {
194
+ const distance = euclideanDistance(embedding, mem.embedding);
195
+ if (distance < this.interferenceRadius) {
196
+ const strength = (this.interferenceRadius - distance) / this.interferenceRadius;
197
+ mem.strength *= (1 - strength * 0.5);
198
+ interference.push(memId);
199
+ }
200
+ }
201
+ this.memories.set(id, {
202
+ id,
203
+ embedding,
204
+ content,
205
+ strength: 1.0,
206
+ timestamp: Date.now(),
207
+ accessCount: 0,
208
+ associations: interference
209
+ });
210
+ return { stored: true, interference };
211
+ }
212
+ async recall(query, topK = 5) {
213
+ validateTextInput(query, 'MemoryPhysics.recall');
214
+ const queryEmb = await this.embedder.embed(query);
215
+ this.applyDecay();
216
+ const results = [];
217
+ for (const mem of this.memories.values()) {
218
+ if (mem.strength < this.forgettingThreshold)
219
+ continue;
220
+ const relevance = cosineSimilarity(queryEmb, mem.embedding);
221
+ mem.accessCount++;
222
+ mem.strength = Math.min(1.0, mem.strength * 1.1); // Retrieval strengthens
223
+ results.push({ ...mem, relevance });
224
+ }
225
+ return results
226
+ .sort((a, b) => (b.relevance * b.strength) - (a.relevance * a.strength))
227
+ .slice(0, topK);
228
+ }
229
+ applyDecay() {
230
+ const now = Date.now();
231
+ for (const mem of this.memories.values()) {
232
+ const hours = (now - mem.timestamp) / 3600000;
233
+ mem.strength *= Math.exp(-this.decayRate * hours);
234
+ mem.timestamp = now;
235
+ }
236
+ }
237
+ consolidate() {
238
+ const clusters = [];
239
+ const used = new Set();
240
+ let merged = 0;
241
+ let forgotten = 0;
242
+ // Remove forgotten memories
243
+ for (const [id, mem] of this.memories) {
244
+ if (mem.strength < this.forgettingThreshold) {
245
+ this.memories.delete(id);
246
+ forgotten++;
247
+ }
248
+ }
249
+ // Cluster similar memories
250
+ for (const mem of this.memories.values()) {
251
+ if (used.has(mem.id))
252
+ continue;
253
+ const cluster = [mem];
254
+ for (const other of this.memories.values()) {
255
+ if (used.has(other.id) || mem.id === other.id)
256
+ continue;
257
+ const sim = cosineSimilarity(mem.embedding, other.embedding);
258
+ if (sim > 0.9) {
259
+ cluster.push(other);
260
+ used.add(other.id);
261
+ merged++;
262
+ }
263
+ }
264
+ if (cluster.length > 1) {
265
+ // Merge: keep strongest, combine strength
266
+ const strongest = cluster.reduce((a, b) => a.strength > b.strength ? a : b);
267
+ strongest.strength = Math.min(1.0, cluster.reduce((s, m) => s + m.strength, 0));
268
+ strongest.associations = [...new Set(cluster.flatMap(c => c.associations))];
269
+ for (const c of cluster) {
270
+ if (c.id !== strongest.id)
271
+ this.memories.delete(c.id);
272
+ }
273
+ }
274
+ clusters.push(cluster);
275
+ }
276
+ this.lastConsolidation = Date.now();
277
+ return { merged, forgotten, remaining: this.memories.size };
278
+ }
279
+ getStats() {
280
+ const active = [...this.memories.values()].filter(m => m.strength > this.forgettingThreshold);
281
+ const avgStrength = active.length > 0
282
+ ? active.reduce((s, m) => s + m.strength, 0) / active.length
283
+ : 0;
284
+ return {
285
+ total: this.memories.size,
286
+ active: active.length,
287
+ avgStrength
288
+ };
289
+ }
290
+ }
291
+ /**
292
+ * Embedding State Machine
293
+ * Agent state through geometry: position, velocity, attention
294
+ */
295
+ export class EmbeddingStateMachine {
296
+ dimension;
297
+ embedder = getOptimizedEmbedder();
298
+ agents = new Map();
299
+ stateRegions = new Map();
300
+ constructor(dimension = 384) {
301
+ this.dimension = dimension;
302
+ }
303
+ async init() {
304
+ await this.embedder.init();
305
+ // Initialize default state regions
306
+ const regions = {
307
+ exploring: 'exploring options, gathering information, uncertain, searching',
308
+ executing: 'executing task, confident, taking action, progressing',
309
+ waiting: 'waiting for input, paused, blocked, need information',
310
+ error: 'error state, confused, failed, need help, recovery'
311
+ };
312
+ for (const [name, desc] of Object.entries(regions)) {
313
+ this.stateRegions.set(name, await this.embedder.embed(desc));
314
+ }
315
+ }
316
+ async registerAgent(id, initialRole) {
317
+ validateId(id, 'EmbeddingStateMachine.registerAgent');
318
+ validateTextInput(initialRole, 'EmbeddingStateMachine.registerAgent');
319
+ // Security: Enforce agent limit
320
+ if (this.agents.size >= MAX_AGENTS && !this.agents.has(id)) {
321
+ throw new Error(`Agent capacity exceeded (max: ${MAX_AGENTS})`);
322
+ }
323
+ const position = await this.embedder.embed(initialRole);
324
+ const state = {
325
+ id,
326
+ position,
327
+ velocity: new Float32Array(this.dimension).fill(0),
328
+ attention: new Float32Array(this.dimension).fill(1),
329
+ energy: 1.0,
330
+ lastUpdate: Date.now()
331
+ };
332
+ this.agents.set(id, state);
333
+ return state;
334
+ }
335
+ async updateState(agentId, observation) {
336
+ validateId(agentId, 'EmbeddingStateMachine.updateState');
337
+ validateTextInput(observation, 'EmbeddingStateMachine.updateState');
338
+ const agent = this.agents.get(agentId);
339
+ if (!agent)
340
+ throw new Error('Agent not found or access denied');
341
+ const obsEmb = await this.embedder.embed(observation);
342
+ // Update velocity and position
343
+ const learningRate = 0.3;
344
+ const momentumRate = 0.7;
345
+ for (let i = 0; i < this.dimension; i++) {
346
+ const gradient = obsEmb[i] - agent.position[i];
347
+ agent.velocity[i] = momentumRate * agent.velocity[i] + learningRate * gradient;
348
+ agent.position[i] += agent.velocity[i];
349
+ }
350
+ // Normalize position
351
+ const norm = Math.sqrt(agent.position.reduce((s, v) => s + v * v, 0));
352
+ for (let i = 0; i < this.dimension; i++) {
353
+ agent.position[i] /= norm;
354
+ }
355
+ // Update attention based on velocity magnitude
356
+ const velocityMag = Math.sqrt(agent.velocity.reduce((s, v) => s + v * v, 0));
357
+ for (let i = 0; i < this.dimension; i++) {
358
+ agent.attention[i] = 1 + velocityMag * Math.abs(agent.velocity[i]);
359
+ }
360
+ // Energy decay with movement
361
+ agent.energy = Math.max(0.1, agent.energy - velocityMag * 0.1);
362
+ agent.lastUpdate = Date.now();
363
+ // Find nearest state region
364
+ let nearestRegion = 'unknown';
365
+ let regionProximity = -1;
366
+ for (const [name, region] of this.stateRegions) {
367
+ const sim = cosineSimilarity(agent.position, region);
368
+ if (sim > regionProximity) {
369
+ regionProximity = sim;
370
+ nearestRegion = name;
371
+ }
372
+ }
373
+ return { newState: agent, nearestRegion, regionProximity };
374
+ }
375
+ getAgent(id) {
376
+ return this.agents.get(id);
377
+ }
378
+ getAllAgents() {
379
+ return [...this.agents.values()];
380
+ }
381
+ }
382
+ /**
383
+ * Swarm Coordinator
384
+ * Multi-agent coordination through shared embedding space
385
+ */
386
+ export class SwarmCoordinator {
387
+ embedder = getOptimizedEmbedder();
388
+ stateMachine;
389
+ constructor(dimension = 384) {
390
+ this.stateMachine = new EmbeddingStateMachine(dimension);
391
+ }
392
+ async init() {
393
+ await this.embedder.init();
394
+ await this.stateMachine.init();
395
+ }
396
+ async addAgent(id, role) {
397
+ validateId(id, 'SwarmCoordinator.addAgent');
398
+ validateTextInput(role, 'SwarmCoordinator.addAgent');
399
+ return this.stateMachine.registerAgent(id, role);
400
+ }
401
+ async coordinate(task) {
402
+ const taskEmb = await this.embedder.embed(task);
403
+ const agents = this.stateMachine.getAllAgents();
404
+ const results = [];
405
+ for (const agent of agents) {
406
+ const taskAlignment = cosineSimilarity(agent.position, taskEmb);
407
+ // Find best collaborator
408
+ let bestCollaborator = null;
409
+ let bestScore = -1;
410
+ for (const other of agents) {
411
+ if (other.id === agent.id)
412
+ continue;
413
+ const otherAlignment = cosineSimilarity(other.position, taskEmb);
414
+ const complementarity = 1 - cosineSimilarity(agent.position, other.position);
415
+ const score = otherAlignment * 0.6 + complementarity * 0.4;
416
+ if (score > bestScore) {
417
+ bestScore = score;
418
+ bestCollaborator = other.id;
419
+ }
420
+ }
421
+ results.push({
422
+ agentId: agent.id,
423
+ taskAlignment,
424
+ bestCollaborator,
425
+ collaborationScore: bestScore
426
+ });
427
+ }
428
+ return results.sort((a, b) => b.taskAlignment - a.taskAlignment);
429
+ }
430
+ specialize() {
431
+ const agents = this.stateMachine.getAllAgents();
432
+ const repulsionStrength = 0.05;
433
+ for (let i = 0; i < agents.length; i++) {
434
+ for (let j = i + 1; j < agents.length; j++) {
435
+ const sim = cosineSimilarity(agents[i].position, agents[j].position);
436
+ if (sim > 0.8) {
437
+ // Repel similar agents
438
+ for (let k = 0; k < agents[i].position.length; k++) {
439
+ const repulsion = repulsionStrength * (agents[j].position[k] - agents[i].position[k]);
440
+ agents[i].position[k] -= repulsion;
441
+ agents[j].position[k] += repulsion;
442
+ }
443
+ }
444
+ }
445
+ }
446
+ // Normalize all
447
+ for (const agent of agents) {
448
+ const norm = Math.sqrt(agent.position.reduce((s, v) => s + v * v, 0));
449
+ for (let k = 0; k < agent.position.length; k++) {
450
+ agent.position[k] /= norm;
451
+ }
452
+ }
453
+ }
454
+ getStatus() {
455
+ const agents = this.stateMachine.getAllAgents();
456
+ if (agents.length === 0)
457
+ return { agentCount: 0, avgEnergy: 0, coherence: 0 };
458
+ const avgEnergy = agents.reduce((s, a) => s + a.energy, 0) / agents.length;
459
+ // Coherence = average pairwise similarity
460
+ let coherence = 0;
461
+ let pairs = 0;
462
+ for (let i = 0; i < agents.length; i++) {
463
+ for (let j = i + 1; j < agents.length; j++) {
464
+ coherence += cosineSimilarity(agents[i].position, agents[j].position);
465
+ pairs++;
466
+ }
467
+ }
468
+ coherence = pairs > 0 ? coherence / pairs : 1;
469
+ return { agentCount: agents.length, avgEnergy, coherence };
470
+ }
471
+ }
472
+ /**
473
+ * Coherence Monitor
474
+ * Safety and alignment detection
475
+ */
476
+ export class CoherenceMonitor {
477
+ embedder = getOptimizedEmbedder();
478
+ baseline = [];
479
+ centroid = null;
480
+ avgDistance = 0;
481
+ async init() {
482
+ await this.embedder.init();
483
+ }
484
+ async calibrate(goodOutputs) {
485
+ // Security: Validate input array
486
+ if (!Array.isArray(goodOutputs)) {
487
+ throw new Error('CoherenceMonitor.calibrate: goodOutputs must be an array');
488
+ }
489
+ if (goodOutputs.length === 0) {
490
+ throw new Error('CoherenceMonitor.calibrate: At least one sample is required');
491
+ }
492
+ if (goodOutputs.length > MAX_BASELINE_SAMPLES) {
493
+ throw new Error(`CoherenceMonitor.calibrate: Sample count exceeds maximum of ${MAX_BASELINE_SAMPLES}`);
494
+ }
495
+ // Validate each sample
496
+ for (const output of goodOutputs) {
497
+ validateTextInput(output, 'CoherenceMonitor.calibrate');
498
+ }
499
+ this.baseline = await this.embedder.embedBatch(goodOutputs);
500
+ const dim = this.baseline[0].length;
501
+ // Calculate centroid
502
+ this.centroid = new Float32Array(dim).fill(0);
503
+ for (const emb of this.baseline) {
504
+ for (let i = 0; i < dim; i++) {
505
+ this.centroid[i] += emb[i];
506
+ }
507
+ }
508
+ for (let i = 0; i < dim; i++) {
509
+ this.centroid[i] /= this.baseline.length;
510
+ }
511
+ // Average distance from centroid
512
+ this.avgDistance = this.baseline.reduce((s, b) => s + euclideanDistance(b, this.centroid), 0) / this.baseline.length;
513
+ return { calibrated: true, sampleCount: this.baseline.length };
514
+ }
515
+ async check(output) {
516
+ validateTextInput(output, 'CoherenceMonitor.check');
517
+ validateEmbedding(this.centroid, 'CoherenceMonitor.check (call calibrate() first)');
518
+ const outputEmb = await this.embedder.embed(output);
519
+ const warnings = [];
520
+ // Anomaly score
521
+ const distance = euclideanDistance(outputEmb, this.centroid);
522
+ const anomalyScore = distance / this.avgDistance;
523
+ // Nearest neighbor
524
+ let maxSim = -1;
525
+ for (const b of this.baseline) {
526
+ const sim = cosineSimilarity(outputEmb, b);
527
+ if (sim > maxSim)
528
+ maxSim = sim;
529
+ }
530
+ const stabilityScore = maxSim;
531
+ // Drift direction
532
+ const driftDirection = new Float32Array(outputEmb.length);
533
+ for (let i = 0; i < outputEmb.length; i++) {
534
+ driftDirection[i] = outputEmb[i] - this.centroid[i];
535
+ }
536
+ // Warnings
537
+ if (anomalyScore > 2.0) {
538
+ warnings.push('CRITICAL: Output significantly outside baseline');
539
+ }
540
+ else if (anomalyScore > 1.5) {
541
+ warnings.push('WARNING: Output drifting from baseline');
542
+ }
543
+ if (stabilityScore < 0.5) {
544
+ warnings.push('WARNING: Low similarity to all baseline examples');
545
+ }
546
+ return {
547
+ isCoherent: anomalyScore < 1.5 && stabilityScore > 0.5,
548
+ anomalyScore,
549
+ stabilityScore,
550
+ driftDirection,
551
+ warnings
552
+ };
553
+ }
554
+ }
555
+ /**
556
+ * Neural Substrate
557
+ * Unified nervous system combining all components
558
+ */
559
+ export class NeuralSubstrate {
560
+ drift;
561
+ memory;
562
+ states;
563
+ swarm;
564
+ coherence;
565
+ startTime = Date.now();
566
+ constructor(config = {}) {
567
+ const { dimension = 384, driftThreshold = 0.15, decayRate = 0.01 } = config;
568
+ this.drift = new SemanticDriftDetector(driftThreshold);
569
+ this.memory = new MemoryPhysics(decayRate);
570
+ this.states = new EmbeddingStateMachine(dimension);
571
+ this.swarm = new SwarmCoordinator(dimension);
572
+ this.coherence = new CoherenceMonitor();
573
+ }
574
+ async init() {
575
+ await Promise.all([
576
+ this.drift.init(),
577
+ this.memory.init(),
578
+ this.states.init(),
579
+ this.swarm.init(),
580
+ this.coherence.init()
581
+ ]);
582
+ }
583
+ async process(input, context) {
584
+ const result = {};
585
+ // Always check drift
586
+ result.drift = await this.drift.detect(input);
587
+ // Update agent state if specified
588
+ if (context?.agentId) {
589
+ const { nearestRegion, regionProximity } = await this.states.updateState(context.agentId, input);
590
+ result.state = { nearestRegion, regionProximity };
591
+ }
592
+ // Store in memory if specified
593
+ if (context?.memoryId) {
594
+ const { stored } = await this.memory.store(context.memoryId, input);
595
+ result.stored = stored;
596
+ }
597
+ // Check coherence if requested
598
+ if (context?.checkCoherence) {
599
+ result.coherence = await this.coherence.check(input);
600
+ }
601
+ return result;
602
+ }
603
+ consolidate() {
604
+ return { memory: this.memory.consolidate() };
605
+ }
606
+ health() {
607
+ const memStats = this.memory.getStats();
608
+ const driftStats = this.drift.getStats();
609
+ const swarmStatus = this.swarm.getStatus();
610
+ return {
611
+ memoryCount: memStats.total,
612
+ activeAgents: swarmStatus.agentCount,
613
+ avgDrift: driftStats.avgDrift,
614
+ avgCoherence: swarmStatus.coherence,
615
+ lastConsolidation: 0, // Would need to track this
616
+ uptime: Date.now() - this.startTime
617
+ };
618
+ }
619
+ }
620
+ // Export singleton factory
621
+ let substrate = null;
622
+ export async function getNeuralSubstrate(config) {
623
+ if (!substrate) {
624
+ substrate = new NeuralSubstrate(config);
625
+ await substrate.init();
626
+ }
627
+ return substrate;
628
+ }
629
+ //# sourceMappingURL=neural-substrate.js.map