@hasna/mementos 0.7.0 → 0.9.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.
Files changed (34) hide show
  1. package/dist/cli/index.js +1997 -132
  2. package/dist/db/database.d.ts.map +1 -1
  3. package/dist/db/session-jobs.d.ts +49 -0
  4. package/dist/db/session-jobs.d.ts.map +1 -0
  5. package/dist/db/synthesis.d.ts +101 -0
  6. package/dist/db/synthesis.d.ts.map +1 -0
  7. package/dist/index.js +92 -0
  8. package/dist/lib/built-in-hooks.d.ts.map +1 -1
  9. package/dist/lib/open-sessions-connector.d.ts +60 -0
  10. package/dist/lib/open-sessions-connector.d.ts.map +1 -0
  11. package/dist/lib/session-auto-resolve.d.ts +28 -0
  12. package/dist/lib/session-auto-resolve.d.ts.map +1 -0
  13. package/dist/lib/session-processor.d.ts +38 -0
  14. package/dist/lib/session-processor.d.ts.map +1 -0
  15. package/dist/lib/session-queue.d.ts +28 -0
  16. package/dist/lib/session-queue.d.ts.map +1 -0
  17. package/dist/lib/synthesis/corpus-builder.d.ts +30 -0
  18. package/dist/lib/synthesis/corpus-builder.d.ts.map +1 -0
  19. package/dist/lib/synthesis/executor.d.ts +14 -0
  20. package/dist/lib/synthesis/executor.d.ts.map +1 -0
  21. package/dist/lib/synthesis/index.d.ts +37 -0
  22. package/dist/lib/synthesis/index.d.ts.map +1 -0
  23. package/dist/lib/synthesis/llm-analyzer.d.ts +18 -0
  24. package/dist/lib/synthesis/llm-analyzer.d.ts.map +1 -0
  25. package/dist/lib/synthesis/metrics.d.ts +13 -0
  26. package/dist/lib/synthesis/metrics.d.ts.map +1 -0
  27. package/dist/lib/synthesis/scheduler.d.ts +18 -0
  28. package/dist/lib/synthesis/scheduler.d.ts.map +1 -0
  29. package/dist/lib/synthesis/validator.d.ts +19 -0
  30. package/dist/lib/synthesis/validator.d.ts.map +1 -0
  31. package/dist/mcp/index.js +1793 -33
  32. package/dist/server/index.d.ts.map +1 -1
  33. package/dist/server/index.js +1856 -19
  34. package/package.json +1 -1
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 (
@@ -2451,7 +2520,30 @@ var init_database = __esm(() => {
2451
2520
  CREATE INDEX IF NOT EXISTS idx_webhook_hooks_type ON webhook_hooks(type);
2452
2521
  CREATE INDEX IF NOT EXISTS idx_webhook_hooks_enabled ON webhook_hooks(enabled);
2453
2522
  INSERT OR IGNORE INTO _migrations (id) VALUES (10);
2454
- `
2523
+ `,
2524
+ `
2525
+ CREATE TABLE IF NOT EXISTS session_memory_jobs (
2526
+ id TEXT PRIMARY KEY,
2527
+ session_id TEXT NOT NULL,
2528
+ agent_id TEXT,
2529
+ project_id TEXT,
2530
+ source TEXT NOT NULL DEFAULT 'manual' CHECK(source IN ('claude-code','codex','manual','open-sessions')),
2531
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','processing','completed','failed')),
2532
+ transcript TEXT NOT NULL,
2533
+ chunk_count INTEGER NOT NULL DEFAULT 0,
2534
+ memories_extracted INTEGER NOT NULL DEFAULT 0,
2535
+ error TEXT,
2536
+ metadata TEXT NOT NULL DEFAULT '{}',
2537
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
2538
+ started_at TEXT,
2539
+ completed_at TEXT
2540
+ );
2541
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_status ON session_memory_jobs(status);
2542
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_agent ON session_memory_jobs(agent_id);
2543
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_project ON session_memory_jobs(project_id);
2544
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_session ON session_memory_jobs(session_id);
2545
+ INSERT OR IGNORE INTO _migrations (id) VALUES (13);
2546
+ `
2455
2547
  ];
2456
2548
  });
2457
2549
 
@@ -4863,171 +4955,1819 @@ function createWebhookHook(input, db) {
4863
4955
  input.description ?? null,
4864
4956
  timestamp
4865
4957
  ]);
