@hasna/mementos 0.7.0 → 0.8.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.
package/dist/cli/index.js CHANGED
@@ -2432,6 +2432,75 @@ var init_database = __esm(() => {
2432
2432
  ALTER TABLE memories ADD COLUMN recall_count INTEGER NOT NULL DEFAULT 0;
2433
2433
  CREATE INDEX IF NOT EXISTS idx_memories_recall_count ON memories(recall_count DESC);
2434
2434
  INSERT OR IGNORE INTO _migrations (id) VALUES (9);
2435
+ `,
2436
+ `
2437
+ CREATE TABLE IF NOT EXISTS synthesis_events (
2438
+ id TEXT PRIMARY KEY,
2439
+ event_type TEXT NOT NULL CHECK(event_type IN ('recalled','searched','saved','updated','deleted','injected')),
2440
+ memory_id TEXT,
2441
+ agent_id TEXT,
2442
+ project_id TEXT,
2443
+ session_id TEXT,
2444
+ query TEXT,
2445
+ importance_at_time INTEGER,
2446
+ metadata TEXT NOT NULL DEFAULT '{}',
2447
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
2448
+ );
2449
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_memory ON synthesis_events(memory_id);
2450
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_project ON synthesis_events(project_id);
2451
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_type ON synthesis_events(event_type);
2452
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_created ON synthesis_events(created_at);
2453
+ INSERT OR IGNORE INTO _migrations (id) VALUES (11);
2454
+ `,
2455
+ `
2456
+ CREATE TABLE IF NOT EXISTS synthesis_runs (
2457
+ id TEXT PRIMARY KEY,
2458
+ triggered_by TEXT NOT NULL DEFAULT 'manual' CHECK(triggered_by IN ('scheduler','manual','threshold','hook')),
2459
+ project_id TEXT,
2460
+ agent_id TEXT,
2461
+ corpus_size INTEGER NOT NULL DEFAULT 0,
2462
+ proposals_generated INTEGER NOT NULL DEFAULT 0,
2463
+ proposals_accepted INTEGER NOT NULL DEFAULT 0,
2464
+ proposals_rejected INTEGER NOT NULL DEFAULT 0,
2465
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','running','completed','failed','rolled_back')),
2466
+ error TEXT,
2467
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
2468
+ completed_at TEXT
2469
+ );
2470
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_project ON synthesis_runs(project_id);
2471
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_status ON synthesis_runs(status);
2472
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_started ON synthesis_runs(started_at);
2473
+
2474
+ CREATE TABLE IF NOT EXISTS synthesis_proposals (
2475
+ id TEXT PRIMARY KEY,
2476
+ run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
2477
+ proposal_type TEXT NOT NULL CHECK(proposal_type IN ('merge','archive','promote','update_value','add_tag','remove_duplicate')),
2478
+ memory_ids TEXT NOT NULL DEFAULT '[]',
2479
+ target_memory_id TEXT,
2480
+ proposed_changes TEXT NOT NULL DEFAULT '{}',
2481
+ reasoning TEXT,
2482
+ confidence REAL NOT NULL DEFAULT 0.5,
2483
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','accepted','rejected','rolled_back')),
2484
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
2485
+ executed_at TEXT,
2486
+ rollback_data TEXT
2487
+ );
2488
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_run ON synthesis_proposals(run_id);
2489
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_status ON synthesis_proposals(status);
2490
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_type ON synthesis_proposals(proposal_type);
2491
+
2492
+ CREATE TABLE IF NOT EXISTS synthesis_metrics (
2493
+ id TEXT PRIMARY KEY,
2494
+ run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
2495
+ metric_type TEXT NOT NULL,
2496
+ value REAL NOT NULL,
2497
+ baseline REAL,
2498
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
2499
+ );
2500
+ CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_run ON synthesis_metrics(run_id);
2501
+ CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_type ON synthesis_metrics(metric_type);
2502
+
2503
+ INSERT OR IGNORE INTO _migrations (id) VALUES (12);
2435
2504
  `,
2436
2505
  `
2437
2506
  CREATE TABLE IF NOT EXISTS webhook_hooks (
@@ -4928,6 +4997,294 @@ var init_webhook_hooks = __esm(() => {
4928
4997
  init_database();
4929
4998
  });
4930
4999
 
5000
+ // src/db/synthesis.ts
5001
+ var exports_synthesis = {};
5002
+ __export(exports_synthesis, {
5003
+ updateSynthesisRun: () => updateSynthesisRun,
5004
+ updateProposal: () => updateProposal,
5005
+ recordSynthesisEvent: () => recordSynthesisEvent,
5006
+ listSynthesisRuns: () => listSynthesisRuns,
5007
+ listSynthesisEvents: () => listSynthesisEvents,
5008
+ listProposals: () => listProposals,
5009
+ listMetrics: () => listMetrics,
5010
+ getSynthesisRun: () => getSynthesisRun,
5011
+ getProposal: () => getProposal,
5012
+ createSynthesisRun: () => createSynthesisRun,
5013
+ createProposal: () => createProposal,
5014
+ createMetric: () => createMetric
5015
+ });
5016
+ function parseRunRow(row) {
5017
+ return {
5018
+ id: row["id"],
5019
+ triggered_by: row["triggered_by"],
5020
+ project_id: row["project_id"] || null,
5021
+ agent_id: row["agent_id"] || null,
5022
+ corpus_size: row["corpus_size"],
5023
+ proposals_generated: row["proposals_generated"],
5024
+ proposals_accepted: row["proposals_accepted"],
5025
+ proposals_rejected: row["proposals_rejected"],
5026
+ status: row["status"],
5027
+ error: row["error"] || null,
5028
+ started_at: row["started_at"],
5029
+ completed_at: row["completed_at"] || null
5030
+ };
5031
+ }
5032
+ function parseProposalRow(row) {
5033
+ return {
5034
+ id: row["id"],
5035
+ run_id: row["run_id"],
5036
+ proposal_type: row["proposal_type"],
5037
+ memory_ids: JSON.parse(row["memory_ids"] || "[]"),
5038
+ target_memory_id: row["target_memory_id"] || null,
5039
+ proposed_changes: JSON.parse(row["proposed_changes"] || "{}"),
5040
+ reasoning: row["reasoning"] || null,
5041
+ confidence: row["confidence"],
5042
+ status: row["status"],
5043
+ created_at: row["created_at"],
5044
+ executed_at: row["executed_at"] || null,
5045
+ rollback_data: row["rollback_data"] ? JSON.parse(row["rollback_data"]) : null
5046
+ };
5047
+ }
5048
+ function parseMetricRow(row) {
5049
+ return {
5050
+ id: row["id"],
5051
+ run_id: row["run_id"],
5052
+ metric_type: row["metric_type"],
5053
+ value: row["value"],
5054
+ baseline: row["baseline"] != null ? row["baseline"] : null,
5055
+ created_at: row["created_at"]
5056
+ };
5057
+ }
5058
+ function parseEventRow(row) {
5059
+ return {
5060
+ id: row["id"],
5061
+ event_type: row["event_type"],
5062
+ memory_id: row["memory_id"] || null,
5063
+ agent_id: row["agent_id"] || null,
5064
+ project_id: row["project_id"] || null,
5065
+ session_id: row["session_id"] || null,
5066
+ query: row["query"] || null,
5067
+ importance_at_time: row["importance_at_time"] != null ? row["importance_at_time"] : null,
5068
+ metadata: JSON.parse(row["metadata"] || "{}"),
5069
+ created_at: row["created_at"]
5070
+ };
5071
+ }
5072
+ function createSynthesisRun(input, db) {
5073
+ const d = db || getDatabase();
5074
+ const id = shortUuid();
5075
+ const timestamp = now();
5076
+ d.run(`INSERT INTO synthesis_runs (id, triggered_by, project_id, agent_id, corpus_size, proposals_generated, proposals_accepted, proposals_rejected, status, started_at)
5077
+ VALUES (?, ?, ?, ?, ?, 0, 0, 0, 'pending', ?)`, [
5078
+ id,
5079
+ input.triggered_by,
5080
+ input.project_id ?? null,
5081
+ input.agent_id ?? null,
5082
+ input.corpus_size ?? 0,
5083
+ timestamp
5084
+ ]);
5085
+ return getSynthesisRun(id, d);
5086
+ }
5087
+ function getSynthesisRun(id, db) {
5088
+ const d = db || getDatabase();
5089
+ const row = d.query("SELECT * FROM synthesis_runs WHERE id = ?").get(id);
5090
+ if (!row)
5091
+ return null;
5092
+ return parseRunRow(row);
5093
+ }
5094
+ function listSynthesisRuns(filter, db) {
5095
+ const d = db || getDatabase();
5096
+ const conditions = [];
5097
+ const params = [];
5098
+ if (filter.project_id !== undefined) {
5099
+ if (filter.project_id === null) {
5100
+ conditions.push("project_id IS NULL");
5101
+ } else {
5102
+ conditions.push("project_id = ?");
5103
+ params.push(filter.project_id);
5104
+ }
5105
+ }
5106
+ if (filter.status) {
5107
+ conditions.push("status = ?");
5108
+ params.push(filter.status);
5109
+ }
5110
+ let sql = "SELECT * FROM synthesis_runs";
5111
+ if (conditions.length > 0) {
5112
+ sql += ` WHERE ${conditions.join(" AND ")}`;
5113
+ }
5114
+ sql += " ORDER BY started_at DESC";
5115
+ if (filter.limit) {
5116
+ sql += " LIMIT ?";
5117
+ params.push(filter.limit);
5118
+ }
5119
+ const rows = d.query(sql).all(...params);
5120
+ return rows.map(parseRunRow);
5121
+ }
5122
+ function updateSynthesisRun(id, updates, db) {
5123
+ const d = db || getDatabase();
5124
+ const sets = [];
5125
+ const params = [];
5126
+ if (updates.status !== undefined) {
5127
+ sets.push("status = ?");
5128
+ params.push(updates.status);
5129
+ }
5130
+ if (updates.error !== undefined) {
5131
+ sets.push("error = ?");
5132
+ params.push(updates.error);
5133
+ }
5134
+ if (updates.corpus_size !== undefined) {
5135
+ sets.push("corpus_size = ?");
5136
+ params.push(updates.corpus_size);
5137
+ }
5138
+ if (updates.proposals_generated !== undefined) {
5139
+ sets.push("proposals_generated = ?");
5140
+ params.push(updates.proposals_generated);
5141
+ }
5142
+ if (updates.proposals_accepted !== undefined) {
5143
+ sets.push("proposals_accepted = ?");
5144
+ params.push(updates.proposals_accepted);
5145
+ }
5146
+ if (updates.proposals_rejected !== undefined) {
5147
+ sets.push("proposals_rejected = ?");
5148
+ params.push(updates.proposals_rejected);
5149
+ }
5150
+ if (updates.completed_at !== undefined) {
5151
+ sets.push("completed_at = ?");
5152
+ params.push(updates.completed_at);
5153
+ }
5154
+ if (sets.length === 0)
5155
+ return getSynthesisRun(id, d);
5156
+ params.push(id);
5157
+ d.run(`UPDATE synthesis_runs SET ${sets.join(", ")} WHERE id = ?`, params);
5158
+ return getSynthesisRun(id, d);
5159
+ }
5160
+ function createProposal(input, db) {
5161
+ const d = db || getDatabase();
5162
+ const id = shortUuid();
5163
+ const timestamp = now();
5164
+ d.run(`INSERT INTO synthesis_proposals (id, run_id, proposal_type, memory_ids, target_memory_id, proposed_changes, reasoning, confidence, status, created_at)
5165
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`, [
5166
+ id,
5167
+ input.run_id,
5168
+ input.proposal_type,
5169
+ JSON.stringify(input.memory_ids),
5170
+ input.target_memory_id ?? null,
5171
+ JSON.stringify(input.proposed_changes),
5172
+ input.reasoning ?? null,
5173
+ input.confidence,
5174
+ timestamp
5175
+ ]);
5176
+ return getProposal(id, d);
5177
+ }
5178
+ function getProposal(id, db) {
5179
+ const d = db || getDatabase();
5180
+ const row = d.query("SELECT * FROM synthesis_proposals WHERE id = ?").get(id);
5181
+ if (!row)
5182
+ return null;
5183
+ return parseProposalRow(row);
5184
+ }
5185
+ function listProposals(run_id, filter, db) {
5186
+ const d = db || getDatabase();
5187
+ const params = [run_id];
5188
+ let sql = "SELECT * FROM synthesis_proposals WHERE run_id = ?";
5189
+ if (filter?.status) {
5190
+ sql += " AND status = ?";
5191
+ params.push(filter.status);
5192
+ }
5193
+ sql += " ORDER BY created_at ASC";
5194
+ const rows = d.query(sql).all(...params);
5195
+ return rows.map(parseProposalRow);
5196
+ }
5197
+ function updateProposal(id, updates, db) {
5198
+ const d = db || getDatabase();
5199
+ const sets = [];
5200
+ const params = [];
5201
+ if (updates.status !== undefined) {
5202
+ sets.push("status = ?");
5203
+ params.push(updates.status);
5204
+ }
5205
+ if (updates.executed_at !== undefined) {
5206
+ sets.push("executed_at = ?");
5207
+ params.push(updates.executed_at);
5208
+ }
5209
+ if (updates.rollback_data !== undefined) {
5210
+ sets.push("rollback_data = ?");
5211
+ params.push(JSON.stringify(updates.rollback_data));
5212
+ }
5213
+ if (sets.length === 0)
5214
+ return getProposal(id, d);
5215
+ params.push(id);
5216
+ d.run(`UPDATE synthesis_proposals SET ${sets.join(", ")} WHERE id = ?`, params);
5217
+ return getProposal(id, d);
5218
+ }
5219
+ function createMetric(input, db) {
5220
+ const d = db || getDatabase();
5221
+ const id = shortUuid();
5222
+ const timestamp = now();
5223
+ d.run(`INSERT INTO synthesis_metrics (id, run_id, metric_type, value, baseline, created_at)
5224
+ VALUES (?, ?, ?, ?, ?, ?)`, [id, input.run_id, input.metric_type, input.value, input.baseline ?? null, timestamp]);
5225
+ return { id, run_id: input.run_id, metric_type: input.metric_type, value: input.value, baseline: input.baseline ?? null, created_at: timestamp };
5226
+ }
5227
+ function listMetrics(run_id, db) {
5228
+ const d = db || getDatabase();
5229
+ const rows = d.query("SELECT * FROM synthesis_metrics WHERE run_id = ? ORDER BY created_at ASC").all(run_id);
5230
+ return rows.map(parseMetricRow);
5231
+ }
5232
+ function recordSynthesisEvent(input, db) {
5233
+ try {
5234
+ const d = db || getDatabase();
5235
+ const id = shortUuid();
5236
+ const timestamp = now();
5237
+ d.run(`INSERT INTO synthesis_events (id, event_type, memory_id, agent_id, project_id, session_id, query, importance_at_time, metadata, created_at)
5238
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
5239
+ id,
5240
+ input.event_type,
5241
+ input.memory_id ?? null,
5242
+ input.agent_id ?? null,
5243
+ input.project_id ?? null,
5244
+ input.session_id ?? null,
5245
+ input.query ?? null,
5246
+ input.importance_at_time ?? null,
5247
+ JSON.stringify(input.metadata ?? {}),
5248
+ timestamp
5249
+ ]);
5250
+ } catch {}
5251
+ }
5252
+ function listSynthesisEvents(filter, db) {
5253
+ const d = db || getDatabase();
5254
+ const conditions = [];
5255
+ const params = [];
5256
+ if (filter.memory_id) {
5257
+ conditions.push("memory_id = ?");
5258
+ params.push(filter.memory_id);
5259
+ }
5260
+ if (filter.project_id) {
5261
+ conditions.push("project_id = ?");
5262
+ params.push(filter.project_id);
5263
+ }
5264
+ if (filter.event_type) {
5265
+ conditions.push("event_type = ?");
5266
+ params.push(filter.event_type);
5267
+ }
5268
+ if (filter.since) {
5269
+ conditions.push("created_at >= ?");
5270
+ params.push(filter.since);
5271
+ }
5272
+ let sql = "SELECT * FROM synthesis_events";
5273
+ if (conditions.length > 0) {
5274
+ sql += ` WHERE ${conditions.join(" AND ")}`;
5275
+ }
5276
+ sql += " ORDER BY created_at DESC";
5277
+ if (filter.limit) {
5278
+ sql += " LIMIT ?";
5279
+ params.push(filter.limit);
5280
+ }
5281
+ const rows = d.query(sql).all(...params);
5282
+ return rows.map(parseEventRow);
5283
+ }
5284
+ var init_synthesis = __esm(() => {
5285
+ init_database();
5286
+ });
5287
+
4931
5288
  // src/lib/built-in-hooks.ts
4932
5289
  var exports_built_in_hooks = {};
4933
5290
  __export(exports_built_in_hooks, {
@@ -5028,6 +5385,964 @@ var init_built_in_hooks = __esm(() => {
5028
5385
  } catch {}
5029
5386
  }
5030
5387
  });
5388
+ hookRegistry.register({
5389
+ type: "PostMemorySave",
5390
+ blocking: false,
5391
+ builtin: true,
5392
+ priority: 200,
5393
+ description: "Record memory save event for synthesis analytics",
5394
+ handler: async (ctx) => {
5395
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
5396
+ recordSynthesisEvent2({
5397
+ event_type: "saved",
5398
+ memory_id: ctx.memory.id,
5399
+ agent_id: ctx.agentId,
5400
+ project_id: ctx.projectId,
5401
+ session_id: ctx.sessionId,
5402
+ importance_at_time: ctx.memory.importance
5403
+ });
5404
+ }
5405
+ });
5406
+ hookRegistry.register({
5407
+ type: "PostMemoryInject",
5408
+ blocking: false,
5409
+ builtin: true,
5410
+ priority: 200,
5411
+ description: "Record injection event for synthesis analytics",
5412
+ handler: async (ctx) => {
5413
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
5414
+ recordSynthesisEvent2({
5415
+ event_type: "injected",
5416
+ agent_id: ctx.agentId,
5417
+ project_id: ctx.projectId,
5418
+ session_id: ctx.sessionId,
5419
+ metadata: { count: ctx.memoriesCount, format: ctx.format }
5420
+ });
5421
+ }
5422
+ });
5423
+ });
5424
+
5425
+ // src/lib/synthesis/corpus-builder.ts
5426
+ function extractTerms(text) {
5427
+ const stopWords = new Set([
5428
+ "a",
5429
+ "an",
5430
+ "the",
5431
+ "is",
5432
+ "it",
5433
+ "in",
5434
+ "of",
5435
+ "for",
5436
+ "to",
5437
+ "and",
5438
+ "or",
5439
+ "but",
5440
+ "not",
5441
+ "with",
5442
+ "this",
5443
+ "that",
5444
+ "are",
5445
+ "was",
5446
+ "be",
5447
+ "by",
5448
+ "at",
5449
+ "as",
5450
+ "on",
5451
+ "has",
5452
+ "have",
5453
+ "had",
5454
+ "do",
5455
+ "did",
5456
+ "does",
5457
+ "will",
5458
+ "would",
5459
+ "can",
5460
+ "could",
5461
+ "should",
5462
+ "may",
5463
+ "might",
5464
+ "shall",
5465
+ "from",
5466
+ "into",
5467
+ "then",
5468
+ "than",
5469
+ "so",
5470
+ "if",
5471
+ "up",
5472
+ "out",
5473
+ "about",
5474
+ "its",
5475
+ "my",
5476
+ "we",
5477
+ "i",
5478
+ "you"
5479
+ ]);
5480
+ return new Set(text.toLowerCase().replace(/[^a-z0-9\s\-_]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w)));
5481
+ }
5482
+ function jaccardSimilarity(a, b) {
5483
+ if (a.size === 0 && b.size === 0)
5484
+ return 0;
5485
+ const intersection = new Set([...a].filter((x) => b.has(x)));
5486
+ const union = new Set([...a, ...b]);
5487
+ return intersection.size / union.size;
5488
+ }
5489
+ function isStale(memory) {
5490
+ if (memory.status !== "active")
5491
+ return false;
5492
+ if (memory.importance >= 7)
5493
+ return false;
5494
+ if (!memory.accessed_at)
5495
+ return true;
5496
+ const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
5497
+ return new Date(memory.accessed_at).getTime() < thirtyDaysAgo;
5498
+ }
5499
+ async function buildCorpus(options) {
5500
+ const d = options.db || getDatabase();
5501
+ const limit = options.limit ?? 500;
5502
+ const projectId = options.projectId ?? null;
5503
+ const memories = listMemories({
5504
+ status: "active",
5505
+ project_id: options.projectId,
5506
+ agent_id: options.agentId,
5507
+ limit
5508
+ }, d);
5509
+ const recallEvents = listSynthesisEvents({
5510
+ event_type: "recalled",
5511
+ project_id: options.projectId
5512
+ }, d);
5513
+ const recallCounts = new Map;
5514
+ const lastRecalledMap = new Map;
5515
+ for (const event of recallEvents) {
5516
+ if (!event.memory_id)
5517
+ continue;
5518
+ recallCounts.set(event.memory_id, (recallCounts.get(event.memory_id) ?? 0) + 1);
5519
+ const existing = lastRecalledMap.get(event.memory_id);
5520
+ if (!existing || event.created_at > existing) {
5521
+ lastRecalledMap.set(event.memory_id, event.created_at);
5522
+ }
5523
+ }
5524
+ const searchEvents = listSynthesisEvents({
5525
+ event_type: "searched",
5526
+ project_id: options.projectId
5527
+ }, d);
5528
+ const searchHits = new Map;
5529
+ for (const event of searchEvents) {
5530
+ if (!event.memory_id)
5531
+ continue;
5532
+ searchHits.set(event.memory_id, (searchHits.get(event.memory_id) ?? 0) + 1);
5533
+ }
5534
+ const termSets = new Map;
5535
+ for (const m of memories) {
5536
+ termSets.set(m.id, extractTerms(`${m.key} ${m.value} ${m.summary ?? ""}`));
5537
+ }
5538
+ const duplicateCandidates = [];
5539
+ const similarityThreshold = 0.5;
5540
+ const similarIds = new Map;
5541
+ for (let i = 0;i < memories.length; i++) {
5542
+ const a = memories[i];
5543
+ const termsA = termSets.get(a.id);
5544
+ const aSimIds = [];
5545
+ for (let j = i + 1;j < memories.length; j++) {
5546
+ const b = memories[j];
5547
+ const termsB = termSets.get(b.id);
5548
+ const sim = jaccardSimilarity(termsA, termsB);
5549
+ if (sim >= similarityThreshold) {
5550
+ duplicateCandidates.push({ a, b, similarity: sim });
5551
+ aSimIds.push(b.id);
5552
+ const bSimIds = similarIds.get(b.id) ?? [];
5553
+ bSimIds.push(a.id);
5554
+ similarIds.set(b.id, bSimIds);
5555
+ }
5556
+ }
5557
+ if (aSimIds.length > 0) {
5558
+ const existing = similarIds.get(a.id) ?? [];
5559
+ similarIds.set(a.id, [...existing, ...aSimIds]);
5560
+ }
5561
+ }
5562
+ duplicateCandidates.sort((a, b) => b.similarity - a.similarity);
5563
+ const items = memories.map((memory) => ({
5564
+ memory,
5565
+ recallCount: recallCounts.get(memory.id) ?? 0,
5566
+ lastRecalled: lastRecalledMap.get(memory.id) ?? null,
5567
+ searchHits: searchHits.get(memory.id) ?? 0,
5568
+ similarMemoryIds: similarIds.get(memory.id) ?? []
5569
+ }));
5570
+ const staleMemories = memories.filter(isStale);
5571
+ const lowImportanceHighRecall = memories.filter((m) => m.importance < 5 && (recallCounts.get(m.id) ?? 0) > 3);
5572
+ const highImportanceLowRecall = memories.filter((m) => m.importance > 7 && (recallCounts.get(m.id) ?? 0) === 0);
5573
+ return {
5574
+ projectId,
5575
+ totalMemories: memories.length,
5576
+ items,
5577
+ staleMemories,
5578
+ duplicateCandidates,
5579
+ lowImportanceHighRecall,
5580
+ highImportanceLowRecall,
5581
+ generatedAt: now()
5582
+ };
5583
+ }
5584
+ var init_corpus_builder = __esm(() => {
5585
+ init_database();
5586
+ init_memories();
5587
+ init_synthesis();
5588
+ });
5589
+
5590
+ // src/lib/synthesis/llm-analyzer.ts
5591
+ function buildCorpusPrompt(corpus, maxProposals) {
5592
+ const lines = [];
5593
+ lines.push(`## Memory Corpus Analysis`);
5594
+ lines.push(`Project: ${corpus.projectId ?? "(global)"}`);
5595
+ lines.push(`Total active memories: ${corpus.totalMemories}`);
5596
+ lines.push(`Analysis generated at: ${corpus.generatedAt}`);
5597
+ lines.push("");
5598
+ if (corpus.staleMemories.length > 0) {
5599
+ lines.push(`## Stale Memories (not accessed in 30+ days, importance < 7)`);
5600
+ lines.push(`Count: ${corpus.staleMemories.length}`);
5601
+ for (const m of corpus.staleMemories.slice(0, 30)) {
5602
+ const accessed = m.accessed_at ?? "never";
5603
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} lastAccessed=${accessed}`);
5604
+ lines.push(` value: ${m.value.slice(0, 120)}`);
5605
+ }
5606
+ lines.push("");
5607
+ }
5608
+ if (corpus.duplicateCandidates.length > 0) {
5609
+ lines.push(`## Potential Duplicates (term overlap \u2265 50%)`);
5610
+ lines.push(`Count: ${corpus.duplicateCandidates.length} pairs`);
5611
+ for (const { a, b, similarity } of corpus.duplicateCandidates.slice(0, 20)) {
5612
+ lines.push(`- similarity=${similarity.toFixed(2)}`);
5613
+ lines.push(` A id:${a.id} key="${a.key}" importance=${a.importance}: ${a.value.slice(0, 80)}`);
5614
+ lines.push(` B id:${b.id} key="${b.key}" importance=${b.importance}: ${b.value.slice(0, 80)}`);
5615
+ }
5616
+ lines.push("");
5617
+ }
5618
+ if (corpus.lowImportanceHighRecall.length > 0) {
5619
+ lines.push(`## Low Importance But High Recall (candidates for importance promotion)`);
5620
+ for (const m of corpus.lowImportanceHighRecall.slice(0, 20)) {
5621
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} recall_count=${m.access_count}`);
5622
+ }
5623
+ lines.push("");
5624
+ }
5625
+ if (corpus.highImportanceLowRecall.length > 0) {
5626
+ lines.push(`## High Importance But Never Recalled (may need value update)`);
5627
+ for (const m of corpus.highImportanceLowRecall.slice(0, 20)) {
5628
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance}: ${m.value.slice(0, 80)}`);
5629
+ }
5630
+ lines.push("");
5631
+ }
5632
+ lines.push(`## Instructions`);
5633
+ lines.push(`Generate up to ${maxProposals} proposals as a JSON array. Each proposal must have:`);
5634
+ lines.push(` - type: "merge" | "archive" | "promote" | "update_value" | "add_tag" | "remove_duplicate"`);
5635
+ lines.push(` - memory_ids: string[] (IDs this proposal acts on)`);
5636
+ lines.push(` - target_memory_id: string (optional \u2014 used for merge/remove_duplicate)`);
5637
+ lines.push(` - proposed_changes: object (e.g. {new_importance:8} or {new_value:"..."} or {tags:["x"]})`);
5638
+ lines.push(` - reasoning: string (one sentence)`);
5639
+ lines.push(` - confidence: number 0.0-1.0`);
5640
+ lines.push("");
5641
+ lines.push(`Return ONLY the JSON array. No markdown, no explanation.`);
5642
+ return lines.join(`
5643
+ `);
5644
+ }
5645
+ async function analyzeCorpus(corpus, options) {
5646
+ const startMs = Date.now();
5647
+ const maxProposals = options?.maxProposals ?? 20;
5648
+ const empty = {
5649
+ proposals: [],
5650
+ summary: "No LLM provider available.",
5651
+ analysisDurationMs: 0
5652
+ };
5653
+ let provider = options?.provider ? providerRegistry.getProvider(options.provider) : providerRegistry.getAvailable();
5654
+ if (!provider) {
5655
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5656
+ }
5657
+ const userPrompt = buildCorpusPrompt(corpus, maxProposals);
5658
+ try {
5659
+ const rawResponse = await callProviderRaw(provider, SYNTHESIS_SYSTEM_PROMPT, userPrompt);
5660
+ if (!rawResponse) {
5661
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5662
+ }
5663
+ const parsed = parseProposalsResponse(rawResponse);
5664
+ const analysisDurationMs = Date.now() - startMs;
5665
+ const validProposals = parsed.slice(0, maxProposals);
5666
+ return {
5667
+ proposals: validProposals,
5668
+ summary: buildSummary(corpus, validProposals.length),
5669
+ analysisDurationMs
5670
+ };
5671
+ } catch {
5672
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5673
+ }
5674
+ }
5675
+ async function callProviderRaw(provider, systemPrompt, userPrompt) {
5676
+ if (!provider)
5677
+ return null;
5678
+ const { config, name } = provider;
5679
+ if (!config.apiKey)
5680
+ return null;
5681
+ const timeoutMs = config.timeoutMs ?? 30000;
5682
+ try {
5683
+ if (name === "anthropic") {
5684
+ return await callAnthropic(config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
5685
+ } else if (name === "openai" || name === "cerebras" || name === "grok") {
5686
+ return await callOpenAICompat(name, config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
5687
+ }
5688
+ } catch {}
5689
+ return null;
5690
+ }
5691
+ async function callAnthropic(apiKey, model, systemPrompt, userPrompt, timeoutMs) {
5692
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
5693
+ method: "POST",
5694
+ headers: {
5695
+ "x-api-key": apiKey,
5696
+ "anthropic-version": "2023-06-01",
5697
+ "content-type": "application/json"
5698
+ },
5699
+ body: JSON.stringify({
5700
+ model,
5701
+ max_tokens: 2048,
5702
+ system: systemPrompt,
5703
+ messages: [{ role: "user", content: userPrompt }]
5704
+ }),
5705
+ signal: AbortSignal.timeout(timeoutMs)
5706
+ });
5707
+ if (!response.ok)
5708
+ return null;
5709
+ const data = await response.json();
5710
+ return data.content?.[0]?.text ?? null;
5711
+ }
5712
+ function getBaseUrlForProvider(providerName) {
5713
+ switch (providerName) {
5714
+ case "openai":
5715
+ return "https://api.openai.com/v1";
5716
+ case "cerebras":
5717
+ return "https://api.cerebras.ai/v1";
5718
+ case "grok":
5719
+ return "https://api.x.ai/v1";
5720
+ default:
5721
+ return "https://api.openai.com/v1";
5722
+ }
5723
+ }
5724
+ async function callOpenAICompat(providerName, apiKey, model, systemPrompt, userPrompt, timeoutMs) {
5725
+ const baseUrl = getBaseUrlForProvider(providerName);
5726
+ const response = await fetch(`${baseUrl}/chat/completions`, {
5727
+ method: "POST",
5728
+ headers: {
5729
+ authorization: `Bearer ${apiKey}`,
5730
+ "content-type": "application/json"
5731
+ },
5732
+ body: JSON.stringify({
5733
+ model,
5734
+ max_tokens: 2048,
5735
+ temperature: 0,
5736
+ messages: [
5737
+ { role: "system", content: systemPrompt },
5738
+ { role: "user", content: userPrompt }
5739
+ ]
5740
+ }),
5741
+ signal: AbortSignal.timeout(timeoutMs)
5742
+ });
5743
+ if (!response.ok)
5744
+ return null;
5745
+ const data = await response.json();
5746
+ return data.choices?.[0]?.message?.content ?? null;
5747
+ }
5748
+ function parseProposalsResponse(raw) {
5749
+ try {
5750
+ const cleaned = raw.replace(/^```(?:json)?\s*/m, "").replace(/\s*```$/m, "").trim();
5751
+ const parsed = JSON.parse(cleaned);
5752
+ if (!Array.isArray(parsed))
5753
+ return [];
5754
+ const validTypes = new Set([
5755
+ "merge",
5756
+ "archive",
5757
+ "promote",
5758
+ "update_value",
5759
+ "add_tag",
5760
+ "remove_duplicate"
5761
+ ]);
5762
+ return parsed.filter((item) => {
5763
+ if (!item || typeof item !== "object")
5764
+ return false;
5765
+ const p = item;
5766
+ return typeof p["type"] === "string" && validTypes.has(p["type"]) && Array.isArray(p["memory_ids"]) && typeof p["proposed_changes"] === "object" && typeof p["reasoning"] === "string" && typeof p["confidence"] === "number";
5767
+ }).map((p) => ({
5768
+ type: p.type,
5769
+ memory_ids: p.memory_ids.filter((id) => typeof id === "string"),
5770
+ target_memory_id: typeof p.target_memory_id === "string" ? p.target_memory_id : undefined,
5771
+ proposed_changes: p.proposed_changes ?? {},
5772
+ reasoning: p.reasoning,
5773
+ confidence: Math.max(0, Math.min(1, p.confidence))
5774
+ }));
5775
+ } catch {
5776
+ return [];
5777
+ }
5778
+ }
5779
+ function buildSummary(corpus, proposalCount) {
5780
+ return `Analyzed ${corpus.totalMemories} memories. ` + `Found ${corpus.staleMemories.length} stale, ` + `${corpus.duplicateCandidates.length} duplicate pairs. ` + `Generated ${proposalCount} proposals.`;
5781
+ }
5782
+ var SYNTHESIS_SYSTEM_PROMPT = "You are a memory synthesizer. Analyze this agent's memory corpus and propose consolidations to improve quality and reduce redundancy. Return ONLY a JSON array of proposal objects.";
5783
+ var init_llm_analyzer = __esm(() => {
5784
+ init_registry();
5785
+ });
5786
+
5787
+ // src/lib/synthesis/validator.ts
5788
+ function validateProposals(proposals, corpus, config) {
5789
+ const cfg = { ...DEFAULT_SAFETY_CONFIG, ...config };
5790
+ const memoryMap = new Map(corpus.items.map((item) => [item.memory.id, item.memory]));
5791
+ const rejectedProposals = [];
5792
+ const warnings = [];
5793
+ let archiveCount = 0;
5794
+ let mergeCount = 0;
5795
+ for (const proposal of proposals) {
5796
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
5797
+ archiveCount++;
5798
+ }
5799
+ if (proposal.type === "merge") {
5800
+ mergeCount++;
5801
+ }
5802
+ }
5803
+ const corpusSize = corpus.totalMemories;
5804
+ const archivePercent = corpusSize > 0 ? archiveCount / corpusSize * 100 : 0;
5805
+ const mergePercent = corpusSize > 0 ? mergeCount / corpusSize * 100 : 0;
5806
+ if (archivePercent > cfg.maxArchivePercent) {
5807
+ warnings.push(`Archive proposals (${archiveCount}) exceed ${cfg.maxArchivePercent}% of corpus (${archivePercent.toFixed(1)}%). Some will be rejected.`);
5808
+ }
5809
+ if (mergePercent > cfg.maxMergePercent) {
5810
+ warnings.push(`Merge proposals (${mergeCount}) exceed ${cfg.maxMergePercent}% of corpus (${mergePercent.toFixed(1)}%). Some will be rejected.`);
5811
+ }
5812
+ let remainingArchiveSlots = Math.floor(cfg.maxArchivePercent / 100 * corpusSize);
5813
+ let remainingMergeSlots = Math.floor(cfg.maxMergePercent / 100 * corpusSize);
5814
+ for (let i = 0;i < proposals.length; i++) {
5815
+ const proposal = proposals[i];
5816
+ const proposalRef = `proposal[${i}]`;
5817
+ if (proposal.confidence < cfg.minConfidence) {
5818
+ rejectedProposals.push({
5819
+ proposalId: proposalRef,
5820
+ reason: `Confidence ${proposal.confidence.toFixed(2)} below minimum ${cfg.minConfidence}`
5821
+ });
5822
+ continue;
5823
+ }
5824
+ const missingIds = proposal.memory_ids.filter((id) => !memoryMap.has(id));
5825
+ if (missingIds.length > 0) {
5826
+ rejectedProposals.push({
5827
+ proposalId: proposalRef,
5828
+ reason: `References unknown memory IDs: ${missingIds.join(", ")}`
5829
+ });
5830
+ continue;
5831
+ }
5832
+ if (cfg.protectPinned) {
5833
+ const pinnedIds = proposal.memory_ids.filter((id) => {
5834
+ const m = memoryMap.get(id);
5835
+ return m?.pinned === true;
5836
+ });
5837
+ if (pinnedIds.length > 0) {
5838
+ rejectedProposals.push({
5839
+ proposalId: proposalRef,
5840
+ reason: `Attempts to modify pinned memories: ${pinnedIds.join(", ")}`
5841
+ });
5842
+ continue;
5843
+ }
5844
+ }
5845
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate" || proposal.type === "merge") {
5846
+ const highImportanceIds = proposal.memory_ids.filter((id) => {
5847
+ const m = memoryMap.get(id);
5848
+ return m && m.importance >= cfg.protectHighImportance;
5849
+ });
5850
+ if (highImportanceIds.length > 0) {
5851
+ rejectedProposals.push({
5852
+ proposalId: proposalRef,
5853
+ reason: `Attempts to archive/merge memories with importance \u2265 ${cfg.protectHighImportance}: ${highImportanceIds.join(", ")}`
5854
+ });
5855
+ continue;
5856
+ }
5857
+ }
5858
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
5859
+ if (remainingArchiveSlots <= 0) {
5860
+ rejectedProposals.push({
5861
+ proposalId: proposalRef,
5862
+ reason: `Archive quota exhausted (max ${cfg.maxArchivePercent}% of corpus)`
5863
+ });
5864
+ continue;
5865
+ }
5866
+ remainingArchiveSlots--;
5867
+ }
5868
+ if (proposal.type === "merge") {
5869
+ if (remainingMergeSlots <= 0) {
5870
+ rejectedProposals.push({
5871
+ proposalId: proposalRef,
5872
+ reason: `Merge quota exhausted (max ${cfg.maxMergePercent}% of corpus)`
5873
+ });
5874
+ continue;
5875
+ }
5876
+ remainingMergeSlots--;
5877
+ }
5878
+ if (proposal.target_memory_id && !memoryMap.has(proposal.target_memory_id)) {
5879
+ rejectedProposals.push({
5880
+ proposalId: proposalRef,
5881
+ reason: `target_memory_id "${proposal.target_memory_id}" does not exist in corpus`
5882
+ });
5883
+ continue;
5884
+ }
5885
+ }
5886
+ return {
5887
+ valid: rejectedProposals.length === 0,
5888
+ rejectedProposals,
5889
+ warnings
5890
+ };
5891
+ }
5892
+ var DEFAULT_SAFETY_CONFIG;
5893
+ var init_validator = __esm(() => {
5894
+ DEFAULT_SAFETY_CONFIG = {
5895
+ maxArchivePercent: 20,
5896
+ maxMergePercent: 30,
5897
+ minConfidence: 0.6,
5898
+ protectPinned: true,
5899
+ protectHighImportance: 9
5900
+ };
5901
+ });
5902
+
5903
+ // src/lib/synthesis/executor.ts
5904
+ async function executeProposals(runId, proposals, db) {
5905
+ const d = db || getDatabase();
5906
+ let executed = 0;
5907
+ let failed = 0;
5908
+ const rollbackData = {};
5909
+ for (const proposal of proposals) {
5910
+ try {
5911
+ const rollback = executeProposal(proposal, d);
5912
+ updateProposal(proposal.id, {
5913
+ status: "accepted",
5914
+ executed_at: now(),
5915
+ rollback_data: rollback
5916
+ }, d);
5917
+ rollbackData[proposal.id] = rollback;
5918
+ executed++;
5919
+ } catch (err) {
5920
+ try {
5921
+ updateProposal(proposal.id, { status: "rejected" }, d);
5922
+ } catch {}
5923
+ failed++;
5924
+ }
5925
+ }
5926
+ return { runId, executed, failed, rollbackData };
5927
+ }
5928
+ function executeProposal(proposal, d) {
5929
+ let rollbackData = {};
5930
+ d.transaction(() => {
5931
+ switch (proposal.proposal_type) {
5932
+ case "archive":
5933
+ rollbackData = executeArchive(proposal, d);
5934
+ break;
5935
+ case "promote":
5936
+ rollbackData = executePromote(proposal, d);
5937
+ break;
5938
+ case "update_value":
5939
+ rollbackData = executeUpdateValue(proposal, d);
5940
+ break;
5941
+ case "add_tag":
5942
+ rollbackData = executeAddTag(proposal, d);
5943
+ break;
5944
+ case "merge":
5945
+ rollbackData = executeMerge(proposal, d);
5946
+ break;
5947
+ case "remove_duplicate":
5948
+ rollbackData = executeRemoveDuplicate(proposal, d);
5949
+ break;
5950
+ default:
5951
+ throw new Error(`Unknown proposal type: ${proposal.proposal_type}`);
5952
+ }
5953
+ })();
5954
+ return rollbackData;
5955
+ }
5956
+ function executeArchive(proposal, d) {
5957
+ const rollback = {};
5958
+ for (const memId of proposal.memory_ids) {
5959
+ const mem = getMemory(memId, d);
5960
+ if (!mem)
5961
+ continue;
5962
+ rollback[memId] = mem.status;
5963
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
5964
+ }
5965
+ return { old_status: rollback };
5966
+ }
5967
+ function executePromote(proposal, d) {
5968
+ const newImportance = proposal.proposed_changes["new_importance"];
5969
+ if (typeof newImportance !== "number") {
5970
+ throw new Error("promote proposal missing new_importance in proposed_changes");
5971
+ }
5972
+ const rollback = {};
5973
+ for (const memId of proposal.memory_ids) {
5974
+ const mem = getMemory(memId, d);
5975
+ if (!mem)
5976
+ continue;
5977
+ rollback[memId] = mem.importance;
5978
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [Math.max(1, Math.min(10, Math.round(newImportance))), now(), memId]);
5979
+ }
5980
+ return { old_importance: rollback };
5981
+ }
5982
+ function executeUpdateValue(proposal, d) {
5983
+ const newValue = proposal.proposed_changes["new_value"];
5984
+ if (typeof newValue !== "string") {
5985
+ throw new Error("update_value proposal missing new_value in proposed_changes");
5986
+ }
5987
+ const rollback = {};
5988
+ const memId = proposal.memory_ids[0];
5989
+ if (!memId)
5990
+ throw new Error("update_value proposal has no memory_ids");
5991
+ const mem = getMemory(memId, d);
5992
+ if (!mem)
5993
+ throw new Error(`Memory ${memId} not found`);
5994
+ rollback[memId] = { value: mem.value, version: mem.version };
5995
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [newValue, now(), memId]);
5996
+ return { old_state: rollback };
5997
+ }
5998
+ function executeAddTag(proposal, d) {
5999
+ const tagsToAdd = proposal.proposed_changes["tags"];
6000
+ if (!Array.isArray(tagsToAdd)) {
6001
+ throw new Error("add_tag proposal missing tags array in proposed_changes");
6002
+ }
6003
+ const rollback = {};
6004
+ for (const memId of proposal.memory_ids) {
6005
+ const mem = getMemory(memId, d);
6006
+ if (!mem)
6007
+ continue;
6008
+ rollback[memId] = [...mem.tags];
6009
+ const newTags = Array.from(new Set([...mem.tags, ...tagsToAdd]));
6010
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(newTags), now(), memId]);
6011
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
6012
+ for (const tag of tagsToAdd) {
6013
+ insertTag.run(memId, tag);
6014
+ }
6015
+ }
6016
+ return { old_tags: rollback };
6017
+ }
6018
+ function executeMerge(proposal, d) {
6019
+ const targetId = proposal.target_memory_id;
6020
+ if (!targetId)
6021
+ throw new Error("merge proposal missing target_memory_id");
6022
+ const target = getMemory(targetId, d);
6023
+ if (!target)
6024
+ throw new Error(`Target memory ${targetId} not found`);
6025
+ const rollback = {
6026
+ target_old_value: target.value,
6027
+ target_old_version: target.version,
6028
+ archived_memories: {}
6029
+ };
6030
+ const sourceValues = [];
6031
+ for (const memId of proposal.memory_ids) {
6032
+ if (memId === targetId)
6033
+ continue;
6034
+ const mem = getMemory(memId, d);
6035
+ if (!mem)
6036
+ continue;
6037
+ sourceValues.push(mem.value);
6038
+ rollback.archived_memories[memId] = mem.status;
6039
+ }
6040
+ const mergedValue = proposal.proposed_changes["merged_value"] ?? [target.value, ...sourceValues].join(`
6041
+ ---
6042
+ `);
6043
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [mergedValue, now(), targetId]);
6044
+ for (const memId of proposal.memory_ids) {
6045
+ if (memId === targetId)
6046
+ continue;
6047
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
6048
+ }
6049
+ return rollback;
6050
+ }
6051
+ function executeRemoveDuplicate(proposal, d) {
6052
+ const memories = proposal.memory_ids.map((id) => getMemory(id, d)).filter((m) => m !== null);
6053
+ if (memories.length < 2) {
6054
+ throw new Error("remove_duplicate requires at least 2 memories");
6055
+ }
6056
+ memories.sort((a, b) => b.importance - a.importance || a.created_at.localeCompare(b.created_at));
6057
+ const keepId = proposal.target_memory_id ?? memories[0].id;
6058
+ const rollback = {};
6059
+ for (const mem of memories) {
6060
+ if (mem.id === keepId)
6061
+ continue;
6062
+ rollback[mem.id] = mem.status;
6063
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), mem.id]);
6064
+ }
6065
+ return { old_status: rollback, kept_id: keepId };
6066
+ }
6067
+ async function rollbackRun(runId, db) {
6068
+ const d = db || getDatabase();
6069
+ const proposals = listProposals(runId, { status: "accepted" }, d);
6070
+ let rolledBack = 0;
6071
+ const errors = [];
6072
+ for (const proposal of proposals) {
6073
+ try {
6074
+ rollbackProposal(proposal, d);
6075
+ updateProposal(proposal.id, { status: "rolled_back" }, d);
6076
+ rolledBack++;
6077
+ } catch (err) {
6078
+ errors.push(`Proposal ${proposal.id} (${proposal.proposal_type}): ${err instanceof Error ? err.message : String(err)}`);
6079
+ }
6080
+ }
6081
+ return { rolled_back: rolledBack, errors };
6082
+ }
6083
+ function rollbackProposal(proposal, d) {
6084
+ const rb = proposal.rollback_data;
6085
+ if (!rb)
6086
+ return;
6087
+ d.transaction(() => {
6088
+ switch (proposal.proposal_type) {
6089
+ case "archive":
6090
+ case "remove_duplicate": {
6091
+ const oldStatus = rb["old_status"];
6092
+ if (!oldStatus)
6093
+ break;
6094
+ for (const [memId, status] of Object.entries(oldStatus)) {
6095
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
6096
+ }
6097
+ break;
6098
+ }
6099
+ case "promote": {
6100
+ const oldImportance = rb["old_importance"];
6101
+ if (!oldImportance)
6102
+ break;
6103
+ for (const [memId, importance] of Object.entries(oldImportance)) {
6104
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [importance, now(), memId]);
6105
+ }
6106
+ break;
6107
+ }
6108
+ case "update_value": {
6109
+ const oldState = rb["old_state"];
6110
+ if (!oldState)
6111
+ break;
6112
+ for (const [memId, state] of Object.entries(oldState)) {
6113
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [state.value, state.version, now(), memId]);
6114
+ }
6115
+ break;
6116
+ }
6117
+ case "add_tag": {
6118
+ const oldTags = rb["old_tags"];
6119
+ if (!oldTags)
6120
+ break;
6121
+ for (const [memId, tags] of Object.entries(oldTags)) {
6122
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(tags), now(), memId]);
6123
+ d.run("DELETE FROM memory_tags WHERE memory_id = ?", [memId]);
6124
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
6125
+ for (const tag of tags) {
6126
+ insertTag.run(memId, tag);
6127
+ }
6128
+ }
6129
+ break;
6130
+ }
6131
+ case "merge": {
6132
+ const targetOldValue = rb["target_old_value"];
6133
+ const targetOldVersion = rb["target_old_version"];
6134
+ const archivedMemories = rb["archived_memories"];
6135
+ const targetId = proposal.target_memory_id;
6136
+ if (targetId && targetOldValue !== undefined && targetOldVersion !== undefined) {
6137
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [targetOldValue, targetOldVersion, now(), targetId]);
6138
+ }
6139
+ if (archivedMemories) {
6140
+ for (const [memId, status] of Object.entries(archivedMemories)) {
6141
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
6142
+ }
6143
+ }
6144
+ break;
6145
+ }
6146
+ default:
6147
+ break;
6148
+ }
6149
+ })();
6150
+ }
6151
+ var init_executor = __esm(() => {
6152
+ init_database();
6153
+ init_memories();
6154
+ init_synthesis();
6155
+ });
6156
+
6157
+ // src/lib/synthesis/metrics.ts
6158
+ async function measureEffectiveness(runId, preCorpus, db) {
6159
+ const d = db || getDatabase();
6160
+ const postMemories = listMemories({
6161
+ status: "active",
6162
+ project_id: preCorpus.projectId ?? undefined
6163
+ }, d);
6164
+ const postCount = postMemories.length;
6165
+ const preCount = preCorpus.totalMemories;
6166
+ const corpusReduction = preCount > 0 ? (preCount - postCount) / preCount * 100 : 0;
6167
+ const preAvgImportance = preCorpus.items.length > 0 ? preCorpus.items.reduce((sum, i) => sum + i.memory.importance, 0) / preCorpus.items.length : 0;
6168
+ const postAvgImportance = postMemories.length > 0 ? postMemories.reduce((sum, m) => sum + m.importance, 0) / postMemories.length : 0;
6169
+ const importanceDrift = postAvgImportance - preAvgImportance;
6170
+ const preDuplicatePairs = preCorpus.duplicateCandidates.length;
6171
+ const acceptedProposals = listProposals(runId, { status: "accepted" }, d);
6172
+ const deduplicationProposals = acceptedProposals.filter((p) => p.proposal_type === "remove_duplicate" || p.proposal_type === "merge");
6173
+ const deduplicationRate = preDuplicatePairs > 0 ? deduplicationProposals.length / preDuplicatePairs * 100 : 0;
6174
+ const recallWeight = {
6175
+ corpusReduction: 0.3,
6176
+ importanceDrift: 0.4,
6177
+ deduplicationRate: 0.3
6178
+ };
6179
+ const estimatedRecallImprovement = Math.max(0, Math.min(100, corpusReduction * recallWeight.corpusReduction + Math.max(0, importanceDrift * 10) * recallWeight.importanceDrift + deduplicationRate * recallWeight.deduplicationRate));
6180
+ const metricDefs = [
6181
+ { metric_type: "corpus_reduction_pct", value: corpusReduction, baseline: 0 },
6182
+ { metric_type: "importance_drift", value: importanceDrift, baseline: 0 },
6183
+ { metric_type: "deduplication_rate_pct", value: deduplicationRate, baseline: 0 },
6184
+ { metric_type: "estimated_recall_improvement_pct", value: estimatedRecallImprovement, baseline: 0 },
6185
+ { metric_type: "pre_corpus_size", value: preCount, baseline: preCount },
6186
+ { metric_type: "post_corpus_size", value: postCount, baseline: preCount },
6187
+ { metric_type: "proposals_accepted", value: acceptedProposals.length, baseline: 0 },
6188
+ { metric_type: "pre_avg_importance", value: preAvgImportance, baseline: preAvgImportance },
6189
+ { metric_type: "post_avg_importance", value: postAvgImportance, baseline: preAvgImportance }
6190
+ ];
6191
+ for (const def of metricDefs) {
6192
+ createMetric({
6193
+ run_id: runId,
6194
+ metric_type: def.metric_type,
6195
+ value: def.value,
6196
+ baseline: def.baseline ?? null
6197
+ }, d);
6198
+ }
6199
+ const metrics = listMetrics(runId, d);
6200
+ return {
6201
+ runId,
6202
+ corpusReduction,
6203
+ importanceDrift,
6204
+ deduplicationRate,
6205
+ estimatedRecallImprovement,
6206
+ metrics
6207
+ };
6208
+ }
6209
+ var init_metrics = __esm(() => {
6210
+ init_database();
6211
+ init_synthesis();
6212
+ init_memories();
6213
+ });
6214
+
6215
+ // src/lib/synthesis/index.ts
6216
+ var exports_synthesis2 = {};
6217
+ __export(exports_synthesis2, {
6218
+ runSynthesis: () => runSynthesis,
6219
+ rollbackSynthesis: () => rollbackSynthesis,
6220
+ getSynthesisStatus: () => getSynthesisStatus
6221
+ });
6222
+ async function runSynthesis(options = {}) {
6223
+ const d = options.db || getDatabase();
6224
+ const projectId = options.projectId ?? null;
6225
+ const agentId = options.agentId ?? null;
6226
+ const dryRun = options.dryRun ?? false;
6227
+ const run = createSynthesisRun({
6228
+ triggered_by: "manual",
6229
+ project_id: projectId,
6230
+ agent_id: agentId
6231
+ }, d);
6232
+ updateSynthesisRun(run.id, { status: "running" }, d);
6233
+ try {
6234
+ const corpus = await buildCorpus({
6235
+ projectId: projectId ?? undefined,
6236
+ agentId: agentId ?? undefined,
6237
+ db: d
6238
+ });
6239
+ updateSynthesisRun(run.id, { corpus_size: corpus.totalMemories }, d);
6240
+ const analysisResult = await analyzeCorpus(corpus, {
6241
+ provider: options.provider,
6242
+ maxProposals: options.maxProposals ?? 20
6243
+ });
6244
+ const validation = validateProposals(analysisResult.proposals, corpus, options.safetyConfig);
6245
+ const rejectedIndices = new Set(validation.rejectedProposals.map((r) => {
6246
+ const match = r.proposalId.match(/\[(\d+)\]/);
6247
+ return match ? parseInt(match[1], 10) : -1;
6248
+ }));
6249
+ const validProposals = analysisResult.proposals.filter((_, idx) => !rejectedIndices.has(idx));
6250
+ const savedProposals = [];
6251
+ for (const p of validProposals) {
6252
+ const saved = createProposal({
6253
+ run_id: run.id,
6254
+ proposal_type: p.type,
6255
+ memory_ids: p.memory_ids,
6256
+ target_memory_id: p.target_memory_id ?? null,
6257
+ proposed_changes: p.proposed_changes,
6258
+ reasoning: p.reasoning,
6259
+ confidence: p.confidence
6260
+ }, d);
6261
+ savedProposals.push(saved);
6262
+ }
6263
+ updateSynthesisRun(run.id, {
6264
+ proposals_generated: analysisResult.proposals.length,
6265
+ proposals_rejected: validation.rejectedProposals.length
6266
+ }, d);
6267
+ let executedCount = 0;
6268
+ if (!dryRun && savedProposals.length > 0) {
6269
+ const execResult = await executeProposals(run.id, savedProposals, d);
6270
+ executedCount = execResult.executed;
6271
+ updateSynthesisRun(run.id, {
6272
+ proposals_accepted: execResult.executed,
6273
+ proposals_rejected: validation.rejectedProposals.length + execResult.failed,
6274
+ status: "completed",
6275
+ completed_at: now()
6276
+ }, d);
6277
+ } else {
6278
+ updateSynthesisRun(run.id, {
6279
+ status: "completed",
6280
+ completed_at: now()
6281
+ }, d);
6282
+ }
6283
+ let effectivenessReport = null;
6284
+ if (!dryRun && executedCount > 0) {
6285
+ try {
6286
+ effectivenessReport = await measureEffectiveness(run.id, corpus, d);
6287
+ } catch {}
6288
+ }
6289
+ const finalRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
6290
+ const finalProposals = listProposals(run.id, undefined, d);
6291
+ return {
6292
+ run: finalRun,
6293
+ proposals: finalProposals,
6294
+ executed: executedCount,
6295
+ metrics: effectivenessReport,
6296
+ dryRun
6297
+ };
6298
+ } catch (err) {
6299
+ updateSynthesisRun(run.id, {
6300
+ status: "failed",
6301
+ error: err instanceof Error ? err.message : String(err),
6302
+ completed_at: now()
6303
+ }, d);
6304
+ const failedRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
6305
+ return {
6306
+ run: failedRun,
6307
+ proposals: [],
6308
+ executed: 0,
6309
+ metrics: null,
6310
+ dryRun
6311
+ };
6312
+ }
6313
+ }
6314
+ async function rollbackSynthesis(runId, db) {
6315
+ const d = db || getDatabase();
6316
+ const result = await rollbackRun(runId, d);
6317
+ if (result.errors.length === 0) {
6318
+ updateSynthesisRun(runId, { status: "rolled_back", completed_at: now() }, d);
6319
+ }
6320
+ return result;
6321
+ }
6322
+ function getSynthesisStatus(runId, projectId, db) {
6323
+ const d = db || getDatabase();
6324
+ if (runId) {
6325
+ const recentRuns2 = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
6326
+ const specificRun = recentRuns2.find((r) => r.id === runId) ?? null;
6327
+ return {
6328
+ lastRun: specificRun ?? recentRuns2[0] ?? null,
6329
+ recentRuns: recentRuns2
6330
+ };
6331
+ }
6332
+ const recentRuns = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
6333
+ return {
6334
+ lastRun: recentRuns[0] ?? null,
6335
+ recentRuns
6336
+ };
6337
+ }
6338
+ var init_synthesis2 = __esm(() => {
6339
+ init_database();
6340
+ init_synthesis();
6341
+ init_corpus_builder();
6342
+ init_llm_analyzer();
6343
+ init_validator();
6344
+ init_executor();
6345
+ init_metrics();
5031
6346
  });
