@claude-flow/cli 3.1.0-alpha.50 → 3.1.0-alpha.52

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 (36) hide show
  1. package/README.md +58 -60
  2. package/dist/src/commands/hooks.d.ts.map +1 -1
  3. package/dist/src/commands/hooks.js +56 -43
  4. package/dist/src/commands/hooks.js.map +1 -1
  5. package/dist/src/init/executor.d.ts.map +1 -1
  6. package/dist/src/init/executor.js +11 -1
  7. package/dist/src/init/executor.js.map +1 -1
  8. package/dist/src/init/settings-generator.d.ts.map +1 -1
  9. package/dist/src/init/settings-generator.js +4 -4
  10. package/dist/src/init/settings-generator.js.map +1 -1
  11. package/dist/src/init/statusline-generator.d.ts.map +1 -1
  12. package/dist/src/init/statusline-generator.js +85 -2
  13. package/dist/src/init/statusline-generator.js.map +1 -1
  14. package/dist/src/mcp-client.d.ts.map +1 -1
  15. package/dist/src/mcp-client.js +4 -0
  16. package/dist/src/mcp-client.js.map +1 -1
  17. package/dist/src/mcp-tools/agentdb-tools.d.ts +21 -0
  18. package/dist/src/mcp-tools/agentdb-tools.d.ts.map +1 -0
  19. package/dist/src/mcp-tools/agentdb-tools.js +267 -0
  20. package/dist/src/mcp-tools/agentdb-tools.js.map +1 -0
  21. package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
  22. package/dist/src/mcp-tools/hooks-tools.js +184 -32
  23. package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
  24. package/dist/src/memory/intelligence.d.ts.map +1 -1
  25. package/dist/src/memory/intelligence.js +34 -6
  26. package/dist/src/memory/intelligence.js.map +1 -1
  27. package/dist/src/memory/memory-bridge.d.ts +339 -0
  28. package/dist/src/memory/memory-bridge.d.ts.map +1 -0
  29. package/dist/src/memory/memory-bridge.js +1250 -0
  30. package/dist/src/memory/memory-bridge.js.map +1 -0
  31. package/dist/src/memory/memory-initializer.d.ts +3 -0
  32. package/dist/src/memory/memory-initializer.d.ts.map +1 -1
  33. package/dist/src/memory/memory-initializer.js +105 -0
  34. package/dist/src/memory/memory-initializer.js.map +1 -1
  35. package/dist/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +1 -1