4866
- return getWebhookHook(id, d);
4958
+ return getWebhookHook(id, d);
4959
+ }
4960
+ function getWebhookHook(id, db) {
4961
+ const d = db || getDatabase();
4962
+ const row = d.query("SELECT * FROM webhook_hooks WHERE id = ?").get(id);
4963
+ return row ? parseRow(row) : null;
4964
+ }
4965
+ function listWebhookHooks(filter = {}, db) {
4966
+ const d = db || getDatabase();
4967
+ const conditions = [];
4968
+ const params = [];
4969
+ if (filter.type) {
4970
+ conditions.push("type = ?");
4971
+ params.push(filter.type);
4972
+ }
4973
+ if (filter.enabled !== undefined) {
4974
+ conditions.push("enabled = ?");
4975
+ params.push(filter.enabled ? 1 : 0);
4976
+ }
4977
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4978
+ const rows = d.query(`SELECT * FROM webhook_hooks ${where} ORDER BY priority ASC, created_at ASC`).all(...params);
4979
+ return rows.map(parseRow);
4980
+ }
4981
+ function updateWebhookHook(id, updates, db) {
4982
+ const d = db || getDatabase();
4983
+ const existing = getWebhookHook(id, d);
4984
+ if (!existing)
4985
+ return null;
4986
+ const sets = [];
4987
+ const params = [];
4988
+ if (updates.enabled !== undefined) {
4989
+ sets.push("enabled = ?");
4990
+ params.push(updates.enabled ? 1 : 0);
4991
+ }
4992
+ if (updates.description !== undefined) {
4993
+ sets.push("description = ?");
4994
+ params.push(updates.description);
4995
+ }
4996
+ if (updates.priority !== undefined) {
4997
+ sets.push("priority = ?");
4998
+ params.push(updates.priority);
4999
+ }
5000
+ if (sets.length > 0) {
5001
+ params.push(id);
5002
+ d.run(`UPDATE webhook_hooks SET ${sets.join(", ")} WHERE id = ?`, params);
5003
+ }
5004
+ return getWebhookHook(id, d);
5005
+ }
5006
+ function deleteWebhookHook(id, db) {
5007
+ const d = db || getDatabase();
5008
+ const result = d.run("DELETE FROM webhook_hooks WHERE id = ?", [id]);
5009
+ return result.changes > 0;
5010
+ }
5011
+ function recordWebhookInvocation(id, success, db) {
5012
+ const d = db || getDatabase();
5013
+ if (success) {
5014
+ d.run("UPDATE webhook_hooks SET invocation_count = invocation_count + 1 WHERE id = ?", [id]);
5015
+ } else {
5016
+ d.run("UPDATE webhook_hooks SET invocation_count = invocation_count + 1, failure_count = failure_count + 1 WHERE id = ?", [id]);
5017
+ }
5018
+ }
5019
+ var init_webhook_hooks = __esm(() => {
5020
+ init_database();
5021
+ });
5022
+
5023
+ // src/db/synthesis.ts
5024
+ var exports_synthesis = {};
5025
+ __export(exports_synthesis, {
5026
+ updateSynthesisRun: () => updateSynthesisRun,
5027
+ updateProposal: () => updateProposal,
5028
+ recordSynthesisEvent: () => recordSynthesisEvent,
5029
+ listSynthesisRuns: () => listSynthesisRuns,
5030
+ listSynthesisEvents: () => listSynthesisEvents,
5031
+ listProposals: () => listProposals,
5032
+ listMetrics: () => listMetrics,
5033
+ getSynthesisRun: () => getSynthesisRun,
5034
+ getProposal: () => getProposal,
5035
+ createSynthesisRun: () => createSynthesisRun,
5036
+ createProposal: () => createProposal,
5037
+ createMetric: () => createMetric
5038
+ });
5039
+ function parseRunRow(row) {
5040
+ return {
5041
+ id: row["id"],
5042
+ triggered_by: row["triggered_by"],
5043
+ project_id: row["project_id"] || null,
5044
+ agent_id: row["agent_id"] || null,
5045
+ corpus_size: row["corpus_size"],
5046
+ proposals_generated: row["proposals_generated"],
5047
+ proposals_accepted: row["proposals_accepted"],
5048
+ proposals_rejected: row["proposals_rejected"],
5049
+ status: row["status"],
5050
+ error: row["error"] || null,
5051
+ started_at: row["started_at"],
5052
+ completed_at: row["completed_at"] || null
5053
+ };
5054
+ }
5055
+ function parseProposalRow(row) {
5056
+ return {
5057
+ id: row["id"],
5058
+ run_id: row["run_id"],
5059
+ proposal_type: row["proposal_type"],
5060
+ memory_ids: JSON.parse(row["memory_ids"] || "[]"),
5061
+ target_memory_id: row["target_memory_id"] || null,
5062
+ proposed_changes: JSON.parse(row["proposed_changes"] || "{}"),
5063
+ reasoning: row["reasoning"] || null,
5064
+ confidence: row["confidence"],
5065
+ status: row["status"],
5066
+ created_at: row["created_at"],
5067
+ executed_at: row["executed_at"] || null,
5068
+ rollback_data: row["rollback_data"] ? JSON.parse(row["rollback_data"]) : null
5069
+ };
5070
+ }
5071
+ function parseMetricRow(row) {
5072
+ return {
5073
+ id: row["id"],
5074
+ run_id: row["run_id"],
5075
+ metric_type: row["metric_type"],
5076
+ value: row["value"],
5077
+ baseline: row["baseline"] != null ? row["baseline"] : null,
5078
+ created_at: row["created_at"]
5079
+ };
5080
+ }
5081
+ function parseEventRow(row) {
5082
+ return {
5083
+ id: row["id"],
5084
+ event_type: row["event_type"],
5085
+ memory_id: row["memory_id"] || null,
5086
+ agent_id: row["agent_id"] || null,
5087
+ project_id: row["project_id"] || null,
5088
+ session_id: row["session_id"] || null,
5089
+ query: row["query"] || null,
5090
+ importance_at_time: row["importance_at_time"] != null ? row["importance_at_time"] : null,
5091
+ metadata: JSON.parse(row["metadata"] || "{}"),
5092
+ created_at: row["created_at"]
5093
+ };
5094
+ }
5095
+ function createSynthesisRun(input, db) {
5096
+ const d = db || getDatabase();
5097
+ const id = shortUuid();
5098
+ const timestamp = now();
5099
+ d.run(`INSERT INTO synthesis_runs (id, triggered_by, project_id, agent_id, corpus_size, proposals_generated, proposals_accepted, proposals_rejected, status, started_at)
5100
+ VALUES (?, ?, ?, ?, ?, 0, 0, 0, 'pending', ?)`, [
5101
+ id,
5102
+ input.triggered_by,
5103
+ input.project_id ?? null,
5104
+ input.agent_id ?? null,
5105
+ input.corpus_size ?? 0,
5106
+ timestamp
5107
+ ]);
5108
+ return getSynthesisRun(id, d);
5109
+ }
5110
+ function getSynthesisRun(id, db) {
5111
+ const d = db || getDatabase();
5112
+ const row = d.query("SELECT * FROM synthesis_runs WHERE id = ?").get(id);
5113
+ if (!row)
5114
+ return null;
5115
+ return parseRunRow(row);
5116
+ }
5117
+ function listSynthesisRuns(filter, db) {
5118
+ const d = db || getDatabase();
5119
+ const conditions = [];
5120
+ const params = [];
5121
+ if (filter.project_id !== undefined) {
5122
+ if (filter.project_id === null) {
5123
+ conditions.push("project_id IS NULL");
5124
+ } else {
5125
+ conditions.push("project_id = ?");
5126
+ params.push(filter.project_id);
5127
+ }
5128
+ }
5129
+ if (filter.status) {
5130
+ conditions.push("status = ?");
5131
+ params.push(filter.status);
5132
+ }
5133
+ let sql = "SELECT * FROM synthesis_runs";
5134
+ if (conditions.length > 0) {
5135
+ sql += ` WHERE ${conditions.join(" AND ")}`;
5136
+ }
5137
+ sql += " ORDER BY started_at DESC";
5138
+ if (filter.limit) {
5139
+ sql += " LIMIT ?";
5140
+ params.push(filter.limit);
5141
+ }
5142
+ const rows = d.query(sql).all(...params);
5143
+ return rows.map(parseRunRow);
5144
+ }
5145
+ function updateSynthesisRun(id, updates, db) {
5146
+ const d = db || getDatabase();
5147
+ const sets = [];
5148
+ const params = [];
5149
+ if (updates.status !== undefined) {
5150
+ sets.push("status = ?");
5151
+ params.push(updates.status);
5152
+ }
5153
+ if (updates.error !== undefined) {
5154
+ sets.push("error = ?");
5155
+ params.push(updates.error);
5156
+ }
5157
+ if (updates.corpus_size !== undefined) {
5158
+ sets.push("corpus_size = ?");
5159
+ params.push(updates.corpus_size);
5160
+ }
5161
+ if (updates.proposals_generated !== undefined) {
5162
+ sets.push("proposals_generated = ?");
5163
+ params.push(updates.proposals_generated);
5164
+ }
5165
+ if (updates.proposals_accepted !== undefined) {
5166
+ sets.push("proposals_accepted = ?");
5167
+ params.push(updates.proposals_accepted);
5168
+ }
5169
+ if (updates.proposals_rejected !== undefined) {
5170
+ sets.push("proposals_rejected = ?");
5171
+ params.push(updates.proposals_rejected);
5172
+ }
5173
+ if (updates.completed_at !== undefined) {
5174
+ sets.push("completed_at = ?");
5175
+ params.push(updates.completed_at);
5176
+ }
5177
+ if (sets.length === 0)
5178
+ return getSynthesisRun(id, d);
5179
+ params.push(id);
5180
+ d.run(`UPDATE synthesis_runs SET ${sets.join(", ")} WHERE id = ?`, params);
5181
+ return getSynthesisRun(id, d);
5182
+ }
5183
+ function createProposal(input, db) {
5184
+ const d = db || getDatabase();
5185
+ const id = shortUuid();
5186
+ const timestamp = now();
5187
+ d.run(`INSERT INTO synthesis_proposals (id, run_id, proposal_type, memory_ids, target_memory_id, proposed_changes, reasoning, confidence, status, created_at)
5188
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`, [
5189
+ id,
5190
+ input.run_id,
5191
+ input.proposal_type,
5192
+ JSON.stringify(input.memory_ids),
5193
+ input.target_memory_id ?? null,
5194
+ JSON.stringify(input.proposed_changes),
5195
+ input.reasoning ?? null,
5196
+ input.confidence,
5197
+ timestamp
5198
+ ]);
5199
+ return getProposal(id, d);
5200
+ }
5201
+ function getProposal(id, db) {
5202
+ const d = db || getDatabase();
5203
+ const row = d.query("SELECT * FROM synthesis_proposals WHERE id = ?").get(id);
5204
+ if (!row)
5205
+ return null;
5206
+ return parseProposalRow(row);
5207
+ }
5208
+ function listProposals(run_id, filter, db) {
5209
+ const d = db || getDatabase();
5210
+ const params = [run_id];
5211
+ let sql = "SELECT * FROM synthesis_proposals WHERE run_id = ?";
5212
+ if (filter?.status) {
5213
+ sql += " AND status = ?";
5214
+ params.push(filter.status);
5215
+ }
5216
+ sql += " ORDER BY created_at ASC";
5217
+ const rows = d.query(sql).all(...params);
5218
+ return rows.map(parseProposalRow);
5219
+ }
5220
+ function updateProposal(id, updates, db) {
5221
+ const d = db || getDatabase();
5222
+ const sets = [];
5223
+ const params = [];
5224
+ if (updates.status !== undefined) {
5225
+ sets.push("status = ?");
5226
+ params.push(updates.status);
5227
+ }
5228
+ if (updates.executed_at !== undefined) {
5229
+ sets.push("executed_at = ?");
5230
+ params.push(updates.executed_at);
5231
+ }
5232
+ if (updates.rollback_data !== undefined) {
5233
+ sets.push("rollback_data = ?");
5234
+ params.push(JSON.stringify(updates.rollback_data));
5235
+ }
5236
+ if (sets.length === 0)
5237
+ return getProposal(id, d);
5238
+ params.push(id);
5239
+ d.run(`UPDATE synthesis_proposals SET ${sets.join(", ")} WHERE id = ?`, params);
5240
+ return getProposal(id, d);
5241
+ }
5242
+ function createMetric(input, db) {
5243
+ const d = db || getDatabase();
5244
+ const id = shortUuid();
5245
+ const timestamp = now();
5246
+ d.run(`INSERT INTO synthesis_metrics (id, run_id, metric_type, value, baseline, created_at)
5247
+ VALUES (?, ?, ?, ?, ?, ?)`, [id, input.run_id, input.metric_type, input.value, input.baseline ?? null, timestamp]);
5248
+ return { id, run_id: input.run_id, metric_type: input.metric_type, value: input.value, baseline: input.baseline ?? null, created_at: timestamp };
5249
+ }
5250
+ function listMetrics(run_id, db) {
5251
+ const d = db || getDatabase();
5252
+ const rows = d.query("SELECT * FROM synthesis_metrics WHERE run_id = ? ORDER BY created_at ASC").all(run_id);
5253
+ return rows.map(parseMetricRow);
5254
+ }
5255
+ function recordSynthesisEvent(input, db) {
5256
+ try {
5257
+ const d = db || getDatabase();
5258
+ const id = shortUuid();
5259
+ const timestamp = now();
5260
+ d.run(`INSERT INTO synthesis_events (id, event_type, memory_id, agent_id, project_id, session_id, query, importance_at_time, metadata, created_at)
5261
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
5262
+ id,
5263
+ input.event_type,
5264
+ input.memory_id ?? null,
5265
+ input.agent_id ?? null,
5266
+ input.project_id ?? null,
5267
+ input.session_id ?? null,
5268
+ input.query ?? null,
5269
+ input.importance_at_time ?? null,
5270
+ JSON.stringify(input.metadata ?? {}),
5271
+ timestamp
5272
+ ]);
5273
+ } catch {}
5274
+ }
5275
+ function listSynthesisEvents(filter, db) {
5276
+ const d = db || getDatabase();
5277
+ const conditions = [];
5278
+ const params = [];
5279
+ if (filter.memory_id) {
5280
+ conditions.push("memory_id = ?");
5281
+ params.push(filter.memory_id);
5282
+ }
5283
+ if (filter.project_id) {
5284
+ conditions.push("project_id = ?");
5285
+ params.push(filter.project_id);
5286
+ }
5287
+ if (filter.event_type) {
5288
+ conditions.push("event_type = ?");
5289
+ params.push(filter.event_type);
5290
+ }
5291
+ if (filter.since) {
5292
+ conditions.push("created_at >= ?");
5293
+ params.push(filter.since);
5294
+ }
5295
+ let sql = "SELECT * FROM synthesis_events";
5296
+ if (conditions.length > 0) {
5297
+ sql += ` WHERE ${conditions.join(" AND ")}`;
5298
+ }
5299
+ sql += " ORDER BY created_at DESC";
5300
+ if (filter.limit) {
5301
+ sql += " LIMIT ?";
5302
+ params.push(filter.limit);
5303
+ }
5304
+ const rows = d.query(sql).all(...params);
5305
+ return rows.map(parseEventRow);
5306
+ }
5307
+ var init_synthesis = __esm(() => {
5308
+ init_database();
5309
+ });
5310
+
5311
+ // src/lib/built-in-hooks.ts
5312
+ var exports_built_in_hooks = {};
5313
+ __export(exports_built_in_hooks, {
5314
+ reloadWebhooks: () => reloadWebhooks,
5315
+ loadWebhooksFromDb: () => loadWebhooksFromDb
5316
+ });
5317
+ async function getAutoMemory() {
5318
+ if (!_processConversationTurn) {
5319
+ const mod = await Promise.resolve().then(() => (init_auto_memory(), exports_auto_memory));
5320
+ _processConversationTurn = mod.processConversationTurn;
5321
+ }
5322
+ return _processConversationTurn;
5323
+ }
5324
+ function loadWebhooksFromDb() {
5325
+ if (_webhooksLoaded)
5326
+ return;
5327
+ _webhooksLoaded = true;
5328
+ try {
5329
+ const webhooks = listWebhookHooks({ enabled: true });
5330
+ for (const wh of webhooks) {
5331
+ hookRegistry.register({
5332
+ type: wh.type,
5333
+ blocking: wh.blocking,
5334
+ priority: wh.priority,
5335
+ agentId: wh.agentId,
5336
+ projectId: wh.projectId,
5337
+ description: wh.description ?? `Webhook: ${wh.handlerUrl}`,
5338
+ handler: makeWebhookHandler(wh.id, wh.handlerUrl)
5339
+ });
5340
+ }
5341
+ if (webhooks.length > 0) {
5342
+ console.log(`[hooks] Loaded ${webhooks.length} webhook(s) from DB`);
5343
+ }
5344
+ } catch (err) {
5345
+ console.error("[hooks] Failed to load webhooks from DB:", err);
5346
+ }
5347
+ }
5348
+ function makeWebhookHandler(webhookId, url) {
5349
+ return async (context) => {
5350
+ try {
5351
+ const res = await fetch(url, {
5352
+ method: "POST",
5353
+ headers: { "Content-Type": "application/json" },
5354
+ body: JSON.stringify(context),
5355
+ signal: AbortSignal.timeout(1e4)
5356
+ });
5357
+ recordWebhookInvocation(webhookId, res.ok);
5358
+ } catch {
5359
+ recordWebhookInvocation(webhookId, false);
5360
+ }
5361
+ };
5362
+ }
5363
+ function reloadWebhooks() {
5364
+ _webhooksLoaded = false;
5365
+ loadWebhooksFromDb();
5366
+ }
5367
+ var _processConversationTurn = null, _webhooksLoaded = false;
5368
+ var init_built_in_hooks = __esm(() => {
5369
+ init_hooks();
5370
+ init_webhook_hooks();
5371
+ hookRegistry.register({
5372
+ type: "PostMemorySave",
5373
+ blocking: false,
5374
+ builtin: true,
5375
+ priority: 100,
5376
+ description: "Trigger async LLM entity extraction when a memory is saved",
5377
+ handler: async (ctx) => {
5378
+ if (ctx.wasUpdated)
5379
+ return;
5380
+ const processConversationTurn2 = await getAutoMemory();
5381
+ processConversationTurn2(`${ctx.memory.key}: ${ctx.memory.value}`, {
5382
+ agentId: ctx.agentId,
5383
+ projectId: ctx.projectId,
5384
+ sessionId: ctx.sessionId
5385
+ });
5386
+ }
5387
+ });
5388
+ hookRegistry.register({
5389
+ type: "OnSessionStart",
5390
+ blocking: false,
5391
+ builtin: true,
5392
+ priority: 100,
5393
+ description: "Record session start as a history memory for analytics",
5394
+ handler: async (ctx) => {
5395
+ const { createMemory: createMemory2 } = await Promise.resolve().then(() => (init_memories(), exports_memories));
5396
+ try {
5397
+ createMemory2({
5398
+ key: `session-start-${ctx.agentId}`,
5399
+ value: `Agent ${ctx.agentId} started session on project ${ctx.projectId} at ${new Date(ctx.timestamp).toISOString()}`,
5400
+ category: "history",
5401
+ scope: "shared",
5402
+ importance: 3,
5403
+ source: "system",
5404
+ agent_id: ctx.agentId,
5405
+ project_id: ctx.projectId,
5406
+ session_id: ctx.sessionId
5407
+ });
5408
+ } catch {}
5409
+ }
5410
+ });
5411
+ hookRegistry.register({
5412
+ type: "PostMemorySave",
5413
+ blocking: false,
5414
+ builtin: true,
5415
+ priority: 200,
5416
+ description: "Record memory save event for synthesis analytics",
5417
+ handler: async (ctx) => {
5418
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
5419
+ recordSynthesisEvent2({
5420
+ event_type: "saved",
5421
+ memory_id: ctx.memory.id,
5422
+ agent_id: ctx.agentId,
5423
+ project_id: ctx.projectId,
5424
+ session_id: ctx.sessionId,
5425
+ importance_at_time: ctx.memory.importance
5426
+ });
5427
+ }
5428
+ });
5429
+ hookRegistry.register({
5430
+ type: "PostMemoryInject",
5431
+ blocking: false,
5432
+ builtin: true,
5433
+ priority: 200,
5434
+ description: "Record injection event for synthesis analytics",
5435
+ handler: async (ctx) => {
5436
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
5437
+ recordSynthesisEvent2({
5438
+ event_type: "injected",
5439
+ agent_id: ctx.agentId,
5440
+ project_id: ctx.projectId,
5441
+ session_id: ctx.sessionId,
5442
+ metadata: { count: ctx.memoriesCount, format: ctx.format }
5443
+ });
5444
+ }
5445
+ });
5446
+ });
5447
+
5448
+ // src/lib/synthesis/corpus-builder.ts
5449
+ function extractTerms(text) {
5450
+ const stopWords = new Set([
5451
+ "a",
5452
+ "an",
5453
+ "the",
5454
+ "is",
5455
+ "it",
5456
+ "in",
5457
+ "of",
5458
+ "for",
5459
+ "to",
5460
+ "and",
5461
+ "or",
5462
+ "but",
5463
+ "not",
5464
+ "with",
5465
+ "this",
5466
+ "that",
5467
+ "are",
5468
+ "was",
5469
+ "be",
5470
+ "by",
5471
+ "at",
5472
+ "as",
5473
+ "on",
5474
+ "has",
5475
+ "have",
5476
+ "had",
5477
+ "do",
5478
+ "did",
5479
+ "does",
5480
+ "will",
5481
+ "would",
5482
+ "can",
5483
+ "could",
5484
+ "should",
5485
+ "may",
5486
+ "might",
5487
+ "shall",
5488
+ "from",
5489
+ "into",
5490
+ "then",
5491
+ "than",
5492
+ "so",
5493
+ "if",
5494
+ "up",
5495
+ "out",
5496
+ "about",
5497
+ "its",
5498
+ "my",
5499
+ "we",
5500
+ "i",
5501
+ "you"
5502
+ ]);
5503
+ return new Set(text.toLowerCase().replace(/[^a-z0-9\s\-_]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w)));
5504
+ }
5505
+ function jaccardSimilarity(a, b) {
5506
+ if (a.size === 0 && b.size === 0)
5507
+ return 0;
5508
+ const intersection = new Set([...a].filter((x) => b.has(x)));
5509
+ const union = new Set([...a, ...b]);
5510
+ return intersection.size / union.size;
5511
+ }
5512
+ function isStale(memory) {
5513
+ if (memory.status !== "active")
5514
+ return false;
5515
+ if (memory.importance >= 7)
5516
+ return false;
5517
+ if (!memory.accessed_at)
5518
+ return true;
5519
+ const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
5520
+ return new Date(memory.accessed_at).getTime() < thirtyDaysAgo;
5521
+ }
5522
+ async function buildCorpus(options) {
5523
+ const d = options.db || getDatabase();
5524
+ const limit = options.limit ?? 500;
5525
+ const projectId = options.projectId ?? null;
5526
+ const memories = listMemories({
5527
+ status: "active",
5528
+ project_id: options.projectId,
5529
+ agent_id: options.agentId,
5530
+ limit
5531
+ }, d);
5532
+ const recallEvents = listSynthesisEvents({
5533
+ event_type: "recalled",
5534
+ project_id: options.projectId
5535
+ }, d);
5536
+ const recallCounts = new Map;
5537
+ const lastRecalledMap = new Map;
5538
+ for (const event of recallEvents) {
5539
+ if (!event.memory_id)
5540
+ continue;
5541
+ recallCounts.set(event.memory_id, (recallCounts.get(event.memory_id) ?? 0) + 1);
5542
+ const existing = lastRecalledMap.get(event.memory_id);
5543
+ if (!existing || event.created_at > existing) {
5544
+ lastRecalledMap.set(event.memory_id, event.created_at);
5545
+ }
5546
+ }
5547
+ const searchEvents = listSynthesisEvents({
5548
+ event_type: "searched",
5549
+ project_id: options.projectId
5550
+ }, d);
5551
+ const searchHits = new Map;
5552
+ for (const event of searchEvents) {
5553
+ if (!event.memory_id)
5554
+ continue;
5555
+ searchHits.set(event.memory_id, (searchHits.get(event.memory_id) ?? 0) + 1);
5556
+ }
5557
+ const termSets = new Map;
5558
+ for (const m of memories) {
5559
+ termSets.set(m.id, extractTerms(`${m.key} ${m.value} ${m.summary ?? ""}`));
5560
+ }
5561
+ const duplicateCandidates = [];
5562
+ const similarityThreshold = 0.5;
5563
+ const similarIds = new Map;
5564
+ for (let i = 0;i < memories.length; i++) {
5565
+ const a = memories[i];
5566
+ const termsA = termSets.get(a.id);
5567
+ const aSimIds = [];
5568
+ for (let j = i + 1;j < memories.length; j++) {
5569
+ const b = memories[j];
5570
+ const termsB = termSets.get(b.id);
5571
+ const sim = jaccardSimilarity(termsA, termsB);
5572
+ if (sim >= similarityThreshold) {
5573
+ duplicateCandidates.push({ a, b, similarity: sim });
5574
+ aSimIds.push(b.id);
5575
+ const bSimIds = similarIds.get(b.id) ?? [];
5576
+ bSimIds.push(a.id);
5577
+ similarIds.set(b.id, bSimIds);
5578
+ }
5579
+ }
5580
+ if (aSimIds.length > 0) {
5581
+ const existing = similarIds.get(a.id) ?? [];
5582
+ similarIds.set(a.id, [...existing, ...aSimIds]);
5583
+ }
5584
+ }
5585
+ duplicateCandidates.sort((a, b) => b.similarity - a.similarity);
5586
+ const items = memories.map((memory) => ({
5587
+ memory,
5588
+ recallCount: recallCounts.get(memory.id) ?? 0,
5589
+ lastRecalled: lastRecalledMap.get(memory.id) ?? null,
5590
+ searchHits: searchHits.get(memory.id) ?? 0,
5591
+ similarMemoryIds: similarIds.get(memory.id) ?? []
5592
+ }));
5593
+ const staleMemories = memories.filter(isStale);
5594
+ const lowImportanceHighRecall = memories.filter((m) => m.importance < 5 && (recallCounts.get(m.id) ?? 0) > 3);
5595
+ const highImportanceLowRecall = memories.filter((m) => m.importance > 7 && (recallCounts.get(m.id) ?? 0) === 0);
5596
+ return {
5597
+ projectId,
5598
+ totalMemories: memories.length,
5599
+ items,
5600
+ staleMemories,
5601
+ duplicateCandidates,
5602
+ lowImportanceHighRecall,
5603
+ highImportanceLowRecall,
5604
+ generatedAt: now()
5605
+ };
5606
+ }
5607
+ var init_corpus_builder = __esm(() => {
5608
+ init_database();
5609
+ init_memories();
5610
+ init_synthesis();
5611
+ });
5612
+
5613
+ // src/lib/synthesis/llm-analyzer.ts
5614
+ function buildCorpusPrompt(corpus, maxProposals) {
5615
+ const lines = [];
5616
+ lines.push(`## Memory Corpus Analysis`);
5617
+ lines.push(`Project: ${corpus.projectId ?? "(global)"}`);
5618
+ lines.push(`Total active memories: ${corpus.totalMemories}`);
5619
+ lines.push(`Analysis generated at: ${corpus.generatedAt}`);
5620
+ lines.push("");
5621
+ if (corpus.staleMemories.length > 0) {
5622
+ lines.push(`## Stale Memories (not accessed in 30+ days, importance < 7)`);
5623
+ lines.push(`Count: ${corpus.staleMemories.length}`);
5624
+ for (const m of corpus.staleMemories.slice(0, 30)) {
5625
+ const accessed = m.accessed_at ?? "never";
5626
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} lastAccessed=${accessed}`);
5627
+ lines.push(` value: ${m.value.slice(0, 120)}`);
5628
+ }
5629
+ lines.push("");
5630
+ }
5631
+ if (corpus.duplicateCandidates.length > 0) {
5632
+ lines.push(`## Potential Duplicates (term overlap \u2265 50%)`);
5633
+ lines.push(`Count: ${corpus.duplicateCandidates.length} pairs`);
5634
+ for (const { a, b, similarity } of corpus.duplicateCandidates.slice(0, 20)) {
5635
+ lines.push(`- similarity=${similarity.toFixed(2)}`);
5636
+ lines.push(` A id:${a.id} key="${a.key}" importance=${a.importance}: ${a.value.slice(0, 80)}`);
5637
+ lines.push(` B id:${b.id} key="${b.key}" importance=${b.importance}: ${b.value.slice(0, 80)}`);
5638
+ }
5639
+ lines.push("");
5640
+ }
5641
+ if (corpus.lowImportanceHighRecall.length > 0) {
5642
+ lines.push(`## Low Importance But High Recall (candidates for importance promotion)`);
5643
+ for (const m of corpus.lowImportanceHighRecall.slice(0, 20)) {
5644
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} recall_count=${m.access_count}`);
5645
+ }
5646
+ lines.push("");
5647
+ }
5648
+ if (corpus.highImportanceLowRecall.length > 0) {
5649
+ lines.push(`## High Importance But Never Recalled (may need value update)`);
5650
+ for (const m of corpus.highImportanceLowRecall.slice(0, 20)) {
5651
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance}: ${m.value.slice(0, 80)}`);
5652
+ }
5653
+ lines.push("");
5654
+ }
5655
+ lines.push(`## Instructions`);
5656
+ lines.push(`Generate up to ${maxProposals} proposals as a JSON array. Each proposal must have:`);
5657
+ lines.push(` - type: "merge" | "archive" | "promote" | "update_value" | "add_tag" | "remove_duplicate"`);
5658
+ lines.push(` - memory_ids: string[] (IDs this proposal acts on)`);
5659
+ lines.push(` - target_memory_id: string (optional \u2014 used for merge/remove_duplicate)`);
5660
+ lines.push(` - proposed_changes: object (e.g. {new_importance:8} or {new_value:"..."} or {tags:["x"]})`);
5661
+ lines.push(` - reasoning: string (one sentence)`);
5662
+ lines.push(` - confidence: number 0.0-1.0`);
5663
+ lines.push("");
5664
+ lines.push(`Return ONLY the JSON array. No markdown, no explanation.`);
5665
+ return lines.join(`
5666
+ `);
5667
+ }
5668
+ async function analyzeCorpus(corpus, options) {
5669
+ const startMs = Date.now();
5670
+ const maxProposals = options?.maxProposals ?? 20;
5671
+ const empty = {
5672
+ proposals: [],
5673
+ summary: "No LLM provider available.",
5674
+ analysisDurationMs: 0
5675
+ };
5676
+ let provider = options?.provider ? providerRegistry.getProvider(options.provider) : providerRegistry.getAvailable();
5677
+ if (!provider) {
5678
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5679
+ }
5680
+ const userPrompt = buildCorpusPrompt(corpus, maxProposals);
5681
+ try {
5682
+ const rawResponse = await callProviderRaw(provider, SYNTHESIS_SYSTEM_PROMPT, userPrompt);
5683
+ if (!rawResponse) {
5684
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5685
+ }
5686
+ const parsed = parseProposalsResponse(rawResponse);
5687
+ const analysisDurationMs = Date.now() - startMs;
5688
+ const validProposals = parsed.slice(0, maxProposals);
5689
+ return {
5690
+ proposals: validProposals,
5691
+ summary: buildSummary(corpus, validProposals.length),
5692
+ analysisDurationMs
5693
+ };
5694
+ } catch {
5695
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
5696
+ }
5697
+ }
5698
+ async function callProviderRaw(provider, systemPrompt, userPrompt) {
5699
+ if (!provider)
5700
+ return null;
5701
+ const { config, name } = provider;
5702
+ if (!config.apiKey)
5703
+ return null;
5704
+ const timeoutMs = config.timeoutMs ?? 30000;
5705
+ try {
5706
+ if (name === "anthropic") {
5707
+ return await callAnthropic(config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
5708
+ } else if (name === "openai" || name === "cerebras" || name === "grok") {
5709
+ return await callOpenAICompat(name, config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
5710
+ }
5711
+ } catch {}
5712
+ return null;
5713
+ }
5714
+ async function callAnthropic(apiKey, model, systemPrompt, userPrompt, timeoutMs) {
5715
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
5716
+ method: "POST",
5717
+ headers: {
5718
+ "x-api-key": apiKey,
5719
+ "anthropic-version": "2023-06-01",
5720
+ "content-type": "application/json"
5721
+ },
5722
+ body: JSON.stringify({
5723
+ model,
5724
+ max_tokens: 2048,
5725
+ system: systemPrompt,
5726
+ messages: [{ role: "user", content: userPrompt }]
5727
+ }),
5728
+ signal: AbortSignal.timeout(timeoutMs)
5729
+ });
5730
+ if (!response.ok)
5731
+ return null;
5732
+ const data = await response.json();
5733
+ return data.content?.[0]?.text ?? null;
5734
+ }
5735
+ function getBaseUrlForProvider(providerName) {
5736
+ switch (providerName) {
5737
+ case "openai":
5738
+ return "https://api.openai.com/v1";
5739
+ case "cerebras":
5740
+ return "https://api.cerebras.ai/v1";
5741
+ case "grok":
5742
+ return "https://api.x.ai/v1";
5743
+ default:
5744
+ return "https://api.openai.com/v1";
5745
+ }
5746
+ }
5747
+ async function callOpenAICompat(providerName, apiKey, model, systemPrompt, userPrompt, timeoutMs) {
5748
+ const baseUrl = getBaseUrlForProvider(providerName);
5749
+ const response = await fetch(`${baseUrl}/chat/completions`, {
5750
+ method: "POST",
5751
+ headers: {
5752
+ authorization: `Bearer ${apiKey}`,
5753
+ "content-type": "application/json"
5754
+ },
5755
+ body: JSON.stringify({
5756
+ model,
5757
+ max_tokens: 2048,
5758
+ temperature: 0,
5759
+ messages: [
5760
+ { role: "system", content: systemPrompt },
5761
+ { role: "user", content: userPrompt }
5762
+ ]
5763
+ }),
5764
+ signal: AbortSignal.timeout(timeoutMs)
5765
+ });
5766
+ if (!response.ok)
5767
+ return null;
5768
+ const data = await response.json();
5769
+ return data.choices?.[0]?.message?.content ?? null;
5770
+ }
5771
+ function parseProposalsResponse(raw) {
5772
+ try {
5773
+ const cleaned = raw.replace(/^```(?:json)?\s*/m, "").replace(/\s*```$/m, "").trim();
5774
+ const parsed = JSON.parse(cleaned);
5775
+ if (!Array.isArray(parsed))
5776
+ return [];
5777
+ const validTypes = new Set([
5778
+ "merge",
5779
+ "archive",
5780
+ "promote",
5781
+ "update_value",
5782
+ "add_tag",
5783
+ "remove_duplicate"
5784
+ ]);
5785
+ return parsed.filter((item) => {
5786
+ if (!item || typeof item !== "object")
5787
+ return false;
5788
+ const p = item;
5789
+ 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";
5790
+ }).map((p) => ({
5791
+ type: p.type,
5792
+ memory_ids: p.memory_ids.filter((id) => typeof id === "string"),
5793
+ target_memory_id: typeof p.target_memory_id === "string" ? p.target_memory_id : undefined,
5794
+ proposed_changes: p.proposed_changes ?? {},
5795
+ reasoning: p.reasoning,
5796
+ confidence: Math.max(0, Math.min(1, p.confidence))
5797
+ }));
5798
+ } catch {
5799
+ return [];
5800
+ }
5801
+ }
5802
+ function buildSummary(corpus, proposalCount) {
5803
+ return `Analyzed ${corpus.totalMemories} memories. ` + `Found ${corpus.staleMemories.length} stale, ` + `${corpus.duplicateCandidates.length} duplicate pairs. ` + `Generated ${proposalCount} proposals.`;
5804
+ }
5805
+ 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.";
5806
+ var init_llm_analyzer = __esm(() => {
5807
+ init_registry();
5808
+ });
5809
+
5810
+ // src/lib/synthesis/validator.ts
5811
+ function validateProposals(proposals, corpus, config) {
5812
+ const cfg = { ...DEFAULT_SAFETY_CONFIG, ...config };
5813
+ const memoryMap = new Map(corpus.items.map((item) => [item.memory.id, item.memory]));
5814
+ const rejectedProposals = [];
5815
+ const warnings = [];
5816
+ let archiveCount = 0;
5817
+ let mergeCount = 0;
5818
+ for (const proposal of proposals) {
5819
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
5820
+ archiveCount++;
5821
+ }
5822
+ if (proposal.type === "merge") {
5823
+ mergeCount++;
5824
+ }
5825
+ }
5826
+ const corpusSize = corpus.totalMemories;
5827
+ const archivePercent = corpusSize > 0 ? archiveCount / corpusSize * 100 : 0;
5828
+ const mergePercent = corpusSize > 0 ? mergeCount / corpusSize * 100 : 0;
5829
+ if (archivePercent > cfg.maxArchivePercent) {
5830
+ warnings.push(`Archive proposals (${archiveCount}) exceed ${cfg.maxArchivePercent}% of corpus (${archivePercent.toFixed(1)}%). Some will be rejected.`);
5831
+ }
5832
+ if (mergePercent > cfg.maxMergePercent) {
5833
+ warnings.push(`Merge proposals (${mergeCount}) exceed ${cfg.maxMergePercent}% of corpus (${mergePercent.toFixed(1)}%). Some will be rejected.`);
5834
+ }
5835
+ let remainingArchiveSlots = Math.floor(cfg.maxArchivePercent / 100 * corpusSize);
5836
+ let remainingMergeSlots = Math.floor(cfg.maxMergePercent / 100 * corpusSize);
5837
+ for (let i = 0;i < proposals.length; i++) {
5838
+ const proposal = proposals[i];
5839
+ const proposalRef = `proposal[${i}]`;
5840
+ if (proposal.confidence < cfg.minConfidence) {
5841
+ rejectedProposals.push({
5842
+ proposalId: proposalRef,
5843
+ reason: `Confidence ${proposal.confidence.toFixed(2)} below minimum ${cfg.minConfidence}`
5844
+ });
5845
+ continue;
5846
+ }
5847
+ const missingIds = proposal.memory_ids.filter((id) => !memoryMap.has(id));
5848
+ if (missingIds.length > 0) {
5849
+ rejectedProposals.push({
5850
+ proposalId: proposalRef,
5851
+ reason: `References unknown memory IDs: ${missingIds.join(", ")}`
5852
+ });
5853
+ continue;
5854
+ }
5855
+ if (cfg.protectPinned) {
5856
+ const pinnedIds = proposal.memory_ids.filter((id) => {
5857
+ const m = memoryMap.get(id);
5858
+ return m?.pinned === true;
5859
+ });
5860
+ if (pinnedIds.length > 0) {
5861
+ rejectedProposals.push({
5862
+ proposalId: proposalRef,
5863
+ reason: `Attempts to modify pinned memories: ${pinnedIds.join(", ")}`
5864
+ });
5865
+ continue;
5866
+ }
5867
+ }
5868
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate" || proposal.type === "merge") {
5869
+ const highImportanceIds = proposal.memory_ids.filter((id) => {
5870
+ const m = memoryMap.get(id);
5871
+ return m && m.importance >= cfg.protectHighImportance;
5872
+ });
5873
+ if (highImportanceIds.length > 0) {
5874
+ rejectedProposals.push({
5875
+ proposalId: proposalRef,
5876
+ reason: `Attempts to archive/merge memories with importance \u2265 ${cfg.protectHighImportance}: ${highImportanceIds.join(", ")}`
5877
+ });
5878
+ continue;
5879
+ }
5880
+ }
5881
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
5882
+ if (remainingArchiveSlots <= 0) {
5883
+ rejectedProposals.push({
5884
+ proposalId: proposalRef,
5885
+ reason: `Archive quota exhausted (max ${cfg.maxArchivePercent}% of corpus)`
5886
+ });
5887
+ continue;
5888
+ }
5889
+ remainingArchiveSlots--;
5890
+ }
5891
+ if (proposal.type === "merge") {
5892
+ if (remainingMergeSlots <= 0) {
5893
+ rejectedProposals.push({
5894
+ proposalId: proposalRef,
5895
+ reason: `Merge quota exhausted (max ${cfg.maxMergePercent}% of corpus)`
5896
+ });
5897
+ continue;
5898
+ }
5899
+ remainingMergeSlots--;
5900
+ }
5901
+ if (proposal.target_memory_id && !memoryMap.has(proposal.target_memory_id)) {
5902
+ rejectedProposals.push({
5903
+ proposalId: proposalRef,
5904
+ reason: `target_memory_id "${proposal.target_memory_id}" does not exist in corpus`
5905
+ });
5906
+ continue;
5907
+ }
5908
+ }
5909
+ return {
5910
+ valid: rejectedProposals.length === 0,
5911
+ rejectedProposals,
5912
+ warnings
5913
+ };
5914
+ }
5915
+ var DEFAULT_SAFETY_CONFIG;
5916
+ var init_validator = __esm(() => {
5917
+ DEFAULT_SAFETY_CONFIG = {
5918
+ maxArchivePercent: 20,
5919
+ maxMergePercent: 30,
5920
+ minConfidence: 0.6,
5921
+ protectPinned: true,
5922
+ protectHighImportance: 9
5923
+ };
5924
+ });
5925
+
5926
+ // src/lib/synthesis/executor.ts
5927
+ async function executeProposals(runId, proposals, db) {
5928
+ const d = db || getDatabase();
5929
+ let executed = 0;
5930
+ let failed = 0;
5931
+ const rollbackData = {};
5932
+ for (const proposal of proposals) {
5933
+ try {
5934
+ const rollback = executeProposal(proposal, d);
5935
+ updateProposal(proposal.id, {
5936
+ status: "accepted",
5937
+ executed_at: now(),
5938
+ rollback_data: rollback
5939
+ }, d);
5940
+ rollbackData[proposal.id] = rollback;
5941
+ executed++;
5942
+ } catch (err) {
5943
+ try {
5944
+ updateProposal(proposal.id, { status: "rejected" }, d);
5945
+ } catch {}
5946
+ failed++;
5947
+ }
5948
+ }
5949
+ return { runId, executed, failed, rollbackData };
5950
+ }
5951
+ function executeProposal(proposal, d) {
5952
+ let rollbackData = {};
5953
+ d.transaction(() => {
5954
+ switch (proposal.proposal_type) {
5955
+ case "archive":
5956
+ rollbackData = executeArchive(proposal, d);
5957
+ break;
5958
+ case "promote":
5959
+ rollbackData = executePromote(proposal, d);
5960
+ break;
5961
+ case "update_value":
5962
+ rollbackData = executeUpdateValue(proposal, d);
5963
+ break;
5964
+ case "add_tag":
5965
+ rollbackData = executeAddTag(proposal, d);
5966
+ break;
5967
+ case "merge":
5968
+ rollbackData = executeMerge(proposal, d);
5969
+ break;
5970
+ case "remove_duplicate":
5971
+ rollbackData = executeRemoveDuplicate(proposal, d);
5972
+ break;
5973
+ default:
5974
+ throw new Error(`Unknown proposal type: ${proposal.proposal_type}`);
5975
+ }
5976
+ })();
5977
+ return rollbackData;
5978
+ }
5979
+ function executeArchive(proposal, d) {
5980
+ const rollback = {};
5981
+ for (const memId of proposal.memory_ids) {
5982
+ const mem = getMemory(memId, d);
5983
+ if (!mem)
5984
+ continue;
5985
+ rollback[memId] = mem.status;
5986
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
5987
+ }
5988
+ return { old_status: rollback };
5989
+ }
5990
+ function executePromote(proposal, d) {
5991
+ const newImportance = proposal.proposed_changes["new_importance"];
5992
+ if (typeof newImportance !== "number") {
5993
+ throw new Error("promote proposal missing new_importance in proposed_changes");
5994
+ }
5995
+ const rollback = {};
5996
+ for (const memId of proposal.memory_ids) {
5997
+ const mem = getMemory(memId, d);
5998
+ if (!mem)
5999
+ continue;
6000
+ rollback[memId] = mem.importance;
6001
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [Math.max(1, Math.min(10, Math.round(newImportance))), now(), memId]);
6002
+ }
6003
+ return { old_importance: rollback };
6004
+ }
6005
+ function executeUpdateValue(proposal, d) {
6006
+ const newValue = proposal.proposed_changes["new_value"];
6007
+ if (typeof newValue !== "string") {
6008
+ throw new Error("update_value proposal missing new_value in proposed_changes");
6009
+ }
6010
+ const rollback = {};
6011
+ const memId = proposal.memory_ids[0];
6012
+ if (!memId)
6013
+ throw new Error("update_value proposal has no memory_ids");
6014
+ const mem = getMemory(memId, d);
6015
+ if (!mem)
6016
+ throw new Error(`Memory ${memId} not found`);
6017
+ rollback[memId] = { value: mem.value, version: mem.version };
6018
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [newValue, now(), memId]);
6019
+ return { old_state: rollback };
6020
+ }
6021
+ function executeAddTag(proposal, d) {
6022
+ const tagsToAdd = proposal.proposed_changes["tags"];
6023
+ if (!Array.isArray(tagsToAdd)) {
6024
+ throw new Error("add_tag proposal missing tags array in proposed_changes");
6025
+ }
6026
+ const rollback = {};
6027
+ for (const memId of proposal.memory_ids) {
6028
+ const mem = getMemory(memId, d);
6029
+ if (!mem)
6030
+ continue;
6031
+ rollback[memId] = [...mem.tags];
6032
+ const newTags = Array.from(new Set([...mem.tags, ...tagsToAdd]));
6033
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(newTags), now(), memId]);
6034
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
6035
+ for (const tag of tagsToAdd) {
6036
+ insertTag.run(memId, tag);
6037
+ }
6038
+ }
6039
+ return { old_tags: rollback };
6040
+ }
6041
+ function executeMerge(proposal, d) {
6042
+ const targetId = proposal.target_memory_id;
6043
+ if (!targetId)
6044
+ throw new Error("merge proposal missing target_memory_id");
6045
+ const target = getMemory(targetId, d);
6046
+ if (!target)
6047
+ throw new Error(`Target memory ${targetId} not found`);
6048
+ const rollback = {
6049
+ target_old_value: target.value,
6050
+ target_old_version: target.version,
6051
+ archived_memories: {}
6052
+ };
6053
+ const sourceValues = [];
6054
+ for (const memId of proposal.memory_ids) {
6055
+ if (memId === targetId)
6056
+ continue;
6057
+ const mem = getMemory(memId, d);
6058
+ if (!mem)
6059
+ continue;
6060
+ sourceValues.push(mem.value);
6061
+ rollback.archived_memories[memId] = mem.status;
6062
+ }
6063
+ const mergedValue = proposal.proposed_changes["merged_value"] ?? [target.value, ...sourceValues].join(`
6064
+ ---
6065
+ `);
6066
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [mergedValue, now(), targetId]);
6067
+ for (const memId of proposal.memory_ids) {
6068
+ if (memId === targetId)
6069
+ continue;
6070
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
6071
+ }
6072
+ return rollback;
6073
+ }
6074
+ function executeRemoveDuplicate(proposal, d) {
6075
+ const memories = proposal.memory_ids.map((id) => getMemory(id, d)).filter((m) => m !== null);
6076
+ if (memories.length < 2) {
6077
+ throw new Error("remove_duplicate requires at least 2 memories");
6078
+ }
6079
+ memories.sort((a, b) => b.importance - a.importance || a.created_at.localeCompare(b.created_at));
6080
+ const keepId = proposal.target_memory_id ?? memories[0].id;
6081
+ const rollback = {};
6082
+ for (const mem of memories) {
6083
+ if (mem.id === keepId)
6084
+ continue;
6085
+ rollback[mem.id] = mem.status;
6086
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), mem.id]);
6087
+ }
6088
+ return { old_status: rollback, kept_id: keepId };
6089
+ }
6090
+ async function rollbackRun(runId, db) {
6091
+ const d = db || getDatabase();
6092
+ const proposals = listProposals(runId, { status: "accepted" }, d);
6093
+ let rolledBack = 0;
6094
+ const errors = [];
6095
+ for (const proposal of proposals) {
6096
+ try {
6097
+ rollbackProposal(proposal, d);
6098
+ updateProposal(proposal.id, { status: "rolled_back" }, d);
6099
+ rolledBack++;
6100
+ } catch (err) {
6101
+ errors.push(`Proposal ${proposal.id} (${proposal.proposal_type}): ${err instanceof Error ? err.message : String(err)}`);
6102
+ }
6103
+ }
6104
+ return { rolled_back: rolledBack, errors };
6105
+ }
6106
+ function rollbackProposal(proposal, d) {
6107
+ const rb = proposal.rollback_data;
6108
+ if (!rb)
6109
+ return;
6110
+ d.transaction(() => {
6111
+ switch (proposal.proposal_type) {
6112
+ case "archive":
6113
+ case "remove_duplicate": {
6114
+ const oldStatus = rb["old_status"];
6115
+ if (!oldStatus)
6116
+ break;
6117
+ for (const [memId, status] of Object.entries(oldStatus)) {
6118
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
6119
+ }
6120
+ break;
6121
+ }
6122
+ case "promote": {
6123
+ const oldImportance = rb["old_importance"];
6124
+ if (!oldImportance)
6125
+ break;
6126
+ for (const [memId, importance] of Object.entries(oldImportance)) {
6127
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [importance, now(), memId]);
6128
+ }
6129
+ break;
6130
+ }
6131
+ case "update_value": {
6132
+ const oldState = rb["old_state"];
6133
+ if (!oldState)
6134
+ break;
6135
+ for (const [memId, state] of Object.entries(oldState)) {
6136
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [state.value, state.version, now(), memId]);
6137
+ }
6138
+ break;
6139
+ }
6140
+ case "add_tag": {
6141
+ const oldTags = rb["old_tags"];
6142
+ if (!oldTags)
6143
+ break;
6144
+ for (const [memId, tags] of Object.entries(oldTags)) {
6145
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(tags), now(), memId]);
6146
+ d.run("DELETE FROM memory_tags WHERE memory_id = ?", [memId]);
6147
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
6148
+ for (const tag of tags) {
6149
+ insertTag.run(memId, tag);
6150
+ }
6151
+ }
6152
+ break;
6153
+ }
6154
+ case "merge": {
6155
+ const targetOldValue = rb["target_old_value"];
6156
+ const targetOldVersion = rb["target_old_version"];
6157
+ const archivedMemories = rb["archived_memories"];
6158
+ const targetId = proposal.target_memory_id;
6159
+ if (targetId && targetOldValue !== undefined && targetOldVersion !== undefined) {
6160
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [targetOldValue, targetOldVersion, now(), targetId]);
6161
+ }
6162
+ if (archivedMemories) {
6163
+ for (const [memId, status] of Object.entries(archivedMemories)) {
6164
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
6165
+ }
6166
+ }
6167
+ break;
6168
+ }
6169
+ default:
6170
+ break;
6171
+ }
6172
+ })();
6173
+ }
6174
+ var init_executor = __esm(() => {
6175
+ init_database();
6176
+ init_memories();
6177
+ init_synthesis();
6178
+ });
6179
+
6180
+ // src/lib/synthesis/metrics.ts
6181
+ async function measureEffectiveness(runId, preCorpus, db) {
6182
+ const d = db || getDatabase();
6183
+ const postMemories = listMemories({
6184
+ status: "active",
6185
+ project_id: preCorpus.projectId ?? undefined
6186
+ }, d);
6187
+ const postCount = postMemories.length;
6188
+ const preCount = preCorpus.totalMemories;
6189
+ const corpusReduction = preCount > 0 ? (preCount - postCount) / preCount * 100 : 0;
6190
+ const preAvgImportance = preCorpus.items.length > 0 ? preCorpus.items.reduce((sum, i) => sum + i.memory.importance, 0) / preCorpus.items.length : 0;
6191
+ const postAvgImportance = postMemories.length > 0 ? postMemories.reduce((sum, m) => sum + m.importance, 0) / postMemories.length : 0;
6192
+ const importanceDrift = postAvgImportance - preAvgImportance;
6193
+ const preDuplicatePairs = preCorpus.duplicateCandidates.length;
6194
+ const acceptedProposals = listProposals(runId, { status: "accepted" }, d);
6195
+ const deduplicationProposals = acceptedProposals.filter((p) => p.proposal_type === "remove_duplicate" || p.proposal_type === "merge");
6196
+ const deduplicationRate = preDuplicatePairs > 0 ? deduplicationProposals.length / preDuplicatePairs * 100 : 0;
6197
+ const recallWeight = {
6198
+ corpusReduction: 0.3,
6199
+ importanceDrift: 0.4,
6200
+ deduplicationRate: 0.3
6201
+ };
6202
+ const estimatedRecallImprovement = Math.max(0, Math.min(100, corpusReduction * recallWeight.corpusReduction + Math.max(0, importanceDrift * 10) * recallWeight.importanceDrift + deduplicationRate * recallWeight.deduplicationRate));
6203
+ const metricDefs = [
6204
+ { metric_type: "corpus_reduction_pct", value: corpusReduction, baseline: 0 },
6205
+ { metric_type: "importance_drift", value: importanceDrift, baseline: 0 },
6206
+ { metric_type: "deduplication_rate_pct", value: deduplicationRate, baseline: 0 },
6207
+ { metric_type: "estimated_recall_improvement_pct", value: estimatedRecallImprovement, baseline: 0 },
6208
+ { metric_type: "pre_corpus_size", value: preCount, baseline: preCount },
6209
+ { metric_type: "post_corpus_size", value: postCount, baseline: preCount },
6210
+ { metric_type: "proposals_accepted", value: acceptedProposals.length, baseline: 0 },
6211
+ { metric_type: "pre_avg_importance", value: preAvgImportance, baseline: preAvgImportance },
6212
+ { metric_type: "post_avg_importance", value: postAvgImportance, baseline: preAvgImportance }
6213
+ ];
6214
+ for (const def of metricDefs) {
6215
+ createMetric({
6216
+ run_id: runId,
6217
+ metric_type: def.metric_type,
6218
+ value: def.value,
6219
+ baseline: def.baseline ?? null
6220
+ }, d);
6221
+ }
6222
+ const metrics = listMetrics(runId, d);
6223
+ return {
6224
+ runId,
6225
+ corpusReduction,
6226
+ importanceDrift,
6227
+ deduplicationRate,
6228
+ estimatedRecallImprovement,
6229
+ metrics
6230
+ };
6231
+ }
6232
+ var init_metrics = __esm(() => {
6233
+ init_database();
6234
+ init_synthesis();
6235
+ init_memories();
6236
+ });
6237
+
6238
+ // src/lib/synthesis/index.ts
6239
+ var exports_synthesis2 = {};
6240
+ __export(exports_synthesis2, {
6241
+ runSynthesis: () => runSynthesis,
6242
+ rollbackSynthesis: () => rollbackSynthesis,
6243
+ getSynthesisStatus: () => getSynthesisStatus
6244
+ });
6245
+ async function runSynthesis(options = {}) {
6246
+ const d = options.db || getDatabase();
6247
+ const projectId = options.projectId ?? null;
6248
+ const agentId = options.agentId ?? null;
6249
+ const dryRun = options.dryRun ?? false;
6250
+ const run = createSynthesisRun({
6251
+ triggered_by: "manual",
6252
+ project_id: projectId,
6253
+ agent_id: agentId
6254
+ }, d);
6255
+ updateSynthesisRun(run.id, { status: "running" }, d);
6256
+ try {
6257
+ const corpus = await buildCorpus({
6258
+ projectId: projectId ?? undefined,
6259
+ agentId: agentId ?? undefined,
6260
+ db: d
6261
+ });
6262
+ updateSynthesisRun(run.id, { corpus_size: corpus.totalMemories }, d);
6263
+ const analysisResult = await analyzeCorpus(corpus, {
6264
+ provider: options.provider,
6265
+ maxProposals: options.maxProposals ?? 20
6266
+ });
6267
+ const validation = validateProposals(analysisResult.proposals, corpus, options.safetyConfig);
6268
+ const rejectedIndices = new Set(validation.rejectedProposals.map((r) => {
6269
+ const match = r.proposalId.match(/\[(\d+)\]/);
6270
+ return match ? parseInt(match[1], 10) : -1;
6271
+ }));
6272
+ const validProposals = analysisResult.proposals.filter((_, idx) => !rejectedIndices.has(idx));
6273
+ const savedProposals = [];
6274
+ for (const p of validProposals) {
6275
+ const saved = createProposal({
6276
+ run_id: run.id,
6277
+ proposal_type: p.type,
6278
+ memory_ids: p.memory_ids,
6279
+ target_memory_id: p.target_memory_id ?? null,
6280
+ proposed_changes: p.proposed_changes,
6281
+ reasoning: p.reasoning,
6282
+ confidence: p.confidence
6283
+ }, d);
6284
+ savedProposals.push(saved);
6285
+ }
6286
+ updateSynthesisRun(run.id, {
6287
+ proposals_generated: analysisResult.proposals.length,
6288
+ proposals_rejected: validation.rejectedProposals.length
6289
+ }, d);
6290
+ let executedCount = 0;
6291
+ if (!dryRun && savedProposals.length > 0) {
6292
+ const execResult = await executeProposals(run.id, savedProposals, d);
6293
+ executedCount = execResult.executed;
6294
+ updateSynthesisRun(run.id, {
6295
+ proposals_accepted: execResult.executed,
6296
+ proposals_rejected: validation.rejectedProposals.length + execResult.failed,
6297
+ status: "completed",
6298
+ completed_at: now()
6299
+ }, d);
6300
+ } else {
6301
+ updateSynthesisRun(run.id, {
6302
+ status: "completed",
6303
+ completed_at: now()
6304
+ }, d);
6305
+ }
6306
+ let effectivenessReport = null;
6307
+ if (!dryRun && executedCount > 0) {
6308
+ try {
6309
+ effectivenessReport = await measureEffectiveness(run.id, corpus, d);
6310
+ } catch {}
6311
+ }
6312
+ const finalRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
6313
+ const finalProposals = listProposals(run.id, undefined, d);
6314
+ return {
6315
+ run: finalRun,
6316
+ proposals: finalProposals,
6317
+ executed: executedCount,
6318
+ metrics: effectivenessReport,
6319
+ dryRun
6320
+ };
6321
+ } catch (err) {
6322
+ updateSynthesisRun(run.id, {
6323
+ status: "failed",
6324
+ error: err instanceof Error ? err.message : String(err),
6325
+ completed_at: now()
6326
+ }, d);
6327
+ const failedRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
6328
+ return {
6329
+ run: failedRun,
6330
+ proposals: [],
6331
+ executed: 0,
6332
+ metrics: null,
6333
+ dryRun
6334
+ };
6335
+ }
6336
+ }
6337
+ async function rollbackSynthesis(runId, db) {
6338
+ const d = db || getDatabase();
6339
+ const result = await rollbackRun(runId, d);
6340
+ if (result.errors.length === 0) {
6341
+ updateSynthesisRun(runId, { status: "rolled_back", completed_at: now() }, d);
6342
+ }
6343
+ return result;
6344
+ }
6345
+ function getSynthesisStatus(runId, projectId, db) {
6346
+ const d = db || getDatabase();
6347
+ if (runId) {
6348
+ const recentRuns2 = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
6349
+ const specificRun = recentRuns2.find((r) => r.id === runId) ?? null;
6350
+ return {
6351
+ lastRun: specificRun ?? recentRuns2[0] ?? null,
6352
+ recentRuns: recentRuns2
6353
+ };
6354
+ }
6355
+ const recentRuns = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
6356
+ return {
6357
+ lastRun: recentRuns[0] ?? null,
6358
+ recentRuns
6359
+ };
6360
+ }
6361
+ var init_synthesis2 = __esm(() => {
6362
+ init_database();
6363
+ init_synthesis();
6364
+ init_corpus_builder();
6365
+ init_llm_analyzer();
6366
+ init_validator();
6367
+ init_executor();
6368
+ init_metrics();
6369
+ });
6370
+
6371
+ // src/db/session-jobs.ts
6372
+ var exports_session_jobs = {};
6373
+ __export(exports_session_jobs, {
6374
+ updateSessionJob: () => updateSessionJob,
6375
+ listSessionJobs: () => listSessionJobs,
6376
+ getSessionJob: () => getSessionJob,
6377
+ getNextPendingJob: () => getNextPendingJob,
6378
+ createSessionJob: () => createSessionJob
6379
+ });
6380
+ function parseJobRow(row) {
6381
+ return {
6382
+ id: row["id"],
6383
+ session_id: row["session_id"],
6384
+ agent_id: row["agent_id"] || null,
6385
+ project_id: row["project_id"] || null,
6386
+ source: row["source"],
6387
+ status: row["status"],
6388
+ transcript: row["transcript"],
6389
+ chunk_count: row["chunk_count"],
6390
+ memories_extracted: row["memories_extracted"],
6391
+ error: row["error"] || null,
6392
+ metadata: JSON.parse(row["metadata"] || "{}"),
6393
+ created_at: row["created_at"],
6394
+ started_at: row["started_at"] || null,
6395
+ completed_at: row["completed_at"] || null
6396
+ };
6397
+ }
6398
+ function createSessionJob(input, db) {
6399
+ const d = db || getDatabase();
6400
+ const id = uuid();
6401
+ const timestamp = now();
6402
+ const source = input.source ?? "manual";
6403
+ const metadata = JSON.stringify(input.metadata ?? {});
6404
+ d.run(`INSERT INTO session_memory_jobs
6405
+ (id, session_id, agent_id, project_id, source, status, transcript, chunk_count, memories_extracted, metadata, created_at)
6406
+ VALUES (?, ?, ?, ?, ?, 'pending', ?, 0, 0, ?, ?)`, [
6407
+ id,
6408
+ input.session_id,
6409
+ input.agent_id ?? null,
6410
+ input.project_id ?? null,
6411
+ source,
6412
+ input.transcript,
6413
+ metadata,
6414
+ timestamp
6415
+ ]);
6416
+ return getSessionJob(id, d);
4867
6417
  }