5032
6347
 
5033
6348
  // node_modules/commander/esm.mjs
@@ -8635,4 +9950,47 @@ webhooksCmd.command("disable <id>").description("Disable a webhook (without dele
8635
9950
  process.exit(1);
8636
9951
  }
8637
9952
  });
9953
+ var synthesisCmd = program2.command("synthesis").alias("synth").description("ALMA memory synthesis \u2014 analyze and consolidate memories");
9954
+ synthesisCmd.command("run").description("Run memory synthesis on the corpus").option("--project <id>", "Project ID to synthesize").option("--dry-run", "Preview proposals without applying them").option("--max-proposals <n>", "Maximum proposals to generate", "20").option("--provider <name>", "LLM provider (anthropic, openai, cerebras, grok)").action(async (opts) => {
9955
+ const { runSynthesis: runSynthesis2 } = await Promise.resolve().then(() => (init_synthesis2(), exports_synthesis2));
9956
+ console.log(chalk.blue("Running memory synthesis..."));
9957
+ const result = await runSynthesis2({
9958
+ projectId: opts.project,
9959
+ dryRun: opts.dryRun ?? false,
9960
+ maxProposals: opts.maxProposals ? parseInt(opts.maxProposals) : 20,
9961
+ provider: opts.provider
9962
+ });
9963
+ if (result.dryRun) {
9964
+ console.log(chalk.yellow(`DRY RUN \u2014 ${result.proposals.length} proposals generated (not applied)`));
9965
+ } else {
9966
+ console.log(chalk.green(`\u2713 Synthesis complete`));
9967
+ console.log(` Corpus: ${result.run.corpus_size} memories`);
9968
+ console.log(` Proposals: ${result.run.proposals_generated} generated, ${result.run.proposals_accepted} applied`);
9969
+ }
9970
+ if (result.metrics) {
9971
+ console.log(` Reduction: ${(result.metrics.corpusReduction * 100).toFixed(1)}%`);
9972
+ }
9973
+ console.log(` Run ID: ${chalk.cyan(result.run.id)}`);
9974
+ });
9975
+ synthesisCmd.command("status").description("Show recent synthesis runs").option("--project <id>", "Filter by project").action(async (opts) => {
9976
+ const { listSynthesisRuns: listSynthesisRuns2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
9977
+ const runs = listSynthesisRuns2({ project_id: opts.project, limit: 10 });
9978
+ if (runs.length === 0) {
9979
+ console.log(chalk.gray("No synthesis runs found."));
9980
+ return;
9981
+ }
9982
+ for (const run of runs) {
9983
+ const statusColor = run.status === "completed" ? chalk.green : run.status === "failed" ? chalk.red : chalk.yellow;
9984
+ console.log(`${chalk.cyan(run.id)} [${statusColor(run.status)}] corpus=${run.corpus_size} accepted=${run.proposals_accepted}/${run.proposals_generated} ${run.started_at.slice(0, 10)}`);
9985
+ }
9986
+ });
9987
+ synthesisCmd.command("rollback <runId>").description("Roll back a synthesis run").action(async (runId) => {
9988
+ const { rollbackSynthesis: rollbackSynthesis2 } = await Promise.resolve().then(() => (init_synthesis2(), exports_synthesis2));
9989
+ console.log(chalk.yellow(`Rolling back synthesis run ${runId}...`));
9990
+ const result = await rollbackSynthesis2(runId);
9991
+ console.log(chalk.green(`\u2713 Rolled back ${result.rolled_back} proposals`));
9992
+ if (result.errors.length > 0) {
9993
+ console.log(chalk.red(` Errors: ${result.errors.join(", ")}`));
9994
+ }
9995
+ });
8638
9996
  program2.parse(process.argv);