sqlite-local-ai-memory 0.0.0-stage → 1.4.3
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/.env.example +66 -0
- package/BENCHMARKS.md +93 -0
- package/LICENSE +21 -0
- package/README.md +497 -3
- package/dist/MemoryEngine.d.ts +101 -0
- package/dist/MemoryEngine.d.ts.map +1 -0
- package/dist/MemoryEngine.js +365 -0
- package/dist/cognitive_agents.d.ts +84 -0
- package/dist/cognitive_agents.d.ts.map +1 -0
- package/dist/cognitive_agents.js +1087 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/mcp_server.d.ts +3 -0
- package/dist/mcp_server.d.ts.map +1 -0
- package/dist/mcp_server.js +258 -0
- package/dist/multi_env_mcp_test.d.ts +2 -0
- package/dist/multi_env_mcp_test.d.ts.map +1 -0
- package/dist/multi_env_mcp_test.js +139 -0
- package/dist/sqlite_store.d.ts +40 -0
- package/dist/sqlite_store.d.ts.map +1 -0
- package/dist/sqlite_store.js +409 -0
- package/dist/stress_test.d.ts +2 -0
- package/dist/stress_test.d.ts.map +1 -0
- package/dist/stress_test.js +149 -0
- package/dist/test_autodream_dual.d.ts +2 -0
- package/dist/test_autodream_dual.d.ts.map +1 -0
- package/dist/test_autodream_dual.js +38 -0
- package/dist/test_autodream_history.d.ts +2 -0
- package/dist/test_autodream_history.d.ts.map +1 -0
- package/dist/test_autodream_history.js +131 -0
- package/dist/test_multitopic_dashboard.d.ts +2 -0
- package/dist/test_multitopic_dashboard.d.ts.map +1 -0
- package/dist/test_multitopic_dashboard.js +82 -0
- package/dist/types.d.ts +134 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +16 -0
- package/package.json +71 -4
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================================
|
|
3
|
+
* FILE: src/memory/MemoryEngine.ts
|
|
4
|
+
* RESPONSIBILITY: Primary Exportable Facade Class (Library + MCP).
|
|
5
|
+
* ============================================================================
|
|
6
|
+
*/
|
|
7
|
+
import * as fs from "fs";
|
|
8
|
+
import * as path from "path";
|
|
9
|
+
import os from "os";
|
|
10
|
+
import { EMBEDDING_DIM } from "./types.js";
|
|
11
|
+
import { SqliteStore } from "./sqlite_store.js";
|
|
12
|
+
import { CognitiveAgents } from "./cognitive_agents.js";
|
|
13
|
+
/** Maximum number of recent turns retained per user in RAM. */
|
|
14
|
+
const MAX_RING_BUFFER_TURNS = 10;
|
|
15
|
+
const defaultTelemetryPath = path.join(os.homedir(), ".local-ai-memory", "telemetry.jsonl");
|
|
16
|
+
/**
|
|
17
|
+
* KeyedMutex: Guarantees deterministic serialization of asynchronous write operations
|
|
18
|
+
* per user ID, eliminating Lost Updates and TOCTOU race conditions.
|
|
19
|
+
*/
|
|
20
|
+
class KeyedMutex {
|
|
21
|
+
queues = new Map();
|
|
22
|
+
async run(key, fn) {
|
|
23
|
+
const prev = this.queues.get(key) ?? Promise.resolve();
|
|
24
|
+
let release;
|
|
25
|
+
// FIX R3-1.1: store `tail` directly (not a derived .then() promise) so the
|
|
26
|
+
// identity comparison below correctly detects whether we are the last waiter.
|
|
27
|
+
const tail = new Promise((resolve) => (release = resolve));
|
|
28
|
+
this.queues.set(key, tail);
|
|
29
|
+
await prev;
|
|
30
|
+
try {
|
|
31
|
+
return await fn();
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
release();
|
|
35
|
+
// Only delete the entry if nobody else enqueued behind us.
|
|
36
|
+
if (this.queues.get(key) === tail)
|
|
37
|
+
this.queues.delete(key);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class MemoryEngine {
|
|
42
|
+
store;
|
|
43
|
+
agents;
|
|
44
|
+
userId;
|
|
45
|
+
debug;
|
|
46
|
+
telemetry;
|
|
47
|
+
telemetryPath;
|
|
48
|
+
telemetryStream;
|
|
49
|
+
MAX_TRACKED_USERS = 500;
|
|
50
|
+
writeMutex = new KeyedMutex();
|
|
51
|
+
backfillInFlight = new Set();
|
|
52
|
+
/** Ephemeral per-user ring buffer of recent conversation turns (RAM only, never persisted). */
|
|
53
|
+
turnBuffers = new Map();
|
|
54
|
+
constructor(config = {}) {
|
|
55
|
+
this.userId = config.userId || "user_default";
|
|
56
|
+
this.debug = config.debug !== undefined
|
|
57
|
+
? config.debug
|
|
58
|
+
: (process.env.MEMORY_DEBUG === "true" || process.env.DEBUG === "true");
|
|
59
|
+
this.telemetry = config.telemetry !== undefined
|
|
60
|
+
? config.telemetry
|
|
61
|
+
: (process.env.MEMORY_TELEMETRY === "true" || process.env.TELEMETRY === "true");
|
|
62
|
+
const rawTelemetryPath = (config.telemetryPath || process.env.MEMORY_TELEMETRY_PATH || defaultTelemetryPath).trim();
|
|
63
|
+
this.telemetryPath = rawTelemetryPath === "~"
|
|
64
|
+
? os.homedir()
|
|
65
|
+
: (rawTelemetryPath.startsWith("~/") || rawTelemetryPath.startsWith("~\\"))
|
|
66
|
+
? path.join(os.homedir(), rawTelemetryPath.slice(2))
|
|
67
|
+
: rawTelemetryPath;
|
|
68
|
+
this.store = new SqliteStore(config.dbPath);
|
|
69
|
+
this.agents = new CognitiveAgents({ ...config, debug: this.debug }, this.store);
|
|
70
|
+
if (this.telemetry) {
|
|
71
|
+
try {
|
|
72
|
+
const targetDir = path.dirname(this.telemetryPath);
|
|
73
|
+
if (!fs.existsSync(targetDir)) {
|
|
74
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
75
|
+
}
|
|
76
|
+
this.telemetryStream = fs.createWriteStream(this.telemetryPath, { flags: "a" });
|
|
77
|
+
this.telemetryStream.on("error", (err) => {
|
|
78
|
+
console.error(`⚠️ [MEMORY:TELEMETRY] Stream error, disabling telemetry: ${err.message}`);
|
|
79
|
+
this.telemetry = false;
|
|
80
|
+
this.telemetryStream = undefined;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (this.debug) {
|
|
85
|
+
console.error(`⚠️ [MEMORY:TELEMETRY] Failed to initialize telemetry stream: ${err.message}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Appends an operational telemetry record to the JSONL log file asynchronously.
|
|
92
|
+
* Fail-safe: Any file system or serialization error is logged and swallowed so it
|
|
93
|
+
* NEVER interferes with the core user query flow.
|
|
94
|
+
*/
|
|
95
|
+
recordTelemetry(payload) {
|
|
96
|
+
if (!this.telemetry || !this.telemetryStream)
|
|
97
|
+
return;
|
|
98
|
+
try {
|
|
99
|
+
const entry = JSON.stringify({
|
|
100
|
+
timestamp: new Date().toISOString(),
|
|
101
|
+
...payload,
|
|
102
|
+
}) + "\n";
|
|
103
|
+
this.telemetryStream.write(entry);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
if (this.debug) {
|
|
107
|
+
console.error(`⚠️ [MEMORY:TELEMETRY] Error writing telemetry record: ${err.message}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Saves text or conversation input, automatically filtering noise with Gatekeeper
|
|
113
|
+
* and extracting atomic facts using the Notary compiler.
|
|
114
|
+
*
|
|
115
|
+
* @param text - Input text or conversational dialogue.
|
|
116
|
+
* @param userId - Target user identifier (defaults to configured userId).
|
|
117
|
+
* @param opts - Execution options including optional AbortSignal and subproject `source` tag.
|
|
118
|
+
*/
|
|
119
|
+
async save(text, userId = this.userId, opts) {
|
|
120
|
+
return this.writeMutex.run(userId, async () => {
|
|
121
|
+
await this.agents.saveMemory(text, userId, opts?.signal, opts?.source);
|
|
122
|
+
if (this.telemetry) {
|
|
123
|
+
this.recordTelemetry({
|
|
124
|
+
event: "SAVE",
|
|
125
|
+
userId,
|
|
126
|
+
source: opts?.source || "system",
|
|
127
|
+
input_text: text,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Saves a pre-formatted fact directly into memory without running through the Notary compiler.
|
|
134
|
+
* Runs through the Semantic Arbiter to detect collisions or updates against existing state.
|
|
135
|
+
*
|
|
136
|
+
* @param fact - Direct fact string (e.g. '[TECHNICAL] Database upgraded to v2').
|
|
137
|
+
* @param userId - Target user identifier.
|
|
138
|
+
* @param opts - Execution options including optional AbortSignal and subproject `source` tag.
|
|
139
|
+
*/
|
|
140
|
+
async saveFact(fact, userId = this.userId, opts) {
|
|
141
|
+
return this.writeMutex.run(userId, async () => {
|
|
142
|
+
await this.agents.injectUnifiedFact(fact, userId, [], opts?.signal, opts?.source);
|
|
143
|
+
if (this.telemetry) {
|
|
144
|
+
this.recordTelemetry({
|
|
145
|
+
event: "SAVE_FACT",
|
|
146
|
+
userId,
|
|
147
|
+
source: opts?.source || "system",
|
|
148
|
+
fact,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Dual Parallel Hybrid RAG Search (FTS5 BM25 + Int8 Scalar Quantized Cosine Similarity).
|
|
155
|
+
* Automatically invokes QUERY_EXPANDER via Smart Gate when conversational context is present.
|
|
156
|
+
*/
|
|
157
|
+
async search(query, limit = 5, userId = this.userId, opts) {
|
|
158
|
+
const searchStartTime = Date.now();
|
|
159
|
+
// --- SMART GATE: Activate QUERY_EXPANDER only when conversational context exists ---
|
|
160
|
+
let effectiveQuery = query;
|
|
161
|
+
const ringTurns = this.turnBuffers.get(userId) || [];
|
|
162
|
+
const ringHistory = this.getFormattedHistory(userId);
|
|
163
|
+
const externalHistory = opts?.history || "";
|
|
164
|
+
const availableHistory = ringHistory || externalHistory;
|
|
165
|
+
let expanderInvoked = false;
|
|
166
|
+
let expanderLatencyMs = 0;
|
|
167
|
+
let expanderError = null;
|
|
168
|
+
if (availableHistory.length > 0) {
|
|
169
|
+
expanderInvoked = true;
|
|
170
|
+
const expanderStart = Date.now();
|
|
171
|
+
try {
|
|
172
|
+
effectiveQuery = await this.agents.contextualizeQuery(query, availableHistory);
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
expanderError = err.message || String(err);
|
|
176
|
+
if (this.debug) {
|
|
177
|
+
console.error(`⚠️ [MemoryEngine] contextualizeQuery failed, using raw query: ${err.message}`);
|
|
178
|
+
}
|
|
179
|
+
effectiveQuery = query;
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
expanderLatencyMs = Date.now() - expanderStart;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const ftsHits = this.store.searchFTS5(effectiveQuery, limit * 2, userId);
|
|
186
|
+
let queryVec = [];
|
|
187
|
+
try {
|
|
188
|
+
queryVec = await this.agents.getEmbedding(effectiveQuery, opts?.signal);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
if (err.name === "AbortError" || opts?.signal?.aborted)
|
|
192
|
+
throw err;
|
|
193
|
+
console.error("⚠️ [MemoryEngine] Embedding generation failed, degrading gracefully to FTS5 exact search:", err.message);
|
|
194
|
+
}
|
|
195
|
+
let vecHits = [];
|
|
196
|
+
if (queryVec.length === EMBEDDING_DIM) {
|
|
197
|
+
vecHits = this.store.searchVectorInt8(queryVec, limit * 2, userId);
|
|
198
|
+
// FIX R2-2: pass `undefined` (not opts?.signal) so backfill survives
|
|
199
|
+
// even if the MCP client cancels the originating search request.
|
|
200
|
+
if (!this.backfillInFlight.has(userId)) {
|
|
201
|
+
this.backfillInFlight.add(userId);
|
|
202
|
+
this.store.backfillMissingVectors((txt) => this.agents.getEmbedding(txt, undefined), userId)
|
|
203
|
+
.catch((err) => console.error("⚠️ [MemoryEngine] Lazy backfill failed in background:", err.message))
|
|
204
|
+
.finally(() => this.backfillInFlight.delete(userId));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const maxRankAbs = Math.max(...ftsHits.map((h) => Math.abs(h.rank ?? 0)), 1);
|
|
208
|
+
const combinedMap = new Map();
|
|
209
|
+
for (const h of ftsHits) {
|
|
210
|
+
const normalizedFtsScore = h.rank != null ? Math.abs(h.rank) / maxRankAbs : 0.5;
|
|
211
|
+
combinedMap.set(h.id, { ...h, score: normalizedFtsScore * 0.8 });
|
|
212
|
+
}
|
|
213
|
+
for (const h of vecHits) {
|
|
214
|
+
if (combinedMap.has(h.id)) {
|
|
215
|
+
const prev = combinedMap.get(h.id);
|
|
216
|
+
combinedMap.set(h.id, {
|
|
217
|
+
...prev,
|
|
218
|
+
score: Math.max(prev.score || 0, (h.score || 0) * 0.9) + 0.1,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
combinedMap.set(h.id, { ...h, score: (h.score || 0) * 0.9 });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const unified = Array.from(combinedMap.values());
|
|
226
|
+
unified.sort((a, b) => (b.score || 0) - (a.score || 0));
|
|
227
|
+
const results = unified.slice(0, limit);
|
|
228
|
+
// Deep Telemetry logging
|
|
229
|
+
if (this.telemetry) {
|
|
230
|
+
this.recordTelemetry({
|
|
231
|
+
event: "SEARCH",
|
|
232
|
+
userId,
|
|
233
|
+
raw_query: query,
|
|
234
|
+
effective_query: effectiveQuery,
|
|
235
|
+
smart_gate: {
|
|
236
|
+
expander_invoked: expanderInvoked,
|
|
237
|
+
ring_turns_count: ringTurns.length,
|
|
238
|
+
ring_history_snapshot: ringTurns.map(t => ({ role: t.role, text: t.text })),
|
|
239
|
+
external_history_provided: Boolean(externalHistory),
|
|
240
|
+
},
|
|
241
|
+
expander: {
|
|
242
|
+
latency_ms: expanderLatencyMs,
|
|
243
|
+
error: expanderError,
|
|
244
|
+
disambiguated: effectiveQuery !== query,
|
|
245
|
+
},
|
|
246
|
+
retrieval: {
|
|
247
|
+
total_duration_ms: Date.now() - searchStartTime,
|
|
248
|
+
raw_fts_matches: ftsHits.length,
|
|
249
|
+
raw_vec_matches: vecHits.length,
|
|
250
|
+
returned_hits: results.map(r => ({
|
|
251
|
+
id: r.id,
|
|
252
|
+
score: Number((r.score ?? 0).toFixed(3)),
|
|
253
|
+
data: r.data.length > 120 ? `${r.data.slice(0, 120)}...` : r.data,
|
|
254
|
+
source: r.source,
|
|
255
|
+
})),
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (this.debug) {
|
|
260
|
+
console.error(`\n🔍 [MEMORY:SEARCH]`);
|
|
261
|
+
console.error(`├─ Query: "${query}" → Effective: "${effectiveQuery}" (User: ${userId})`);
|
|
262
|
+
console.error(`├─ Raw Matches: FTS5 BM25 = ${ftsHits.length} | Vector Cosine = ${vecHits.length}`);
|
|
263
|
+
console.error(`└─ Ranked Results (Top ${results.length}):`);
|
|
264
|
+
if (results.length === 0) {
|
|
265
|
+
console.error(` (No matching memories found)`);
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
results.forEach((r, i) => {
|
|
269
|
+
const scoreStr = (r.score ?? 0).toFixed(3);
|
|
270
|
+
const snippet = r.data.length > 90 ? `${r.data.slice(0, 90)}...` : r.data;
|
|
271
|
+
console.error(` [${i + 1}] [Score: ${scoreStr}] ${snippet}`);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
console.error(`────────────────────────────────────────────────────\n`);
|
|
275
|
+
}
|
|
276
|
+
return results;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Retrieves the current consolidated active working state summary (Dashboard).
|
|
280
|
+
*/
|
|
281
|
+
getDashboard(userId = this.userId) {
|
|
282
|
+
const dash = this.store.getDashboardFact(userId);
|
|
283
|
+
if (this.debug) {
|
|
284
|
+
console.error(`\n📋 [MEMORY:DASHBOARD]`);
|
|
285
|
+
console.error(`├─ User: ${userId}`);
|
|
286
|
+
console.error(`├─ Updated: ${dash?.updated_at || "Never"}`);
|
|
287
|
+
console.error(`└─ Content:\n${dash?.data || "(Empty dashboard)"}`);
|
|
288
|
+
console.error(`────────────────────────────────────────────────────\n`);
|
|
289
|
+
}
|
|
290
|
+
return dash;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Executes the AutoDream cognitive pruning and state consolidation cycle.
|
|
294
|
+
* Analyzes recent facts, prunes TTL-expired working notes, graduates resolved
|
|
295
|
+
* incubator cases into long-term memory, and produces a unified executive narrative.
|
|
296
|
+
*
|
|
297
|
+
* @param userId - Target user identifier.
|
|
298
|
+
* @param source - Optional subproject or source being consolidated (e.g. 'TOTALCONNECT').
|
|
299
|
+
* When provided, guarantees deterministic cross-topic preservation of other projects.
|
|
300
|
+
* @returns AutoDreamResult containing executive narrative, active dashboard, and triage facts.
|
|
301
|
+
*/
|
|
302
|
+
async consolidate(userId = this.userId, source, opts) {
|
|
303
|
+
return this.writeMutex.run(userId, async () => {
|
|
304
|
+
return await this.agents.runAutoDream(userId, source, opts?.signal);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Registers a conversation turn in the ephemeral ring buffer.
|
|
309
|
+
* This provides the QUERY_EXPANDER with recent conversational context
|
|
310
|
+
* to resolve ambiguous queries (pronouns, references, ellipsis).
|
|
311
|
+
* Turns are stored in RAM only and never written to SQLite.
|
|
312
|
+
*
|
|
313
|
+
* @param role - "user" or "assistant"
|
|
314
|
+
* @param text - The message content
|
|
315
|
+
* @param userId - Target user identifier (defaults to configured userId)
|
|
316
|
+
*/
|
|
317
|
+
addTurn(role, text, userId = this.userId) {
|
|
318
|
+
let buffer = this.turnBuffers.get(userId);
|
|
319
|
+
if (buffer) {
|
|
320
|
+
this.turnBuffers.delete(userId);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
if (this.turnBuffers.size >= this.MAX_TRACKED_USERS) {
|
|
324
|
+
const oldestKey = this.turnBuffers.keys().next().value;
|
|
325
|
+
if (oldestKey !== undefined)
|
|
326
|
+
this.turnBuffers.delete(oldestKey);
|
|
327
|
+
}
|
|
328
|
+
buffer = [];
|
|
329
|
+
}
|
|
330
|
+
buffer.push({ role, text });
|
|
331
|
+
if (buffer.length > MAX_RING_BUFFER_TURNS) {
|
|
332
|
+
buffer.splice(0, buffer.length - MAX_RING_BUFFER_TURNS);
|
|
333
|
+
}
|
|
334
|
+
this.turnBuffers.set(userId, buffer);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Returns the last N turns formatted as "U: ...\nA: ..." for the QUERY_EXPANDER.
|
|
338
|
+
* Returns empty string if no turns are available.
|
|
339
|
+
*/
|
|
340
|
+
getFormattedHistory(userId, maxTurns = 5) {
|
|
341
|
+
const buffer = this.turnBuffers.get(userId);
|
|
342
|
+
if (!buffer || buffer.length === 0)
|
|
343
|
+
return "";
|
|
344
|
+
const recent = buffer.slice(-maxTurns);
|
|
345
|
+
return recent
|
|
346
|
+
.map((t) => `${t.role === "user" ? "U" : "A"}: ${t.text}`)
|
|
347
|
+
.join("\n");
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* @deprecated Use addTurn() + search() instead. The smart gate inside search()
|
|
351
|
+
* now calls contextualizeQuery automatically when turns are available.
|
|
352
|
+
*/
|
|
353
|
+
async contextualizeQuery(query, shortHistory) {
|
|
354
|
+
return await this.agents.contextualizeQuery(query, shortHistory);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Gracefully closes the SQLite database connection.
|
|
358
|
+
*/
|
|
359
|
+
close() {
|
|
360
|
+
this.store.close();
|
|
361
|
+
if (this.telemetryStream) {
|
|
362
|
+
this.telemetryStream.end();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { type MemoryConfig, type AgentModelConfig, type AutoDreamResult, type ModelProvider } from "./types.js";
|
|
2
|
+
import { SqliteStore } from "./sqlite_store.js";
|
|
3
|
+
export interface ParsedModelTarget {
|
|
4
|
+
provider: ModelProvider;
|
|
5
|
+
model: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function parseModelTarget(raw?: string, defaultProvider?: ModelProvider, defaultModel?: string): ParsedModelTarget | null;
|
|
8
|
+
export declare function extractJsonPayload(text: string): string;
|
|
9
|
+
export interface DeterministicAnchorResult {
|
|
10
|
+
paths: string[];
|
|
11
|
+
ipsAndEndpoints: string[];
|
|
12
|
+
nodesAndEnvironments: string[];
|
|
13
|
+
dates: string[];
|
|
14
|
+
formattedText: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Extracts hard, deterministic entities (filesystem paths, IPv4/IPv6 addresses,
|
|
18
|
+
* network ports, URLs, cluster nodes/containers, and timestamps) from raw working facts
|
|
19
|
+
* to guarantee zero compression loss during AutoDream state consolidation.
|
|
20
|
+
*/
|
|
21
|
+
export declare function extractDeterministicAnchor(sources: string[]): DeterministicAnchorResult;
|
|
22
|
+
export declare class CognitiveAgents {
|
|
23
|
+
private config;
|
|
24
|
+
private store;
|
|
25
|
+
private genAI;
|
|
26
|
+
constructor(config: MemoryConfig, store: SqliteStore);
|
|
27
|
+
private sanitizeTag;
|
|
28
|
+
private stripLeadingTag;
|
|
29
|
+
private normalizeTriageFact;
|
|
30
|
+
private getGenAIClient;
|
|
31
|
+
private getOllamaApiUrl;
|
|
32
|
+
getAgentsMatrix(): {
|
|
33
|
+
GATEKEEPER: AgentModelConfig;
|
|
34
|
+
QUERY_EXPANDER: AgentModelConfig;
|
|
35
|
+
NOTARY: AgentModelConfig;
|
|
36
|
+
STATE_ORCHESTRATOR: AgentModelConfig;
|
|
37
|
+
SEMANTIC_ARBITER: AgentModelConfig;
|
|
38
|
+
EMBEDDER: AgentModelConfig;
|
|
39
|
+
};
|
|
40
|
+
getEmbedding(text: string, signal?: AbortSignal): Promise<number[]>;
|
|
41
|
+
executeAgent(agentConfig: AgentModelConfig, systemPrompt: string, userPrompt: string, isJson?: boolean, signal?: AbortSignal): Promise<string>;
|
|
42
|
+
private getResponseSchema;
|
|
43
|
+
contextualizeQuery(originalQuery: string, shortHistory: string): Promise<string>;
|
|
44
|
+
/**
|
|
45
|
+
* Directly ingests a unified memory fact into SQLite (FTS5 + Int8 Vector).
|
|
46
|
+
* Automatically performs consistency auditing via Semantic Arbiter if enabled,
|
|
47
|
+
* deactivating superseded facts and tagging the record with its origin source.
|
|
48
|
+
*
|
|
49
|
+
* @param fact - Complete fact string to ingest.
|
|
50
|
+
* @param userId - Target user identifier.
|
|
51
|
+
* @param protectedIds - Array of newly generated UUIDs that should not be superseded in the same batch.
|
|
52
|
+
* @param signal - Optional AbortSignal.
|
|
53
|
+
* @param source - Project or origin identifier (e.g. 'TOTALCONNECT', 'system').
|
|
54
|
+
*/
|
|
55
|
+
injectUnifiedFact(fact: string, userId?: string, protectedIds?: string[], signal?: AbortSignal, source?: string, skipArbiter?: boolean): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Processes raw text or conversational turns through the cognitive pipeline:
|
|
58
|
+
* Layer 1: Regex chatter filtering.
|
|
59
|
+
* Layer 2: Gatekeeper noise classifier.
|
|
60
|
+
* Layer 3: Notary atomic fact compilation.
|
|
61
|
+
* Layer 4: Semantic Arbiter collision auditing and SQLite persistence with source tagging.
|
|
62
|
+
*
|
|
63
|
+
* @param text - Raw message or conversational turn.
|
|
64
|
+
* @param userId - Target user identifier.
|
|
65
|
+
* @param signal - Optional AbortSignal.
|
|
66
|
+
* @param source - Subproject or client origin label.
|
|
67
|
+
*/
|
|
68
|
+
saveMemory(text: string, userId?: string, signal?: AbortSignal, source?: string): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Orchestrates the AutoDream consolidation cycle:
|
|
71
|
+
* 1. Applies deterministic TTL pruning on working notes.
|
|
72
|
+
* 2. Auto-archives expired unresolved incubator cases into long-term memory.
|
|
73
|
+
* 3. Executes the State Orchestrator agent to generate executive narrative and triage cards.
|
|
74
|
+
* 4. Enforces the Deterministic Cross-Topic Preservation Guardrail: items from other
|
|
75
|
+
* projects are guaranteed never to be dropped or overwritten.
|
|
76
|
+
* 5. Saves the updated unified dashboard singleton in SQLite under DASHBOARD_UUID.
|
|
77
|
+
*
|
|
78
|
+
* @param userId - Target user identifier.
|
|
79
|
+
* @param currentSource - Subproject or client source triggering consolidation (e.g. 'TOTALCONNECT').
|
|
80
|
+
* @returns AutoDreamResult with executive summary, active dashboard items, and triage cards.
|
|
81
|
+
*/
|
|
82
|
+
runAutoDream(userId?: string, currentSource?: string, signal?: AbortSignal): Promise<AutoDreamResult>;
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=cognitive_agents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cognitive_agents.d.ts","sourceRoot":"","sources":["../src/cognitive_agents.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,gBAAgB,EAAE,KAAK,eAAe,EAA0D,KAAK,aAAa,EAAsC,MAAM,YAAY,CAAC;AAC5M,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,aAAa,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,gBAAgB,CAC9B,GAAG,CAAC,EAAE,MAAM,EACZ,eAAe,GAAE,aAAwB,EACzC,YAAY,GAAE,MAAgC,GAC7C,iBAAiB,GAAG,IAAI,CAyB1B;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYvD;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,oBAAoB,EAAE,MAAM,EAAE,CAAC;IAC/B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,yBAAyB,CAkDvF;AAgBD,qBAAa,eAAe;IAC1B,OAAO,CAAC,MAAM,CAAyB;IACvC,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAa;gBAEd,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW;IAmBpD,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,mBAAmB;YAoCb,cAAc;IAc5B,OAAO,CAAC,eAAe;IAQhB,eAAe;;;;;;;;IA2IT,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IA0EnE,YAAY,CACvB,WAAW,EAAE,gBAAgB,EAC7B,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,GAAE,OAAe,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC;IAsIlB,OAAO,CAAC,iBAAiB;IAoFZ,kBAAkB,CAAC,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAsD7F;;;;;;;;;;OAUG;IACU,iBAAiB,CAC5B,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,MAA2B,EACnC,YAAY,GAAE,MAAM,EAAO,EAC3B,MAAM,CAAC,EAAE,WAAW,EACpB,MAAM,GAAE,MAA8C,EACtD,WAAW,GAAE,OAAe,GAC3B,OAAO,CAAC,IAAI,CAAC;IAoFhB;;;;;;;;;;;OAWG;IACU,UAAU,CACrB,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,MAA2B,EACnC,MAAM,CAAC,EAAE,WAAW,EACpB,MAAM,GAAE,MAA8C,GACrD,OAAO,CAAC,IAAI,CAAC;IA0EhB;;;;;;;;;;;;OAYG;IACU,YAAY,CACvB,MAAM,GAAE,MAA2B,EACnC,aAAa,CAAC,EAAE,MAAM,EACtB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,eAAe,CAAC;CA0T5B"}
|