4868
- function getWebhookHook(id, db) {
6418
+ function getSessionJob(id, db) {
4869
6419
  const d = db || getDatabase();
4870
- const row = d.query("SELECT * FROM webhook_hooks WHERE id = ?").get(id);
4871
- return row ? parseRow(row) : null;
6420
+ const row = d.query("SELECT * FROM session_memory_jobs WHERE id = ?").get(id);
6421
+ if (!row)
6422
+ return null;
6423
+ return parseJobRow(row);
4872
6424
  }
4873
- function listWebhookHooks(filter = {}, db) {
6425
+ function listSessionJobs(filter, db) {
4874
6426
  const d = db || getDatabase();
4875
6427
  const conditions = [];
4876
6428
  const params = [];
4877
- if (filter.type) {
4878
- conditions.push("type = ?");
4879
- params.push(filter.type);
6429
+ if (filter?.agent_id) {
6430
+ conditions.push("agent_id = ?");
6431
+ params.push(filter.agent_id);
4880
6432
  }
4881
- if (filter.enabled !== undefined) {
4882
- conditions.push("enabled = ?");
4883
- params.push(filter.enabled ? 1 : 0);
6433
+ if (filter?.project_id) {
6434
+ conditions.push("project_id = ?");
6435
+ params.push(filter.project_id);
6436
+ }
6437
+ if (filter?.status) {
6438
+ conditions.push("status = ?");
6439
+ params.push(filter.status);
6440
+ }
6441
+ if (filter?.session_id) {
6442
+ conditions.push("session_id = ?");
6443
+ params.push(filter.session_id);
4884
6444
  }
4885
6445
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4886
- const rows = d.query(`SELECT * FROM webhook_hooks ${where} ORDER BY priority ASC, created_at ASC`).all(...params);
4887
- return rows.map(parseRow);
6446
+ const limit = filter?.limit ?? 20;
6447
+ const offset = filter?.offset ?? 0;
6448
+ const rows = d.query(`SELECT * FROM session_memory_jobs ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...params, limit, offset);
6449
+ return rows.map(parseJobRow);
4888
6450
  }
4889
- function updateWebhookHook(id, updates, db) {
6451
+ function updateSessionJob(id, updates, db) {
4890
6452
  const d = db || getDatabase();
4891
- const existing = getWebhookHook(id, d);
4892
- if (!existing)
4893
- return null;
4894
- const sets = [];
6453
+ const setClauses = [];
4895
6454
  const params = [];
4896
- if (updates.enabled !== undefined) {
4897
- sets.push("enabled = ?");
4898
- params.push(updates.enabled ? 1 : 0);
6455
+ if (updates.status !== undefined) {
6456
+ setClauses.push("status = ?");
6457
+ params.push(updates.status);
4899
6458
  }
4900
- if (updates.description !== undefined) {
4901
- sets.push("description = ?");
4902
- params.push(updates.description);
6459
+ if (updates.chunk_count !== undefined) {
6460
+ setClauses.push("chunk_count = ?");
6461
+ params.push(updates.chunk_count);
4903
6462
  }
4904
- if (updates.priority !== undefined) {
4905
- sets.push("priority = ?");
4906
- params.push(updates.priority);
6463
+ if (updates.memories_extracted !== undefined) {
6464
+ setClauses.push("memories_extracted = ?");
6465
+ params.push(updates.memories_extracted);
4907
6466
  }
4908
- if (sets.length > 0) {
4909
- params.push(id);
4910
- d.run(`UPDATE webhook_hooks SET ${sets.join(", ")} WHERE id = ?`, params);
6467
+ if ("error" in updates) {
6468
+ setClauses.push("error = ?");
6469
+ params.push(updates.error ?? null);
4911
6470
  }
4912
- return getWebhookHook(id, d);
4913
- }
4914
- function deleteWebhookHook(id, db) {
4915
- const d = db || getDatabase();
4916
- const result = d.run("DELETE FROM webhook_hooks WHERE id = ?", [id]);
4917
- return result.changes > 0;
6471
+ if ("started_at" in updates) {
6472
+ setClauses.push("started_at = ?");
6473
+ params.push(updates.started_at ?? null);
6474
+ }
6475
+ if ("completed_at" in updates) {
6476
+ setClauses.push("completed_at = ?");
6477
+ params.push(updates.completed_at ?? null);
6478
+ }
6479
+ if (setClauses.length === 0)
6480
+ return getSessionJob(id, d);
6481
+ params.push(id);
6482
+ d.run(`UPDATE session_memory_jobs SET ${setClauses.join(", ")} WHERE id = ?`, params);
6483
+ return getSessionJob(id, d);
4918
6484
  }
4919
- function recordWebhookInvocation(id, success, db) {
6485
+ function getNextPendingJob(db) {
4920
6486
  const d = db || getDatabase();
4921
- if (success) {
4922
- d.run("UPDATE webhook_hooks SET invocation_count = invocation_count + 1 WHERE id = ?", [id]);
4923
- } else {
4924
- d.run("UPDATE webhook_hooks SET invocation_count = invocation_count + 1, failure_count = failure_count + 1 WHERE id = ?", [id]);
4925
- }
6487
+ const row = d.query("SELECT * FROM session_memory_jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1").get();
6488
+ if (!row)
6489
+ return null;
6490
+ return parseJobRow(row);
4926
6491
  }
4927
- var init_webhook_hooks = __esm(() => {
6492
+ var init_session_jobs = __esm(() => {
4928
6493
  init_database();
4929
6494
  });
4930
6495
 
4931
- // src/lib/built-in-hooks.ts
4932
- var exports_built_in_hooks = {};
4933
- __export(exports_built_in_hooks, {
4934
- reloadWebhooks: () => reloadWebhooks,
4935
- loadWebhooksFromDb: () => loadWebhooksFromDb
4936
- });
4937
- async function getAutoMemory() {
4938
- if (!_processConversationTurn) {
4939
- const mod = await Promise.resolve().then(() => (init_auto_memory(), exports_auto_memory));
4940
- _processConversationTurn = mod.processConversationTurn;
6496
+ // src/lib/session-processor.ts
6497
+ function chunkTranscript(transcript, chunkSize = 2000, overlap = 200) {
6498
+ if (!transcript || transcript.length === 0)
6499
+ return [];
6500
+ if (transcript.length <= chunkSize)
6501
+ return [transcript];
6502
+ const chunks = [];
6503
+ let start = 0;
6504
+ while (start < transcript.length) {
6505
+ const end = Math.min(start + chunkSize, transcript.length);
6506
+ chunks.push(transcript.slice(start, end));
6507
+ if (end === transcript.length)
6508
+ break;
6509
+ start += chunkSize - overlap;
4941
6510
  }
4942
- return _processConversationTurn;
6511
+ return chunks;
4943
6512
  }
4944
- function loadWebhooksFromDb() {
4945
- if (_webhooksLoaded)
4946
- return;
4947
- _webhooksLoaded = true;
6513
+ async function extractMemoriesFromChunk(chunk, context, db) {
6514
+ const provider = providerRegistry.getAvailable();
6515
+ if (!provider)
6516
+ return 0;
4948
6517
  try {
4949
- const webhooks = listWebhookHooks({ enabled: true });
4950
- for (const wh of webhooks) {
4951
- hookRegistry.register({
4952
- type: wh.type,
4953
- blocking: wh.blocking,
4954
- priority: wh.priority,
4955
- agentId: wh.agentId,
4956
- projectId: wh.projectId,
4957
- description: wh.description ?? `Webhook: ${wh.handlerUrl}`,
4958
- handler: makeWebhookHandler(wh.id, wh.handlerUrl)
4959
- });
4960
- }
4961
- if (webhooks.length > 0) {
4962
- console.log(`[hooks] Loaded ${webhooks.length} webhook(s) from DB`);
6518
+ const extracted = await provider.extractMemories(SESSION_EXTRACTION_USER_TEMPLATE(chunk, context.sessionId), {
6519
+ sessionId: context.sessionId,
6520
+ agentId: context.agentId,
6521
+ projectId: context.projectId
6522
+ });
6523
+ let savedCount = 0;
6524
+ const sourceTag = context.source ? `source:${context.source}` : "source:manual";
6525
+ for (const memory of extracted) {
6526
+ if (!memory.content || !memory.content.trim())
6527
+ continue;
6528
+ try {
6529
+ createMemory({
6530
+ key: memory.content.slice(0, 120).replace(/\s+/g, "-").toLowerCase(),
6531
+ value: memory.content,
6532
+ category: memory.category,
6533
+ scope: memory.suggestedScope ?? "shared",
6534
+ importance: memory.importance,
6535
+ tags: [
6536
+ ...memory.tags,
6537
+ "session-extracted",
6538
+ sourceTag,
6539
+ `session:${context.sessionId}`
6540
+ ],
6541
+ source: "auto",
6542
+ agent_id: context.agentId,
6543
+ project_id: context.projectId,
6544
+ session_id: context.sessionId,
6545
+ metadata: {
6546
+ auto_extracted: true,
6547
+ session_source: context.source ?? "manual",
6548
+ extracted_at: new Date().toISOString(),
6549
+ reasoning: memory.reasoning
6550
+ }
6551
+ }, "merge", db);
6552
+ savedCount++;
6553
+ } catch {}
4963
6554
  }
4964
- } catch (err) {
4965
- console.error("[hooks] Failed to load webhooks from DB:", err);
6555
+ return savedCount;
6556
+ } catch {
6557
+ try {
6558
+ const fallbacks = providerRegistry.getFallbacks();
6559
+ for (const fallback of fallbacks) {
6560
+ try {
6561
+ const extracted = await fallback.extractMemories(SESSION_EXTRACTION_USER_TEMPLATE(chunk, context.sessionId), {
6562
+ sessionId: context.sessionId,
6563
+ agentId: context.agentId,
6564
+ projectId: context.projectId
6565
+ });
6566
+ let savedCount = 0;
6567
+ const sourceTag = context.source ? `source:${context.source}` : "source:manual";
6568
+ for (const memory of extracted) {
6569
+ if (!memory.content || !memory.content.trim())
6570
+ continue;
6571
+ try {
6572
+ createMemory({
6573
+ key: memory.content.slice(0, 120).replace(/\s+/g, "-").toLowerCase(),
6574
+ value: memory.content,
6575
+ category: memory.category,
6576
+ scope: memory.suggestedScope ?? "shared",
6577
+ importance: memory.importance,
6578
+ tags: [
6579
+ ...memory.tags,
6580
+ "session-extracted",
6581
+ sourceTag,
6582
+ `session:${context.sessionId}`
6583
+ ],
6584
+ source: "auto",
6585
+ agent_id: context.agentId,
6586
+ project_id: context.projectId,
6587
+ session_id: context.sessionId,
6588
+ metadata: {
6589
+ auto_extracted: true,
6590
+ session_source: context.source ?? "manual",
6591
+ extracted_at: new Date().toISOString(),
6592
+ reasoning: memory.reasoning
6593
+ }
6594
+ }, "merge", db);
6595
+ savedCount++;
6596
+ } catch {}
6597
+ }
6598
+ if (savedCount > 0)
6599
+ return savedCount;
6600
+ } catch {
6601
+ continue;
6602
+ }
6603
+ }
6604
+ } catch {}
6605
+ return 0;
4966
6606
  }
4967
6607
  }
4968
- function makeWebhookHandler(webhookId, url) {
4969
- return async (context) => {
6608
+ async function processSessionJob(jobId, db) {
6609
+ const result = {
6610
+ jobId,
6611
+ chunksProcessed: 0,
6612
+ memoriesExtracted: 0,
6613
+ errors: []
6614
+ };
6615
+ let job;
6616
+ try {
6617
+ job = getSessionJob(jobId, db);
6618
+ if (!job) {
6619
+ result.errors.push(`Job not found: ${jobId}`);
6620
+ return result;
6621
+ }
6622
+ } catch (e) {
6623
+ result.errors.push(`Failed to fetch job: ${String(e)}`);
6624
+ return result;
6625
+ }
6626
+ try {
6627
+ updateSessionJob(jobId, { status: "processing", started_at: new Date().toISOString() }, db);
6628
+ } catch (e) {
6629
+ result.errors.push(`Failed to mark job as processing: ${String(e)}`);
6630
+ return result;
6631
+ }
6632
+ const chunks = chunkTranscript(job.transcript);
6633
+ try {
6634
+ updateSessionJob(jobId, { chunk_count: chunks.length }, db);
6635
+ } catch {}
6636
+ let totalMemories = 0;
6637
+ for (let i = 0;i < chunks.length; i++) {
6638
+ const chunk = chunks[i];
4970
6639
  try {
4971
- const res = await fetch(url, {
4972
- method: "POST",
4973
- headers: { "Content-Type": "application/json" },
4974
- body: JSON.stringify(context),
4975
- signal: AbortSignal.timeout(1e4)
4976
- });
4977
- recordWebhookInvocation(webhookId, res.ok);
4978
- } catch {
4979
- recordWebhookInvocation(webhookId, false);
6640
+ const count = await extractMemoriesFromChunk(chunk, {
6641
+ sessionId: job.session_id,
6642
+ agentId: job.agent_id ?? undefined,
6643
+ projectId: job.project_id ?? undefined,
6644
+ source: job.source
6645
+ }, db);
6646
+ totalMemories += count;
6647
+ result.chunksProcessed++;
6648
+ } catch (e) {
6649
+ result.errors.push(`Chunk ${i} failed: ${String(e)}`);
4980
6650
  }
4981
- };
6651
+ }
6652
+ result.memoriesExtracted = totalMemories;
6653
+ try {
6654
+ if (result.errors.length > 0 && result.chunksProcessed === 0) {
6655
+ updateSessionJob(jobId, {
6656
+ status: "failed",
6657
+ error: result.errors.join("; "),
6658
+ completed_at: new Date().toISOString(),
6659
+ memories_extracted: totalMemories,
6660
+ chunk_count: chunks.length
6661
+ }, db);
6662
+ } else {
6663
+ updateSessionJob(jobId, {
6664
+ status: "completed",
6665
+ completed_at: new Date().toISOString(),
6666
+ memories_extracted: totalMemories,
6667
+ chunk_count: chunks.length
6668
+ }, db);
6669
+ }
6670
+ } catch (e) {
6671
+ result.errors.push(`Failed to update job status: ${String(e)}`);
6672
+ }
6673
+ return result;
4982
6674
  }
4983
- function reloadWebhooks() {
4984
- _webhooksLoaded = false;
4985
- loadWebhooksFromDb();
6675
+ var SESSION_EXTRACTION_USER_TEMPLATE = (chunk, sessionId) => `Extract memories from this session chunk (session: ${sessionId}):
6676
+
6677
+ ${chunk}
6678
+
6679
+ Return JSON array: [{"key": "...", "value": "...", "category": "knowledge|fact|preference|history", "importance": 1-10, "tags": [...]}]`;
6680
+ var init_session_processor = __esm(() => {
6681
+ init_memories();
6682
+ init_registry();
6683
+ init_session_jobs();
6684
+ });
6685
+
6686
+ // src/lib/session-queue.ts
6687
+ var exports_session_queue = {};
6688
+ __export(exports_session_queue, {
6689
+ startSessionQueueWorker: () => startSessionQueueWorker,
6690
+ getSessionQueueStats: () => getSessionQueueStats,
6691
+ enqueueSessionJob: () => enqueueSessionJob
6692
+ });
6693
+ function enqueueSessionJob(jobId) {
6694
+ _pendingQueue.add(jobId);
6695
+ if (!_isProcessing) {
6696
+ _processNext();
6697
+ }
4986
6698
  }
4987
- var _processConversationTurn = null, _webhooksLoaded = false;
4988
- var init_built_in_hooks = __esm(() => {
4989
- init_hooks();
4990
- init_webhook_hooks();
4991
- hookRegistry.register({
4992
- type: "PostMemorySave",
4993
- blocking: false,
4994
- builtin: true,
4995
- priority: 100,
4996
- description: "Trigger async LLM entity extraction when a memory is saved",
4997
- handler: async (ctx) => {
4998
- if (ctx.wasUpdated)
4999
- return;
5000
- const processConversationTurn2 = await getAutoMemory();
5001
- processConversationTurn2(`${ctx.memory.key}: ${ctx.memory.value}`, {
5002
- agentId: ctx.agentId,
5003
- projectId: ctx.projectId,
5004
- sessionId: ctx.sessionId
5005
- });
6699
+ function getSessionQueueStats() {
6700
+ try {
6701
+ const db = getDatabase();
6702
+ const rows = db.query("SELECT status, COUNT(*) as count FROM session_memory_jobs GROUP BY status").all();
6703
+ const stats = {
6704
+ pending: 0,
6705
+ processing: 0,
6706
+ completed: 0,
6707
+ failed: 0
6708
+ };
6709
+ for (const row of rows) {
6710
+ if (row.status === "pending")
6711
+ stats.pending = row.count;
6712
+ else if (row.status === "processing")
6713
+ stats.processing = row.count;
6714
+ else if (row.status === "completed")
6715
+ stats.completed = row.count;
6716
+ else if (row.status === "failed")
6717
+ stats.failed = row.count;
6718
+ }
6719
+ return stats;
6720
+ } catch {
6721
+ return {
6722
+ pending: _pendingQueue.size,
6723
+ processing: _isProcessing ? 1 : 0,
6724
+ completed: 0,
6725
+ failed: 0
6726
+ };
6727
+ }
6728
+ }
6729
+ function startSessionQueueWorker() {
6730
+ if (_workerStarted)
6731
+ return;
6732
+ _workerStarted = true;
6733
+ setInterval(() => {
6734
+ _processNext();
6735
+ }, 5000);
6736
+ }
6737
+ async function _processNext() {
6738
+ if (_isProcessing)
6739
+ return;
6740
+ let jobId;
6741
+ if (_pendingQueue.size > 0) {
6742
+ jobId = [..._pendingQueue][0];
6743
+ _pendingQueue.delete(jobId);
6744
+ } else {
6745
+ try {
6746
+ const job = getNextPendingJob();
6747
+ if (job)
6748
+ jobId = job.id;
6749
+ } catch {
6750
+ return;
5006
6751
  }
5007
- });
5008
- hookRegistry.register({
5009
- type: "OnSessionStart",
5010
- blocking: false,
5011
- builtin: true,
5012
- priority: 100,
5013
- description: "Record session start as a history memory for analytics",
5014
- handler: async (ctx) => {
5015
- const { createMemory: createMemory2 } = await Promise.resolve().then(() => (init_memories(), exports_memories));
5016
- try {
5017
- createMemory2({
5018
- key: `session-start-${ctx.agentId}`,
5019
- value: `Agent ${ctx.agentId} started session on project ${ctx.projectId} at ${new Date(ctx.timestamp).toISOString()}`,
5020
- category: "history",
5021
- scope: "shared",
5022
- importance: 3,
5023
- source: "system",
5024
- agent_id: ctx.agentId,
5025
- project_id: ctx.projectId,
5026
- session_id: ctx.sessionId
5027
- });
5028
- } catch {}
6752
+ }
6753
+ if (!jobId)
6754
+ return;
6755
+ _isProcessing = true;
6756
+ try {
6757
+ await processSessionJob(jobId);
6758
+ } catch {} finally {
6759
+ _isProcessing = false;
6760
+ if (_pendingQueue.size > 0) {
6761
+ _processNext();
5029
6762
  }
5030
- });
6763
+ }
6764
+ }
6765
+ var _pendingQueue, _isProcessing = false, _workerStarted = false;
6766
+ var init_session_queue = __esm(() => {
6767
+ init_database();
6768
+ init_session_jobs();
6769
+ init_session_processor();
6770
+ _pendingQueue = new Set;
5031
6771
  });
5032
6772
 
5033
6773
  // node_modules/commander/esm.mjs
@@ -8635,4 +10375,129 @@ webhooksCmd.command("disable <id>").description("Disable a webhook (without dele
8635
10375
  process.exit(1);
8636
10376
  }
8637
10377
  });
10378
+ var synthesisCmd = program2.command("synthesis").alias("synth").description("ALMA memory synthesis \u2014 analyze and consolidate memories");
10379
+ 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) => {
10380
+ const { runSynthesis: runSynthesis2 } = await Promise.resolve().then(() => (init_synthesis2(), exports_synthesis2));
10381
+ console.log(chalk.blue("Running memory synthesis..."));
10382
+ const result = await runSynthesis2({
10383
+ projectId: opts.project,
10384
+ dryRun: opts.dryRun ?? false,
10385
+ maxProposals: opts.maxProposals ? parseInt(opts.maxProposals) : 20,
10386
+ provider: opts.provider
10387
+ });
10388
+ if (result.dryRun) {
10389
+ console.log(chalk.yellow(`DRY RUN \u2014 ${result.proposals.length} proposals generated (not applied)`));
10390
+ } else {
10391
+ console.log(chalk.green(`\u2713 Synthesis complete`));
10392
+ console.log(` Corpus: ${result.run.corpus_size} memories`);
10393
+ console.log(` Proposals: ${result.run.proposals_generated} generated, ${result.run.proposals_accepted} applied`);
10394
+ }
10395
+ if (result.metrics) {
10396
+ console.log(` Reduction: ${(result.metrics.corpusReduction * 100).toFixed(1)}%`);
10397
+ }
10398
+ console.log(` Run ID: ${chalk.cyan(result.run.id)}`);
10399
+ });
10400
+ synthesisCmd.command("status").description("Show recent synthesis runs").option("--project <id>", "Filter by project").action(async (opts) => {
10401
+ const { listSynthesisRuns: listSynthesisRuns2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
10402
+ const runs = listSynthesisRuns2({ project_id: opts.project, limit: 10 });
10403
+ if (runs.length === 0) {
10404
+ console.log(chalk.gray("No synthesis runs found."));
10405
+ return;
10406
+ }
10407
+ for (const run of runs) {
10408
+ const statusColor = run.status === "completed" ? chalk.green : run.status === "failed" ? chalk.red : chalk.yellow;
10409
+ 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)}`);
10410
+ }
10411
+ });
10412
+ synthesisCmd.command("rollback <runId>").description("Roll back a synthesis run").action(async (runId) => {
10413
+ const { rollbackSynthesis: rollbackSynthesis2 } = await Promise.resolve().then(() => (init_synthesis2(), exports_synthesis2));
10414
+ console.log(chalk.yellow(`Rolling back synthesis run ${runId}...`));
10415
+ const result = await rollbackSynthesis2(runId);
10416
+ console.log(chalk.green(`\u2713 Rolled back ${result.rolled_back} proposals`));
10417
+ if (result.errors.length > 0) {
10418
+ console.log(chalk.red(` Errors: ${result.errors.join(", ")}`));
10419
+ }
10420
+ });
10421
+ var sessionCmd = program2.command("session").description("Session auto-memory \u2014 ingest session transcripts for memory extraction");
10422
+ sessionCmd.command("ingest <transcriptFile>").description("Ingest a session transcript file for memory extraction").option("--session-id <id>", "Session ID (default: auto-generated)").option("--agent <id>", "Agent ID").option("--project <id>", "Project ID").option("--source <source>", "Source (claude-code, codex, manual, open-sessions)", "manual").action(async (transcriptFile, opts) => {
10423
+ const { readFileSync: readFileSync3 } = await import("fs");
10424
+ const { createSessionJob: createSessionJob2 } = await Promise.resolve().then(() => (init_session_jobs(), exports_session_jobs));
10425
+ const { enqueueSessionJob: enqueueSessionJob2 } = await Promise.resolve().then(() => (init_session_queue(), exports_session_queue));
10426
+ const transcript = readFileSync3(transcriptFile, "utf-8");
10427
+ const sessionId = opts.sessionId ?? `cli-${Date.now()}`;
10428
+ const job = createSessionJob2({
10429
+ session_id: sessionId,
10430
+ transcript,
10431
+ source: opts.source,
10432
+ agent_id: opts.agent,
10433
+ project_id: opts.project
10434
+ });
10435
+ enqueueSessionJob2(job.id);
10436
+ console.log(chalk.green(`\u2713 Session queued: ${chalk.cyan(job.id)}`));
10437
+ console.log(` Session: ${sessionId}`);
10438
+ console.log(` Length: ${transcript.length} chars`);
10439
+ });
10440
+ sessionCmd.command("status <jobId>").description("Check status of a session extraction job").action(async (jobId) => {
10441
+ const { getSessionJob: getSessionJob2 } = await Promise.resolve().then(() => (init_session_jobs(), exports_session_jobs));
10442
+ const job = getSessionJob2(jobId);
10443
+ if (!job) {
10444
+ console.error(chalk.red(`Job not found: ${jobId}`));
10445
+ process.exit(1);
10446
+ }
10447
+ const statusColor = job.status === "completed" ? chalk.green : job.status === "failed" ? chalk.red : chalk.yellow;
10448
+ console.log(`${chalk.cyan(job.id)} [${statusColor(job.status)}]`);
10449
+ console.log(` Session: ${job.session_id}`);
10450
+ console.log(` Chunks: ${job.chunk_count}`);
10451
+ console.log(` Extracted: ${job.memories_extracted} memories`);
10452
+ if (job.error)
10453
+ console.log(chalk.red(` Error: ${job.error}`));
10454
+ });
10455
+ sessionCmd.command("list").description("List session extraction jobs").option("--agent <id>", "Filter by agent").option("--project <id>", "Filter by project").option("--status <status>", "Filter by status").option("--limit <n>", "Max results", "20").action(async (opts) => {
10456
+ const { listSessionJobs: listSessionJobs2 } = await Promise.resolve().then(() => (init_session_jobs(), exports_session_jobs));
10457
+ const jobs = listSessionJobs2({
10458
+ agent_id: opts.agent,
10459
+ project_id: opts.project,
10460
+ status: opts.status,
10461
+ limit: parseInt(opts.limit)
10462
+ });
10463
+ if (jobs.length === 0) {
10464
+ console.log(chalk.gray("No session jobs found."));
10465
+ return;
10466
+ }
10467
+ for (const job of jobs) {
10468
+ const statusColor = job.status === "completed" ? chalk.green : job.status === "failed" ? chalk.red : chalk.yellow;
10469
+ console.log(`${chalk.cyan(job.id.slice(0, 8))} [${statusColor(job.status)}] ${job.memories_extracted} memories | ${job.created_at.slice(0, 10)}`);
10470
+ }
10471
+ });
10472
+ sessionCmd.command("setup-hook").description("Install mementos session hook into Claude Code or Codex").option("--claude", "Install Claude Code stop hook").option("--codex", "Install Codex session hook").option("--show", "Print hook script instead of installing").action(async (opts) => {
10473
+ const { resolve: resolve4 } = await import("path");
10474
+ const hookPath = resolve4(import.meta.dirname, "../../scripts/hooks");
10475
+ if (opts.claude) {
10476
+ const script = `${hookPath}/claude-stop-hook.ts`;
10477
+ if (opts.show) {
10478
+ const { readFileSync: readFileSync3 } = await import("fs");
10479
+ console.log(readFileSync3(script, "utf-8"));
10480
+ return;
10481
+ }
10482
+ console.log(chalk.bold("Claude Code stop hook installation:"));
10483
+ console.log("");
10484
+ console.log("Add to your .claude/settings.json:");
10485
+ console.log(chalk.cyan(JSON.stringify({
10486
+ hooks: {
10487
+ Stop: [{ matcher: "", hooks: [{ type: "command", command: `bun ${script}` }] }]
10488
+ }
10489
+ }, null, 2)));
10490
+ console.log("");
10491
+ console.log(`Or run: ${chalk.cyan(`claude hooks add Stop "bun ${script}"`)}`);
10492
+ } else if (opts.codex) {
10493
+ const script = `${hookPath}/codex-stop-hook.ts`;
10494
+ console.log(chalk.bold("Codex session hook installation:"));
10495
+ console.log("");
10496
+ console.log("Add to ~/.codex/config.toml:");
10497
+ console.log(chalk.cyan(`[hooks]
10498
+ session_end = "bun ${script}"`));
10499
+ } else {
10500
+ console.log("Usage: mementos session setup-hook --claude | --codex");
10501
+ }
10502
+ });
8638
10503
  program2.parse(process.argv);