moflo 4.8.19 → 4.8.20

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 (241) hide show
  1. package/.claude/guidance/shipped/moflo.md +45 -0
  2. package/.claude/helpers/statusline.cjs +1 -1
  3. package/.claude/workflow-state.json +9 -0
  4. package/package.json +2 -2
  5. package/src/@claude-flow/cli/dist/src/init/statusline-generator.js +1 -1
  6. package/src/@claude-flow/cli/dist/src/services/agentic-flow-bridge.js +5 -3
  7. package/src/@claude-flow/cli/package.json +1 -1
  8. package/src/@claude-flow/memory/dist/agent-memory-scope.d.ts +131 -0
  9. package/src/@claude-flow/memory/dist/agent-memory-scope.js +223 -0
  10. package/src/@claude-flow/memory/dist/agent-memory-scope.test.d.ts +8 -0
  11. package/src/@claude-flow/memory/dist/agent-memory-scope.test.js +466 -0
  12. package/src/@claude-flow/memory/dist/agentdb-adapter.d.ts +165 -0
  13. package/src/@claude-flow/memory/dist/agentdb-adapter.js +806 -0
  14. package/src/@claude-flow/memory/dist/agentdb-backend.d.ts +212 -0
  15. package/src/@claude-flow/memory/dist/agentdb-backend.js +842 -0
  16. package/src/@claude-flow/memory/dist/agentdb-backend.test.d.ts +7 -0
  17. package/src/@claude-flow/memory/dist/agentdb-backend.test.js +258 -0
  18. package/src/@claude-flow/memory/dist/application/commands/delete-memory.command.d.ts +65 -0
  19. package/src/@claude-flow/memory/dist/application/commands/delete-memory.command.js +129 -0
  20. package/src/@claude-flow/memory/dist/application/commands/store-memory.command.d.ts +48 -0
  21. package/src/@claude-flow/memory/dist/application/commands/store-memory.command.js +72 -0
  22. package/src/@claude-flow/memory/dist/application/index.d.ts +12 -0
  23. package/src/@claude-flow/memory/dist/application/index.js +15 -0
  24. package/src/@claude-flow/memory/dist/application/queries/search-memory.query.d.ts +72 -0
  25. package/src/@claude-flow/memory/dist/application/queries/search-memory.query.js +143 -0
  26. package/src/@claude-flow/memory/dist/application/services/memory-application-service.d.ts +121 -0
  27. package/src/@claude-flow/memory/dist/application/services/memory-application-service.js +190 -0
  28. package/src/@claude-flow/memory/dist/auto-memory-bridge.d.ts +226 -0
  29. package/src/@claude-flow/memory/dist/auto-memory-bridge.js +709 -0
  30. package/src/@claude-flow/memory/dist/auto-memory-bridge.test.d.ts +8 -0
  31. package/src/@claude-flow/memory/dist/auto-memory-bridge.test.js +757 -0
  32. package/src/@claude-flow/memory/dist/benchmark.test.d.ts +2 -0
  33. package/src/@claude-flow/memory/dist/benchmark.test.js +277 -0
  34. package/src/@claude-flow/memory/dist/cache-manager.d.ts +134 -0
  35. package/src/@claude-flow/memory/dist/cache-manager.js +407 -0
  36. package/src/@claude-flow/memory/dist/controller-registry.d.ts +216 -0
  37. package/src/@claude-flow/memory/dist/controller-registry.js +893 -0
  38. package/src/@claude-flow/memory/dist/controller-registry.test.d.ts +14 -0
  39. package/src/@claude-flow/memory/dist/controller-registry.test.js +593 -0
  40. package/src/@claude-flow/memory/dist/database-provider.d.ts +87 -0
  41. package/src/@claude-flow/memory/dist/database-provider.js +372 -0
  42. package/src/@claude-flow/memory/dist/database-provider.test.d.ts +7 -0
  43. package/src/@claude-flow/memory/dist/database-provider.test.js +287 -0
  44. package/src/@claude-flow/memory/dist/domain/entities/memory-entry.d.ts +143 -0
  45. package/src/@claude-flow/memory/dist/domain/entities/memory-entry.js +226 -0
  46. package/src/@claude-flow/memory/dist/domain/index.d.ts +11 -0
  47. package/src/@claude-flow/memory/dist/domain/index.js +12 -0
  48. package/src/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.d.ts +102 -0
  49. package/src/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.js +11 -0
  50. package/src/@claude-flow/memory/dist/domain/services/memory-domain-service.d.ts +105 -0
  51. package/src/@claude-flow/memory/dist/domain/services/memory-domain-service.js +297 -0
  52. package/src/@claude-flow/memory/dist/hnsw-index.d.ts +111 -0
  53. package/src/@claude-flow/memory/dist/hnsw-index.js +781 -0
  54. package/src/@claude-flow/memory/dist/hnsw-lite.d.ts +23 -0
  55. package/src/@claude-flow/memory/dist/hnsw-lite.js +168 -0
  56. package/src/@claude-flow/memory/dist/index.d.ts +204 -0
  57. package/src/@claude-flow/memory/dist/index.js +358 -0
  58. package/src/@claude-flow/memory/dist/infrastructure/index.d.ts +17 -0
  59. package/src/@claude-flow/memory/dist/infrastructure/index.js +16 -0
  60. package/src/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.d.ts +66 -0
  61. package/src/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.js +409 -0
  62. package/src/@claude-flow/memory/dist/learning-bridge.d.ts +137 -0
  63. package/src/@claude-flow/memory/dist/learning-bridge.js +335 -0
  64. package/src/@claude-flow/memory/dist/learning-bridge.test.d.ts +8 -0
  65. package/src/@claude-flow/memory/dist/learning-bridge.test.js +578 -0
  66. package/src/@claude-flow/memory/dist/memory-graph.d.ts +100 -0
  67. package/src/@claude-flow/memory/dist/memory-graph.js +333 -0
  68. package/src/@claude-flow/memory/dist/memory-graph.test.d.ts +8 -0
  69. package/src/@claude-flow/memory/dist/memory-graph.test.js +609 -0
  70. package/src/@claude-flow/memory/dist/migration.d.ts +68 -0
  71. package/src/@claude-flow/memory/dist/migration.js +513 -0
  72. package/src/@claude-flow/memory/dist/persistent-sona.d.ts +144 -0
  73. package/src/@claude-flow/memory/dist/persistent-sona.js +332 -0
  74. package/src/@claude-flow/memory/dist/query-builder.d.ts +211 -0
  75. package/src/@claude-flow/memory/dist/query-builder.js +438 -0
  76. package/src/@claude-flow/memory/dist/rvf-backend.d.ts +51 -0
  77. package/src/@claude-flow/memory/dist/rvf-backend.js +481 -0
  78. package/src/@claude-flow/memory/dist/rvf-learning-store.d.ts +139 -0
  79. package/src/@claude-flow/memory/dist/rvf-learning-store.js +295 -0
  80. package/src/@claude-flow/memory/dist/rvf-migration.d.ts +45 -0
  81. package/src/@claude-flow/memory/dist/rvf-migration.js +234 -0
  82. package/src/@claude-flow/memory/dist/sqljs-backend.d.ts +127 -0
  83. package/src/@claude-flow/memory/dist/sqljs-backend.js +600 -0
  84. package/src/@claude-flow/memory/dist/types.d.ts +484 -0
  85. package/src/@claude-flow/memory/dist/types.js +58 -0
  86. package/src/@claude-flow/shared/dist/core/config/defaults.d.ts +41 -0
  87. package/src/@claude-flow/shared/dist/core/config/defaults.js +186 -0
  88. package/src/@claude-flow/shared/dist/core/config/index.d.ts +8 -0
  89. package/src/@claude-flow/shared/dist/core/config/index.js +12 -0
  90. package/src/@claude-flow/shared/dist/core/config/loader.d.ts +45 -0
  91. package/src/@claude-flow/shared/dist/core/config/loader.js +222 -0
  92. package/src/@claude-flow/shared/dist/core/config/schema.d.ts +1134 -0
  93. package/src/@claude-flow/shared/dist/core/config/schema.js +158 -0
  94. package/src/@claude-flow/shared/dist/core/config/validator.d.ts +92 -0
  95. package/src/@claude-flow/shared/dist/core/config/validator.js +147 -0
  96. package/src/@claude-flow/shared/dist/core/event-bus.d.ts +31 -0
  97. package/src/@claude-flow/shared/dist/core/event-bus.js +197 -0
  98. package/src/@claude-flow/shared/dist/core/index.d.ts +15 -0
  99. package/src/@claude-flow/shared/dist/core/index.js +19 -0
  100. package/src/@claude-flow/shared/dist/core/interfaces/agent.interface.d.ts +200 -0
  101. package/src/@claude-flow/shared/dist/core/interfaces/agent.interface.js +6 -0
  102. package/src/@claude-flow/shared/dist/core/interfaces/coordinator.interface.d.ts +310 -0
  103. package/src/@claude-flow/shared/dist/core/interfaces/coordinator.interface.js +7 -0
  104. package/src/@claude-flow/shared/dist/core/interfaces/event.interface.d.ts +224 -0
  105. package/src/@claude-flow/shared/dist/core/interfaces/event.interface.js +46 -0
  106. package/src/@claude-flow/shared/dist/core/interfaces/index.d.ts +10 -0
  107. package/src/@claude-flow/shared/dist/core/interfaces/index.js +15 -0
  108. package/src/@claude-flow/shared/dist/core/interfaces/memory.interface.d.ts +298 -0
  109. package/src/@claude-flow/shared/dist/core/interfaces/memory.interface.js +7 -0
  110. package/src/@claude-flow/shared/dist/core/interfaces/task.interface.d.ts +185 -0
  111. package/src/@claude-flow/shared/dist/core/interfaces/task.interface.js +6 -0
  112. package/src/@claude-flow/shared/dist/core/orchestrator/event-coordinator.d.ts +35 -0
  113. package/src/@claude-flow/shared/dist/core/orchestrator/event-coordinator.js +101 -0
  114. package/src/@claude-flow/shared/dist/core/orchestrator/health-monitor.d.ts +60 -0
  115. package/src/@claude-flow/shared/dist/core/orchestrator/health-monitor.js +166 -0
  116. package/src/@claude-flow/shared/dist/core/orchestrator/index.d.ts +46 -0
  117. package/src/@claude-flow/shared/dist/core/orchestrator/index.js +64 -0
  118. package/src/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.d.ts +56 -0
  119. package/src/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.js +195 -0
  120. package/src/@claude-flow/shared/dist/core/orchestrator/session-manager.d.ts +83 -0
  121. package/src/@claude-flow/shared/dist/core/orchestrator/session-manager.js +193 -0
  122. package/src/@claude-flow/shared/dist/core/orchestrator/task-manager.d.ts +49 -0
  123. package/src/@claude-flow/shared/dist/core/orchestrator/task-manager.js +253 -0
  124. package/src/@claude-flow/shared/dist/events/domain-events.d.ts +282 -0
  125. package/src/@claude-flow/shared/dist/events/domain-events.js +165 -0
  126. package/src/@claude-flow/shared/dist/events/event-store.d.ts +126 -0
  127. package/src/@claude-flow/shared/dist/events/event-store.js +432 -0
  128. package/src/@claude-flow/shared/dist/events/event-store.test.d.ts +8 -0
  129. package/src/@claude-flow/shared/dist/events/event-store.test.js +297 -0
  130. package/src/@claude-flow/shared/dist/events/example-usage.d.ts +10 -0
  131. package/src/@claude-flow/shared/dist/events/example-usage.js +193 -0
  132. package/src/@claude-flow/shared/dist/events/index.d.ts +21 -0
  133. package/src/@claude-flow/shared/dist/events/index.js +22 -0
  134. package/src/@claude-flow/shared/dist/events/projections.d.ts +177 -0
  135. package/src/@claude-flow/shared/dist/events/projections.js +421 -0
  136. package/src/@claude-flow/shared/dist/events/rvf-event-log.d.ts +82 -0
  137. package/src/@claude-flow/shared/dist/events/rvf-event-log.js +340 -0
  138. package/src/@claude-flow/shared/dist/events/state-reconstructor.d.ts +101 -0
  139. package/src/@claude-flow/shared/dist/events/state-reconstructor.js +263 -0
  140. package/src/@claude-flow/shared/dist/events.d.ts +80 -0
  141. package/src/@claude-flow/shared/dist/events.js +249 -0
  142. package/src/@claude-flow/shared/dist/hooks/example-usage.d.ts +42 -0
  143. package/src/@claude-flow/shared/dist/hooks/example-usage.js +351 -0
  144. package/src/@claude-flow/shared/dist/hooks/executor.d.ts +100 -0
  145. package/src/@claude-flow/shared/dist/hooks/executor.js +267 -0
  146. package/src/@claude-flow/shared/dist/hooks/hooks.test.d.ts +9 -0
  147. package/src/@claude-flow/shared/dist/hooks/hooks.test.js +322 -0
  148. package/src/@claude-flow/shared/dist/hooks/index.d.ts +52 -0
  149. package/src/@claude-flow/shared/dist/hooks/index.js +51 -0
  150. package/src/@claude-flow/shared/dist/hooks/registry.d.ts +133 -0
  151. package/src/@claude-flow/shared/dist/hooks/registry.js +277 -0
  152. package/src/@claude-flow/shared/dist/hooks/safety/bash-safety.d.ts +105 -0
  153. package/src/@claude-flow/shared/dist/hooks/safety/bash-safety.js +481 -0
  154. package/src/@claude-flow/shared/dist/hooks/safety/file-organization.d.ts +144 -0
  155. package/src/@claude-flow/shared/dist/hooks/safety/file-organization.js +328 -0
  156. package/src/@claude-flow/shared/dist/hooks/safety/git-commit.d.ts +158 -0
  157. package/src/@claude-flow/shared/dist/hooks/safety/git-commit.js +450 -0
  158. package/src/@claude-flow/shared/dist/hooks/safety/index.d.ts +17 -0
  159. package/src/@claude-flow/shared/dist/hooks/safety/index.js +17 -0
  160. package/src/@claude-flow/shared/dist/hooks/session-hooks.d.ts +234 -0
  161. package/src/@claude-flow/shared/dist/hooks/session-hooks.js +334 -0
  162. package/src/@claude-flow/shared/dist/hooks/task-hooks.d.ts +163 -0
  163. package/src/@claude-flow/shared/dist/hooks/task-hooks.js +326 -0
  164. package/src/@claude-flow/shared/dist/hooks/types.d.ts +267 -0
  165. package/src/@claude-flow/shared/dist/hooks/types.js +62 -0
  166. package/src/@claude-flow/shared/dist/hooks/verify-exports.test.d.ts +9 -0
  167. package/src/@claude-flow/shared/dist/hooks/verify-exports.test.js +93 -0
  168. package/src/@claude-flow/shared/dist/index.d.ts +20 -0
  169. package/src/@claude-flow/shared/dist/index.js +50 -0
  170. package/src/@claude-flow/shared/dist/mcp/connection-pool.d.ts +98 -0
  171. package/src/@claude-flow/shared/dist/mcp/connection-pool.js +364 -0
  172. package/src/@claude-flow/shared/dist/mcp/index.d.ts +69 -0
  173. package/src/@claude-flow/shared/dist/mcp/index.js +84 -0
  174. package/src/@claude-flow/shared/dist/mcp/server.d.ts +166 -0
  175. package/src/@claude-flow/shared/dist/mcp/server.js +593 -0
  176. package/src/@claude-flow/shared/dist/mcp/session-manager.d.ts +136 -0
  177. package/src/@claude-flow/shared/dist/mcp/session-manager.js +335 -0
  178. package/src/@claude-flow/shared/dist/mcp/tool-registry.d.ts +178 -0
  179. package/src/@claude-flow/shared/dist/mcp/tool-registry.js +439 -0
  180. package/src/@claude-flow/shared/dist/mcp/transport/http.d.ts +104 -0
  181. package/src/@claude-flow/shared/dist/mcp/transport/http.js +476 -0
  182. package/src/@claude-flow/shared/dist/mcp/transport/index.d.ts +102 -0
  183. package/src/@claude-flow/shared/dist/mcp/transport/index.js +238 -0
  184. package/src/@claude-flow/shared/dist/mcp/transport/stdio.d.ts +104 -0
  185. package/src/@claude-flow/shared/dist/mcp/transport/stdio.js +263 -0
  186. package/src/@claude-flow/shared/dist/mcp/transport/websocket.d.ts +133 -0
  187. package/src/@claude-flow/shared/dist/mcp/transport/websocket.js +396 -0
  188. package/src/@claude-flow/shared/dist/mcp/types.d.ts +438 -0
  189. package/src/@claude-flow/shared/dist/mcp/types.js +54 -0
  190. package/src/@claude-flow/shared/dist/plugin-interface.d.ts +544 -0
  191. package/src/@claude-flow/shared/dist/plugin-interface.js +23 -0
  192. package/src/@claude-flow/shared/dist/plugin-loader.d.ts +139 -0
  193. package/src/@claude-flow/shared/dist/plugin-loader.js +434 -0
  194. package/src/@claude-flow/shared/dist/plugin-registry.d.ts +183 -0
  195. package/src/@claude-flow/shared/dist/plugin-registry.js +457 -0
  196. package/src/@claude-flow/shared/dist/plugins/index.d.ts +10 -0
  197. package/src/@claude-flow/shared/dist/plugins/index.js +10 -0
  198. package/src/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.d.ts +106 -0
  199. package/src/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.js +241 -0
  200. package/src/@claude-flow/shared/dist/plugins/official/index.d.ts +10 -0
  201. package/src/@claude-flow/shared/dist/plugins/official/index.js +10 -0
  202. package/src/@claude-flow/shared/dist/plugins/official/maestro-plugin.d.ts +121 -0
  203. package/src/@claude-flow/shared/dist/plugins/official/maestro-plugin.js +355 -0
  204. package/src/@claude-flow/shared/dist/plugins/types.d.ts +93 -0
  205. package/src/@claude-flow/shared/dist/plugins/types.js +9 -0
  206. package/src/@claude-flow/shared/dist/resilience/bulkhead.d.ts +105 -0
  207. package/src/@claude-flow/shared/dist/resilience/bulkhead.js +206 -0
  208. package/src/@claude-flow/shared/dist/resilience/circuit-breaker.d.ts +132 -0
  209. package/src/@claude-flow/shared/dist/resilience/circuit-breaker.js +233 -0
  210. package/src/@claude-flow/shared/dist/resilience/index.d.ts +19 -0
  211. package/src/@claude-flow/shared/dist/resilience/index.js +19 -0
  212. package/src/@claude-flow/shared/dist/resilience/rate-limiter.d.ts +168 -0
  213. package/src/@claude-flow/shared/dist/resilience/rate-limiter.js +314 -0
  214. package/src/@claude-flow/shared/dist/resilience/retry.d.ts +91 -0
  215. package/src/@claude-flow/shared/dist/resilience/retry.js +159 -0
  216. package/src/@claude-flow/shared/dist/security/index.d.ts +10 -0
  217. package/src/@claude-flow/shared/dist/security/index.js +12 -0
  218. package/src/@claude-flow/shared/dist/security/input-validation.d.ts +73 -0
  219. package/src/@claude-flow/shared/dist/security/input-validation.js +201 -0
  220. package/src/@claude-flow/shared/dist/security/secure-random.d.ts +92 -0
  221. package/src/@claude-flow/shared/dist/security/secure-random.js +142 -0
  222. package/src/@claude-flow/shared/dist/services/index.d.ts +7 -0
  223. package/src/@claude-flow/shared/dist/services/index.js +7 -0
  224. package/src/@claude-flow/shared/dist/services/v3-progress.service.d.ts +124 -0
  225. package/src/@claude-flow/shared/dist/services/v3-progress.service.js +402 -0
  226. package/src/@claude-flow/shared/dist/types/agent.types.d.ts +137 -0
  227. package/src/@claude-flow/shared/dist/types/agent.types.js +6 -0
  228. package/src/@claude-flow/shared/dist/types/index.d.ts +11 -0
  229. package/src/@claude-flow/shared/dist/types/index.js +17 -0
  230. package/src/@claude-flow/shared/dist/types/mcp.types.d.ts +266 -0
  231. package/src/@claude-flow/shared/dist/types/mcp.types.js +7 -0
  232. package/src/@claude-flow/shared/dist/types/memory.types.d.ts +236 -0
  233. package/src/@claude-flow/shared/dist/types/memory.types.js +7 -0
  234. package/src/@claude-flow/shared/dist/types/swarm.types.d.ts +186 -0
  235. package/src/@claude-flow/shared/dist/types/swarm.types.js +65 -0
  236. package/src/@claude-flow/shared/dist/types/task.types.d.ts +178 -0
  237. package/src/@claude-flow/shared/dist/types/task.types.js +32 -0
  238. package/src/@claude-flow/shared/dist/types.d.ts +197 -0
  239. package/src/@claude-flow/shared/dist/types.js +21 -0
  240. package/src/@claude-flow/shared/dist/utils/secure-logger.d.ts +69 -0
  241. package/src/@claude-flow/shared/dist/utils/secure-logger.js +208 -0
