@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
@@ -402,6 +402,75 @@ var init_database = __esm(() => {
402
402
  ALTER TABLE memories ADD COLUMN recall_count INTEGER NOT NULL DEFAULT 0;
403
403
  CREATE INDEX IF NOT EXISTS idx_memories_recall_count ON memories(recall_count DESC);
404
404
  INSERT OR IGNORE INTO _migrations (id) VALUES (9);
405
+ `,
406
+ `
407
+ CREATE TABLE IF NOT EXISTS synthesis_events (
408
+ id TEXT PRIMARY KEY,
409
+ event_type TEXT NOT NULL CHECK(event_type IN ('recalled','searched','saved','updated','deleted','injected')),
410
+ memory_id TEXT,
411
+ agent_id TEXT,
412
+ project_id TEXT,
413
+ session_id TEXT,
414
+ query TEXT,
415
+ importance_at_time INTEGER,
416
+ metadata TEXT NOT NULL DEFAULT '{}',
417
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
418
+ );
419
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_memory ON synthesis_events(memory_id);
420
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_project ON synthesis_events(project_id);
421
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_type ON synthesis_events(event_type);
422
+ CREATE INDEX IF NOT EXISTS idx_synthesis_events_created ON synthesis_events(created_at);
423
+ INSERT OR IGNORE INTO _migrations (id) VALUES (11);
424
+ `,
425
+ `
426
+ CREATE TABLE IF NOT EXISTS synthesis_runs (
427
+ id TEXT PRIMARY KEY,
428
+ triggered_by TEXT NOT NULL DEFAULT 'manual' CHECK(triggered_by IN ('scheduler','manual','threshold','hook')),
429
+ project_id TEXT,
430
+ agent_id TEXT,
431
+ corpus_size INTEGER NOT NULL DEFAULT 0,
432
+ proposals_generated INTEGER NOT NULL DEFAULT 0,
433
+ proposals_accepted INTEGER NOT NULL DEFAULT 0,
434
+ proposals_rejected INTEGER NOT NULL DEFAULT 0,
435
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','running','completed','failed','rolled_back')),
436
+ error TEXT,
437
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
438
+ completed_at TEXT
439
+ );
440
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_project ON synthesis_runs(project_id);
441
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_status ON synthesis_runs(status);
442
+ CREATE INDEX IF NOT EXISTS idx_synthesis_runs_started ON synthesis_runs(started_at);
443
+
444
+ CREATE TABLE IF NOT EXISTS synthesis_proposals (
445
+ id TEXT PRIMARY KEY,
446
+ run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
447
+ proposal_type TEXT NOT NULL CHECK(proposal_type IN ('merge','archive','promote','update_value','add_tag','remove_duplicate')),
448
+ memory_ids TEXT NOT NULL DEFAULT '[]',
449
+ target_memory_id TEXT,
450
+ proposed_changes TEXT NOT NULL DEFAULT '{}',
451
+ reasoning TEXT,
452
+ confidence REAL NOT NULL DEFAULT 0.5,
453
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','accepted','rejected','rolled_back')),
454
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
455
+ executed_at TEXT,
456
+ rollback_data TEXT
457
+ );
458
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_run ON synthesis_proposals(run_id);
459
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_status ON synthesis_proposals(status);
460
+ CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_type ON synthesis_proposals(proposal_type);
461
+
462
+ CREATE TABLE IF NOT EXISTS synthesis_metrics (
463
+ id TEXT PRIMARY KEY,
464
+ run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
465
+ metric_type TEXT NOT NULL,
466
+ value REAL NOT NULL,
467
+ baseline REAL,
468
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
469
+ );
470
+ CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_run ON synthesis_metrics(run_id);
471
+ CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_type ON synthesis_metrics(metric_type);
472
+
473
+ INSERT OR IGNORE INTO _migrations (id) VALUES (12);
405
474
  `,
406
475
  `
407
476
  CREATE TABLE IF NOT EXISTS webhook_hooks (
@@ -421,7 +490,30 @@ var init_database = __esm(() => {
421
490
  CREATE INDEX IF NOT EXISTS idx_webhook_hooks_type ON webhook_hooks(type);
422
491
  CREATE INDEX IF NOT EXISTS idx_webhook_hooks_enabled ON webhook_hooks(enabled);
423
492
  INSERT OR IGNORE INTO _migrations (id) VALUES (10);
424
- `
493
+ `,
494
+ `
495
+ CREATE TABLE IF NOT EXISTS session_memory_jobs (
496
+ id TEXT PRIMARY KEY,
497
+ session_id TEXT NOT NULL,
498
+ agent_id TEXT,
499
+ project_id TEXT,
500
+ source TEXT NOT NULL DEFAULT 'manual' CHECK(source IN ('claude-code','codex','manual','open-sessions')),
501
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','processing','completed','failed')),
502
+ transcript TEXT NOT NULL,
503
+ chunk_count INTEGER NOT NULL DEFAULT 0,
504
+ memories_extracted INTEGER NOT NULL DEFAULT 0,
505
+ error TEXT,
506
+ metadata TEXT NOT NULL DEFAULT '{}',
507
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
508
+ started_at TEXT,
509
+ completed_at TEXT
510
+ );
511
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_status ON session_memory_jobs(status);
512
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_agent ON session_memory_jobs(agent_id);
513
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_project ON session_memory_jobs(project_id);
514
+ CREATE INDEX IF NOT EXISTS idx_session_memory_jobs_session ON session_memory_jobs(session_id);
515
+ INSERT OR IGNORE INTO _migrations (id) VALUES (13);
516
+ `
425
517
  ];
426
518
  });
427
519
 
@@ -2616,6 +2708,294 @@ var init_auto_memory = __esm(() => {
2616
2708
  autoMemoryQueue.setHandler(processJob);
2617
2709
  });
2618
2710
 
2711
+ // src/db/synthesis.ts
2712
+ var exports_synthesis = {};
2713
+ __export(exports_synthesis, {
2714
+ updateSynthesisRun: () => updateSynthesisRun,
2715
+ updateProposal: () => updateProposal,
2716
+ recordSynthesisEvent: () => recordSynthesisEvent,
2717
+ listSynthesisRuns: () => listSynthesisRuns,
2718
+ listSynthesisEvents: () => listSynthesisEvents,
2719
+ listProposals: () => listProposals,
2720
+ listMetrics: () => listMetrics,
2721
+ getSynthesisRun: () => getSynthesisRun,
2722
+ getProposal: () => getProposal,
2723
+ createSynthesisRun: () => createSynthesisRun,
2724
+ createProposal: () => createProposal,
2725
+ createMetric: () => createMetric
2726
+ });
2727
+ function parseRunRow(row) {
2728
+ return {
2729
+ id: row["id"],
2730
+ triggered_by: row["triggered_by"],
2731
+ project_id: row["project_id"] || null,
2732
+ agent_id: row["agent_id"] || null,
2733
+ corpus_size: row["corpus_size"],
2734
+ proposals_generated: row["proposals_generated"],
2735
+ proposals_accepted: row["proposals_accepted"],
2736
+ proposals_rejected: row["proposals_rejected"],
2737
+ status: row["status"],
2738
+ error: row["error"] || null,
2739
+ started_at: row["started_at"],
2740
+ completed_at: row["completed_at"] || null
2741
+ };
2742
+ }
2743
+ function parseProposalRow(row) {
2744
+ return {
2745
+ id: row["id"],
2746
+ run_id: row["run_id"],
2747
+ proposal_type: row["proposal_type"],
2748
+ memory_ids: JSON.parse(row["memory_ids"] || "[]"),
2749
+ target_memory_id: row["target_memory_id"] || null,
2750
+ proposed_changes: JSON.parse(row["proposed_changes"] || "{}"),
2751
+ reasoning: row["reasoning"] || null,
2752
+ confidence: row["confidence"],
2753
+ status: row["status"],
2754
+ created_at: row["created_at"],
2755
+ executed_at: row["executed_at"] || null,
2756
+ rollback_data: row["rollback_data"] ? JSON.parse(row["rollback_data"]) : null
2757
+ };
2758
+ }
2759
+ function parseMetricRow(row) {
2760
+ return {
2761
+ id: row["id"],
2762
+ run_id: row["run_id"],
2763
+ metric_type: row["metric_type"],
2764
+ value: row["value"],
2765
+ baseline: row["baseline"] != null ? row["baseline"] : null,
2766
+ created_at: row["created_at"]
2767
+ };
2768
+ }
2769
+ function parseEventRow(row) {
2770
+ return {
2771
+ id: row["id"],
2772
+ event_type: row["event_type"],
2773
+ memory_id: row["memory_id"] || null,
2774
+ agent_id: row["agent_id"] || null,
2775
+ project_id: row["project_id"] || null,
2776
+ session_id: row["session_id"] || null,
2777
+ query: row["query"] || null,
2778
+ importance_at_time: row["importance_at_time"] != null ? row["importance_at_time"] : null,
2779
+ metadata: JSON.parse(row["metadata"] || "{}"),
2780
+ created_at: row["created_at"]
2781
+ };
2782
+ }
2783
+ function createSynthesisRun(input, db) {
2784
+ const d = db || getDatabase();
2785
+ const id = shortUuid();
2786
+ const timestamp = now();
2787
+ d.run(`INSERT INTO synthesis_runs (id, triggered_by, project_id, agent_id, corpus_size, proposals_generated, proposals_accepted, proposals_rejected, status, started_at)
2788
+ VALUES (?, ?, ?, ?, ?, 0, 0, 0, 'pending', ?)`, [
2789
+ id,
2790
+ input.triggered_by,
2791
+ input.project_id ?? null,
2792
+ input.agent_id ?? null,
2793
+ input.corpus_size ?? 0,
2794
+ timestamp
2795
+ ]);
2796
+ return getSynthesisRun(id, d);
2797
+ }
2798
+ function getSynthesisRun(id, db) {
2799
+ const d = db || getDatabase();
2800
+ const row = d.query("SELECT * FROM synthesis_runs WHERE id = ?").get(id);
2801
+ if (!row)
2802
+ return null;
2803
+ return parseRunRow(row);
2804
+ }
2805
+ function listSynthesisRuns(filter, db) {
2806
+ const d = db || getDatabase();
2807
+ const conditions = [];
2808
+ const params = [];
2809
+ if (filter.project_id !== undefined) {
2810
+ if (filter.project_id === null) {
2811
+ conditions.push("project_id IS NULL");
2812
+ } else {
2813
+ conditions.push("project_id = ?");
2814
+ params.push(filter.project_id);
2815
+ }
2816
+ }
2817
+ if (filter.status) {
2818
+ conditions.push("status = ?");
2819
+ params.push(filter.status);
2820
+ }
2821
+ let sql = "SELECT * FROM synthesis_runs";
2822
+ if (conditions.length > 0) {
2823
+ sql += ` WHERE ${conditions.join(" AND ")}`;
2824
+ }
2825
+ sql += " ORDER BY started_at DESC";
2826
+ if (filter.limit) {
2827
+ sql += " LIMIT ?";
2828
+ params.push(filter.limit);
2829
+ }
2830
+ const rows = d.query(sql).all(...params);
2831
+ return rows.map(parseRunRow);
2832
+ }
2833
+ function updateSynthesisRun(id, updates, db) {
2834
+ const d = db || getDatabase();
2835
+ const sets = [];
2836
+ const params = [];
2837
+ if (updates.status !== undefined) {
2838
+ sets.push("status = ?");
2839
+ params.push(updates.status);
2840
+ }
2841
+ if (updates.error !== undefined) {
2842
+ sets.push("error = ?");
2843
+ params.push(updates.error);
2844
+ }
2845
+ if (updates.corpus_size !== undefined) {
2846
+ sets.push("corpus_size = ?");
2847
+ params.push(updates.corpus_size);
2848
+ }
2849
+ if (updates.proposals_generated !== undefined) {
2850
+ sets.push("proposals_generated = ?");
2851
+ params.push(updates.proposals_generated);
2852
+ }
2853
+ if (updates.proposals_accepted !== undefined) {
2854
+ sets.push("proposals_accepted = ?");
2855
+ params.push(updates.proposals_accepted);
2856
+ }
2857
+ if (updates.proposals_rejected !== undefined) {
2858
+ sets.push("proposals_rejected = ?");
2859
+ params.push(updates.proposals_rejected);
2860
+ }
2861
+ if (updates.completed_at !== undefined) {
2862
+ sets.push("completed_at = ?");
2863
+ params.push(updates.completed_at);
2864
+ }
2865
+ if (sets.length === 0)
2866
+ return getSynthesisRun(id, d);
2867
+ params.push(id);
2868
+ d.run(`UPDATE synthesis_runs SET ${sets.join(", ")} WHERE id = ?`, params);
2869
+ return getSynthesisRun(id, d);
2870
+ }
2871
+ function createProposal(input, db) {
2872
+ const d = db || getDatabase();
2873
+ const id = shortUuid();
2874
+ const timestamp = now();
2875
+ d.run(`INSERT INTO synthesis_proposals (id, run_id, proposal_type, memory_ids, target_memory_id, proposed_changes, reasoning, confidence, status, created_at)
2876
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`, [
2877
+ id,
2878
+ input.run_id,
2879
+ input.proposal_type,
2880
+ JSON.stringify(input.memory_ids),
2881
+ input.target_memory_id ?? null,
2882
+ JSON.stringify(input.proposed_changes),
2883
+ input.reasoning ?? null,
2884
+ input.confidence,
2885
+ timestamp
2886
+ ]);
2887
+ return getProposal(id, d);
2888
+ }
2889
+ function getProposal(id, db) {
2890
+ const d = db || getDatabase();
2891
+ const row = d.query("SELECT * FROM synthesis_proposals WHERE id = ?").get(id);
2892
+ if (!row)
2893
+ return null;
2894
+ return parseProposalRow(row);
2895
+ }
2896
+ function listProposals(run_id, filter, db) {
2897
+ const d = db || getDatabase();
2898
+ const params = [run_id];
2899
+ let sql = "SELECT * FROM synthesis_proposals WHERE run_id = ?";
2900
+ if (filter?.status) {
2901
+ sql += " AND status = ?";
2902
+ params.push(filter.status);
2903
+ }
2904
+ sql += " ORDER BY created_at ASC";
2905
+ const rows = d.query(sql).all(...params);
2906
+ return rows.map(parseProposalRow);
2907
+ }
2908
+ function updateProposal(id, updates, db) {
2909
+ const d = db || getDatabase();
2910
+ const sets = [];
2911
+ const params = [];
2912
+ if (updates.status !== undefined) {
2913
+ sets.push("status = ?");
2914
+ params.push(updates.status);
2915
+ }
2916
+ if (updates.executed_at !== undefined) {
2917
+ sets.push("executed_at = ?");
2918
+ params.push(updates.executed_at);
2919
+ }
2920
+ if (updates.rollback_data !== undefined) {
2921
+ sets.push("rollback_data = ?");
2922
+ params.push(JSON.stringify(updates.rollback_data));
2923
+ }
2924
+ if (sets.length === 0)
2925
+ return getProposal(id, d);
2926
+ params.push(id);
2927
+ d.run(`UPDATE synthesis_proposals SET ${sets.join(", ")} WHERE id = ?`, params);
2928
+ return getProposal(id, d);
2929
+ }
2930
+ function createMetric(input, db) {
2931
+ const d = db || getDatabase();
2932
+ const id = shortUuid();
2933
+ const timestamp = now();
2934
+ d.run(`INSERT INTO synthesis_metrics (id, run_id, metric_type, value, baseline, created_at)
2935
+ VALUES (?, ?, ?, ?, ?, ?)`, [id, input.run_id, input.metric_type, input.value, input.baseline ?? null, timestamp]);
2936
+ return { id, run_id: input.run_id, metric_type: input.metric_type, value: input.value, baseline: input.baseline ?? null, created_at: timestamp };
2937
+ }
2938
+ function listMetrics(run_id, db) {
2939
+ const d = db || getDatabase();
2940
+ const rows = d.query("SELECT * FROM synthesis_metrics WHERE run_id = ? ORDER BY created_at ASC").all(run_id);
2941
+ return rows.map(parseMetricRow);
2942
+ }
2943
+ function recordSynthesisEvent(input, db) {
2944
+ try {
2945
+ const d = db || getDatabase();
2946
+ const id = shortUuid();
2947
+ const timestamp = now();
2948
+ d.run(`INSERT INTO synthesis_events (id, event_type, memory_id, agent_id, project_id, session_id, query, importance_at_time, metadata, created_at)
2949
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
2950
+ id,
2951
+ input.event_type,
2952
+ input.memory_id ?? null,
2953
+ input.agent_id ?? null,
2954
+ input.project_id ?? null,
2955
+ input.session_id ?? null,
2956
+ input.query ?? null,
2957
+ input.importance_at_time ?? null,
2958
+ JSON.stringify(input.metadata ?? {}),
2959
+ timestamp
2960
+ ]);
2961
+ } catch {}
2962
+ }
2963
+ function listSynthesisEvents(filter, db) {
2964
+ const d = db || getDatabase();
2965
+ const conditions = [];
2966
+ const params = [];
2967
+ if (filter.memory_id) {
2968
+ conditions.push("memory_id = ?");
2969
+ params.push(filter.memory_id);
2970
+ }
2971
+ if (filter.project_id) {
2972
+ conditions.push("project_id = ?");
2973
+ params.push(filter.project_id);
2974
+ }
2975
+ if (filter.event_type) {
2976
+ conditions.push("event_type = ?");
2977
+ params.push(filter.event_type);
2978
+ }
2979
+ if (filter.since) {
2980
+ conditions.push("created_at >= ?");
2981
+ params.push(filter.since);
2982
+ }
2983
+ let sql = "SELECT * FROM synthesis_events";
2984
+ if (conditions.length > 0) {
2985
+ sql += ` WHERE ${conditions.join(" AND ")}`;
2986
+ }
2987
+ sql += " ORDER BY created_at DESC";
2988
+ if (filter.limit) {
2989
+ sql += " LIMIT ?";
2990
+ params.push(filter.limit);
2991
+ }
2992
+ const rows = d.query(sql).all(...params);
2993
+ return rows.map(parseEventRow);
2994
+ }
2995
+ var init_synthesis = __esm(() => {
2996
+ init_database();
2997
+ });
2998
+
2619
2999
  // src/server/index.ts
2620
3000
  init_memories();
2621
3001
  import { existsSync as existsSync3 } from "fs";
@@ -3159,6 +3539,41 @@ hookRegistry.register({
3159
3539
  } catch {}
3160
3540
  }
3161
3541
  });
3542
+ hookRegistry.register({
3543
+ type: "PostMemorySave",
3544
+ blocking: false,
3545
+ builtin: true,
3546
+ priority: 200,
3547
+ description: "Record memory save event for synthesis analytics",
3548
+ handler: async (ctx) => {
3549
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
3550
+ recordSynthesisEvent2({
3551
+ event_type: "saved",
3552
+ memory_id: ctx.memory.id,
3553
+ agent_id: ctx.agentId,
3554
+ project_id: ctx.projectId,
3555
+ session_id: ctx.sessionId,
3556
+ importance_at_time: ctx.memory.importance
3557
+ });
3558
+ }
3559
+ });
3560
+ hookRegistry.register({
3561
+ type: "PostMemoryInject",
3562
+ blocking: false,
3563
+ builtin: true,
3564
+ priority: 200,
3565
+ description: "Record injection event for synthesis analytics",
3566
+ handler: async (ctx) => {
3567
+ const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
3568
+ recordSynthesisEvent2({
3569
+ event_type: "injected",
3570
+ agent_id: ctx.agentId,
3571
+ project_id: ctx.projectId,
3572
+ session_id: ctx.sessionId,
3573
+ metadata: { count: ctx.memoriesCount, format: ctx.format }
3574
+ });
3575
+ }
3576
+ });
3162
3577
  var _webhooksLoaded = false;
3163
3578
  function loadWebhooksFromDb() {
3164
3579
  if (_webhooksLoaded)
@@ -3204,28 +3619,1381 @@ function reloadWebhooks() {
3204
3619
  loadWebhooksFromDb();
3205
3620
  }
3206
3621
 
3207
- // src/server/index.ts
3208
- var DEFAULT_PORT = 19428;
3209
- function parsePort() {
3210
- const envPort = process.env["PORT"];
3211
- if (envPort) {
3212
- const p = parseInt(envPort, 10);
3213
- if (!Number.isNaN(p))
3214
- return p;
3622
+ // src/lib/synthesis/index.ts
3623
+ init_database();
3624
+ init_synthesis();
3625
+
3626
+ // src/lib/synthesis/corpus-builder.ts
3627
+ init_database();
3628
+ init_memories();
3629
+ init_synthesis();
3630
+ function extractTerms(text) {
3631
+ const stopWords = new Set([
3632
+ "a",
3633
+ "an",
3634
+ "the",
3635
+ "is",
3636
+ "it",
3637
+ "in",
3638
+ "of",
3639
+ "for",
3640
+ "to",
3641
+ "and",
3642
+ "or",
3643
+ "but",
3644
+ "not",
3645
+ "with",
3646
+ "this",
3647
+ "that",
3648
+ "are",
3649
+ "was",
3650
+ "be",
3651
+ "by",
3652
+ "at",
3653
+ "as",
3654
+ "on",
3655
+ "has",
3656
+ "have",
3657
+ "had",
3658
+ "do",
3659
+ "did",
3660
+ "does",
3661
+ "will",
3662
+ "would",
3663
+ "can",
3664
+ "could",
3665
+ "should",
3666
+ "may",
3667
+ "might",
3668
+ "shall",
3669
+ "from",
3670
+ "into",
3671
+ "then",
3672
+ "than",
3673
+ "so",
3674
+ "if",
3675
+ "up",
3676
+ "out",
3677
+ "about",
3678
+ "its",
3679
+ "my",
3680
+ "we",
3681
+ "i",
3682
+ "you"
3683
+ ]);
3684
+ return new Set(text.toLowerCase().replace(/[^a-z0-9\s\-_]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w)));
3685
+ }
3686
+ function jaccardSimilarity(a, b) {
3687
+ if (a.size === 0 && b.size === 0)
3688
+ return 0;
3689
+ const intersection = new Set([...a].filter((x) => b.has(x)));
3690
+ const union = new Set([...a, ...b]);
3691
+ return intersection.size / union.size;
3692
+ }
3693
+ function isStale(memory) {
3694
+ if (memory.status !== "active")
3695
+ return false;
3696
+ if (memory.importance >= 7)
3697
+ return false;
3698
+ if (!memory.accessed_at)
3699
+ return true;
3700
+ const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
3701
+ return new Date(memory.accessed_at).getTime() < thirtyDaysAgo;
3702
+ }
3703
+ async function buildCorpus(options) {
3704
+ const d = options.db || getDatabase();
3705
+ const limit = options.limit ?? 500;
3706
+ const projectId = options.projectId ?? null;
3707
+ const memories = listMemories({
3708
+ status: "active",
3709
+ project_id: options.projectId,
3710
+ agent_id: options.agentId,
3711
+ limit
3712
+ }, d);
3713
+ const recallEvents = listSynthesisEvents({
3714
+ event_type: "recalled",
3715
+ project_id: options.projectId
3716
+ }, d);
3717
+ const recallCounts = new Map;
3718
+ const lastRecalledMap = new Map;
3719
+ for (const event of recallEvents) {
3720
+ if (!event.memory_id)
3721
+ continue;
3722
+ recallCounts.set(event.memory_id, (recallCounts.get(event.memory_id) ?? 0) + 1);
3723
+ const existing = lastRecalledMap.get(event.memory_id);
3724
+ if (!existing || event.created_at > existing) {
3725
+ lastRecalledMap.set(event.memory_id, event.created_at);
3726
+ }
3215
3727
  }
3216
- const portArg = process.argv.find((a) => a === "--port" || a.startsWith("--port="));
3217
- if (portArg) {
3218
- if (portArg.includes("=")) {
3219
- return parseInt(portArg.split("=")[1], 10) || DEFAULT_PORT;
3728
+ const searchEvents = listSynthesisEvents({
3729
+ event_type: "searched",
3730
+ project_id: options.projectId
3731
+ }, d);
3732
+ const searchHits = new Map;
3733
+ for (const event of searchEvents) {
3734
+ if (!event.memory_id)
3735
+ continue;
3736
+ searchHits.set(event.memory_id, (searchHits.get(event.memory_id) ?? 0) + 1);
3737
+ }
3738
+ const termSets = new Map;
3739
+ for (const m of memories) {
3740
+ termSets.set(m.id, extractTerms(`${m.key} ${m.value} ${m.summary ?? ""}`));
3741
+ }
3742
+ const duplicateCandidates = [];
3743
+ const similarityThreshold = 0.5;
3744
+ const similarIds = new Map;
3745
+ for (let i = 0;i < memories.length; i++) {
3746
+ const a = memories[i];
3747
+ const termsA = termSets.get(a.id);
3748
+ const aSimIds = [];
3749
+ for (let j = i + 1;j < memories.length; j++) {
3750
+ const b = memories[j];
3751
+ const termsB = termSets.get(b.id);
3752
+ const sim = jaccardSimilarity(termsA, termsB);
3753
+ if (sim >= similarityThreshold) {
3754
+ duplicateCandidates.push({ a, b, similarity: sim });
3755
+ aSimIds.push(b.id);
3756
+ const bSimIds = similarIds.get(b.id) ?? [];
3757
+ bSimIds.push(a.id);
3758
+ similarIds.set(b.id, bSimIds);
3759
+ }
3760
+ }
3761
+ if (aSimIds.length > 0) {
3762
+ const existing = similarIds.get(a.id) ?? [];
3763
+ similarIds.set(a.id, [...existing, ...aSimIds]);
3220
3764
  }
3221
- const idx = process.argv.indexOf(portArg);
3222
- return parseInt(process.argv[idx + 1], 10) || DEFAULT_PORT;
3223
3765
  }
3224
- return DEFAULT_PORT;
3766
+ duplicateCandidates.sort((a, b) => b.similarity - a.similarity);
3767
+ const items = memories.map((memory) => ({
3768
+ memory,
3769
+ recallCount: recallCounts.get(memory.id) ?? 0,
3770
+ lastRecalled: lastRecalledMap.get(memory.id) ?? null,
3771
+ searchHits: searchHits.get(memory.id) ?? 0,
3772
+ similarMemoryIds: similarIds.get(memory.id) ?? []
3773
+ }));
3774
+ const staleMemories = memories.filter(isStale);
3775
+ const lowImportanceHighRecall = memories.filter((m) => m.importance < 5 && (recallCounts.get(m.id) ?? 0) > 3);
3776
+ const highImportanceLowRecall = memories.filter((m) => m.importance > 7 && (recallCounts.get(m.id) ?? 0) === 0);
3777
+ return {
3778
+ projectId,
3779
+ totalMemories: memories.length,
3780
+ items,
3781
+ staleMemories,
3782
+ duplicateCandidates,
3783
+ lowImportanceHighRecall,
3784
+ highImportanceLowRecall,
3785
+ generatedAt: now()
3786
+ };
3225
3787
  }
3226
- function resolveDashboardDir() {
3227
- const candidates = [];
3228
- try {
3788
+
3789
+ // src/lib/synthesis/llm-analyzer.ts
3790
+ init_registry();
3791
+ 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.";
3792
+ function buildCorpusPrompt(corpus, maxProposals) {
3793
+ const lines = [];
3794
+ lines.push(`## Memory Corpus Analysis`);
3795
+ lines.push(`Project: ${corpus.projectId ?? "(global)"}`);
3796
+ lines.push(`Total active memories: ${corpus.totalMemories}`);
3797
+ lines.push(`Analysis generated at: ${corpus.generatedAt}`);
3798
+ lines.push("");
3799
+ if (corpus.staleMemories.length > 0) {
3800
+ lines.push(`## Stale Memories (not accessed in 30+ days, importance < 7)`);
3801
+ lines.push(`Count: ${corpus.staleMemories.length}`);
3802
+ for (const m of corpus.staleMemories.slice(0, 30)) {
3803
+ const accessed = m.accessed_at ?? "never";
3804
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} lastAccessed=${accessed}`);
3805
+ lines.push(` value: ${m.value.slice(0, 120)}`);
3806
+ }
3807
+ lines.push("");
3808
+ }
3809
+ if (corpus.duplicateCandidates.length > 0) {
3810
+ lines.push(`## Potential Duplicates (term overlap \u2265 50%)`);
3811
+ lines.push(`Count: ${corpus.duplicateCandidates.length} pairs`);
3812
+ for (const { a, b, similarity } of corpus.duplicateCandidates.slice(0, 20)) {
3813
+ lines.push(`- similarity=${similarity.toFixed(2)}`);
3814
+ lines.push(` A id:${a.id} key="${a.key}" importance=${a.importance}: ${a.value.slice(0, 80)}`);
3815
+ lines.push(` B id:${b.id} key="${b.key}" importance=${b.importance}: ${b.value.slice(0, 80)}`);
3816
+ }
3817
+ lines.push("");
3818
+ }
3819
+ if (corpus.lowImportanceHighRecall.length > 0) {
3820
+ lines.push(`## Low Importance But High Recall (candidates for importance promotion)`);
3821
+ for (const m of corpus.lowImportanceHighRecall.slice(0, 20)) {
3822
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} recall_count=${m.access_count}`);
3823
+ }
3824
+ lines.push("");
3825
+ }
3826
+ if (corpus.highImportanceLowRecall.length > 0) {
3827
+ lines.push(`## High Importance But Never Recalled (may need value update)`);
3828
+ for (const m of corpus.highImportanceLowRecall.slice(0, 20)) {
3829
+ lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance}: ${m.value.slice(0, 80)}`);
3830
+ }
3831
+ lines.push("");
3832
+ }
3833
+ lines.push(`## Instructions`);
3834
+ lines.push(`Generate up to ${maxProposals} proposals as a JSON array. Each proposal must have:`);
3835
+ lines.push(` - type: "merge" | "archive" | "promote" | "update_value" | "add_tag" | "remove_duplicate"`);
3836
+ lines.push(` - memory_ids: string[] (IDs this proposal acts on)`);
3837
+ lines.push(` - target_memory_id: string (optional \u2014 used for merge/remove_duplicate)`);
3838
+ lines.push(` - proposed_changes: object (e.g. {new_importance:8} or {new_value:"..."} or {tags:["x"]})`);
3839
+ lines.push(` - reasoning: string (one sentence)`);
3840
+ lines.push(` - confidence: number 0.0-1.0`);
3841
+ lines.push("");
3842
+ lines.push(`Return ONLY the JSON array. No markdown, no explanation.`);
3843
+ return lines.join(`
3844
+ `);
3845
+ }
3846
+ async function analyzeCorpus(corpus, options) {
3847
+ const startMs = Date.now();
3848
+ const maxProposals = options?.maxProposals ?? 20;
3849
+ const empty = {
3850
+ proposals: [],
3851
+ summary: "No LLM provider available.",
3852
+ analysisDurationMs: 0
3853
+ };
3854
+ let provider = options?.provider ? providerRegistry.getProvider(options.provider) : providerRegistry.getAvailable();
3855
+ if (!provider) {
3856
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
3857
+ }
3858
+ const userPrompt = buildCorpusPrompt(corpus, maxProposals);
3859
+ try {
3860
+ const rawResponse = await callProviderRaw(provider, SYNTHESIS_SYSTEM_PROMPT, userPrompt);
3861
+ if (!rawResponse) {
3862
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
3863
+ }
3864
+ const parsed = parseProposalsResponse(rawResponse);
3865
+ const analysisDurationMs = Date.now() - startMs;
3866
+ const validProposals = parsed.slice(0, maxProposals);
3867
+ return {
3868
+ proposals: validProposals,
3869
+ summary: buildSummary(corpus, validProposals.length),
3870
+ analysisDurationMs
3871
+ };
3872
+ } catch {
3873
+ return { ...empty, analysisDurationMs: Date.now() - startMs };
3874
+ }
3875
+ }
3876
+ async function callProviderRaw(provider, systemPrompt, userPrompt) {
3877
+ if (!provider)
3878
+ return null;
3879
+ const { config, name } = provider;
3880
+ if (!config.apiKey)
3881
+ return null;
3882
+ const timeoutMs = config.timeoutMs ?? 30000;
3883
+ try {
3884
+ if (name === "anthropic") {
3885
+ return await callAnthropic(config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
3886
+ } else if (name === "openai" || name === "cerebras" || name === "grok") {
3887
+ return await callOpenAICompat(name, config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
3888
+ }
3889
+ } catch {}
3890
+ return null;
3891
+ }
3892
+ async function callAnthropic(apiKey, model, systemPrompt, userPrompt, timeoutMs) {
3893
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
3894
+ method: "POST",
3895
+ headers: {
3896
+ "x-api-key": apiKey,
3897
+ "anthropic-version": "2023-06-01",
3898
+ "content-type": "application/json"
3899
+ },
3900
+ body: JSON.stringify({
3901
+ model,
3902
+ max_tokens: 2048,
3903
+ system: systemPrompt,
3904
+ messages: [{ role: "user", content: userPrompt }]
3905
+ }),
3906
+ signal: AbortSignal.timeout(timeoutMs)
3907
+ });
3908
+ if (!response.ok)
3909
+ return null;
3910
+ const data = await response.json();
3911
+ return data.content?.[0]?.text ?? null;
3912
+ }
3913
+ function getBaseUrlForProvider(providerName) {
3914
+ switch (providerName) {
3915
+ case "openai":
3916
+ return "https://api.openai.com/v1";
3917
+ case "cerebras":
3918
+ return "https://api.cerebras.ai/v1";
3919
+ case "grok":
3920
+ return "https://api.x.ai/v1";
3921
+ default:
3922
+ return "https://api.openai.com/v1";
3923
+ }
3924
+ }
3925
+ async function callOpenAICompat(providerName, apiKey, model, systemPrompt, userPrompt, timeoutMs) {
3926
+ const baseUrl = getBaseUrlForProvider(providerName);
3927
+ const response = await fetch(`${baseUrl}/chat/completions`, {
3928
+ method: "POST",
3929
+ headers: {
3930
+ authorization: `Bearer ${apiKey}`,
3931
+ "content-type": "application/json"
3932
+ },
3933
+ body: JSON.stringify({
3934
+ model,
3935
+ max_tokens: 2048,
3936
+ temperature: 0,
3937
+ messages: [
3938
+ { role: "system", content: systemPrompt },
3939
+ { role: "user", content: userPrompt }
3940
+ ]
3941
+ }),
3942
+ signal: AbortSignal.timeout(timeoutMs)
3943
+ });
3944
+ if (!response.ok)
3945
+ return null;
3946
+ const data = await response.json();
3947
+ return data.choices?.[0]?.message?.content ?? null;
3948
+ }
3949
+ function parseProposalsResponse(raw) {
3950
+ try {
3951
+ const cleaned = raw.replace(/^```(?:json)?\s*/m, "").replace(/\s*```$/m, "").trim();
3952
+ const parsed = JSON.parse(cleaned);
3953
+ if (!Array.isArray(parsed))
3954
+ return [];
3955
+ const validTypes = new Set([
3956
+ "merge",
3957
+ "archive",
3958
+ "promote",
3959
+ "update_value",
3960
+ "add_tag",
3961
+ "remove_duplicate"
3962
+ ]);
3963
+ return parsed.filter((item) => {
3964
+ if (!item || typeof item !== "object")
3965
+ return false;
3966
+ const p = item;
3967
+ 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";
3968
+ }).map((p) => ({
3969
+ type: p.type,
3970
+ memory_ids: p.memory_ids.filter((id) => typeof id === "string"),
3971
+ target_memory_id: typeof p.target_memory_id === "string" ? p.target_memory_id : undefined,
3972
+ proposed_changes: p.proposed_changes ?? {},
3973
+ reasoning: p.reasoning,
3974
+ confidence: Math.max(0, Math.min(1, p.confidence))
3975
+ }));
3976
+ } catch {
3977
+ return [];
3978
+ }
3979
+ }
3980
+ function buildSummary(corpus, proposalCount) {
3981
+ return `Analyzed ${corpus.totalMemories} memories. ` + `Found ${corpus.staleMemories.length} stale, ` + `${corpus.duplicateCandidates.length} duplicate pairs. ` + `Generated ${proposalCount} proposals.`;
3982
+ }
3983
+
3984
+ // src/lib/synthesis/validator.ts
3985
+ var DEFAULT_SAFETY_CONFIG = {
3986
+ maxArchivePercent: 20,
3987
+ maxMergePercent: 30,
3988
+ minConfidence: 0.6,
3989
+ protectPinned: true,
3990
+ protectHighImportance: 9
3991
+ };
3992
+ function validateProposals(proposals, corpus, config) {
3993
+ const cfg = { ...DEFAULT_SAFETY_CONFIG, ...config };
3994
+ const memoryMap = new Map(corpus.items.map((item) => [item.memory.id, item.memory]));
3995
+ const rejectedProposals = [];
3996
+ const warnings = [];
3997
+ let archiveCount = 0;
3998
+ let mergeCount = 0;
3999
+ for (const proposal of proposals) {
4000
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
4001
+ archiveCount++;
4002
+ }
4003
+ if (proposal.type === "merge") {
4004
+ mergeCount++;
4005
+ }
4006
+ }
4007
+ const corpusSize = corpus.totalMemories;
4008
+ const archivePercent = corpusSize > 0 ? archiveCount / corpusSize * 100 : 0;
4009
+ const mergePercent = corpusSize > 0 ? mergeCount / corpusSize * 100 : 0;
4010
+ if (archivePercent > cfg.maxArchivePercent) {
4011
+ warnings.push(`Archive proposals (${archiveCount}) exceed ${cfg.maxArchivePercent}% of corpus (${archivePercent.toFixed(1)}%). Some will be rejected.`);
4012
+ }
4013
+ if (mergePercent > cfg.maxMergePercent) {
4014
+ warnings.push(`Merge proposals (${mergeCount}) exceed ${cfg.maxMergePercent}% of corpus (${mergePercent.toFixed(1)}%). Some will be rejected.`);
4015
+ }
4016
+ let remainingArchiveSlots = Math.floor(cfg.maxArchivePercent / 100 * corpusSize);
4017
+ let remainingMergeSlots = Math.floor(cfg.maxMergePercent / 100 * corpusSize);
4018
+ for (let i = 0;i < proposals.length; i++) {
4019
+ const proposal = proposals[i];
4020
+ const proposalRef = `proposal[${i}]`;
4021
+ if (proposal.confidence < cfg.minConfidence) {
4022
+ rejectedProposals.push({
4023
+ proposalId: proposalRef,
4024
+ reason: `Confidence ${proposal.confidence.toFixed(2)} below minimum ${cfg.minConfidence}`
4025
+ });
4026
+ continue;
4027
+ }
4028
+ const missingIds = proposal.memory_ids.filter((id) => !memoryMap.has(id));
4029
+ if (missingIds.length > 0) {
4030
+ rejectedProposals.push({
4031
+ proposalId: proposalRef,
4032
+ reason: `References unknown memory IDs: ${missingIds.join(", ")}`
4033
+ });
4034
+ continue;
4035
+ }
4036
+ if (cfg.protectPinned) {
4037
+ const pinnedIds = proposal.memory_ids.filter((id) => {
4038
+ const m = memoryMap.get(id);
4039
+ return m?.pinned === true;
4040
+ });
4041
+ if (pinnedIds.length > 0) {
4042
+ rejectedProposals.push({
4043
+ proposalId: proposalRef,
4044
+ reason: `Attempts to modify pinned memories: ${pinnedIds.join(", ")}`
4045
+ });
4046
+ continue;
4047
+ }
4048
+ }
4049
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate" || proposal.type === "merge") {
4050
+ const highImportanceIds = proposal.memory_ids.filter((id) => {
4051
+ const m = memoryMap.get(id);
4052
+ return m && m.importance >= cfg.protectHighImportance;
4053
+ });
4054
+ if (highImportanceIds.length > 0) {
4055
+ rejectedProposals.push({
4056
+ proposalId: proposalRef,
4057
+ reason: `Attempts to archive/merge memories with importance \u2265 ${cfg.protectHighImportance}: ${highImportanceIds.join(", ")}`
4058
+ });
4059
+ continue;
4060
+ }
4061
+ }
4062
+ if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
4063
+ if (remainingArchiveSlots <= 0) {
4064
+ rejectedProposals.push({
4065
+ proposalId: proposalRef,
4066
+ reason: `Archive quota exhausted (max ${cfg.maxArchivePercent}% of corpus)`
4067
+ });
4068
+ continue;
4069
+ }
4070
+ remainingArchiveSlots--;
4071
+ }
4072
+ if (proposal.type === "merge") {
4073
+ if (remainingMergeSlots <= 0) {
4074
+ rejectedProposals.push({
4075
+ proposalId: proposalRef,
4076
+ reason: `Merge quota exhausted (max ${cfg.maxMergePercent}% of corpus)`
4077
+ });
4078
+ continue;
4079
+ }
4080
+ remainingMergeSlots--;
4081
+ }
4082
+ if (proposal.target_memory_id && !memoryMap.has(proposal.target_memory_id)) {
4083
+ rejectedProposals.push({
4084
+ proposalId: proposalRef,
4085
+ reason: `target_memory_id "${proposal.target_memory_id}" does not exist in corpus`
4086
+ });
4087
+ continue;
4088
+ }
4089
+ }
4090
+ return {
4091
+ valid: rejectedProposals.length === 0,
4092
+ rejectedProposals,
4093
+ warnings
4094
+ };
4095
+ }
4096
+
4097
+ // src/lib/synthesis/executor.ts
4098
+ init_database();
4099
+ init_memories();
4100
+ init_synthesis();
4101
+ async function executeProposals(runId, proposals, db) {
4102
+ const d = db || getDatabase();
4103
+ let executed = 0;
4104
+ let failed = 0;
4105
+ const rollbackData = {};
4106
+ for (const proposal of proposals) {
4107
+ try {
4108
+ const rollback = executeProposal(proposal, d);
4109
+ updateProposal(proposal.id, {
4110
+ status: "accepted",
4111
+ executed_at: now(),
4112
+ rollback_data: rollback
4113
+ }, d);
4114
+ rollbackData[proposal.id] = rollback;
4115
+ executed++;
4116
+ } catch (err) {
4117
+ try {
4118
+ updateProposal(proposal.id, { status: "rejected" }, d);
4119
+ } catch {}
4120
+ failed++;
4121
+ }
4122
+ }
4123
+ return { runId, executed, failed, rollbackData };
4124
+ }
4125
+ function executeProposal(proposal, d) {
4126
+ let rollbackData = {};
4127
+ d.transaction(() => {
4128
+ switch (proposal.proposal_type) {
4129
+ case "archive":
4130
+ rollbackData = executeArchive(proposal, d);
4131
+ break;
4132
+ case "promote":
4133
+ rollbackData = executePromote(proposal, d);
4134
+ break;
4135
+ case "update_value":
4136
+ rollbackData = executeUpdateValue(proposal, d);
4137
+ break;
4138
+ case "add_tag":
4139
+ rollbackData = executeAddTag(proposal, d);
4140
+ break;
4141
+ case "merge":
4142
+ rollbackData = executeMerge(proposal, d);
4143
+ break;
4144
+ case "remove_duplicate":
4145
+ rollbackData = executeRemoveDuplicate(proposal, d);
4146
+ break;
4147
+ default:
4148
+ throw new Error(`Unknown proposal type: ${proposal.proposal_type}`);
4149
+ }
4150
+ })();
4151
+ return rollbackData;
4152
+ }
4153
+ function executeArchive(proposal, d) {
4154
+ const rollback = {};
4155
+ for (const memId of proposal.memory_ids) {
4156
+ const mem = getMemory(memId, d);
4157
+ if (!mem)
4158
+ continue;
4159
+ rollback[memId] = mem.status;
4160
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
4161
+ }
4162
+ return { old_status: rollback };
4163
+ }
4164
+ function executePromote(proposal, d) {
4165
+ const newImportance = proposal.proposed_changes["new_importance"];
4166
+ if (typeof newImportance !== "number") {
4167
+ throw new Error("promote proposal missing new_importance in proposed_changes");
4168
+ }
4169
+ const rollback = {};
4170
+ for (const memId of proposal.memory_ids) {
4171
+ const mem = getMemory(memId, d);
4172
+ if (!mem)
4173
+ continue;
4174
+ rollback[memId] = mem.importance;
4175
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [Math.max(1, Math.min(10, Math.round(newImportance))), now(), memId]);
4176
+ }
4177
+ return { old_importance: rollback };
4178
+ }
4179
+ function executeUpdateValue(proposal, d) {
4180
+ const newValue = proposal.proposed_changes["new_value"];
4181
+ if (typeof newValue !== "string") {
4182
+ throw new Error("update_value proposal missing new_value in proposed_changes");
4183
+ }
4184
+ const rollback = {};
4185
+ const memId = proposal.memory_ids[0];
4186
+ if (!memId)
4187
+ throw new Error("update_value proposal has no memory_ids");
4188
+ const mem = getMemory(memId, d);
4189
+ if (!mem)
4190
+ throw new Error(`Memory ${memId} not found`);
4191
+ rollback[memId] = { value: mem.value, version: mem.version };
4192
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [newValue, now(), memId]);
4193
+ return { old_state: rollback };
4194
+ }
4195
+ function executeAddTag(proposal, d) {
4196
+ const tagsToAdd = proposal.proposed_changes["tags"];
4197
+ if (!Array.isArray(tagsToAdd)) {
4198
+ throw new Error("add_tag proposal missing tags array in proposed_changes");
4199
+ }
4200
+ const rollback = {};
4201
+ for (const memId of proposal.memory_ids) {
4202
+ const mem = getMemory(memId, d);
4203
+ if (!mem)
4204
+ continue;
4205
+ rollback[memId] = [...mem.tags];
4206
+ const newTags = Array.from(new Set([...mem.tags, ...tagsToAdd]));
4207
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(newTags), now(), memId]);
4208
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
4209
+ for (const tag of tagsToAdd) {
4210
+ insertTag.run(memId, tag);
4211
+ }
4212
+ }
4213
+ return { old_tags: rollback };
4214
+ }
4215
+ function executeMerge(proposal, d) {
4216
+ const targetId = proposal.target_memory_id;
4217
+ if (!targetId)
4218
+ throw new Error("merge proposal missing target_memory_id");
4219
+ const target = getMemory(targetId, d);
4220
+ if (!target)
4221
+ throw new Error(`Target memory ${targetId} not found`);
4222
+ const rollback = {
4223
+ target_old_value: target.value,
4224
+ target_old_version: target.version,
4225
+ archived_memories: {}
4226
+ };
4227
+ const sourceValues = [];
4228
+ for (const memId of proposal.memory_ids) {
4229
+ if (memId === targetId)
4230
+ continue;
4231
+ const mem = getMemory(memId, d);
4232
+ if (!mem)
4233
+ continue;
4234
+ sourceValues.push(mem.value);
4235
+ rollback.archived_memories[memId] = mem.status;
4236
+ }
4237
+ const mergedValue = proposal.proposed_changes["merged_value"] ?? [target.value, ...sourceValues].join(`
4238
+ ---
4239
+ `);
4240
+ d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [mergedValue, now(), targetId]);
4241
+ for (const memId of proposal.memory_ids) {
4242
+ if (memId === targetId)
4243
+ continue;
4244
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
4245
+ }
4246
+ return rollback;
4247
+ }
4248
+ function executeRemoveDuplicate(proposal, d) {
4249
+ const memories = proposal.memory_ids.map((id) => getMemory(id, d)).filter((m) => m !== null);
4250
+ if (memories.length < 2) {
4251
+ throw new Error("remove_duplicate requires at least 2 memories");
4252
+ }
4253
+ memories.sort((a, b) => b.importance - a.importance || a.created_at.localeCompare(b.created_at));
4254
+ const keepId = proposal.target_memory_id ?? memories[0].id;
4255
+ const rollback = {};
4256
+ for (const mem of memories) {
4257
+ if (mem.id === keepId)
4258
+ continue;
4259
+ rollback[mem.id] = mem.status;
4260
+ d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), mem.id]);
4261
+ }
4262
+ return { old_status: rollback, kept_id: keepId };
4263
+ }
4264
+ async function rollbackRun(runId, db) {
4265
+ const d = db || getDatabase();
4266
+ const proposals = listProposals(runId, { status: "accepted" }, d);
4267
+ let rolledBack = 0;
4268
+ const errors = [];
4269
+ for (const proposal of proposals) {
4270
+ try {
4271
+ rollbackProposal(proposal, d);
4272
+ updateProposal(proposal.id, { status: "rolled_back" }, d);
4273
+ rolledBack++;
4274
+ } catch (err) {
4275
+ errors.push(`Proposal ${proposal.id} (${proposal.proposal_type}): ${err instanceof Error ? err.message : String(err)}`);
4276
+ }
4277
+ }
4278
+ return { rolled_back: rolledBack, errors };
4279
+ }
4280
+ function rollbackProposal(proposal, d) {
4281
+ const rb = proposal.rollback_data;
4282
+ if (!rb)
4283
+ return;
4284
+ d.transaction(() => {
4285
+ switch (proposal.proposal_type) {
4286
+ case "archive":
4287
+ case "remove_duplicate": {
4288
+ const oldStatus = rb["old_status"];
4289
+ if (!oldStatus)
4290
+ break;
4291
+ for (const [memId, status] of Object.entries(oldStatus)) {
4292
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
4293
+ }
4294
+ break;
4295
+ }
4296
+ case "promote": {
4297
+ const oldImportance = rb["old_importance"];
4298
+ if (!oldImportance)
4299
+ break;
4300
+ for (const [memId, importance] of Object.entries(oldImportance)) {
4301
+ d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [importance, now(), memId]);
4302
+ }
4303
+ break;
4304
+ }
4305
+ case "update_value": {
4306
+ const oldState = rb["old_state"];
4307
+ if (!oldState)
4308
+ break;
4309
+ for (const [memId, state] of Object.entries(oldState)) {
4310
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [state.value, state.version, now(), memId]);
4311
+ }
4312
+ break;
4313
+ }
4314
+ case "add_tag": {
4315
+ const oldTags = rb["old_tags"];
4316
+ if (!oldTags)
4317
+ break;
4318
+ for (const [memId, tags] of Object.entries(oldTags)) {
4319
+ d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(tags), now(), memId]);
4320
+ d.run("DELETE FROM memory_tags WHERE memory_id = ?", [memId]);
4321
+ const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
4322
+ for (const tag of tags) {
4323
+ insertTag.run(memId, tag);
4324
+ }
4325
+ }
4326
+ break;
4327
+ }
4328
+ case "merge": {
4329
+ const targetOldValue = rb["target_old_value"];
4330
+ const targetOldVersion = rb["target_old_version"];
4331
+ const archivedMemories = rb["archived_memories"];
4332
+ const targetId = proposal.target_memory_id;
4333
+ if (targetId && targetOldValue !== undefined && targetOldVersion !== undefined) {
4334
+ d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [targetOldValue, targetOldVersion, now(), targetId]);
4335
+ }
4336
+ if (archivedMemories) {
4337
+ for (const [memId, status] of Object.entries(archivedMemories)) {
4338
+ d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
4339
+ }
4340
+ }
4341
+ break;
4342
+ }
4343
+ default:
4344
+ break;
4345
+ }
4346
+ })();
4347
+ }
4348
+
4349
+ // src/lib/synthesis/metrics.ts
4350
+ init_database();
4351
+ init_synthesis();
4352
+ init_memories();
4353
+ async function measureEffectiveness(runId, preCorpus, db) {
4354
+ const d = db || getDatabase();
4355
+ const postMemories = listMemories({
4356
+ status: "active",
4357
+ project_id: preCorpus.projectId ?? undefined
4358
+ }, d);
4359
+ const postCount = postMemories.length;
4360
+ const preCount = preCorpus.totalMemories;
4361
+ const corpusReduction = preCount > 0 ? (preCount - postCount) / preCount * 100 : 0;
4362
+ const preAvgImportance = preCorpus.items.length > 0 ? preCorpus.items.reduce((sum, i) => sum + i.memory.importance, 0) / preCorpus.items.length : 0;
4363
+ const postAvgImportance = postMemories.length > 0 ? postMemories.reduce((sum, m) => sum + m.importance, 0) / postMemories.length : 0;
4364
+ const importanceDrift = postAvgImportance - preAvgImportance;
4365
+ const preDuplicatePairs = preCorpus.duplicateCandidates.length;
4366
+ const acceptedProposals = listProposals(runId, { status: "accepted" }, d);
4367
+ const deduplicationProposals = acceptedProposals.filter((p) => p.proposal_type === "remove_duplicate" || p.proposal_type === "merge");
4368
+ const deduplicationRate = preDuplicatePairs > 0 ? deduplicationProposals.length / preDuplicatePairs * 100 : 0;
4369
+ const recallWeight = {
4370
+ corpusReduction: 0.3,
4371
+ importanceDrift: 0.4,
4372
+ deduplicationRate: 0.3
4373
+ };
4374
+ const estimatedRecallImprovement = Math.max(0, Math.min(100, corpusReduction * recallWeight.corpusReduction + Math.max(0, importanceDrift * 10) * recallWeight.importanceDrift + deduplicationRate * recallWeight.deduplicationRate));
4375
+ const metricDefs = [
4376
+ { metric_type: "corpus_reduction_pct", value: corpusReduction, baseline: 0 },
4377
+ { metric_type: "importance_drift", value: importanceDrift, baseline: 0 },
4378
+ { metric_type: "deduplication_rate_pct", value: deduplicationRate, baseline: 0 },
4379
+ { metric_type: "estimated_recall_improvement_pct", value: estimatedRecallImprovement, baseline: 0 },
4380
+ { metric_type: "pre_corpus_size", value: preCount, baseline: preCount },
4381
+ { metric_type: "post_corpus_size", value: postCount, baseline: preCount },
4382
+ { metric_type: "proposals_accepted", value: acceptedProposals.length, baseline: 0 },
4383
+ { metric_type: "pre_avg_importance", value: preAvgImportance, baseline: preAvgImportance },
4384
+ { metric_type: "post_avg_importance", value: postAvgImportance, baseline: preAvgImportance }
4385
+ ];
4386
+ for (const def of metricDefs) {
4387
+ createMetric({
4388
+ run_id: runId,
4389
+ metric_type: def.metric_type,
4390
+ value: def.value,
4391
+ baseline: def.baseline ?? null
4392
+ }, d);
4393
+ }
4394
+ const metrics = listMetrics(runId, d);
4395
+ return {
4396
+ runId,
4397
+ corpusReduction,
4398
+ importanceDrift,
4399
+ deduplicationRate,
4400
+ estimatedRecallImprovement,
4401
+ metrics
4402
+ };
4403
+ }
4404
+
4405
+ // src/lib/synthesis/index.ts
4406
+ async function runSynthesis(options = {}) {
4407
+ const d = options.db || getDatabase();
4408
+ const projectId = options.projectId ?? null;
4409
+ const agentId = options.agentId ?? null;
4410
+ const dryRun = options.dryRun ?? false;
4411
+ const run = createSynthesisRun({
4412
+ triggered_by: "manual",
4413
+ project_id: projectId,
4414
+ agent_id: agentId
4415
+ }, d);
4416
+ updateSynthesisRun(run.id, { status: "running" }, d);
4417
+ try {
4418
+ const corpus = await buildCorpus({
4419
+ projectId: projectId ?? undefined,
4420
+ agentId: agentId ?? undefined,
4421
+ db: d
4422
+ });
4423
+ updateSynthesisRun(run.id, { corpus_size: corpus.totalMemories }, d);
4424
+ const analysisResult = await analyzeCorpus(corpus, {
4425
+ provider: options.provider,
4426
+ maxProposals: options.maxProposals ?? 20
4427
+ });
4428
+ const validation = validateProposals(analysisResult.proposals, corpus, options.safetyConfig);
4429
+ const rejectedIndices = new Set(validation.rejectedProposals.map((r) => {
4430
+ const match = r.proposalId.match(/\[(\d+)\]/);
4431
+ return match ? parseInt(match[1], 10) : -1;
4432
+ }));
4433
+ const validProposals = analysisResult.proposals.filter((_, idx) => !rejectedIndices.has(idx));
4434
+ const savedProposals = [];
4435
+ for (const p of validProposals) {
4436
+ const saved = createProposal({
4437
+ run_id: run.id,
4438
+ proposal_type: p.type,
4439
+ memory_ids: p.memory_ids,
4440
+ target_memory_id: p.target_memory_id ?? null,
4441
+ proposed_changes: p.proposed_changes,
4442
+ reasoning: p.reasoning,
4443
+ confidence: p.confidence
4444
+ }, d);
4445
+ savedProposals.push(saved);
4446
+ }
4447
+ updateSynthesisRun(run.id, {
4448
+ proposals_generated: analysisResult.proposals.length,
4449
+ proposals_rejected: validation.rejectedProposals.length
4450
+ }, d);
4451
+ let executedCount = 0;
4452
+ if (!dryRun && savedProposals.length > 0) {
4453
+ const execResult = await executeProposals(run.id, savedProposals, d);
4454
+ executedCount = execResult.executed;
4455
+ updateSynthesisRun(run.id, {
4456
+ proposals_accepted: execResult.executed,
4457
+ proposals_rejected: validation.rejectedProposals.length + execResult.failed,
4458
+ status: "completed",
4459
+ completed_at: now()
4460
+ }, d);
4461
+ } else {
4462
+ updateSynthesisRun(run.id, {
4463
+ status: "completed",
4464
+ completed_at: now()
4465
+ }, d);
4466
+ }
4467
+ let effectivenessReport = null;
4468
+ if (!dryRun && executedCount > 0) {
4469
+ try {
4470
+ effectivenessReport = await measureEffectiveness(run.id, corpus, d);
4471
+ } catch {}
4472
+ }
4473
+ const finalRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
4474
+ const finalProposals = listProposals(run.id, undefined, d);
4475
+ return {
4476
+ run: finalRun,
4477
+ proposals: finalProposals,
4478
+ executed: executedCount,
4479
+ metrics: effectivenessReport,
4480
+ dryRun
4481
+ };
4482
+ } catch (err) {
4483
+ updateSynthesisRun(run.id, {
4484
+ status: "failed",
4485
+ error: err instanceof Error ? err.message : String(err),
4486
+ completed_at: now()
4487
+ }, d);
4488
+ const failedRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
4489
+ return {
4490
+ run: failedRun,
4491
+ proposals: [],
4492
+ executed: 0,
4493
+ metrics: null,
4494
+ dryRun
4495
+ };
4496
+ }
4497
+ }
4498
+ async function rollbackSynthesis(runId, db) {
4499
+ const d = db || getDatabase();
4500
+ const result = await rollbackRun(runId, d);
4501
+ if (result.errors.length === 0) {
4502
+ updateSynthesisRun(runId, { status: "rolled_back", completed_at: now() }, d);
4503
+ }
4504
+ return result;
4505
+ }
4506
+ function getSynthesisStatus(runId, projectId, db) {
4507
+ const d = db || getDatabase();
4508
+ if (runId) {
4509
+ const recentRuns2 = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
4510
+ const specificRun = recentRuns2.find((r) => r.id === runId) ?? null;
4511
+ return {
4512
+ lastRun: specificRun ?? recentRuns2[0] ?? null,
4513
+ recentRuns: recentRuns2
4514
+ };
4515
+ }
4516
+ const recentRuns = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
4517
+ return {
4518
+ lastRun: recentRuns[0] ?? null,
4519
+ recentRuns
4520
+ };
4521
+ }
4522
+
4523
+ // src/server/index.ts
4524
+ init_synthesis();
4525
+
4526
+ // src/db/session-jobs.ts
4527
+ init_database();
4528
+ function parseJobRow(row) {
4529
+ return {
4530
+ id: row["id"],
4531
+ session_id: row["session_id"],
4532
+ agent_id: row["agent_id"] || null,
4533
+ project_id: row["project_id"] || null,
4534
+ source: row["source"],
4535
+ status: row["status"],
4536
+ transcript: row["transcript"],
4537
+ chunk_count: row["chunk_count"],
4538
+ memories_extracted: row["memories_extracted"],
4539
+ error: row["error"] || null,
4540
+ metadata: JSON.parse(row["metadata"] || "{}"),
4541
+ created_at: row["created_at"],
4542
+ started_at: row["started_at"] || null,
4543
+ completed_at: row["completed_at"] || null
4544
+ };
4545
+ }
4546
+ function createSessionJob(input, db) {
4547
+ const d = db || getDatabase();
4548
+ const id = uuid();
4549
+ const timestamp = now();
4550
+ const source = input.source ?? "manual";
4551
+ const metadata = JSON.stringify(input.metadata ?? {});
4552
+ d.run(`INSERT INTO session_memory_jobs
4553
+ (id, session_id, agent_id, project_id, source, status, transcript, chunk_count, memories_extracted, metadata, created_at)
4554
+ VALUES (?, ?, ?, ?, ?, 'pending', ?, 0, 0, ?, ?)`, [
4555
+ id,
4556
+ input.session_id,
4557
+ input.agent_id ?? null,
4558
+ input.project_id ?? null,
4559
+ source,
4560
+ input.transcript,
4561
+ metadata,
4562
+ timestamp
4563
+ ]);
4564
+ return getSessionJob(id, d);
4565
+ }
4566
+ function getSessionJob(id, db) {
4567
+ const d = db || getDatabase();
4568
+ const row = d.query("SELECT * FROM session_memory_jobs WHERE id = ?").get(id);
4569
+ if (!row)
4570
+ return null;
4571
+ return parseJobRow(row);
4572
+ }
4573
+ function listSessionJobs(filter, db) {
4574
+ const d = db || getDatabase();
4575
+ const conditions = [];
4576
+ const params = [];
4577
+ if (filter?.agent_id) {
4578
+ conditions.push("agent_id = ?");
4579
+ params.push(filter.agent_id);
4580
+ }
4581
+ if (filter?.project_id) {
4582
+ conditions.push("project_id = ?");
4583
+ params.push(filter.project_id);
4584
+ }
4585
+ if (filter?.status) {
4586
+ conditions.push("status = ?");
4587
+ params.push(filter.status);
4588
+ }
4589
+ if (filter?.session_id) {
4590
+ conditions.push("session_id = ?");
4591
+ params.push(filter.session_id);
4592
+ }
4593
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4594
+ const limit = filter?.limit ?? 20;
4595
+ const offset = filter?.offset ?? 0;
4596
+ const rows = d.query(`SELECT * FROM session_memory_jobs ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...params, limit, offset);
4597
+ return rows.map(parseJobRow);
4598
+ }
4599
+ function updateSessionJob(id, updates, db) {
4600
+ const d = db || getDatabase();
4601
+ const setClauses = [];
4602
+ const params = [];
4603
+ if (updates.status !== undefined) {
4604
+ setClauses.push("status = ?");
4605
+ params.push(updates.status);
4606
+ }
4607
+ if (updates.chunk_count !== undefined) {
4608
+ setClauses.push("chunk_count = ?");
4609
+ params.push(updates.chunk_count);
4610
+ }
4611
+ if (updates.memories_extracted !== undefined) {
4612
+ setClauses.push("memories_extracted = ?");
4613
+ params.push(updates.memories_extracted);
4614
+ }
4615
+ if ("error" in updates) {
4616
+ setClauses.push("error = ?");
4617
+ params.push(updates.error ?? null);
4618
+ }
4619
+ if ("started_at" in updates) {
4620
+ setClauses.push("started_at = ?");
4621
+ params.push(updates.started_at ?? null);
4622
+ }
4623
+ if ("completed_at" in updates) {
4624
+ setClauses.push("completed_at = ?");
4625
+ params.push(updates.completed_at ?? null);
4626
+ }
4627
+ if (setClauses.length === 0)
4628
+ return getSessionJob(id, d);
4629
+ params.push(id);
4630
+ d.run(`UPDATE session_memory_jobs SET ${setClauses.join(", ")} WHERE id = ?`, params);
4631
+ return getSessionJob(id, d);
4632
+ }
4633
+ function getNextPendingJob(db) {
4634
+ const d = db || getDatabase();
4635
+ const row = d.query("SELECT * FROM session_memory_jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1").get();
4636
+ if (!row)
4637
+ return null;
4638
+ return parseJobRow(row);
4639
+ }
4640
+
4641
+ // src/lib/session-queue.ts
4642
+ init_database();
4643
+
4644
+ // src/lib/session-processor.ts
4645
+ init_memories();
4646
+ init_registry();
4647
+ var SESSION_EXTRACTION_USER_TEMPLATE = (chunk, sessionId) => `Extract memories from this session chunk (session: ${sessionId}):
4648
+
4649
+ ${chunk}
4650
+
4651
+ Return JSON array: [{"key": "...", "value": "...", "category": "knowledge|fact|preference|history", "importance": 1-10, "tags": [...]}]`;
4652
+ function chunkTranscript(transcript, chunkSize = 2000, overlap = 200) {
4653
+ if (!transcript || transcript.length === 0)
4654
+ return [];
4655
+ if (transcript.length <= chunkSize)
4656
+ return [transcript];
4657
+ const chunks = [];
4658
+ let start = 0;
4659
+ while (start < transcript.length) {
4660
+ const end = Math.min(start + chunkSize, transcript.length);
4661
+ chunks.push(transcript.slice(start, end));
4662
+ if (end === transcript.length)
4663
+ break;
4664
+ start += chunkSize - overlap;
4665
+ }
4666
+ return chunks;
4667
+ }
4668
+ async function extractMemoriesFromChunk(chunk, context, db) {
4669
+ const provider = providerRegistry.getAvailable();
4670
+ if (!provider)
4671
+ return 0;
4672
+ try {
4673
+ const extracted = await provider.extractMemories(SESSION_EXTRACTION_USER_TEMPLATE(chunk, context.sessionId), {
4674
+ sessionId: context.sessionId,
4675
+ agentId: context.agentId,
4676
+ projectId: context.projectId
4677
+ });
4678
+ let savedCount = 0;
4679
+ const sourceTag = context.source ? `source:${context.source}` : "source:manual";
4680
+ for (const memory of extracted) {
4681
+ if (!memory.content || !memory.content.trim())
4682
+ continue;
4683
+ try {
4684
+ createMemory({
4685
+ key: memory.content.slice(0, 120).replace(/\s+/g, "-").toLowerCase(),
4686
+ value: memory.content,
4687
+ category: memory.category,
4688
+ scope: memory.suggestedScope ?? "shared",
4689
+ importance: memory.importance,
4690
+ tags: [
4691
+ ...memory.tags,
4692
+ "session-extracted",
4693
+ sourceTag,
4694
+ `session:${context.sessionId}`
4695
+ ],
4696
+ source: "auto",
4697
+ agent_id: context.agentId,
4698
+ project_id: context.projectId,
4699
+ session_id: context.sessionId,
4700
+ metadata: {
4701
+ auto_extracted: true,
4702
+ session_source: context.source ?? "manual",
4703
+ extracted_at: new Date().toISOString(),
4704
+ reasoning: memory.reasoning
4705
+ }
4706
+ }, "merge", db);
4707
+ savedCount++;
4708
+ } catch {}
4709
+ }
4710
+ return savedCount;
4711
+ } catch {
4712
+ try {
4713
+ const fallbacks = providerRegistry.getFallbacks();
4714
+ for (const fallback of fallbacks) {
4715
+ try {
4716
+ const extracted = await fallback.extractMemories(SESSION_EXTRACTION_USER_TEMPLATE(chunk, context.sessionId), {
4717
+ sessionId: context.sessionId,
4718
+ agentId: context.agentId,
4719
+ projectId: context.projectId
4720
+ });
4721
+ let savedCount = 0;
4722
+ const sourceTag = context.source ? `source:${context.source}` : "source:manual";
4723
+ for (const memory of extracted) {
4724
+ if (!memory.content || !memory.content.trim())
4725
+ continue;
4726
+ try {
4727
+ createMemory({
4728
+ key: memory.content.slice(0, 120).replace(/\s+/g, "-").toLowerCase(),
4729
+ value: memory.content,
4730
+ category: memory.category,
4731
+ scope: memory.suggestedScope ?? "shared",
4732
+ importance: memory.importance,
4733
+ tags: [
4734
+ ...memory.tags,
4735
+ "session-extracted",
4736
+ sourceTag,
4737
+ `session:${context.sessionId}`
4738
+ ],
4739
+ source: "auto",
4740
+ agent_id: context.agentId,
4741
+ project_id: context.projectId,
4742
+ session_id: context.sessionId,
4743
+ metadata: {
4744
+ auto_extracted: true,
4745
+ session_source: context.source ?? "manual",
4746
+ extracted_at: new Date().toISOString(),
4747
+ reasoning: memory.reasoning
4748
+ }
4749
+ }, "merge", db);
4750
+ savedCount++;
4751
+ } catch {}
4752
+ }
4753
+ if (savedCount > 0)
4754
+ return savedCount;
4755
+ } catch {
4756
+ continue;
4757
+ }
4758
+ }
4759
+ } catch {}
4760
+ return 0;
4761
+ }
4762
+ }
4763
+ async function processSessionJob(jobId, db) {
4764
+ const result = {
4765
+ jobId,
4766
+ chunksProcessed: 0,
4767
+ memoriesExtracted: 0,
4768
+ errors: []
4769
+ };
4770
+ let job;
4771
+ try {
4772
+ job = getSessionJob(jobId, db);
4773
+ if (!job) {
4774
+ result.errors.push(`Job not found: ${jobId}`);
4775
+ return result;
4776
+ }
4777
+ } catch (e) {
4778
+ result.errors.push(`Failed to fetch job: ${String(e)}`);
4779
+ return result;
4780
+ }
4781
+ try {
4782
+ updateSessionJob(jobId, { status: "processing", started_at: new Date().toISOString() }, db);
4783
+ } catch (e) {
4784
+ result.errors.push(`Failed to mark job as processing: ${String(e)}`);
4785
+ return result;
4786
+ }
4787
+ const chunks = chunkTranscript(job.transcript);
4788
+ try {
4789
+ updateSessionJob(jobId, { chunk_count: chunks.length }, db);
4790
+ } catch {}
4791
+ let totalMemories = 0;
4792
+ for (let i = 0;i < chunks.length; i++) {
4793
+ const chunk = chunks[i];
4794
+ try {
4795
+ const count = await extractMemoriesFromChunk(chunk, {
4796
+ sessionId: job.session_id,
4797
+ agentId: job.agent_id ?? undefined,
4798
+ projectId: job.project_id ?? undefined,
4799
+ source: job.source
4800
+ }, db);
4801
+ totalMemories += count;
4802
+ result.chunksProcessed++;
4803
+ } catch (e) {
4804
+ result.errors.push(`Chunk ${i} failed: ${String(e)}`);
4805
+ }
4806
+ }
4807
+ result.memoriesExtracted = totalMemories;
4808
+ try {
4809
+ if (result.errors.length > 0 && result.chunksProcessed === 0) {
4810
+ updateSessionJob(jobId, {
4811
+ status: "failed",
4812
+ error: result.errors.join("; "),
4813
+ completed_at: new Date().toISOString(),
4814
+ memories_extracted: totalMemories,
4815
+ chunk_count: chunks.length
4816
+ }, db);
4817
+ } else {
4818
+ updateSessionJob(jobId, {
4819
+ status: "completed",
4820
+ completed_at: new Date().toISOString(),
4821
+ memories_extracted: totalMemories,
4822
+ chunk_count: chunks.length
4823
+ }, db);
4824
+ }
4825
+ } catch (e) {
4826
+ result.errors.push(`Failed to update job status: ${String(e)}`);
4827
+ }
4828
+ return result;
4829
+ }
4830
+
4831
+ // src/lib/session-queue.ts
4832
+ var _pendingQueue = new Set;
4833
+ var _isProcessing = false;
4834
+ var _workerStarted = false;
4835
+ function enqueueSessionJob(jobId) {
4836
+ _pendingQueue.add(jobId);
4837
+ if (!_isProcessing) {
4838
+ _processNext();
4839
+ }
4840
+ }
4841
+ function getSessionQueueStats() {
4842
+ try {
4843
+ const db = getDatabase();
4844
+ const rows = db.query("SELECT status, COUNT(*) as count FROM session_memory_jobs GROUP BY status").all();
4845
+ const stats = {
4846
+ pending: 0,
4847
+ processing: 0,
4848
+ completed: 0,
4849
+ failed: 0
4850
+ };
4851
+ for (const row of rows) {
4852
+ if (row.status === "pending")
4853
+ stats.pending = row.count;
4854
+ else if (row.status === "processing")
4855
+ stats.processing = row.count;
4856
+ else if (row.status === "completed")
4857
+ stats.completed = row.count;
4858
+ else if (row.status === "failed")
4859
+ stats.failed = row.count;
4860
+ }
4861
+ return stats;
4862
+ } catch {
4863
+ return {
4864
+ pending: _pendingQueue.size,
4865
+ processing: _isProcessing ? 1 : 0,
4866
+ completed: 0,
4867
+ failed: 0
4868
+ };
4869
+ }
4870
+ }
4871
+ function startSessionQueueWorker() {
4872
+ if (_workerStarted)
4873
+ return;
4874
+ _workerStarted = true;
4875
+ setInterval(() => {
4876
+ _processNext();
4877
+ }, 5000);
4878
+ }
4879
+ async function _processNext() {
4880
+ if (_isProcessing)
4881
+ return;
4882
+ let jobId;
4883
+ if (_pendingQueue.size > 0) {
4884
+ jobId = [..._pendingQueue][0];
4885
+ _pendingQueue.delete(jobId);
4886
+ } else {
4887
+ try {
4888
+ const job = getNextPendingJob();
4889
+ if (job)
4890
+ jobId = job.id;
4891
+ } catch {
4892
+ return;
4893
+ }
4894
+ }
4895
+ if (!jobId)
4896
+ return;
4897
+ _isProcessing = true;
4898
+ try {
4899
+ await processSessionJob(jobId);
4900
+ } catch {} finally {
4901
+ _isProcessing = false;
4902
+ if (_pendingQueue.size > 0) {
4903
+ _processNext();
4904
+ }
4905
+ }
4906
+ }
4907
+
4908
+ // src/lib/session-auto-resolve.ts
4909
+ function autoResolveAgentProject(metadata, db) {
4910
+ let agentId = null;
4911
+ let projectId = null;
4912
+ let confidence = "none";
4913
+ const methods = [];
4914
+ if (metadata.agentName) {
4915
+ try {
4916
+ const agent = getAgent(metadata.agentName, db);
4917
+ if (agent) {
4918
+ agentId = agent.id;
4919
+ confidence = "high";
4920
+ methods.push(`agent-by-name:${metadata.agentName}`);
4921
+ if (agent.active_project_id && !projectId) {
4922
+ projectId = agent.active_project_id;
4923
+ methods.push("project-from-agent-active");
4924
+ }
4925
+ }
4926
+ } catch {}
4927
+ }
4928
+ if (metadata.workingDir && !projectId) {
4929
+ try {
4930
+ const project = getProject(metadata.workingDir, db);
4931
+ if (project) {
4932
+ projectId = project.id;
4933
+ if (confidence !== "high")
4934
+ confidence = "high";
4935
+ methods.push(`project-by-path:${metadata.workingDir}`);
4936
+ } else {
4937
+ const allProjects = listProjects(db);
4938
+ for (const p of allProjects) {
4939
+ if (p.path && metadata.workingDir.startsWith(p.path)) {
4940
+ projectId = p.id;
4941
+ if (confidence !== "high")
4942
+ confidence = "high";
4943
+ methods.push(`project-by-path-prefix:${p.path}`);
4944
+ break;
4945
+ }
4946
+ }
4947
+ }
4948
+ } catch {}
4949
+ }
4950
+ if (metadata.gitRemote && !projectId) {
4951
+ try {
4952
+ const repoName = metadata.gitRemote.replace(/\.git$/, "").split(/[/:]/).filter(Boolean).pop();
4953
+ if (repoName) {
4954
+ const project = getProject(repoName, db);
4955
+ if (project) {
4956
+ projectId = project.id;
4957
+ if (confidence === "none")
4958
+ confidence = "low";
4959
+ methods.push(`project-by-git-remote:${repoName}`);
4960
+ }
4961
+ }
4962
+ } catch {}
4963
+ }
4964
+ if (methods.length === 0) {
4965
+ confidence = "none";
4966
+ }
4967
+ return {
4968
+ agentId,
4969
+ projectId,
4970
+ confidence,
4971
+ method: methods.join(", ") || "none"
4972
+ };
4973
+ }
4974
+
4975
+ // src/server/index.ts
4976
+ var DEFAULT_PORT = 19428;
4977
+ function parsePort() {
4978
+ const envPort = process.env["PORT"];
4979
+ if (envPort) {
4980
+ const p = parseInt(envPort, 10);
4981
+ if (!Number.isNaN(p))
4982
+ return p;
4983
+ }
4984
+ const portArg = process.argv.find((a) => a === "--port" || a.startsWith("--port="));
4985
+ if (portArg) {
4986
+ if (portArg.includes("=")) {
4987
+ return parseInt(portArg.split("=")[1], 10) || DEFAULT_PORT;
4988
+ }
4989
+ const idx = process.argv.indexOf(portArg);
4990
+ return parseInt(process.argv[idx + 1], 10) || DEFAULT_PORT;
4991
+ }
4992
+ return DEFAULT_PORT;
4993
+ }
4994
+ function resolveDashboardDir() {
4995
+ const candidates = [];
4996
+ try {
3229
4997
  const scriptDir = dirname3(fileURLToPath(import.meta.url));
3230
4998
  candidates.push(join3(scriptDir, "..", "dashboard", "dist"));
3231
4999
  candidates.push(join3(scriptDir, "..", "..", "dashboard", "dist"));
@@ -4280,8 +6048,77 @@ addRoute("DELETE", "/api/webhooks/:id", (_req, _url, params) => {
4280
6048
  return errorResponse("Webhook not found", 404);
4281
6049
  return new Response(null, { status: 204 });
4282
6050
  });
6051
+ addRoute("POST", "/api/synthesis/run", async (req) => {
6052
+ const body = await readJson(req) ?? {};
6053
+ const result = await runSynthesis({
6054
+ projectId: body.project_id,
6055
+ agentId: body.agent_id,
6056
+ dryRun: body.dry_run,
6057
+ maxProposals: body.max_proposals,
6058
+ provider: body.provider
6059
+ });
6060
+ return json(result, result.dryRun ? 200 : 201);
6061
+ });
6062
+ addRoute("GET", "/api/synthesis/runs", (_req, url) => {
6063
+ const projectId = url.searchParams.get("project_id") ?? undefined;
6064
+ const limit = url.searchParams.get("limit") ? parseInt(url.searchParams.get("limit")) : 20;
6065
+ const runs = listSynthesisRuns({ project_id: projectId, limit });
6066
+ return json({ runs, count: runs.length });
6067
+ });
6068
+ addRoute("GET", "/api/synthesis/status", (_req, url) => {
6069
+ const projectId = url.searchParams.get("project_id") ?? undefined;
6070
+ const runId = url.searchParams.get("run_id") ?? undefined;
6071
+ return json(getSynthesisStatus(runId, projectId));
6072
+ });
6073
+ addRoute("POST", "/api/synthesis/rollback/:run_id", async (_req, _url, params) => {
6074
+ const result = await rollbackSynthesis(params["run_id"]);
6075
+ return json(result);
6076
+ });
6077
+ addRoute("POST", "/api/sessions/ingest", async (req) => {
6078
+ const body = await readJson(req) ?? {};
6079
+ const { transcript, session_id, agent_id, project_id, source, metadata } = body;
6080
+ if (!transcript || typeof transcript !== "string")
6081
+ return errorResponse("transcript is required", 400);
6082
+ if (!session_id || typeof session_id !== "string")
6083
+ return errorResponse("session_id is required", 400);
6084
+ let resolvedAgentId = agent_id;
6085
+ let resolvedProjectId = project_id;
6086
+ if (!resolvedAgentId || !resolvedProjectId) {
6087
+ const resolved = autoResolveAgentProject(metadata ?? {});
6088
+ if (!resolvedAgentId && resolved.agentId)
6089
+ resolvedAgentId = resolved.agentId;
6090
+ if (!resolvedProjectId && resolved.projectId)
6091
+ resolvedProjectId = resolved.projectId;
6092
+ }
6093
+ const job = createSessionJob({
6094
+ session_id,
6095
+ transcript,
6096
+ source: source ?? "manual",
6097
+ agent_id: resolvedAgentId,
6098
+ project_id: resolvedProjectId,
6099
+ metadata: metadata ?? {}
6100
+ });
6101
+ enqueueSessionJob(job.id);
6102
+ return json({ job_id: job.id, status: "queued", message: "Session queued for memory extraction" }, 202);
6103
+ });
6104
+ addRoute("GET", "/api/sessions/jobs", (_req, url) => {
6105
+ const agentId = url.searchParams.get("agent_id") ?? undefined;
6106
+ const projectId = url.searchParams.get("project_id") ?? undefined;
6107
+ const status = url.searchParams.get("status") ?? undefined;
6108
+ const limit = url.searchParams.get("limit") ? parseInt(url.searchParams.get("limit")) : 20;
6109
+ const jobs = listSessionJobs({ agent_id: agentId, project_id: projectId, status, limit });
6110
+ return json({ jobs, count: jobs.length });
6111
+ });
6112
+ addRoute("GET", "/api/sessions/jobs/:id", (_req, _url, params) => {
6113
+ const job = getSessionJob(params["id"]);
6114
+ if (!job)
6115
+ return errorResponse("Session job not found", 404);
6116
+ return json(job);
6117
+ });
6118
+ addRoute("GET", "/api/sessions/queue/stats", () => json(getSessionQueueStats()));
4283
6119
  function startServer(port) {
4284
6120
  loadWebhooksFromDb();
6121
+ startSessionQueueWorker();
4285
6122
  const hostname = process.env["MEMENTOS_HOST"] ?? "127.0.0.1";
4286
6123
  Bun.serve({
4287
6124
  port,