memosebui 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,915 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { MEMORY_CATEGORIES, } from "../types/mind.js";
7
+ export const DEFAULT_DIMENSIONS = 384;
8
+ export const SCHEMA_SQL = `
9
+ CREATE TABLE IF NOT EXISTS projects (
10
+ id TEXT PRIMARY KEY,
11
+ name TEXT NOT NULL,
12
+ root_path TEXT NOT NULL,
13
+ updated_at TEXT NOT NULL
14
+ );
15
+
16
+ CREATE TABLE IF NOT EXISTS memories (
17
+ id TEXT PRIMARY KEY,
18
+ project_id TEXT NOT NULL,
19
+ category TEXT NOT NULL,
20
+ title TEXT NOT NULL,
21
+ content TEXT NOT NULL,
22
+ tags TEXT NOT NULL DEFAULT '[]',
23
+ source_agent TEXT,
24
+ content_hash TEXT NOT NULL,
25
+ token_count INTEGER NOT NULL DEFAULT 1,
26
+ importance REAL NOT NULL DEFAULT 0.5,
27
+ access_count INTEGER NOT NULL DEFAULT 0,
28
+ created_at TEXT NOT NULL,
29
+ updated_at TEXT NOT NULL,
30
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
31
+ UNIQUE (project_id, content_hash)
32
+ );
33
+
34
+ CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id);
35
+ CREATE INDEX IF NOT EXISTS idx_memories_category ON memories(project_id, category);
36
+ CREATE INDEX IF NOT EXISTS idx_memories_hash ON memories(project_id, content_hash);
37
+
38
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
39
+ memory_id UNINDEXED,
40
+ project_id UNINDEXED,
41
+ title,
42
+ content,
43
+ tags
44
+ );
45
+
46
+ CREATE TABLE IF NOT EXISTS memory_vectors (
47
+ memory_id TEXT PRIMARY KEY,
48
+ dimensions INTEGER NOT NULL,
49
+ embedding BLOB NOT NULL,
50
+ model TEXT NOT NULL,
51
+ FOREIGN KEY (memory_id) REFERENCES memories(id) ON DELETE CASCADE
52
+ );
53
+
54
+ CREATE TABLE IF NOT EXISTS memory_tombstones (
55
+ memory_id TEXT PRIMARY KEY,
56
+ project_id TEXT NOT NULL,
57
+ content_hash TEXT NOT NULL,
58
+ deleted_at TEXT NOT NULL,
59
+ origin_node_id TEXT
60
+ );
61
+
62
+ CREATE INDEX IF NOT EXISTS idx_tombstones_updated ON memory_tombstones(deleted_at);
63
+ CREATE INDEX IF NOT EXISTS idx_tombstones_project_hash ON memory_tombstones(project_id, content_hash);
64
+
65
+ CREATE TABLE IF NOT EXISTS node_meta (
66
+ key TEXT PRIMARY KEY,
67
+ value TEXT NOT NULL,
68
+ updated_at TEXT NOT NULL
69
+ );
70
+
71
+ CREATE TABLE IF NOT EXISTS sync_peers (
72
+ id TEXT PRIMARY KEY,
73
+ peer_node_id TEXT,
74
+ role TEXT NOT NULL,
75
+ name TEXT NOT NULL,
76
+ url TEXT NOT NULL UNIQUE,
77
+ auth_token TEXT,
78
+ last_sync_at TEXT,
79
+ last_status TEXT,
80
+ updated_at TEXT NOT NULL
81
+ );
82
+
83
+ CREATE INDEX IF NOT EXISTS idx_sync_peers_role ON sync_peers(role);
84
+
85
+ CREATE TABLE IF NOT EXISTS sync_groups (
86
+ id TEXT PRIMARY KEY,
87
+ name TEXT NOT NULL UNIQUE,
88
+ description TEXT NOT NULL DEFAULT '',
89
+ projects TEXT NOT NULL DEFAULT '["*"]',
90
+ categories TEXT NOT NULL DEFAULT '["*"]',
91
+ permissions TEXT NOT NULL DEFAULT 'readwrite',
92
+ group_token TEXT,
93
+ created_at TEXT NOT NULL,
94
+ updated_at TEXT NOT NULL
95
+ );
96
+
97
+ CREATE TABLE IF NOT EXISTS sync_group_members (
98
+ group_id TEXT NOT NULL,
99
+ peer_identifier TEXT NOT NULL,
100
+ added_at TEXT NOT NULL,
101
+ PRIMARY KEY (group_id, peer_identifier),
102
+ FOREIGN KEY (group_id) REFERENCES sync_groups(id) ON DELETE CASCADE
103
+ );
104
+
105
+ CREATE INDEX IF NOT EXISTS idx_sync_group_members_peer ON sync_group_members(peer_identifier);
106
+ `;
107
+ export function isMemoryCategory(value) {
108
+ return MEMORY_CATEGORIES.includes(value);
109
+ }
110
+ export function slugifyProjectId(raw) {
111
+ const withoutScope = raw.trim().replace(/^@[^/]+\//, '');
112
+ const slug = withoutScope
113
+ .toLowerCase()
114
+ .replace(/[^a-z0-9-]+/g, '-')
115
+ .replace(/-+/g, '-')
116
+ .replace(/^-+|-+$/g, '');
117
+ return slug || 'default-project';
118
+ }
119
+ export function estimateTokens(text) {
120
+ const trimmed = text.trim();
121
+ if (trimmed.length === 0)
122
+ return 0;
123
+ return Math.max(1, Math.ceil(trimmed.length / 4));
124
+ }
125
+ export function cosineSimilarity(a, b) {
126
+ const len = Math.min(a.length, b.length);
127
+ if (len === 0)
128
+ return 0;
129
+ let dot = 0;
130
+ let normA = 0;
131
+ let normB = 0;
132
+ for (let i = 0; i < len; i++) {
133
+ const va = a[i];
134
+ const vb = b[i];
135
+ dot += va * vb;
136
+ normA += va * va;
137
+ normB += vb * vb;
138
+ }
139
+ if (normA === 0 || normB === 0)
140
+ return 0;
141
+ return dot / Math.sqrt(normA * normB);
142
+ }
143
+ export function serializeVector(vec) {
144
+ return new Uint8Array(vec.buffer, vec.byteOffset, vec.byteLength);
145
+ }
146
+ export function deserializeVector(blob) {
147
+ const usableLength = blob.byteLength - (blob.byteLength % 4);
148
+ const copy = new Uint8Array(usableLength);
149
+ copy.set(blob.subarray(0, usableLength));
150
+ return new Float32Array(copy.buffer);
151
+ }
152
+ function fnv1a32(input, seed = 0x811c9dc5) {
153
+ let hash = seed >>> 0;
154
+ for (let i = 0; i < input.length; i++) {
155
+ hash ^= input.charCodeAt(i);
156
+ hash = Math.imul(hash, 0x01000193) >>> 0;
157
+ }
158
+ return hash >>> 0;
159
+ }
160
+ export class LocalFeatureHashEmbedder {
161
+ model = 'local-feature-hash-v1';
162
+ dimensions;
163
+ constructor(dimensions = DEFAULT_DIMENSIONS) {
164
+ this.dimensions = dimensions;
165
+ }
166
+ embed(text) {
167
+ const vec = new Float32Array(this.dimensions);
168
+ const normalized = text.toLowerCase().normalize('NFKD');
169
+ const words = normalized.match(/[a-z0-9]+/g) ?? [];
170
+ if (words.length === 0)
171
+ return vec;
172
+ const addFeature = (feature, weight) => {
173
+ const h1 = fnv1a32(feature, 0x811c9dc5);
174
+ const h2 = fnv1a32(feature, 0x9e3779b9);
175
+ const index = h1 % this.dimensions;
176
+ const sign = (h2 & 1) === 0 ? 1 : -1;
177
+ vec[index] = vec[index] + sign * weight;
178
+ };
179
+ for (let i = 0; i < words.length; i++) {
180
+ const word = words[i];
181
+ addFeature(`w:${word}`, 2.0);
182
+ if (word.length >= 4)
183
+ addFeature(`p4:${word.slice(0, 4)}`, 1.0);
184
+ if (word.length >= 5)
185
+ addFeature(`p5:${word.slice(0, 5)}`, 1.0);
186
+ if (i + 1 < words.length) {
187
+ addFeature(`b:${word}_${words[i + 1]}`, 1.5);
188
+ }
189
+ const padded = `^${word}$`;
190
+ for (let j = 0; j <= padded.length - 3; j++) {
191
+ addFeature(`c3:${padded.slice(j, j + 3)}`, 0.75);
192
+ }
193
+ }
194
+ let normSq = 0;
195
+ for (let i = 0; i < this.dimensions; i++) {
196
+ const v = vec[i];
197
+ normSq += v * v;
198
+ }
199
+ if (normSq > 0) {
200
+ const invNorm = 1 / Math.sqrt(normSq);
201
+ for (let i = 0; i < this.dimensions; i++) {
202
+ vec[i] = vec[i] * invNorm;
203
+ }
204
+ }
205
+ return vec;
206
+ }
207
+ }
208
+ export function getDefaultVaultDbPath() {
209
+ if (process.env.MEMOSEB_DB_PATH && process.env.MEMOSEB_DB_PATH.trim().length > 0) {
210
+ return path.resolve(process.env.MEMOSEB_DB_PATH.trim());
211
+ }
212
+ const xdgData = process.env.XDG_DATA_HOME?.trim();
213
+ const baseDir = xdgData && xdgData.length > 0
214
+ ? xdgData
215
+ : process.platform === 'win32'
216
+ ? process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
217
+ : process.platform === 'darwin'
218
+ ? path.join(os.homedir(), 'Library', 'Application Support')
219
+ : path.join(os.homedir(), '.local', 'share');
220
+ return path.join(baseDir, 'memoseb', 'vault.sqlite');
221
+ }
222
+ function parseTags(raw) {
223
+ try {
224
+ const parsed = JSON.parse(raw);
225
+ if (Array.isArray(parsed)) {
226
+ return parsed
227
+ .filter((item) => typeof item === 'string')
228
+ .map((item) => item.trim())
229
+ .filter((item) => item.length > 0);
230
+ }
231
+ }
232
+ catch {
233
+ // ignore malformed json
234
+ }
235
+ return [];
236
+ }
237
+ function mapRowToMemoryRecord(row) {
238
+ const category = isMemoryCategory(row.category)
239
+ ? row.category
240
+ : 'domain';
241
+ return {
242
+ id: row.id,
243
+ projectId: row.project_id,
244
+ category,
245
+ title: row.title,
246
+ content: row.content,
247
+ tags: parseTags(row.tags),
248
+ sourceAgent: row.source_agent ?? null,
249
+ contentHash: row.content_hash,
250
+ tokenCount: Number(row.token_count),
251
+ importance: Number(row.importance),
252
+ accessCount: Number(row.access_count),
253
+ createdAt: row.created_at,
254
+ updatedAt: row.updated_at,
255
+ };
256
+ }
257
+ export function sanitizeFtsQuery(query) {
258
+ const tokens = query
259
+ .toLowerCase()
260
+ .match(/[a-z0-9_]+/g)
261
+ ?.filter((token) => token.length > 0);
262
+ if (!tokens || tokens.length === 0)
263
+ return '';
264
+ const unique = Array.from(new Set(tokens));
265
+ return unique.map((token) => `"${token.replace(/"/g, '""')}"`).join(' OR ');
266
+ }
267
+ function clampImportance(value) {
268
+ if (typeof value !== 'number' || Number.isNaN(value))
269
+ return 0.5;
270
+ return Math.min(1, Math.max(0, value));
271
+ }
272
+ function deriveDefaultTitle(content) {
273
+ const firstLine = content.trim().split(/\r?\n/)[0]?.trim() ?? 'Memory';
274
+ if (firstLine.length <= 72)
275
+ return firstLine;
276
+ return `${firstLine.slice(0, 69)}...`;
277
+ }
278
+ export class VaultBridge {
279
+ dbPath;
280
+ db;
281
+ embedder;
282
+ constructor(options) {
283
+ this.dbPath = options?.dbPath ?? getDefaultVaultDbPath();
284
+ if (this.dbPath !== ':memory:') {
285
+ fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
286
+ }
287
+ this.db = new DatabaseSync(this.dbPath);
288
+ this.db.exec('PRAGMA journal_mode = WAL;');
289
+ this.db.exec('PRAGMA busy_timeout = 5000;');
290
+ this.db.exec('PRAGMA foreign_keys = ON;');
291
+ this.db.exec(SCHEMA_SQL);
292
+ this.embedder = new LocalFeatureHashEmbedder(options?.dimensions ?? DEFAULT_DIMENSIONS);
293
+ }
294
+ getStats() {
295
+ const projectRow = this.db
296
+ .prepare(`SELECT COUNT(*) AS cnt FROM projects`)
297
+ .get();
298
+ const memoryRow = this.db
299
+ .prepare(`SELECT COUNT(*) AS cnt, COALESCE(SUM(token_count), 0) AS tokens FROM memories`)
300
+ .get();
301
+ const vectorRow = this.db
302
+ .prepare(`SELECT COUNT(*) AS cnt FROM memory_vectors`)
303
+ .get();
304
+ return {
305
+ dbPath: this.dbPath,
306
+ projectCount: Number(projectRow.cnt),
307
+ memoryCount: Number(memoryRow.cnt),
308
+ vectorCount: Number(vectorRow.cnt),
309
+ totalTokens: Number(memoryRow.tokens),
310
+ };
311
+ }
312
+ listProjects() {
313
+ const rows = this.db
314
+ .prepare(`SELECT
315
+ p.id,
316
+ p.name,
317
+ p.root_path,
318
+ p.updated_at,
319
+ COUNT(m.id) AS memory_count,
320
+ COALESCE(SUM(m.token_count), 0) AS total_tokens
321
+ FROM projects p
322
+ LEFT JOIN memories m ON m.project_id = p.id
323
+ GROUP BY p.id
324
+ ORDER BY memory_count DESC, p.updated_at DESC`)
325
+ .all();
326
+ return rows.map((row) => ({
327
+ id: row.id,
328
+ name: row.name,
329
+ rootPath: row.root_path,
330
+ updatedAt: row.updated_at,
331
+ memoryCount: Number(row.memory_count),
332
+ totalTokens: Number(row.total_tokens),
333
+ }));
334
+ }
335
+ listMemoriesWithVectors(filter) {
336
+ const clauses = [];
337
+ const params = [];
338
+ if (filter?.projectId && filter.projectId !== 'all') {
339
+ clauses.push('m.project_id = ?');
340
+ params.push(slugifyProjectId(filter.projectId));
341
+ }
342
+ if (filter?.category && isMemoryCategory(filter.category)) {
343
+ clauses.push('m.category = ?');
344
+ params.push(filter.category);
345
+ }
346
+ const whereSql = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
347
+ const limitSql = typeof filter?.limit === 'number' && filter.limit > 0
348
+ ? 'LIMIT ?'
349
+ : '';
350
+ if (limitSql) {
351
+ params.push(Math.floor(filter.limit));
352
+ }
353
+ const rows = this.db
354
+ .prepare(`SELECT m.*, mv.embedding AS vector_blob
355
+ FROM memories m
356
+ LEFT JOIN memory_vectors mv ON mv.memory_id = m.id
357
+ ${whereSql}
358
+ ORDER BY m.importance DESC, m.updated_at DESC
359
+ ${limitSql}`)
360
+ .all(...params);
361
+ return rows.map((row) => {
362
+ const record = mapRowToMemoryRecord(row);
363
+ let vector = null;
364
+ if (row.vector_blob && row.vector_blob.byteLength > 0) {
365
+ vector = deserializeVector(row.vector_blob);
366
+ }
367
+ else {
368
+ vector = this.embedder.embed(`${record.title}\n${record.content}\n${record.tags.join(' ')}`);
369
+ }
370
+ return {
371
+ ...record,
372
+ vector,
373
+ };
374
+ });
375
+ }
376
+ getMemoryById(id) {
377
+ const row = this.db
378
+ .prepare(`SELECT * FROM memories WHERE id = ? LIMIT 1`)
379
+ .get(id);
380
+ if (!row)
381
+ return null;
382
+ return mapRowToMemoryRecord(row);
383
+ }
384
+ searchMemories(query, options) {
385
+ const trimmedQuery = query.trim();
386
+ const limit = Math.max(1, options?.limit ?? 20);
387
+ const maxTokens = Math.max(50, options?.maxTokens ?? 4000);
388
+ const candidates = this.listMemoriesWithVectors({
389
+ projectId: options?.projectId,
390
+ category: options?.category,
391
+ });
392
+ if (candidates.length === 0 || trimmedQuery.length === 0) {
393
+ const top = candidates.slice(0, limit).map((c) => ({
394
+ ...c,
395
+ score: Number(c.importance.toFixed(4)),
396
+ vectorScore: 0,
397
+ ftsScore: 0,
398
+ }));
399
+ return {
400
+ memories: top,
401
+ totalTokens: top.reduce((acc, m) => acc + m.tokenCount, 0),
402
+ truncatedByBudget: false,
403
+ };
404
+ }
405
+ const candidatesById = new Map();
406
+ for (const c of candidates) {
407
+ candidatesById.set(c.id, c);
408
+ }
409
+ const ftsRankById = new Map();
410
+ const ftsQuery = sanitizeFtsQuery(trimmedQuery);
411
+ if (ftsQuery.length > 0) {
412
+ try {
413
+ const ftsRows = this.db
414
+ .prepare(`SELECT memory_id, bm25(memories_fts, 2.0, 1.0, 1.5) AS bm25_score
415
+ FROM memories_fts
416
+ WHERE memories_fts MATCH ?
417
+ ORDER BY bm25_score ASC`)
418
+ .all(ftsQuery);
419
+ let rankIndex = 1;
420
+ for (const ftsRow of ftsRows) {
421
+ if (!candidatesById.has(ftsRow.memory_id))
422
+ continue;
423
+ const positiveLexical = Math.max(0, -Number(ftsRow.bm25_score));
424
+ ftsRankById.set(ftsRow.memory_id, {
425
+ rank: rankIndex,
426
+ rawScore: positiveLexical,
427
+ });
428
+ rankIndex++;
429
+ }
430
+ }
431
+ catch {
432
+ // fallback to vector similarity
433
+ }
434
+ }
435
+ const queryVec = this.embedder.embed(trimmedQuery);
436
+ const vectorScored = [];
437
+ for (const [id, entry] of candidatesById.entries()) {
438
+ const similarity = entry.vector
439
+ ? Math.max(0, cosineSimilarity(queryVec, entry.vector))
440
+ : 0;
441
+ vectorScored.push({ id, similarity });
442
+ }
443
+ vectorScored.sort((a, b) => b.similarity - a.similarity);
444
+ const vecRankById = new Map();
445
+ vectorScored.forEach((item, idx) => {
446
+ vecRankById.set(item.id, { rank: idx + 1, similarity: item.similarity });
447
+ });
448
+ const rrfK = 10;
449
+ const scoredCandidates = [];
450
+ for (const [id, entry] of candidatesById.entries()) {
451
+ const vecInfo = vecRankById.get(id);
452
+ const ftsInfo = ftsRankById.get(id);
453
+ const vectorScore = vecInfo?.similarity ?? 0;
454
+ const ftsScore = ftsInfo?.rawScore ?? 0;
455
+ if (vectorScore <= 0.05 && !ftsInfo)
456
+ continue;
457
+ const vecRrf = vecInfo && vecInfo.similarity > 0 ? 1.0 / (rrfK + vecInfo.rank) : 0;
458
+ const ftsRrf = ftsInfo ? 1.2 / (rrfK + ftsInfo.rank) : 0;
459
+ const rrfScore = vecRrf + ftsRrf + 0.25 * vectorScore + 0.1 * entry.importance;
460
+ const { vector: _vec, ...record } = entry;
461
+ scoredCandidates.push({
462
+ ...record,
463
+ score: Number(rrfScore.toFixed(6)),
464
+ vectorScore: Number(vectorScore.toFixed(6)),
465
+ ftsScore: Number(ftsScore.toFixed(6)),
466
+ });
467
+ }
468
+ scoredCandidates.sort((a, b) => {
469
+ if (b.score !== a.score)
470
+ return b.score - a.score;
471
+ return b.updatedAt.localeCompare(a.updatedAt);
472
+ });
473
+ const topLimited = scoredCandidates.slice(0, limit);
474
+ const selected = [];
475
+ let totalTokens = 0;
476
+ let truncatedByBudget = false;
477
+ for (const candidate of topLimited) {
478
+ const cost = Math.max(1, candidate.tokenCount);
479
+ if (totalTokens + cost > maxTokens) {
480
+ truncatedByBudget = true;
481
+ continue;
482
+ }
483
+ selected.push(candidate);
484
+ totalTokens += cost;
485
+ }
486
+ return {
487
+ memories: selected,
488
+ totalTokens,
489
+ truncatedByBudget,
490
+ };
491
+ }
492
+ createMemory(input) {
493
+ const trimmedContent = input.content.trim();
494
+ if (trimmedContent.length === 0) {
495
+ throw new Error('Memory content must not be empty.');
496
+ }
497
+ const projectId = slugifyProjectId(input.projectId || 'global');
498
+ const projectName = input.projectName?.trim() || projectId;
499
+ const rootPath = input.rootPath?.trim() ||
500
+ (projectId === 'global' ? 'global' : process.cwd());
501
+ const category = input.category && isMemoryCategory(input.category)
502
+ ? input.category
503
+ : 'domain';
504
+ const title = input.title && input.title.trim().length > 0
505
+ ? input.title.trim()
506
+ : deriveDefaultTitle(trimmedContent);
507
+ const tags = Array.from(new Set((input.tags ?? [])
508
+ .map((t) => t.trim())
509
+ .filter((t) => t.length > 0)));
510
+ const tagsJson = JSON.stringify(tags);
511
+ const tagsText = tags.join(' ');
512
+ const sourceAgent = input.sourceAgent?.trim() || 'memosebui';
513
+ const importance = clampImportance(input.importance);
514
+ const now = new Date().toISOString();
515
+ const contentHash = crypto
516
+ .createHash('sha256')
517
+ .update(`${projectId}:${category}:${trimmedContent}`)
518
+ .digest('hex');
519
+ this.db
520
+ .prepare(`INSERT INTO projects (id, name, root_path, updated_at)
521
+ VALUES (?, ?, ?, ?)
522
+ ON CONFLICT(id) DO UPDATE SET
523
+ name = excluded.name,
524
+ updated_at = excluded.updated_at`)
525
+ .run(projectId, projectName, rootPath, now);
526
+ const existing = this.db
527
+ .prepare(`SELECT * FROM memories WHERE project_id = ? AND content_hash = ? LIMIT 1`)
528
+ .get(projectId, contentHash);
529
+ const embeddingText = `${title}\n${trimmedContent}\n${tagsText}`;
530
+ const vector = this.embedder.embed(embeddingText);
531
+ const serializedVector = serializeVector(vector);
532
+ const tokenCount = estimateTokens(`${title}\n${trimmedContent}`);
533
+ if (existing) {
534
+ this.db
535
+ .prepare(`DELETE FROM memory_tombstones
536
+ WHERE (project_id = ? AND content_hash = ?) OR memory_id = ?`)
537
+ .run(projectId, contentHash, existing.id);
538
+ this.db
539
+ .prepare(`UPDATE memories
540
+ SET title = ?,
541
+ tags = ?,
542
+ source_agent = ?,
543
+ importance = ?,
544
+ token_count = ?,
545
+ updated_at = ?
546
+ WHERE id = ?`)
547
+ .run(title, tagsJson, sourceAgent, importance, tokenCount, now, existing.id);
548
+ this.db
549
+ .prepare(`DELETE FROM memories_fts WHERE memory_id = ?`)
550
+ .run(existing.id);
551
+ this.db
552
+ .prepare(`INSERT INTO memories_fts (memory_id, project_id, title, content, tags)
553
+ VALUES (?, ?, ?, ?, ?)`)
554
+ .run(existing.id, projectId, title, trimmedContent, tagsText);
555
+ this.db
556
+ .prepare(`INSERT INTO memory_vectors (memory_id, dimensions, embedding, model)
557
+ VALUES (?, ?, ?, ?)
558
+ ON CONFLICT(memory_id) DO UPDATE SET
559
+ dimensions = excluded.dimensions,
560
+ embedding = excluded.embedding,
561
+ model = excluded.model`)
562
+ .run(existing.id, this.embedder.dimensions, serializedVector, this.embedder.model);
563
+ const updatedRow = this.db
564
+ .prepare(`SELECT * FROM memories WHERE id = ?`)
565
+ .get(existing.id);
566
+ return {
567
+ memory: mapRowToMemoryRecord(updatedRow),
568
+ created: false,
569
+ };
570
+ }
571
+ const id = crypto.randomUUID();
572
+ this.db
573
+ .prepare(`DELETE FROM memory_tombstones
574
+ WHERE (project_id = ? AND content_hash = ?) OR memory_id = ?`)
575
+ .run(projectId, contentHash, id);
576
+ this.db
577
+ .prepare(`INSERT INTO memories (
578
+ id, project_id, category, title, content, tags, source_agent,
579
+ content_hash, token_count, importance, access_count, created_at, updated_at
580
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`)
581
+ .run(id, projectId, category, title, trimmedContent, tagsJson, sourceAgent, contentHash, tokenCount, importance, now, now);
582
+ this.db
583
+ .prepare(`INSERT INTO memories_fts (memory_id, project_id, title, content, tags)
584
+ VALUES (?, ?, ?, ?, ?)`)
585
+ .run(id, projectId, title, trimmedContent, tagsText);
586
+ this.db
587
+ .prepare(`INSERT INTO memory_vectors (memory_id, dimensions, embedding, model)
588
+ VALUES (?, ?, ?, ?)`)
589
+ .run(id, this.embedder.dimensions, serializedVector, this.embedder.model);
590
+ const insertedRow = this.db
591
+ .prepare(`SELECT * FROM memories WHERE id = ?`)
592
+ .get(id);
593
+ return {
594
+ memory: mapRowToMemoryRecord(insertedRow),
595
+ created: true,
596
+ };
597
+ }
598
+ updateMemory(id, patch) {
599
+ const existing = this.getMemoryById(id);
600
+ if (!existing)
601
+ return null;
602
+ const nextTitle = patch.title !== undefined && patch.title.trim().length > 0
603
+ ? patch.title.trim()
604
+ : existing.title;
605
+ const nextContent = patch.content !== undefined && patch.content.trim().length > 0
606
+ ? patch.content.trim()
607
+ : existing.content;
608
+ const nextCategory = patch.category && isMemoryCategory(patch.category)
609
+ ? patch.category
610
+ : existing.category;
611
+ const nextProjectId = patch.projectId && patch.projectId.trim().length > 0
612
+ ? slugifyProjectId(patch.projectId)
613
+ : existing.projectId;
614
+ const nextTags = patch.tags !== undefined
615
+ ? Array.from(new Set(patch.tags
616
+ .map((t) => t.trim())
617
+ .filter((t) => t.length > 0)))
618
+ : existing.tags;
619
+ const nextImportance = patch.importance !== undefined
620
+ ? clampImportance(patch.importance)
621
+ : existing.importance;
622
+ const now = new Date().toISOString();
623
+ const contentHash = crypto
624
+ .createHash('sha256')
625
+ .update(`${nextProjectId}:${nextCategory}:${nextContent}`)
626
+ .digest('hex');
627
+ const tagsJson = JSON.stringify(nextTags);
628
+ const tagsText = nextTags.join(' ');
629
+ const tokenCount = estimateTokens(`${nextTitle}\n${nextContent}`);
630
+ const embeddingText = `${nextTitle}\n${nextContent}\n${tagsText}`;
631
+ const vector = this.embedder.embed(embeddingText);
632
+ const serializedVector = serializeVector(vector);
633
+ this.db
634
+ .prepare(`INSERT INTO projects (id, name, root_path, updated_at)
635
+ VALUES (?, ?, ?, ?)
636
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`)
637
+ .run(nextProjectId, nextProjectId, nextProjectId, now);
638
+ this.db
639
+ .prepare(`UPDATE memories
640
+ SET project_id = ?,
641
+ category = ?,
642
+ title = ?,
643
+ content = ?,
644
+ tags = ?,
645
+ content_hash = ?,
646
+ token_count = ?,
647
+ importance = ?,
648
+ updated_at = ?
649
+ WHERE id = ?`)
650
+ .run(nextProjectId, nextCategory, nextTitle, nextContent, tagsJson, contentHash, tokenCount, nextImportance, now, id);
651
+ this.db.prepare(`DELETE FROM memories_fts WHERE memory_id = ?`).run(id);
652
+ this.db
653
+ .prepare(`INSERT INTO memories_fts (memory_id, project_id, title, content, tags)
654
+ VALUES (?, ?, ?, ?, ?)`)
655
+ .run(id, nextProjectId, nextTitle, nextContent, tagsText);
656
+ this.db
657
+ .prepare(`INSERT INTO memory_vectors (memory_id, dimensions, embedding, model)
658
+ VALUES (?, ?, ?, ?)
659
+ ON CONFLICT(memory_id) DO UPDATE SET
660
+ dimensions = excluded.dimensions,
661
+ embedding = excluded.embedding,
662
+ model = excluded.model`)
663
+ .run(id, this.embedder.dimensions, serializedVector, this.embedder.model);
664
+ return this.getMemoryById(id);
665
+ }
666
+ deleteMemory(id) {
667
+ const existing = this.db
668
+ .prepare(`SELECT id, project_id, content_hash FROM memories WHERE id = ?`)
669
+ .get(id);
670
+ if (!existing)
671
+ return false;
672
+ const now = new Date().toISOString();
673
+ const nodeId = this.getNodeId();
674
+ this.db.prepare(`DELETE FROM memories_fts WHERE memory_id = ?`).run(id);
675
+ this.db.prepare(`DELETE FROM memory_vectors WHERE memory_id = ?`).run(id);
676
+ this.db.prepare(`DELETE FROM memories WHERE id = ?`).run(id);
677
+ this.db
678
+ .prepare(`INSERT INTO memory_tombstones (
679
+ memory_id, project_id, content_hash, deleted_at, origin_node_id
680
+ ) VALUES (?, ?, ?, ?, ?)
681
+ ON CONFLICT(memory_id) DO UPDATE SET
682
+ project_id = excluded.project_id,
683
+ content_hash = excluded.content_hash,
684
+ deleted_at = excluded.deleted_at,
685
+ origin_node_id = excluded.origin_node_id`)
686
+ .run(existing.id, existing.project_id, existing.content_hash, now, nodeId);
687
+ return true;
688
+ }
689
+ analyzeProjectDirectory(targetDir) {
690
+ const resolvedRoot = path.resolve(targetDir);
691
+ if (!fs.existsSync(resolvedRoot)) {
692
+ throw new Error(`Project directory does not exist: ${resolvedRoot}`);
693
+ }
694
+ let pkg = null;
695
+ const pkgPath = path.join(resolvedRoot, 'package.json');
696
+ if (fs.existsSync(pkgPath)) {
697
+ try {
698
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
699
+ }
700
+ catch {
701
+ pkg = null;
702
+ }
703
+ }
704
+ const rawName = typeof pkg?.name === 'string' && pkg.name.trim().length > 0
705
+ ? pkg.name.trim()
706
+ : path.basename(resolvedRoot);
707
+ const projectId = slugifyProjectId(rawName);
708
+ const projectName = rawName.replace(/^@[^/]+\//, '');
709
+ const manifests = [
710
+ 'package.json',
711
+ 'tsconfig.json',
712
+ 'Cargo.toml',
713
+ 'pyproject.toml',
714
+ 'go.mod',
715
+ 'Dockerfile',
716
+ ].filter((f) => fs.existsSync(path.join(resolvedRoot, f)));
717
+ const topDirs = fs
718
+ .readdirSync(resolvedRoot, { withFileTypes: true })
719
+ .filter((d) => d.isDirectory() &&
720
+ !d.name.startsWith('.') &&
721
+ d.name !== 'node_modules' &&
722
+ d.name !== 'dist' &&
723
+ d.name !== 'target')
724
+ .map((d) => d.name)
725
+ .sort();
726
+ const archContent = [
727
+ `Proyecto: ${projectName} (${projectId}).`,
728
+ manifests.length > 0
729
+ ? `Manifiestos detectados: ${manifests.join(', ')}.`
730
+ : '',
731
+ topDirs.length > 0 ? `Directorios raíz: ${topDirs.join(', ')}.` : '',
732
+ ]
733
+ .filter(Boolean)
734
+ .join(' ');
735
+ const scriptsObj = pkg?.scripts && typeof pkg.scripts === 'object'
736
+ ? pkg.scripts
737
+ : {};
738
+ const scriptEntries = Object.entries(scriptsObj)
739
+ .slice(0, 8)
740
+ .map(([k, v]) => `${k}: "${v}"`);
741
+ const convContent = scriptEntries.length > 0
742
+ ? `Scripts npm: ${scriptEntries.join('; ')}.`
743
+ : `Repositorio ${projectName} ubicado en ${resolvedRoot}.`;
744
+ const desc = typeof pkg?.description === 'string' && pkg.description.trim().length > 0
745
+ ? pkg.description.trim()
746
+ : `Dominio funcional del proyecto ${projectName} (${projectId}).`;
747
+ const drafts = [
748
+ {
749
+ category: 'architecture',
750
+ title: `Arquitectura y topología de ${projectName}`,
751
+ content: archContent,
752
+ tags: ['architecture', 'topology', projectId],
753
+ importance: 0.9,
754
+ },
755
+ {
756
+ category: 'convention',
757
+ title: `Convenciones, scripts y verificación de ${projectName}`,
758
+ content: convContent,
759
+ tags: ['convention', 'scripts', 'verification'],
760
+ importance: 0.85,
761
+ },
762
+ {
763
+ category: 'domain',
764
+ title: `Propósito funcional y dominio de ${projectName}`,
765
+ content: `Descripción: ${desc}`,
766
+ tags: ['domain', 'overview', projectId],
767
+ importance: 0.8,
768
+ },
769
+ ];
770
+ const stored = [];
771
+ for (const draft of drafts) {
772
+ const res = this.createMemory({
773
+ projectId,
774
+ projectName,
775
+ rootPath: resolvedRoot,
776
+ category: draft.category,
777
+ title: draft.title,
778
+ content: draft.content,
779
+ tags: draft.tags,
780
+ importance: draft.importance,
781
+ sourceAgent: 'memosebui-analyzer',
782
+ });
783
+ stored.push(res.memory);
784
+ }
785
+ return {
786
+ projectId,
787
+ projectName,
788
+ rootPath: resolvedRoot,
789
+ stored,
790
+ };
791
+ }
792
+ getNodeId() {
793
+ const row = this.db
794
+ .prepare(`SELECT value FROM node_meta WHERE key = 'node.id'`)
795
+ .get();
796
+ if (row && row.value.trim().length > 0) {
797
+ return row.value.trim();
798
+ }
799
+ const newId = crypto.randomUUID();
800
+ const now = new Date().toISOString();
801
+ this.db
802
+ .prepare(`INSERT INTO node_meta (key, value, updated_at)
803
+ VALUES ('node.id', ?, ?)
804
+ ON CONFLICT(key) DO UPDATE SET
805
+ value = excluded.value,
806
+ updated_at = excluded.updated_at`)
807
+ .run(newId, now);
808
+ return newId;
809
+ }
810
+ getNodeConfig() {
811
+ const rows = this.db
812
+ .prepare(`SELECT key, value FROM node_meta`)
813
+ .all();
814
+ const meta = new Map();
815
+ for (const r of rows) {
816
+ meta.set(r.key, r.value);
817
+ }
818
+ const nodeId = this.getNodeId();
819
+ const rawName = meta.get('node.name')?.trim();
820
+ const nodeName = rawName && rawName.length > 0 ? rawName : os.hostname();
821
+ const enabled = meta.get('node.enabled') === 'true';
822
+ const rawRole = meta.get('node.role');
823
+ const role = rawRole === 'parent' || rawRole === 'child' ? rawRole : 'standalone';
824
+ const listenHost = meta.get('node.listen_host')?.trim() || '0.0.0.0';
825
+ const rawPort = Number(meta.get('node.listen_port'));
826
+ const listenPort = Number.isInteger(rawPort) && rawPort > 0 ? rawPort : 7432;
827
+ const hasToken = Boolean(meta.get('node.auth_token')?.trim());
828
+ const authToken = hasToken ? '***redacted***' : null;
829
+ const autoSync = meta.get('node.auto_sync') !== 'false';
830
+ const lanDiscovery = meta.get('node.lan_discovery') !== 'false';
831
+ const unassignedGroupPolicy = meta.get('node.unassigned_group_policy') === 'all' ? 'all' : 'none';
832
+ return {
833
+ nodeId,
834
+ nodeName,
835
+ enabled,
836
+ role,
837
+ listenHost,
838
+ listenPort,
839
+ authToken,
840
+ autoSync,
841
+ lanDiscovery,
842
+ unassignedGroupPolicy,
843
+ };
844
+ }
845
+ listPeers() {
846
+ const rows = this.db
847
+ .prepare(`SELECT * FROM sync_peers ORDER BY updated_at DESC`)
848
+ .all();
849
+ return rows.map((row) => ({
850
+ id: row.id,
851
+ peerNodeId: row.peer_node_id ?? null,
852
+ role: row.role === 'parent' ? 'parent' : 'child',
853
+ name: row.name,
854
+ url: row.url,
855
+ lastSyncAt: row.last_sync_at ?? null,
856
+ lastStatus: row.last_status ?? null,
857
+ updatedAt: row.updated_at,
858
+ }));
859
+ }
860
+ listGroups() {
861
+ const rows = this.db
862
+ .prepare(`SELECT * FROM sync_groups ORDER BY name ASC`)
863
+ .all();
864
+ return rows.map((row) => {
865
+ const members = this.db
866
+ .prepare(`SELECT peer_identifier FROM sync_group_members
867
+ WHERE group_id = ?
868
+ ORDER BY added_at ASC`)
869
+ .all(row.id);
870
+ let projects = ['*'];
871
+ try {
872
+ const parsed = JSON.parse(row.projects);
873
+ if (Array.isArray(parsed))
874
+ projects = parsed.map(String);
875
+ }
876
+ catch { }
877
+ let categories = ['*'];
878
+ try {
879
+ const parsed = JSON.parse(row.categories);
880
+ if (Array.isArray(parsed))
881
+ categories = parsed.map(String);
882
+ }
883
+ catch { }
884
+ const permissions = row.permissions === 'readonly' || row.permissions === 'writeonly'
885
+ ? row.permissions
886
+ : 'readwrite';
887
+ return {
888
+ id: row.id,
889
+ name: row.name,
890
+ description: row.description ?? '',
891
+ projects,
892
+ categories,
893
+ permissions,
894
+ memberNodeIds: members.map((m) => m.peer_identifier),
895
+ createdAt: row.created_at,
896
+ updatedAt: row.updated_at,
897
+ };
898
+ });
899
+ }
900
+ getFingerprint() {
901
+ const row = this.db
902
+ .prepare(`SELECT
903
+ COUNT(*) AS mem_cnt,
904
+ COALESCE(MAX(updated_at), '') AS max_upd,
905
+ (SELECT COUNT(*) FROM memory_tombstones) AS tomb_cnt,
906
+ (SELECT COALESCE(MAX(deleted_at), '') FROM memory_tombstones) AS max_del
907
+ FROM memories`)
908
+ .get();
909
+ return `${row.mem_cnt}:${row.max_upd}:${row.tomb_cnt}:${row.max_del}`;
910
+ }
911
+ close() {
912
+ this.db.close();
913
+ }
914
+ }
915
+ //# sourceMappingURL=vault-bridge.js.map