@@ -0,0 +1,1250 @@
1
+ /**
2
+ * Memory Bridge — Routes CLI memory operations through ControllerRegistry + AgentDB v3
3
+ *
4
+ * Per ADR-053 Phases 1-6: Full controller activation pipeline.
5
+ * CLI → ControllerRegistry → AgentDB v3 controllers.
6
+ *
7
+ * Phase 1: Core CRUD + embeddings + HNSW + controller access (complete)
8
+ * Phase 2: BM25 hybrid search, TieredCache read/write, MutationGuard validation
9
+ * Phase 3: ReasoningBank pattern store, recordFeedback, CausalMemoryGraph edges
10
+ * Phase 4: SkillLibrary promotion, ExplainableRecall provenance, AttestationLog
11
+ * Phase 5: ReflexionMemory session lifecycle, WitnessChain attestation
12
+ * Phase 6: AgentDB MCP tools (separate file), COW branching
13
+ *
14
+ * Uses better-sqlite3 API (synchronous .all()/.get()/.run()) since that's
15
+ * what AgentDB v3 uses internally.
16
+ *
17
+ * @module v3/cli/memory-bridge
18
+ */
19
+ import * as path from 'path';
20
+ // ===== Lazy singleton =====
21
+ let registryPromise = null;
22
+ let registryInstance = null;
23
+ let bridgeAvailable = null;
24
+ function getDbPath(customPath) {
25
+ const swarmDir = path.join(process.cwd(), '.swarm');
26
+ return customPath || path.join(swarmDir, 'memory.db');
27
+ }
28
+ /**
29
+ * Lazily initialize the ControllerRegistry singleton.
30
+ * Returns null if @claude-flow/memory is not available.
31
+ */
32
+ async function getRegistry(dbPath) {
33
+ if (bridgeAvailable === false)
34
+ return null;
35
+ if (registryInstance)
36
+ return registryInstance;
37
+ if (!registryPromise) {
38
+ registryPromise = (async () => {
39
+ try {
40
+ const { ControllerRegistry } = await import('@claude-flow/memory');
41
+ const registry = new ControllerRegistry();
42
+ // Suppress noisy console.log during init
43
+ const origLog = console.log;
44
+ console.log = (...args) => {
45
+ const msg = String(args[0] ?? '');
46
+ if (msg.includes('Transformers.js') ||
47
+ msg.includes('better-sqlite3') ||
48
+ msg.includes('[AgentDB]') ||
49
+ msg.includes('[HNSWLibBackend]') ||
50
+ msg.includes('RuVector graph'))
51
+ return;
52
+ origLog.apply(console, args);
53
+ };
54
+ try {
55
+ await registry.initialize({
56
+ dbPath: dbPath || getDbPath(),
57
+ dimension: 384,
58
+ controllers: {
59
+ reasoningBank: true,
60
+ learningBridge: false,
61
+ tieredCache: true,
62
+ },
63
+ });
64
+ }
65
+ finally {
66
+ console.log = origLog;
67
+ }
68
+ registryInstance = registry;
69
+ bridgeAvailable = true;
70
+ return registry;
71
+ }
72
+ catch {
73
+ bridgeAvailable = false;
74
+ registryPromise = null;
75
+ return null;
76
+ }
77
+ })();
78
+ }
79
+ return registryPromise;
80
+ }
81
+ // ===== Phase 2: BM25 hybrid scoring =====
82
+ /**
83
+ * BM25 scoring for keyword-based search.
84
+ * Replaces naive String.includes() with proper information retrieval scoring.
85
+ * Parameters tuned for short memory entries (k1=1.2, b=0.75).
86
+ */
87
+ function bm25Score(queryTerms, docContent, avgDocLength, docCount, termDocFreqs) {
88
+ const k1 = 1.2;
89
+ const b = 0.75;
90
+ const docWords = docContent.toLowerCase().split(/\s+/);
91
+ const docLength = docWords.length;
92
+ let score = 0;
93
+ for (const term of queryTerms) {
94
+ const tf = docWords.filter(w => w === term || w.includes(term)).length;
95
+ if (tf === 0)
96
+ continue;
97
+ const df = termDocFreqs.get(term) || 1;
98
+ const idf = Math.log((docCount - df + 0.5) / (df + 0.5) + 1);
99
+ const tfNorm = (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (docLength / Math.max(1, avgDocLength))));
100
+ score += idf * tfNorm;
101
+ }
102
+ return score;
103
+ }
104
+ /**
105
+ * Compute BM25 term document frequencies for a set of rows.
106
+ */
107
+ function computeTermDocFreqs(queryTerms, rows) {
108
+ const termDocFreqs = new Map();
109
+ let totalLength = 0;
110
+ for (const row of rows) {
111
+ const content = (row.content || '').toLowerCase();
112
+ const words = content.split(/\s+/);
113
+ totalLength += words.length;
114
+ for (const term of queryTerms) {
115
+ if (content.includes(term)) {
116
+ termDocFreqs.set(term, (termDocFreqs.get(term) || 0) + 1);
117
+ }
118
+ }
119
+ }
120
+ return { termDocFreqs, avgDocLength: rows.length > 0 ? totalLength / rows.length : 1 };
121
+ }
122
+ // ===== Phase 2: TieredCache helpers =====
123
+ /**
124
+ * Try to read from TieredCache before hitting DB.
125
+ * Returns cached value or null if cache miss.
126
+ */
127
+ async function cacheGet(registry, cacheKey) {
128
+ try {
129
+ const cache = registry.get('tieredCache');
130
+ if (!cache || typeof cache.get !== 'function')
131
+ return null;
132
+ return cache.get(cacheKey) ?? null;
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ /**
139
+ * Write to TieredCache after DB write.
140
+ */
141
+ async function cacheSet(registry, cacheKey, value) {
142
+ try {
143
+ const cache = registry.get('tieredCache');
144
+ if (cache && typeof cache.set === 'function') {
145
+ cache.set(cacheKey, value);
146
+ }
147
+ }
148
+ catch {
149
+ // Non-fatal
150
+ }
151
+ }
152
+ /**
153
+ * Invalidate a cache key after mutation.
154
+ */
155
+ async function cacheInvalidate(registry, cacheKey) {
156
+ try {
157
+ const cache = registry.get('tieredCache');
158
+ if (cache && typeof cache.delete === 'function') {
159
+ cache.delete(cacheKey);
160
+ }
161
+ }
162
+ catch {
163
+ // Non-fatal
164
+ }
165
+ }
166
+ // ===== Phase 2: MutationGuard helpers =====
167
+ /**
168
+ * Validate a mutation through MutationGuard before executing.
169
+ * Returns true if the mutation is allowed, false if rejected.
170
+ * Falls back to allowing if guard is unavailable.
171
+ */
172
+ async function guardValidate(registry, operation, params) {
173
+ try {
174
+ const guard = registry.get('mutationGuard');
175
+ if (!guard || typeof guard.validate !== 'function') {
176
+ return { allowed: true }; // No guard = allow
177
+ }
178
+ const result = guard.validate({ operation, params, timestamp: Date.now() });
179
+ return { allowed: result?.allowed !== false, reason: result?.reason };
180
+ }
181
+ catch {
182
+ return { allowed: true }; // Guard error = allow (graceful degradation)
183
+ }
184
+ }
185
+ // ===== Phase 3: AttestationLog helpers =====
186
+ /**
187
+ * Log a write operation to AttestationLog/WitnessChain.
188
+ */
189
+ async function logAttestation(registry, operation, entryId, metadata) {
190
+ try {
191
+ const attestation = registry.get('attestationLog');
192
+ if (!attestation)
193
+ return;
194
+ if (typeof attestation.record === 'function') {
195
+ attestation.record({ operation, entryId, timestamp: Date.now(), ...metadata });
196
+ }
197
+ else if (typeof attestation.log === 'function') {
198
+ attestation.log(operation, entryId, metadata);
199
+ }
200
+ }
201
+ catch {
202
+ // Non-fatal — attestation is observability, not correctness
203
+ }
204
+ }
205
+ /**
206
+ * Get the AgentDB database handle and ensure memory_entries table exists.
207
+ * Returns null if not available.
208
+ */
209
+ function getDb(registry) {
210
+ const agentdb = registry.getAgentDB();
211
+ if (!agentdb?.database)
212
+ return null;
213
+ const db = agentdb.database;
214
+ // Ensure memory_entries table exists (idempotent)
215
+ try {
216
+ db.exec(`CREATE TABLE IF NOT EXISTS memory_entries (
217
+ id TEXT PRIMARY KEY,
218
+ key TEXT NOT NULL,
219
+ namespace TEXT DEFAULT 'default',
220
+ content TEXT NOT NULL,
221
+ type TEXT DEFAULT 'semantic',
222
+ embedding TEXT,
223
+ embedding_model TEXT DEFAULT 'local',
224
+ embedding_dimensions INTEGER,
225
+ tags TEXT,
226
+ metadata TEXT,
227
+ owner_id TEXT,
228
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
229
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
230
+ expires_at INTEGER,
231
+ last_accessed_at INTEGER,
232
+ access_count INTEGER DEFAULT 0,
233
+ status TEXT DEFAULT 'active',
234
+ UNIQUE(namespace, key)
235
+ )`);
236
+ // Ensure indexes
237
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_bridge_ns ON memory_entries(namespace)`);
238
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_bridge_key ON memory_entries(key)`);
239
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_bridge_status ON memory_entries(status)`);
240
+ }
241
+ catch {
242
+ // Table already exists or db is read-only — that's fine
243
+ }
244
+ return { db, agentdb };
245
+ }
246
+ // ===== Bridge functions — match memory-initializer.ts signatures =====
247
+ /**
248
+ * Store an entry via AgentDB v3.
249
+ * Phase 2-5: Routes through MutationGuard → TieredCache → DB → AttestationLog.
250
+ * Returns null to signal fallback to sql.js.
251
+ */
252
+ export async function bridgeStoreEntry(options) {
253
+ const registry = await getRegistry(options.dbPath);
254
+ if (!registry)
255
+ return null;
256
+ const ctx = getDb(registry);
257
+ if (!ctx)
258
+ return null;
259
+ try {
260
+ const { key, value, namespace = 'default', tags = [], ttl } = options;
261
+ const id = `entry_${Date.now()}_${Math.random().toString(36).substring(7)}`;
262
+ const now = Date.now();
263
+ // Phase 5: MutationGuard validation before write
264
+ const guardResult = await guardValidate(registry, 'store', { key, namespace, size: value.length });
265
+ if (!guardResult.allowed) {
266
+ return { success: false, id, error: `MutationGuard rejected: ${guardResult.reason}` };
267
+ }
268
+ // Generate embedding via AgentDB's embedder
269
+ let embeddingJson = null;
270
+ let dimensions = 0;
271
+ let model = 'local';
272
+ if (options.generateEmbeddingFlag !== false && value.length > 0) {
273
+ try {
274
+ const embedder = ctx.agentdb.embedder;
275
+ if (embedder) {
276
+ const emb = await embedder.embed(value);
277
+ if (emb) {
278
+ embeddingJson = JSON.stringify(Array.from(emb));
279
+ dimensions = emb.length;
280
+ model = 'Xenova/all-MiniLM-L6-v2';
281
+ }
282
+ }
283
+ }
284
+ catch {
285
+ // Embedding failed — store without
286
+ }
287
+ }
288
+ // better-sqlite3 uses synchronous .run() with positional params
289
+ const insertSql = options.upsert
290
+ ? `INSERT OR REPLACE INTO memory_entries (
291
+ id, key, namespace, content, type,
292
+ embedding, embedding_dimensions, embedding_model,
293
+ tags, metadata, created_at, updated_at, expires_at, status
294
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, 'active')`
295
+ : `INSERT INTO memory_entries (
296
+ id, key, namespace, content, type,
297
+ embedding, embedding_dimensions, embedding_model,
298
+ tags, metadata, created_at, updated_at, expires_at, status
299
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, 'active')`;
300
+ const stmt = ctx.db.prepare(insertSql);
301
+ stmt.run(id, key, namespace, value, embeddingJson, dimensions || null, model, tags.length > 0 ? JSON.stringify(tags) : null, '{}', now, now, ttl ? now + (ttl * 1000) : null);
302
+ // Phase 2: Write-through to TieredCache
303
+ const cacheKey = `entry:${namespace}:${key}`;
304
+ await cacheSet(registry, cacheKey, { id, key, namespace, content: value, embedding: embeddingJson });
305
+ // Phase 4: AttestationLog write audit
306
+ await logAttestation(registry, 'store', id, { key, namespace, hasEmbedding: !!embeddingJson });
307
+ return {
308
+ success: true,
309
+ id,
310
+ embedding: embeddingJson ? { dimensions, model } : undefined,
311
+ guarded: true,
312
+ cached: true,
313
+ attested: true,
314
+ };
315
+ }
316
+ catch {
317
+ return null;
318
+ }
319
+ }
320
+ /**
321
+ * Search entries via AgentDB v3.
322
+ * Phase 2: BM25 hybrid scoring replaces naive String.includes() keyword fallback.
323
+ * Combines cosine similarity (semantic) with BM25 (lexical) via reciprocal rank fusion.
324
+ */
325
+ export async function bridgeSearchEntries(options) {
326
+ const registry = await getRegistry(options.dbPath);
327
+ if (!registry)
328
+ return null;
329
+ const ctx = getDb(registry);
330
+ if (!ctx)
331
+ return null;
332
+ try {
333
+ const { query: queryStr, namespace = 'default', limit = 10, threshold = 0.3 } = options;
334
+ const startTime = Date.now();
335
+ // Generate query embedding
336
+ let queryEmbedding = null;
337
+ try {
338
+ const embedder = ctx.agentdb.embedder;
339
+ if (embedder) {
340
+ const emb = await embedder.embed(queryStr);
341
+ queryEmbedding = Array.from(emb);
342
+ }
343
+ }
344
+ catch {
345
+ // Fall back to keyword search
346
+ }
347
+ // better-sqlite3: .prepare().all() returns array of objects
348
+ const nsFilter = namespace !== 'all'
349
+ ? `AND namespace = ?`
350
+ : '';
351
+ let rows;
352
+ try {
353
+ const stmt = ctx.db.prepare(`
354
+ SELECT id, key, namespace, content, embedding
355
+ FROM memory_entries
356
+ WHERE status = 'active' ${nsFilter}
357
+ LIMIT 1000
358
+ `);
359
+ rows = namespace !== 'all' ? stmt.all(namespace) : stmt.all();
360
+ }
361
+ catch {
362
+ return null;
363
+ }
364
+ // Phase 2: Compute BM25 term stats for the corpus
365
+ const queryTerms = queryStr.toLowerCase().split(/\s+/).filter(t => t.length > 1);
366
+ const { termDocFreqs, avgDocLength } = computeTermDocFreqs(queryTerms, rows);
367
+ const docCount = rows.length;
368
+ const results = [];
369
+ for (const row of rows) {
370
+ let semanticScore = 0;
371
+ let bm25ScoreVal = 0;
372
+ // Semantic scoring via cosine similarity
373
+ if (queryEmbedding && row.embedding) {
374
+ try {
375
+ const embedding = JSON.parse(row.embedding);
376
+ semanticScore = cosineSim(queryEmbedding, embedding);
377
+ }
378
+ catch {
379
+ // Invalid embedding
380
+ }
381
+ }
382
+ // Phase 2: BM25 keyword scoring (replaces String.includes fallback)
383
+ if (queryTerms.length > 0 && row.content) {
384
+ bm25ScoreVal = bm25Score(queryTerms, row.content, avgDocLength, docCount, termDocFreqs);
385
+ // Normalize BM25 to 0-1 range (cap at 10 for normalization)
386
+ bm25ScoreVal = Math.min(bm25ScoreVal / 10, 1.0);
387
+ }
388
+ // Reciprocal rank fusion: combine semantic and BM25
389
+ // Weight: 0.7 semantic + 0.3 BM25 (semantic preferred when embeddings available)
390
+ const score = queryEmbedding
391
+ ? (0.7 * semanticScore + 0.3 * bm25ScoreVal)
392
+ : bm25ScoreVal; // BM25-only when no embeddings
393
+ if (score >= threshold) {
394
+ // Phase 4: ExplainableRecall provenance
395
+ const provenance = queryEmbedding
396
+ ? `semantic:${semanticScore.toFixed(3)}+bm25:${bm25ScoreVal.toFixed(3)}`
397
+ : `bm25:${bm25ScoreVal.toFixed(3)}`;
398
+ results.push({
399
+ id: String(row.id).substring(0, 12),
400
+ key: row.key || String(row.id).substring(0, 15),
401
+ content: (row.content || '').substring(0, 60) + ((row.content || '').length > 60 ? '...' : ''),
402
+ score,
403
+ namespace: row.namespace || 'default',
404
+ provenance,
405
+ });
406
+ }
407
+ }
408
+ results.sort((a, b) => b.score - a.score);
409
+ return {
410
+ success: true,
411
+ results: results.slice(0, limit),
412
+ searchTime: Date.now() - startTime,
413
+ searchMethod: queryEmbedding ? 'hybrid-bm25-semantic' : 'bm25-only',
414
+ };
415
+ }
416
+ catch {
417
+ return null;
418
+ }
419
+ }
420
+ /**
421
+ * List entries via AgentDB v3.
422
+ */
423
+ export async function bridgeListEntries(options) {
424
+ const registry = await getRegistry(options.dbPath);
425
+ if (!registry)
426
+ return null;
427
+ const ctx = getDb(registry);
428
+ if (!ctx)
429
+ return null;
430
+ try {
431
+ const { namespace, limit = 20, offset = 0 } = options;
432
+ const nsFilter = namespace ? `AND namespace = ?` : '';
433
+ const nsParams = namespace ? [namespace] : [];
434
+ // Count
435
+ let total = 0;
436
+ try {
437
+ const countStmt = ctx.db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active' ${nsFilter}`);
438
+ const countRow = countStmt.get(...nsParams);
439
+ total = countRow?.cnt || 0;
440
+ }
441
+ catch {
442
+ return null;
443
+ }
444
+ // List
445
+ const entries = [];
446
+ try {
447
+ const stmt = ctx.db.prepare(`
448
+ SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at
449
+ FROM memory_entries
450
+ WHERE status = 'active' ${nsFilter}
451
+ ORDER BY updated_at DESC
452
+ LIMIT ? OFFSET ?
453
+ `);
454
+ const rows = stmt.all(...nsParams, limit, offset);
455
+ for (const row of rows) {
456
+ entries.push({
457
+ id: String(row.id).substring(0, 20),
458
+ key: row.key || String(row.id).substring(0, 15),
459
+ namespace: row.namespace || 'default',
460
+ size: (row.content || '').length,
461
+ accessCount: row.access_count || 0,
462
+ createdAt: row.created_at || new Date().toISOString(),
463
+ updatedAt: row.updated_at || new Date().toISOString(),
464
+ hasEmbedding: !!(row.embedding && String(row.embedding).length > 10),
465
+ });
466
+ }
467
+ }
468
+ catch {
469
+ return null;
470
+ }
471
+ return { success: true, entries, total };
472
+ }
473
+ catch {
474
+ return null;
475
+ }
476
+ }
477
+ /**
478
+ * Get a specific entry via AgentDB v3.
479
+ * Phase 2: TieredCache consulted before DB hit.
480
+ */
481
+ export async function bridgeGetEntry(options) {
482
+ const registry = await getRegistry(options.dbPath);
483
+ if (!registry)
484
+ return null;
485
+ const ctx = getDb(registry);
486
+ if (!ctx)
487
+ return null;
488
+ try {
489
+ const { key, namespace = 'default' } = options;
490
+ // Phase 2: Check TieredCache first
491
+ const cacheKey = `entry:${namespace}:${key}`;
492
+ const cached = await cacheGet(registry, cacheKey);
493
+ if (cached && cached.content) {
494
+ return {
495
+ success: true,
496
+ found: true,
497
+ cacheHit: true,
498
+ entry: {
499
+ id: String(cached.id || ''),
500
+ key: cached.key || key,
501
+ namespace: cached.namespace || namespace,
502
+ content: cached.content || '',
503
+ accessCount: cached.accessCount || 0,
504
+ createdAt: cached.createdAt || new Date().toISOString(),
505
+ updatedAt: cached.updatedAt || new Date().toISOString(),
506
+ hasEmbedding: !!cached.embedding,
507
+ tags: cached.tags || [],
508
+ },
509
+ };
510
+ }
511
+ let row;
512
+ try {
513
+ const stmt = ctx.db.prepare(`
514
+ SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, tags
515
+ FROM memory_entries
516
+ WHERE status = 'active' AND key = ? AND namespace = ?
517
+ LIMIT 1
518
+ `);
519
+ row = stmt.get(key, namespace);
520
+ }
521
+ catch {
522
+ return null;
523
+ }
524
+ if (!row) {
525
+ return { success: true, found: false };
526
+ }
527
+ // Update access count
528
+ try {
529
+ ctx.db.prepare(`UPDATE memory_entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?`).run(Date.now(), row.id);
530
+ }
531
+ catch {
532
+ // Non-fatal
533
+ }
534
+ let tags = [];
535
+ if (row.tags) {
536
+ try {
537
+ tags = JSON.parse(row.tags);
538
+ }
539
+ catch { /* invalid */ }
540
+ }
541
+ const entry = {
542
+ id: String(row.id),
543
+ key: row.key || String(row.id),
544
+ namespace: row.namespace || 'default',
545
+ content: row.content || '',
546
+ accessCount: (row.access_count || 0) + 1,
547
+ createdAt: row.created_at || new Date().toISOString(),
548
+ updatedAt: row.updated_at || new Date().toISOString(),
549
+ hasEmbedding: !!(row.embedding && String(row.embedding).length > 10),
550
+ tags,
551
+ };
552
+ // Phase 2: Populate cache for next read
553
+ await cacheSet(registry, cacheKey, entry);
554
+ return { success: true, found: true, cacheHit: false, entry };
555
+ }
556
+ catch {
557
+ return null;
558
+ }
559
+ }
560
+ /**
561
+ * Delete an entry via AgentDB v3.
562
+ * Phase 5: MutationGuard validation, cache invalidation, attestation logging.
563
+ */
564
+ export async function bridgeDeleteEntry(options) {
565
+ const registry = await getRegistry(options.dbPath);
566
+ if (!registry)
567
+ return null;
568
+ const ctx = getDb(registry);
569
+ if (!ctx)
570
+ return null;
571
+ try {
572
+ const { key, namespace = 'default' } = options;
573
+ // Phase 5: MutationGuard validation before delete
574
+ const guardResult = await guardValidate(registry, 'delete', { key, namespace });
575
+ if (!guardResult.allowed) {
576
+ return { success: false, deleted: false, key, namespace, remainingEntries: 0, error: `MutationGuard rejected: ${guardResult.reason}` };
577
+ }
578
+ // Soft delete using parameterized query
579
+ let changes = 0;
580
+ try {
581
+ const result = ctx.db.prepare(`
582
+ UPDATE memory_entries
583
+ SET status = 'deleted', updated_at = ?
584
+ WHERE key = ? AND namespace = ? AND status = 'active'
585
+ `).run(Date.now(), key, namespace);
586
+ changes = result?.changes ?? 0;
587
+ }
588
+ catch {
589
+ return null;
590
+ }
591
+ // Phase 2: Invalidate cache
592
+ await cacheInvalidate(registry, `entry:${namespace}:${key}`);
593
+ // Phase 4: AttestationLog delete audit
594
+ if (changes > 0) {
595
+ await logAttestation(registry, 'delete', key, { namespace });
596
+ }
597
+ let remaining = 0;
598
+ try {
599
+ const row = ctx.db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active'`).get();
600
+ remaining = row?.cnt || 0;
601
+ }
602
+ catch {
603
+ // Non-fatal
604
+ }
605
+ return {
606
+ success: true,
607
+ deleted: changes > 0,
608
+ key,
609
+ namespace,
610
+ remainingEntries: remaining,
611
+ guarded: true,
612
+ };
613
+ }
614
+ catch {
615
+ return null;
616
+ }
617
+ }
618
+ // ===== Phase 2: Embedding bridge =====
619
+ /**
620
+ * Generate embedding via AgentDB v3's embedder.
621
+ * Returns null if bridge unavailable — caller falls back to own ONNX/hash.
622
+ */
623
+ export async function bridgeGenerateEmbedding(text, dbPath) {
624
+ const registry = await getRegistry(dbPath);
625
+ if (!registry)
626
+ return null;
627
+ try {
628
+ const agentdb = registry.getAgentDB();
629
+ const embedder = agentdb?.embedder;
630
+ if (!embedder)
631
+ return null;
632
+ const emb = await embedder.embed(text);
633
+ if (!emb)
634
+ return null;
635
+ return {
636
+ embedding: Array.from(emb),
637
+ dimensions: emb.length,
638
+ model: 'Xenova/all-MiniLM-L6-v2',
639
+ };
640
+ }
641
+ catch {
642
+ return null;
643
+ }
644
+ }
645
+ /**
646
+ * Load embedding model via AgentDB v3 (it loads on init).
647
+ * Returns null if unavailable.
648
+ */
649
+ export async function bridgeLoadEmbeddingModel(dbPath) {
650
+ const startTime = Date.now();
651
+ const registry = await getRegistry(dbPath);
652
+ if (!registry)
653
+ return null;
654
+ try {
655
+ const agentdb = registry.getAgentDB();
656
+ const embedder = agentdb?.embedder;
657
+ if (!embedder)
658
+ return null;
659
+ // Verify embedder works by generating a test embedding
660
+ const test = await embedder.embed('test');
661
+ if (!test)
662
+ return null;
663
+ return {
664
+ success: true,
665
+ dimensions: test.length,
666
+ modelName: 'Xenova/all-MiniLM-L6-v2',
667
+ loadTime: Date.now() - startTime,
668
+ };
669
+ }
670
+ catch {
671
+ return null;
672
+ }
673
+ }
674
+ // ===== Phase 3: HNSW bridge =====
675
+ /**
676
+ * Get HNSW status from AgentDB v3's vector backend or HNSW index.
677
+ * Returns null if unavailable.
678
+ */
679
+ export async function bridgeGetHNSWStatus(dbPath) {
680
+ const registry = await getRegistry(dbPath);
681
+ if (!registry)
682
+ return null;
683
+ try {
684
+ const ctx = getDb(registry);
685
+ if (!ctx)
686
+ return null;
687
+ // Count entries with embeddings
688
+ let entryCount = 0;
689
+ try {
690
+ const row = ctx.db.prepare(`SELECT COUNT(*) as cnt FROM memory_entries WHERE status = 'active' AND embedding IS NOT NULL`).get();
691
+ entryCount = row?.cnt || 0;
692
+ }
693
+ catch {
694
+ // Table might not exist
695
+ }
696
+ return {
697
+ available: true,
698
+ initialized: true,
699
+ entryCount,
700
+ dimensions: 384,
701
+ };
702
+ }
703
+ catch {
704
+ return null;
705
+ }
706
+ }
707
+ /**
708
+ * Search using AgentDB v3's embedder + SQLite entries.
709
+ * This is the HNSW-equivalent search through the bridge.
710
+ * Returns null if unavailable.
711
+ */
712
+ export async function bridgeSearchHNSW(queryEmbedding, options, dbPath) {
713
+ const registry = await getRegistry(dbPath);
714
+ if (!registry)
715
+ return null;
716
+ const ctx = getDb(registry);
717
+ if (!ctx)
718
+ return null;
719
+ try {
720
+ const k = options?.k ?? 10;
721
+ const threshold = options?.threshold ?? 0.3;
722
+ const nsFilter = options?.namespace && options.namespace !== 'all'
723
+ ? `AND namespace = ?`
724
+ : '';
725
+ let rows;
726
+ try {
727
+ const stmt = ctx.db.prepare(`
728
+ SELECT id, key, namespace, content, embedding
729
+ FROM memory_entries
730
+ WHERE status = 'active' AND embedding IS NOT NULL ${nsFilter}
731
+ LIMIT 10000
732
+ `);
733
+ rows = nsFilter
734
+ ? stmt.all(options.namespace)
735
+ : stmt.all();
736
+ }
737
+ catch {
738
+ return null;
739
+ }
740
+ const results = [];
741
+ for (const row of rows) {
742
+ if (!row.embedding)
743
+ continue;
744
+ try {
745
+ const emb = JSON.parse(row.embedding);
746
+ const score = cosineSim(queryEmbedding, emb);
747
+ if (score >= threshold) {
748
+ results.push({
749
+ id: String(row.id).substring(0, 12),
750
+ key: row.key || String(row.id).substring(0, 15),
751
+ content: (row.content || '').substring(0, 60) +
752
+ ((row.content || '').length > 60 ? '...' : ''),
753
+ score,
754
+ namespace: row.namespace || 'default',
755
+ });
756
+ }
757
+ }
758
+ catch {
759
+ // Skip invalid embeddings
760
+ }
761
+ }
762
+ results.sort((a, b) => b.score - a.score);
763
+ return results.slice(0, k);
764
+ }
765
+ catch {
766
+ return null;
767
+ }
768
+ }
769
+ /**
770
+ * Add entry to the bridge's database with embedding.
771
+ * Returns null if unavailable.
772
+ */
773
+ export async function bridgeAddToHNSW(id, embedding, entry, dbPath) {
774
+ const registry = await getRegistry(dbPath);
775
+ if (!registry)
776
+ return null;
777
+ const ctx = getDb(registry);
778
+ if (!ctx)
779
+ return null;
780
+ try {
781
+ const now = Date.now();
782
+ const embeddingJson = JSON.stringify(embedding);
783
+ ctx.db.prepare(`
784
+ INSERT OR REPLACE INTO memory_entries (
785
+ id, key, namespace, content, type,
786
+ embedding, embedding_dimensions, embedding_model,
787
+ created_at, updated_at, status
788
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, 'Xenova/all-MiniLM-L6-v2', ?, ?, 'active')
789
+ `).run(id, entry.key, entry.namespace, entry.content, embeddingJson, embedding.length, now, now);
790
+ return true;
791
+ }
792
+ catch {
793
+ return null;
794
+ }
795
+ }
796
+ // ===== Phase 4: Controller access =====
797
+ /**
798
+ * Get a named controller from AgentDB v3 via ControllerRegistry.
799
+ * Returns null if unavailable.
800
+ */
801
+ export async function bridgeGetController(name, dbPath) {
802
+ const registry = await getRegistry(dbPath);
803
+ if (!registry)
804
+ return null;
805
+ try {
806
+ return registry.get(name) ?? null;
807
+ }
808
+ catch {
809
+ return null;
810
+ }
811
+ }
812
+ /**
813
+ * Check if a controller is available.
814
+ */
815
+ export async function bridgeHasController(name, dbPath) {
816
+ const registry = await getRegistry(dbPath);
817
+ if (!registry)
818
+ return false;
819
+ try {
820
+ const controller = registry.get(name);
821
+ return controller !== null && controller !== undefined;
822
+ }
823
+ catch {
824
+ return false;
825
+ }
826
+ }
827
+ /**
828
+ * List all controllers and their status.
829
+ */
830
+ export async function bridgeListControllers(dbPath) {
831
+ const registry = await getRegistry(dbPath);
832
+ if (!registry)
833
+ return null;
834
+ try {
835
+ return registry.listControllers();
836
+ }
837
+ catch {
838
+ return null;
839
+ }
840
+ }
841
+ /**
842
+ * Check if the AgentDB v3 bridge is available.
843
+ */
844
+ export async function isBridgeAvailable(dbPath) {
845
+ if (bridgeAvailable !== null)
846
+ return bridgeAvailable;
847
+ const registry = await getRegistry(dbPath);
848
+ return registry !== null;
849
+ }
850
+ /**
851
+ * Get the ControllerRegistry instance (for advanced consumers).
852
+ */
853
+ export async function getControllerRegistry(dbPath) {
854
+ return getRegistry(dbPath);
855
+ }
856
+ /**
857
+ * Shutdown the bridge and release resources.
858
+ */
859
+ export async function shutdownBridge() {
860
+ if (registryInstance) {
861
+ try {
862
+ await registryInstance.shutdown();
863
+ }
864
+ catch {
865
+ // Best-effort
866
+ }
867
+ registryInstance = null;
868
+ registryPromise = null;
869
+ bridgeAvailable = null;
870
+ }
871
+ }
872
+ // ===== Phase 3: ReasoningBank pattern operations =====
873
+ /**
874
+ * Store a pattern via ReasoningBank controller.
875
+ * Falls back to raw SQL if ReasoningBank unavailable.
876
+ */
877
+ export async function bridgeStorePattern(options) {
878
+ const registry = await getRegistry(options.dbPath);
879
+ if (!registry)
880
+ return null;
881
+ try {
882
+ const reasoningBank = registry.get('reasoningBank');
883
+ const patternId = `pattern-${Date.now()}-${Math.random().toString(36).substring(7)}`;
884
+ if (reasoningBank && typeof reasoningBank.store === 'function') {
885
+ await reasoningBank.store({
886
+ id: patternId,
887
+ content: options.pattern,
888
+ type: options.type,
889
+ confidence: options.confidence,
890
+ metadata: options.metadata,
891
+ timestamp: Date.now(),
892
+ });
893
+ return { success: true, patternId, controller: 'reasoningBank' };
894
+ }
895
+ // Fallback: store via bridge SQL
896
+ const result = await bridgeStoreEntry({
897
+ key: patternId,
898
+ value: JSON.stringify({ pattern: options.pattern, type: options.type, confidence: options.confidence, metadata: options.metadata }),
899
+ namespace: 'pattern',
900
+ generateEmbeddingFlag: true,
901
+ tags: [options.type, 'reasoning-pattern'],
902
+ dbPath: options.dbPath,
903
+ });
904
+ return result ? { success: true, patternId: result.id, controller: 'bridge-fallback' } : null;
905
+ }
906
+ catch {
907
+ return null;
908
+ }
909
+ }
910
+ /**
911
+ * Search patterns via ReasoningBank controller.
912
+ */
913
+ export async function bridgeSearchPatterns(options) {
914
+ const registry = await getRegistry(options.dbPath);
915
+ if (!registry)
916
+ return null;
917
+ try {
918
+ const reasoningBank = registry.get('reasoningBank');
919
+ if (reasoningBank && typeof reasoningBank.search === 'function') {
920
+ const results = await reasoningBank.search(options.query, {
921
+ topK: options.topK || 5,
922
+ minScore: options.minConfidence || 0.3,
923
+ });
924
+ return {
925
+ results: Array.isArray(results) ? results.map((r) => ({
926
+ id: r.id || r.patternId || '',
927
+ content: r.content || r.pattern || '',
928
+ score: r.score || r.confidence || 0,
929
+ })) : [],
930
+ controller: 'reasoningBank',
931
+ };
932
+ }
933
+ // Fallback: search via bridge
934
+ const result = await bridgeSearchEntries({
935
+ query: options.query,
936
+ namespace: 'pattern',
937
+ limit: options.topK || 5,
938
+ threshold: options.minConfidence || 0.3,
939
+ dbPath: options.dbPath,
940
+ });
941
+ return result ? {
942
+ results: result.results.map(r => ({ id: r.id, content: r.content, score: r.score })),
943
+ controller: 'bridge-fallback',
944
+ } : null;
945
+ }
946
+ catch {
947
+ return null;
948
+ }
949
+ }
950
+ // ===== Phase 3: Feedback recording =====
951
+ /**
952
+ * Record task feedback for learning via ReasoningBank or LearningSystem.
953
+ * Wired into hooks_post-task handler.
954
+ */
955
+ export async function bridgeRecordFeedback(options) {
956
+ const registry = await getRegistry(options.dbPath);
957
+ if (!registry)
958
+ return null;
959
+ try {
960
+ let controller = 'none';
961
+ let updated = 0;
962
+ // Try LearningSystem first (Phase 4)
963
+ const learningSystem = registry.get('learningSystem');
964
+ if (learningSystem) {
965
+ try {
966
+ if (typeof learningSystem.recordFeedback === 'function') {
967
+ await learningSystem.recordFeedback({
968
+ taskId: options.taskId, success: options.success, quality: options.quality,
969
+ agent: options.agent, duration: options.duration, timestamp: Date.now(),
970
+ });
971
+ controller = 'learningSystem';
972
+ updated++;
973
+ }
974
+ else if (typeof learningSystem.record === 'function') {
975
+ await learningSystem.record(options.taskId, options.quality, options.success ? 'success' : 'failure');
976
+ controller = 'learningSystem';
977
+ updated++;
978
+ }
979
+ }
980
+ catch { /* API mismatch — skip */ }
981
+ }
982
+ // Also record in ReasoningBank for pattern reinforcement
983
+ const reasoningBank = registry.get('reasoningBank');
984
+ if (reasoningBank) {
985
+ try {
986
+ if (typeof reasoningBank.recordOutcome === 'function') {
987
+ await reasoningBank.recordOutcome({
988
+ taskId: options.taskId, verdict: options.success ? 'success' : 'failure',
989
+ score: options.quality, timestamp: Date.now(),
990
+ });
991
+ controller = controller === 'none' ? 'reasoningBank' : `${controller}+reasoningBank`;
992
+ updated++;
993
+ }
994
+ else if (typeof reasoningBank.record === 'function') {
995
+ await reasoningBank.record(options.taskId, options.quality);
996
+ controller = controller === 'none' ? 'reasoningBank' : `${controller}+reasoningBank`;
997
+ updated++;
998
+ }
999
+ }
1000
+ catch { /* API mismatch — skip */ }
1001
+ }
1002
+ // Phase 4: SkillLibrary promotion for high-quality patterns
1003
+ if (options.success && options.quality >= 0.9 && options.patterns?.length) {
1004
+ const skills = registry.get('skills');
1005
+ if (skills && typeof skills.promote === 'function') {
1006
+ for (const pattern of options.patterns) {
1007
+ try {
1008
+ await skills.promote(pattern, options.quality);
1009
+ updated++;
1010
+ }
1011
+ catch { /* skip */ }
1012
+ }
1013
+ controller += '+skills';
1014
+ }
1015
+ }
1016
+ // Always store feedback as a memory entry for retrieval (ensures it persists)
1017
+ const storeResult = await bridgeStoreEntry({
1018
+ key: `feedback-${options.taskId}`,
1019
+ value: JSON.stringify(options),
1020
+ namespace: 'feedback',
1021
+ tags: [options.success ? 'success' : 'failure', options.agent || 'unknown'],
1022
+ dbPath: options.dbPath,
1023
+ });
1024
+ if (storeResult?.success) {
1025
+ controller = controller === 'none' ? 'bridge-store' : `${controller}+bridge-store`;
1026
+ updated++;
1027
+ }
1028
+ return { success: true, controller, updated };
1029
+ }
1030
+ catch {
1031
+ return null;
1032
+ }
1033
+ }
1034
+ // ===== Phase 3: CausalMemoryGraph =====
1035
+ /**
1036
+ * Record a causal edge between two entries (e.g., task → result).
1037
+ */
1038
+ export async function bridgeRecordCausalEdge(options) {
1039
+ const registry = await getRegistry(options.dbPath);
1040
+ if (!registry)
1041
+ return null;
1042
+ try {
1043
+ const causalGraph = registry.get('causalGraph');
1044
+ if (causalGraph && typeof causalGraph.addEdge === 'function') {
1045
+ causalGraph.addEdge(options.sourceId, options.targetId, {
1046
+ relation: options.relation,
1047
+ weight: options.weight || 1.0,
1048
+ timestamp: Date.now(),
1049
+ });
1050
+ return { success: true, controller: 'causalGraph' };
1051
+ }
1052
+ // Fallback: store edge as metadata
1053
+ const ctx = getDb(registry);
1054
+ if (ctx) {
1055
+ try {
1056
+ ctx.db.prepare(`
1057
+ INSERT OR REPLACE INTO memory_entries (id, key, namespace, content, type, created_at, updated_at, status)
1058
+ VALUES (?, ?, 'causal-edges', ?, 'procedural', ?, ?, 'active')
1059
+ `).run(`edge-${Date.now()}`, `${options.sourceId}→${options.targetId}`, JSON.stringify(options), Date.now(), Date.now());
1060
+ return { success: true, controller: 'bridge-fallback' };
1061
+ }
1062
+ catch { /* skip */ }
1063
+ }
1064
+ return null;
1065
+ }
1066
+ catch {
1067
+ return null;
1068
+ }
1069
+ }
1070
+ // ===== Phase 5: ReflexionMemory session lifecycle =====
1071
+ /**
1072
+ * Start a session with ReflexionMemory episodic replay.
1073
+ * Loads relevant past session patterns for the new session.
1074
+ */
1075
+ export async function bridgeSessionStart(options) {
1076
+ const registry = await getRegistry(options.dbPath);
1077
+ if (!registry)
1078
+ return null;
1079
+ try {
1080
+ let restoredPatterns = 0;
1081
+ let controller = 'none';
1082
+ // Try ReflexionMemory for episodic session replay
1083
+ const reflexion = registry.get('reflexion');
1084
+ if (reflexion && typeof reflexion.startEpisode === 'function') {
1085
+ await reflexion.startEpisode(options.sessionId, { context: options.context });
1086
+ controller = 'reflexion';
1087
+ }
1088
+ // Load recent patterns from past sessions
1089
+ const searchResult = await bridgeSearchEntries({
1090
+ query: options.context || 'session patterns',
1091
+ namespace: 'session',
1092
+ limit: 10,
1093
+ threshold: 0.2,
1094
+ dbPath: options.dbPath,
1095
+ });
1096
+ if (searchResult?.results) {
1097
+ restoredPatterns = searchResult.results.length;
1098
+ }
1099
+ return {
1100
+ success: true,
1101
+ controller: controller === 'none' ? 'bridge-search' : controller,
1102
+ restoredPatterns,
1103
+ sessionId: options.sessionId,
1104
+ };
1105
+ }
1106
+ catch {
1107
+ return null;
1108
+ }
1109
+ }
1110
+ /**
1111
+ * End a session and persist episodic summary to ReflexionMemory.
1112
+ */
1113
+ export async function bridgeSessionEnd(options) {
1114
+ const registry = await getRegistry(options.dbPath);
1115
+ if (!registry)
1116
+ return null;
1117
+ try {
1118
+ let controller = 'none';
1119
+ let persisted = false;
1120
+ // End episode in ReflexionMemory
1121
+ const reflexion = registry.get('reflexion');
1122
+ if (reflexion && typeof reflexion.endEpisode === 'function') {
1123
+ await reflexion.endEpisode(options.sessionId, {
1124
+ summary: options.summary,
1125
+ tasksCompleted: options.tasksCompleted,
1126
+ patternsLearned: options.patternsLearned,
1127
+ });
1128
+ controller = 'reflexion';
1129
+ persisted = true;
1130
+ }
1131
+ // Persist session summary as memory entry
1132
+ await bridgeStoreEntry({
1133
+ key: `session-${options.sessionId}`,
1134
+ value: JSON.stringify({
1135
+ sessionId: options.sessionId,
1136
+ summary: options.summary || 'Session ended',
1137
+ tasksCompleted: options.tasksCompleted || 0,
1138
+ patternsLearned: options.patternsLearned || 0,
1139
+ endedAt: new Date().toISOString(),
1140
+ }),
1141
+ namespace: 'session',
1142
+ tags: ['session-end'],
1143
+ upsert: true,
1144
+ dbPath: options.dbPath,
1145
+ });
1146
+ if (controller === 'none')
1147
+ controller = 'bridge-store';
1148
+ persisted = true;
1149
+ // Phase 3: Trigger NightlyLearner consolidation if available
1150
+ const nightlyLearner = registry.get('nightlyLearner');
1151
+ if (nightlyLearner && typeof nightlyLearner.consolidate === 'function') {
1152
+ try {
1153
+ await nightlyLearner.consolidate({ sessionId: options.sessionId });
1154
+ controller += '+nightlyLearner';
1155
+ }
1156
+ catch { /* non-fatal */ }
1157
+ }
1158
+ return { success: true, controller, persisted };
1159
+ }
1160
+ catch {
1161
+ return null;
1162
+ }
1163
+ }
1164
+ // ===== Phase 5: SemanticRouter bridge =====
1165
+ /**
1166
+ * Route a task via AgentDB's SemanticRouter.
1167
+ * Returns null to fall back to local ruvector router.
1168
+ */
1169
+ export async function bridgeRouteTask(options) {
1170
+ const registry = await getRegistry(options.dbPath);
1171
+ if (!registry)
1172
+ return null;
1173
+ try {
1174
+ // Try AgentDB's SemanticRouter
1175
+ const semanticRouter = registry.get('semanticRouter');
1176
+ if (semanticRouter && typeof semanticRouter.route === 'function') {
1177
+ const result = await semanticRouter.route(options.task, { context: options.context });
1178
+ if (result) {
1179
+ return {
1180
+ route: result.route || result.category || 'general',
1181
+ confidence: result.confidence || result.score || 0.5,
1182
+ agents: result.agents || result.suggestedAgents || [],
1183
+ controller: 'semanticRouter',
1184
+ };
1185
+ }
1186
+ }
1187
+ // Try LearningSystem recommendAlgorithm (Phase 4)
1188
+ const learningSystem = registry.get('learningSystem');
1189
+ if (learningSystem && typeof learningSystem.recommendAlgorithm === 'function') {
1190
+ const rec = await learningSystem.recommendAlgorithm(options.task);
1191
+ if (rec) {
1192
+ return {
1193
+ route: rec.algorithm || rec.route || 'general',
1194
+ confidence: rec.confidence || 0.5,
1195
+ agents: rec.agents || [],
1196
+ controller: 'learningSystem',
1197
+ };
1198
+ }
1199
+ }
1200
+ return null; // Fall back to local router
1201
+ }
1202
+ catch {
1203
+ return null;
1204
+ }
1205
+ }
1206
+ // ===== Phase 4: Health check with attestation =====
1207
+ /**
1208
+ * Get comprehensive bridge health including all controller statuses.
1209
+ */
1210
+ export async function bridgeHealthCheck(dbPath) {
1211
+ const registry = await getRegistry(dbPath);
1212
+ if (!registry)
1213
+ return null;
1214
+ try {
1215
+ const controllers = registry.listControllers();
1216
+ // Phase 4: AttestationLog stats
1217
+ let attestationCount = 0;
1218
+ const attestation = registry.get('attestationLog');
1219
+ if (attestation && typeof attestation.count === 'function') {
1220
+ attestationCount = attestation.count();
1221
+ }
1222
+ // Phase 2: TieredCache stats
1223
+ let cacheStats = { size: 0, hits: 0, misses: 0 };
1224
+ const cache = registry.get('tieredCache');
1225
+ if (cache && typeof cache.stats === 'function') {
1226
+ const s = cache.stats();
1227
+ cacheStats = { size: s.size || 0, hits: s.hits || 0, misses: s.misses || 0 };
1228
+ }
1229
+ return { available: true, controllers, attestationCount, cacheStats };
1230
+ }
1231
+ catch {
1232
+ return null;
1233
+ }
1234
+ }
1235
+ // ===== Utility =====
1236
+ function cosineSim(a, b) {
1237
+ if (!a || !b || a.length === 0 || b.length === 0)
1238
+ return 0;
1239
+ const len = Math.min(a.length, b.length);
1240
+ let dot = 0, normA = 0, normB = 0;
1241
+ for (let i = 0; i < len; i++) {
1242
+ const ai = a[i], bi = b[i];
1243
+ dot += ai * bi;
1244
+ normA += ai * ai;
1245
+ normB += bi * bi;
1246
+ }
1247
+ const mag = Math.sqrt(normA * normB);
1248
+ return mag === 0 ? 0 : dot / mag;
1249
+ }
1250
+ //# sourceMappingURL=memory-bridge.js.map