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