@@ -0,0 +1,600 @@
1
+ /**
2
+ * SqlJsBackend - Pure JavaScript SQLite for Windows compatibility
3
+ *
4
+ * Pure JavaScript/WASM SQLite backend that works everywhere
5
+ * without native compilation.
6
+ *
7
+ * @module v3/memory/sqljs-backend
8
+ */
9
+ import { EventEmitter } from 'node:events';
10
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
11
+ import initSqlJs from 'sql.js';
12
+ /**
13
+ * Default configuration values
14
+ */
15
+ const DEFAULT_CONFIG = {
16
+ databasePath: ':memory:',
17
+ optimize: true,
18
+ defaultNamespace: 'default',
19
+ maxEntries: 1000000,
20
+ verbose: false,
21
+ autoPersistInterval: 5000, // 5 seconds
22
+ };
23
+ /**
24
+ * SqlJs Backend for Cross-Platform Memory Storage
25
+ *
26
+ * Provides:
27
+ * - Pure JavaScript/WASM implementation (no native compilation)
28
+ * - Windows, macOS, Linux compatibility
29
+ * - Same SQL interface as native SQLite
30
+ * - In-memory with periodic disk persistence
31
+ */
32
+ export class SqlJsBackend extends EventEmitter {
33
+ config;
34
+ db = null;
35
+ initialized = false;
36
+ persistTimer = null;
37
+ SQL = null;
38
+ // Performance tracking
39
+ stats = {
40
+ queryCount: 0,
41
+ totalQueryTime: 0,
42
+ writeCount: 0,
43
+ totalWriteTime: 0,
44
+ };
45
+ constructor(config = {}) {
46
+ super();
47
+ this.config = { ...DEFAULT_CONFIG, ...config };
48
+ }
49
+ /**
50
+ * Initialize the SqlJs backend
51
+ */
52
+ async initialize() {
53
+ if (this.initialized)
54
+ return;
55
+ // Load sql.js WASM
56
+ this.SQL = await initSqlJs({
57
+ locateFile: this.config.wasmPath
58
+ ? () => this.config.wasmPath
59
+ : (file) => `https://sql.js.org/dist/${file}`,
60
+ });
61
+ // Load existing database if exists and not in-memory
62
+ if (this.config.databasePath !== ':memory:' && existsSync(this.config.databasePath)) {
63
+ const buffer = readFileSync(this.config.databasePath);
64
+ this.db = new this.SQL.Database(new Uint8Array(buffer));
65
+ if (this.config.verbose) {
66
+ console.log(`[SqlJsBackend] Loaded database from ${this.config.databasePath}`);
67
+ }
68
+ }
69
+ else {
70
+ // Create new database
71
+ this.db = new this.SQL.Database();
72
+ if (this.config.verbose) {
73
+ console.log('[SqlJsBackend] Created new in-memory database');
74
+ }
75
+ }
76
+ // Create schema
77
+ this.createSchema();
78
+ // Set up auto-persist if enabled
79
+ if (this.config.autoPersistInterval > 0 && this.config.databasePath !== ':memory:') {
80
+ this.persistTimer = setInterval(() => {
81
+ this.persist().catch((err) => {
82
+ this.emit('error', { operation: 'auto-persist', error: err });
83
+ });
84
+ }, this.config.autoPersistInterval);
85
+ }
86
+ this.initialized = true;
87
+ this.emit('initialized');
88
+ }
89
+ /**
90
+ * Shutdown the backend
91
+ */
92
+ async shutdown() {
93
+ if (!this.initialized || !this.db)
94
+ return;
95
+ // Stop auto-persist timer
96
+ if (this.persistTimer) {
97
+ clearInterval(this.persistTimer);
98
+ this.persistTimer = null;
99
+ }
100
+ // Final persist before shutdown
101
+ if (this.config.databasePath !== ':memory:') {
102
+ await this.persist();
103
+ }
104
+ this.db.close();
105
+ this.db = null;
106
+ this.initialized = false;
107
+ this.emit('shutdown');
108
+ }
109
+ /**
110
+ * Create database schema
111
+ */
112
+ createSchema() {
113
+ if (!this.db)
114
+ return;
115
+ // Main entries table
116
+ this.db.run(`
117
+ CREATE TABLE IF NOT EXISTS memory_entries (
118
+ id TEXT PRIMARY KEY,
119
+ key TEXT NOT NULL,
120
+ content TEXT NOT NULL,
121
+ embedding BLOB,
122
+ type TEXT NOT NULL,
123
+ namespace TEXT NOT NULL,
124
+ tags TEXT NOT NULL,
125
+ metadata TEXT NOT NULL,
126
+ owner_id TEXT,
127
+ access_level TEXT NOT NULL,
128
+ created_at INTEGER NOT NULL,
129
+ updated_at INTEGER NOT NULL,
130
+ expires_at INTEGER,
131
+ version INTEGER NOT NULL DEFAULT 1,
132
+ "references" TEXT NOT NULL,
133
+ access_count INTEGER NOT NULL DEFAULT 0,
134
+ last_accessed_at INTEGER NOT NULL
135
+ )
136
+ `);
137
+ // Indexes for performance
138
+ this.db.run('CREATE INDEX IF NOT EXISTS idx_namespace ON memory_entries(namespace)');
139
+ this.db.run('CREATE INDEX IF NOT EXISTS idx_key ON memory_entries(key)');
140
+ this.db.run('CREATE INDEX IF NOT EXISTS idx_type ON memory_entries(type)');
141
+ this.db.run('CREATE INDEX IF NOT EXISTS idx_created_at ON memory_entries(created_at)');
142
+ this.db.run('CREATE INDEX IF NOT EXISTS idx_expires_at ON memory_entries(expires_at)');
143
+ this.db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_namespace_key ON memory_entries(namespace, key)');
144
+ if (this.config.verbose) {
145
+ console.log('[SqlJsBackend] Schema created successfully');
146
+ }
147
+ }
148
+ /**
149
+ * Store a memory entry
150
+ */
151
+ async store(entry) {
152
+ this.ensureInitialized();
153
+ const startTime = performance.now();
154
+ const stmt = `
155
+ INSERT OR REPLACE INTO memory_entries (
156
+ id, key, content, embedding, type, namespace, tags, metadata,
157
+ owner_id, access_level, created_at, updated_at, expires_at,
158
+ version, "references", access_count, last_accessed_at
159
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
160
+ `;
161
+ const embeddingBuffer = entry.embedding
162
+ ? Buffer.from(entry.embedding.buffer)
163
+ : null;
164
+ this.db.run(stmt, [
165
+ entry.id,
166
+ entry.key,
167
+ entry.content,
168
+ embeddingBuffer,
169
+ entry.type,
170
+ entry.namespace,
171
+ JSON.stringify(entry.tags),
172
+ JSON.stringify(entry.metadata),
173
+ entry.ownerId || null,
174
+ entry.accessLevel,
175
+ entry.createdAt,
176
+ entry.updatedAt,
177
+ entry.expiresAt || null,
178
+ entry.version,
179
+ JSON.stringify(entry.references),
180
+ entry.accessCount,
181
+ entry.lastAccessedAt,
182
+ ]);
183
+ const duration = performance.now() - startTime;
184
+ this.stats.writeCount++;
185
+ this.stats.totalWriteTime += duration;
186
+ this.emit('entry:stored', { entry, duration });
187
+ }
188
+ /**
189
+ * Retrieve a memory entry by ID
190
+ */
191
+ async get(id) {
192
+ this.ensureInitialized();
193
+ const startTime = performance.now();
194
+ const stmt = this.db.prepare('SELECT * FROM memory_entries WHERE id = ?');
195
+ const row = stmt.getAsObject([id]);
196
+ stmt.free();
197
+ const duration = performance.now() - startTime;
198
+ this.stats.queryCount++;
199
+ this.stats.totalQueryTime += duration;
200
+ if (!row || Object.keys(row).length === 0) {
201
+ return null;
202
+ }
203
+ const entry = this.rowToEntry(row);
204
+ // Update access tracking
205
+ this.updateAccessTracking(id);
206
+ this.emit('entry:retrieved', { id, duration });
207
+ return entry;
208
+ }
209
+ /**
210
+ * Retrieve a memory entry by key within a namespace
211
+ */
212
+ async getByKey(namespace, key) {
213
+ this.ensureInitialized();
214
+ const startTime = performance.now();
215
+ const stmt = this.db.prepare('SELECT * FROM memory_entries WHERE namespace = ? AND key = ?');
216
+ const row = stmt.getAsObject([namespace, key]);
217
+ stmt.free();
218
+ const duration = performance.now() - startTime;
219
+ this.stats.queryCount++;
220
+ this.stats.totalQueryTime += duration;
221
+ if (!row || Object.keys(row).length === 0) {
222
+ return null;
223
+ }
224
+ const entry = this.rowToEntry(row);
225
+ // Update access tracking
226
+ this.updateAccessTracking(entry.id);
227
+ this.emit('entry:retrieved', { namespace, key, duration });
228
+ return entry;
229
+ }
230
+ /**
231
+ * Update a memory entry
232
+ */
233
+ async update(id, updateData) {
234
+ this.ensureInitialized();
235
+ const startTime = performance.now();
236
+ // Get existing entry
237
+ const existing = await this.get(id);
238
+ if (!existing)
239
+ return null;
240
+ // Merge updates
241
+ const updated = {
242
+ ...existing,
243
+ ...updateData,
244
+ updatedAt: Date.now(),
245
+ version: existing.version + 1,
246
+ };
247
+ // Store updated entry
248
+ await this.store(updated);
249
+ const duration = performance.now() - startTime;
250
+ this.emit('entry:updated', { id, update: updateData, duration });
251
+ return updated;
252
+ }
253
+ /**
254
+ * Delete a memory entry
255
+ */
256
+ async delete(id) {
257
+ this.ensureInitialized();
258
+ const startTime = performance.now();
259
+ this.db.run('DELETE FROM memory_entries WHERE id = ?', [id]);
260
+ const duration = performance.now() - startTime;
261
+ this.stats.writeCount++;
262
+ this.stats.totalWriteTime += duration;
263
+ this.emit('entry:deleted', { id, duration });
264
+ return true;
265
+ }
266
+ /**
267
+ * Query memory entries
268
+ */
269
+ async query(query) {
270
+ this.ensureInitialized();
271
+ const startTime = performance.now();
272
+ let sql = 'SELECT * FROM memory_entries WHERE 1=1';
273
+ const params = [];
274
+ // Namespace filter
275
+ if (query.namespace) {
276
+ sql += ' AND namespace = ?';
277
+ params.push(query.namespace);
278
+ }
279
+ // Type filter
280
+ if (query.memoryType) {
281
+ sql += ' AND type = ?';
282
+ params.push(query.memoryType);
283
+ }
284
+ // Owner filter
285
+ if (query.ownerId) {
286
+ sql += ' AND owner_id = ?';
287
+ params.push(query.ownerId);
288
+ }
289
+ // Access level filter
290
+ if (query.accessLevel) {
291
+ sql += ' AND access_level = ?';
292
+ params.push(query.accessLevel);
293
+ }
294
+ // Key filters
295
+ if (query.key) {
296
+ sql += ' AND key = ?';
297
+ params.push(query.key);
298
+ }
299
+ else if (query.keyPrefix) {
300
+ sql += ' AND key LIKE ?';
301
+ params.push(query.keyPrefix + '%');
302
+ }
303
+ // Time range filters
304
+ if (query.createdAfter) {
305
+ sql += ' AND created_at >= ?';
306
+ params.push(query.createdAfter);
307
+ }
308
+ if (query.createdBefore) {
309
+ sql += ' AND created_at <= ?';
310
+ params.push(query.createdBefore);
311
+ }
312
+ if (query.updatedAfter) {
313
+ sql += ' AND updated_at >= ?';
314
+ params.push(query.updatedAfter);
315
+ }
316
+ if (query.updatedBefore) {
317
+ sql += ' AND updated_at <= ?';
318
+ params.push(query.updatedBefore);
319
+ }
320
+ // Expiration filter
321
+ if (!query.includeExpired) {
322
+ sql += ' AND (expires_at IS NULL OR expires_at > ?)';
323
+ params.push(Date.now());
324
+ }
325
+ // Ordering and pagination
326
+ sql += ' ORDER BY created_at DESC';
327
+ if (query.limit) {
328
+ sql += ' LIMIT ?';
329
+ params.push(query.limit);
330
+ }
331
+ if (query.offset) {
332
+ sql += ' OFFSET ?';
333
+ params.push(query.offset);
334
+ }
335
+ const stmt = this.db.prepare(sql);
336
+ if (params.length > 0) {
337
+ stmt.bind(params);
338
+ }
339
+ const results = [];
340
+ while (stmt.step()) {
341
+ const row = stmt.getAsObject();
342
+ const entry = this.rowToEntry(row);
343
+ // Tag filtering (post-query since tags are JSON)
344
+ if (query.tags && query.tags.length > 0) {
345
+ const hasAllTags = query.tags.every((tag) => entry.tags.includes(tag));
346
+ if (!hasAllTags)
347
+ continue;
348
+ }
349
+ // Metadata filtering (post-query since metadata is JSON)
350
+ if (query.metadata) {
351
+ const matchesMetadata = Object.entries(query.metadata).every(([key, value]) => entry.metadata[key] === value);
352
+ if (!matchesMetadata)
353
+ continue;
354
+ }
355
+ results.push(entry);
356
+ }
357
+ stmt.free();
358
+ const duration = performance.now() - startTime;
359
+ this.stats.queryCount++;
360
+ this.stats.totalQueryTime += duration;
361
+ this.emit('query:executed', { query, resultCount: results.length, duration });
362
+ return results;
363
+ }
364
+ /**
365
+ * Semantic vector search (limited without vector index)
366
+ */
367
+ async search(embedding, options) {
368
+ this.ensureInitialized();
369
+ // Get all entries with embeddings
370
+ const entries = await this.query({
371
+ type: 'hybrid',
372
+ limit: options.filters?.limit || 1000,
373
+ });
374
+ // Calculate cosine similarity for each entry
375
+ const results = [];
376
+ for (const entry of entries) {
377
+ if (!entry.embedding)
378
+ continue;
379
+ const similarity = this.cosineSimilarity(embedding, entry.embedding);
380
+ if (options.threshold && similarity < options.threshold) {
381
+ continue;
382
+ }
383
+ results.push({
384
+ entry,
385
+ score: similarity,
386
+ distance: 1 - similarity,
387
+ });
388
+ }
389
+ // Sort by score descending
390
+ results.sort((a, b) => b.score - a.score);
391
+ // Return top k results
392
+ return results.slice(0, options.k);
393
+ }
394
+ /**
395
+ * Bulk insert entries
396
+ */
397
+ async bulkInsert(entries) {
398
+ this.ensureInitialized();
399
+ for (const entry of entries) {
400
+ await this.store(entry);
401
+ }
402
+ this.emit('bulk:inserted', { count: entries.length });
403
+ }
404
+ /**
405
+ * Bulk delete entries
406
+ */
407
+ async bulkDelete(ids) {
408
+ this.ensureInitialized();
409
+ let count = 0;
410
+ for (const id of ids) {
411
+ const success = await this.delete(id);
412
+ if (success)
413
+ count++;
414
+ }
415
+ this.emit('bulk:deleted', { count });
416
+ return count;
417
+ }
418
+ /**
419
+ * Get entry count
420
+ */
421
+ async count(namespace) {
422
+ this.ensureInitialized();
423
+ let sql = 'SELECT COUNT(*) as count FROM memory_entries';
424
+ const params = [];
425
+ if (namespace) {
426
+ sql += ' WHERE namespace = ?';
427
+ params.push(namespace);
428
+ }
429
+ const stmt = this.db.prepare(sql);
430
+ const row = stmt.getAsObject(params);
431
+ stmt.free();
432
+ return row.count || 0;
433
+ }
434
+ /**
435
+ * List all namespaces
436
+ */
437
+ async listNamespaces() {
438
+ this.ensureInitialized();
439
+ const stmt = this.db.prepare('SELECT DISTINCT namespace FROM memory_entries');
440
+ const namespaces = [];
441
+ while (stmt.step()) {
442
+ const row = stmt.getAsObject();
443
+ namespaces.push(row.namespace);
444
+ }
445
+ stmt.free();
446
+ return namespaces;
447
+ }
448
+ /**
449
+ * Clear all entries in a namespace
450
+ */
451
+ async clearNamespace(namespace) {
452
+ this.ensureInitialized();
453
+ const countBefore = await this.count(namespace);
454
+ this.db.run('DELETE FROM memory_entries WHERE namespace = ?', [namespace]);
455
+ this.emit('namespace:cleared', { namespace, count: countBefore });
456
+ return countBefore;
457
+ }
458
+ /**
459
+ * Get backend statistics
460
+ */
461
+ async getStats() {
462
+ this.ensureInitialized();
463
+ const total = await this.count();
464
+ // Count by namespace
465
+ const entriesByNamespace = {};
466
+ const namespaces = await this.listNamespaces();
467
+ for (const ns of namespaces) {
468
+ entriesByNamespace[ns] = await this.count(ns);
469
+ }
470
+ // Count by type
471
+ const entriesByType = {};
472
+ const types = ['episodic', 'semantic', 'procedural', 'working', 'cache'];
473
+ for (const type of types) {
474
+ const stmt = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries WHERE type = ?');
475
+ const row = stmt.getAsObject([type]);
476
+ stmt.free();
477
+ entriesByType[type] = row.count || 0;
478
+ }
479
+ return {
480
+ totalEntries: total,
481
+ entriesByNamespace,
482
+ entriesByType,
483
+ memoryUsage: this.estimateMemoryUsage(),
484
+ avgQueryTime: this.stats.queryCount > 0 ? this.stats.totalQueryTime / this.stats.queryCount : 0,
485
+ avgSearchTime: 0, // Not tracked separately
486
+ };
487
+ }
488
+ /**
489
+ * Perform health check
490
+ */
491
+ async healthCheck() {
492
+ const issues = [];
493
+ const recommendations = [];
494
+ // Storage health
495
+ const storageStart = performance.now();
496
+ const storageHealthy = this.db !== null;
497
+ const storageLatency = performance.now() - storageStart;
498
+ if (!storageHealthy) {
499
+ issues.push('Database not initialized');
500
+ }
501
+ // Index health (sql.js doesn't have native vector index)
502
+ const indexHealth = {
503
+ status: 'healthy',
504
+ latency: 0,
505
+ message: 'No vector index (brute-force search)',
506
+ };
507
+ recommendations.push('Consider using AgentDB with HNSW for faster vector search');
508
+ // Cache health (not applicable for sql.js)
509
+ const cacheHealth = {
510
+ status: 'healthy',
511
+ latency: 0,
512
+ message: 'No separate cache layer',
513
+ };
514
+ const status = issues.length === 0 ? 'healthy' : 'degraded';
515
+ return {
516
+ status,
517
+ components: {
518
+ storage: {
519
+ status: storageHealthy ? 'healthy' : 'unhealthy',
520
+ latency: storageLatency,
521
+ },
522
+ index: indexHealth,
523
+ cache: cacheHealth,
524
+ },
525
+ timestamp: Date.now(),
526
+ issues,
527
+ recommendations,
528
+ };
529
+ }
530
+ /**
531
+ * Persist changes to disk (sql.js is in-memory, needs explicit save)
532
+ */
533
+ async persist() {
534
+ if (!this.db || this.config.databasePath === ':memory:') {
535
+ return;
536
+ }
537
+ const data = this.db.export();
538
+ const buffer = Buffer.from(data);
539
+ writeFileSync(this.config.databasePath, buffer);
540
+ if (this.config.verbose) {
541
+ console.log(`[SqlJsBackend] Persisted ${buffer.length} bytes to ${this.config.databasePath}`);
542
+ }
543
+ this.emit('persisted', { size: buffer.length, path: this.config.databasePath });
544
+ }
545
+ // ===== Helper Methods =====
546
+ ensureInitialized() {
547
+ if (!this.initialized || !this.db) {
548
+ throw new Error('SqlJsBackend not initialized. Call initialize() first.');
549
+ }
550
+ }
551
+ rowToEntry(row) {
552
+ return {
553
+ id: row.id,
554
+ key: row.key,
555
+ content: row.content,
556
+ embedding: row.embedding
557
+ ? new Float32Array(new Uint8Array(row.embedding).buffer)
558
+ : undefined,
559
+ type: row.type,
560
+ namespace: row.namespace,
561
+ tags: JSON.parse(row.tags),
562
+ metadata: JSON.parse(row.metadata),
563
+ ownerId: row.owner_id,
564
+ accessLevel: row.access_level,
565
+ createdAt: row.created_at,
566
+ updatedAt: row.updated_at,
567
+ expiresAt: row.expires_at,
568
+ version: row.version,
569
+ references: JSON.parse(row.references),
570
+ accessCount: row.access_count,
571
+ lastAccessedAt: row.last_accessed_at,
572
+ };
573
+ }
574
+ updateAccessTracking(id) {
575
+ if (!this.db)
576
+ return;
577
+ this.db.run('UPDATE memory_entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?', [Date.now(), id]);
578
+ }
579
+ cosineSimilarity(a, b) {
580
+ let dotProduct = 0;
581
+ let normA = 0;
582
+ let normB = 0;
583
+ for (let i = 0; i < a.length; i++) {
584
+ dotProduct += a[i] * b[i];
585
+ normA += a[i] * a[i];
586
+ normB += b[i] * b[i];
587
+ }
588
+ if (normA === 0 || normB === 0)
589
+ return 0;
590
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
591
+ }
592
+ estimateMemoryUsage() {
593
+ if (!this.db)
594
+ return 0;
595
+ // Export to get size
596
+ const data = this.db.export();
597
+ return data.length;
598
+ }
599
+ }
600
+ //# sourceMappingURL=sqljs-backend.js.map