@hasna/mementos 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +1358 -0
- package/dist/db/database.d.ts.map +1 -1
- package/dist/db/synthesis.d.ts +101 -0
- package/dist/db/synthesis.d.ts.map +1 -0
- package/dist/index.js +69 -0
- package/dist/lib/built-in-hooks.d.ts.map +1 -1
- package/dist/lib/synthesis/corpus-builder.d.ts +30 -0
- package/dist/lib/synthesis/corpus-builder.d.ts.map +1 -0
- package/dist/lib/synthesis/executor.d.ts +14 -0
- package/dist/lib/synthesis/executor.d.ts.map +1 -0
- package/dist/lib/synthesis/index.d.ts +37 -0
- package/dist/lib/synthesis/index.d.ts.map +1 -0
- package/dist/lib/synthesis/llm-analyzer.d.ts +18 -0
- package/dist/lib/synthesis/llm-analyzer.d.ts.map +1 -0
- package/dist/lib/synthesis/metrics.d.ts +13 -0
- package/dist/lib/synthesis/metrics.d.ts.map +1 -0
- package/dist/lib/synthesis/scheduler.d.ts +18 -0
- package/dist/lib/synthesis/scheduler.d.ts.map +1 -0
- package/dist/lib/synthesis/validator.d.ts +19 -0
- package/dist/lib/synthesis/validator.d.ts.map +1 -0
- package/dist/mcp/index.js +1348 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1320 -0
- package/package.json +1 -1
package/dist/mcp/index.js
CHANGED
|
@@ -403,6 +403,75 @@ var init_database = __esm(() => {
|
|
|
403
403
|
ALTER TABLE memories ADD COLUMN recall_count INTEGER NOT NULL DEFAULT 0;
|
|
404
404
|
CREATE INDEX IF NOT EXISTS idx_memories_recall_count ON memories(recall_count DESC);
|
|
405
405
|
INSERT OR IGNORE INTO _migrations (id) VALUES (9);
|
|
406
|
+
`,
|
|
407
|
+
`
|
|
408
|
+
CREATE TABLE IF NOT EXISTS synthesis_events (
|
|
409
|
+
id TEXT PRIMARY KEY,
|
|
410
|
+
event_type TEXT NOT NULL CHECK(event_type IN ('recalled','searched','saved','updated','deleted','injected')),
|
|
411
|
+
memory_id TEXT,
|
|
412
|
+
agent_id TEXT,
|
|
413
|
+
project_id TEXT,
|
|
414
|
+
session_id TEXT,
|
|
415
|
+
query TEXT,
|
|
416
|
+
importance_at_time INTEGER,
|
|
417
|
+
metadata TEXT NOT NULL DEFAULT '{}',
|
|
418
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
419
|
+
);
|
|
420
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_events_memory ON synthesis_events(memory_id);
|
|
421
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_events_project ON synthesis_events(project_id);
|
|
422
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_events_type ON synthesis_events(event_type);
|
|
423
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_events_created ON synthesis_events(created_at);
|
|
424
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (11);
|
|
425
|
+
`,
|
|
426
|
+
`
|
|
427
|
+
CREATE TABLE IF NOT EXISTS synthesis_runs (
|
|
428
|
+
id TEXT PRIMARY KEY,
|
|
429
|
+
triggered_by TEXT NOT NULL DEFAULT 'manual' CHECK(triggered_by IN ('scheduler','manual','threshold','hook')),
|
|
430
|
+
project_id TEXT,
|
|
431
|
+
agent_id TEXT,
|
|
432
|
+
corpus_size INTEGER NOT NULL DEFAULT 0,
|
|
433
|
+
proposals_generated INTEGER NOT NULL DEFAULT 0,
|
|
434
|
+
proposals_accepted INTEGER NOT NULL DEFAULT 0,
|
|
435
|
+
proposals_rejected INTEGER NOT NULL DEFAULT 0,
|
|
436
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','running','completed','failed','rolled_back')),
|
|
437
|
+
error TEXT,
|
|
438
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
439
|
+
completed_at TEXT
|
|
440
|
+
);
|
|
441
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_runs_project ON synthesis_runs(project_id);
|
|
442
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_runs_status ON synthesis_runs(status);
|
|
443
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_runs_started ON synthesis_runs(started_at);
|
|
444
|
+
|
|
445
|
+
CREATE TABLE IF NOT EXISTS synthesis_proposals (
|
|
446
|
+
id TEXT PRIMARY KEY,
|
|
447
|
+
run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
|
|
448
|
+
proposal_type TEXT NOT NULL CHECK(proposal_type IN ('merge','archive','promote','update_value','add_tag','remove_duplicate')),
|
|
449
|
+
memory_ids TEXT NOT NULL DEFAULT '[]',
|
|
450
|
+
target_memory_id TEXT,
|
|
451
|
+
proposed_changes TEXT NOT NULL DEFAULT '{}',
|
|
452
|
+
reasoning TEXT,
|
|
453
|
+
confidence REAL NOT NULL DEFAULT 0.5,
|
|
454
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','accepted','rejected','rolled_back')),
|
|
455
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
456
|
+
executed_at TEXT,
|
|
457
|
+
rollback_data TEXT
|
|
458
|
+
);
|
|
459
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_run ON synthesis_proposals(run_id);
|
|
460
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_status ON synthesis_proposals(status);
|
|
461
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_proposals_type ON synthesis_proposals(proposal_type);
|
|
462
|
+
|
|
463
|
+
CREATE TABLE IF NOT EXISTS synthesis_metrics (
|
|
464
|
+
id TEXT PRIMARY KEY,
|
|
465
|
+
run_id TEXT NOT NULL REFERENCES synthesis_runs(id) ON DELETE CASCADE,
|
|
466
|
+
metric_type TEXT NOT NULL,
|
|
467
|
+
value REAL NOT NULL,
|
|
468
|
+
baseline REAL,
|
|
469
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
470
|
+
);
|
|
471
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_run ON synthesis_metrics(run_id);
|
|
472
|
+
CREATE INDEX IF NOT EXISTS idx_synthesis_metrics_type ON synthesis_metrics(metric_type);
|
|
473
|
+
|
|
474
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (12);
|
|
406
475
|
`,
|
|
407
476
|
`
|
|
408
477
|
CREATE TABLE IF NOT EXISTS webhook_hooks (
|
|
@@ -2716,6 +2785,294 @@ var init_auto_memory = __esm(() => {
|
|
|
2716
2785
|
autoMemoryQueue.setHandler(processJob);
|
|
2717
2786
|
});
|
|
2718
2787
|
|
|
2788
|
+
// src/db/synthesis.ts
|
|
2789
|
+
var exports_synthesis = {};
|
|
2790
|
+
__export(exports_synthesis, {
|
|
2791
|
+
updateSynthesisRun: () => updateSynthesisRun,
|
|
2792
|
+
updateProposal: () => updateProposal,
|
|
2793
|
+
recordSynthesisEvent: () => recordSynthesisEvent,
|
|
2794
|
+
listSynthesisRuns: () => listSynthesisRuns,
|
|
2795
|
+
listSynthesisEvents: () => listSynthesisEvents,
|
|
2796
|
+
listProposals: () => listProposals,
|
|
2797
|
+
listMetrics: () => listMetrics,
|
|
2798
|
+
getSynthesisRun: () => getSynthesisRun,
|
|
2799
|
+
getProposal: () => getProposal,
|
|
2800
|
+
createSynthesisRun: () => createSynthesisRun,
|
|
2801
|
+
createProposal: () => createProposal,
|
|
2802
|
+
createMetric: () => createMetric
|
|
2803
|
+
});
|
|
2804
|
+
function parseRunRow(row) {
|
|
2805
|
+
return {
|
|
2806
|
+
id: row["id"],
|
|
2807
|
+
triggered_by: row["triggered_by"],
|
|
2808
|
+
project_id: row["project_id"] || null,
|
|
2809
|
+
agent_id: row["agent_id"] || null,
|
|
2810
|
+
corpus_size: row["corpus_size"],
|
|
2811
|
+
proposals_generated: row["proposals_generated"],
|
|
2812
|
+
proposals_accepted: row["proposals_accepted"],
|
|
2813
|
+
proposals_rejected: row["proposals_rejected"],
|
|
2814
|
+
status: row["status"],
|
|
2815
|
+
error: row["error"] || null,
|
|
2816
|
+
started_at: row["started_at"],
|
|
2817
|
+
completed_at: row["completed_at"] || null
|
|
2818
|
+
};
|
|
2819
|
+
}
|
|
2820
|
+
function parseProposalRow(row) {
|
|
2821
|
+
return {
|
|
2822
|
+
id: row["id"],
|
|
2823
|
+
run_id: row["run_id"],
|
|
2824
|
+
proposal_type: row["proposal_type"],
|
|
2825
|
+
memory_ids: JSON.parse(row["memory_ids"] || "[]"),
|
|
2826
|
+
target_memory_id: row["target_memory_id"] || null,
|
|
2827
|
+
proposed_changes: JSON.parse(row["proposed_changes"] || "{}"),
|
|
2828
|
+
reasoning: row["reasoning"] || null,
|
|
2829
|
+
confidence: row["confidence"],
|
|
2830
|
+
status: row["status"],
|
|
2831
|
+
created_at: row["created_at"],
|
|
2832
|
+
executed_at: row["executed_at"] || null,
|
|
2833
|
+
rollback_data: row["rollback_data"] ? JSON.parse(row["rollback_data"]) : null
|
|
2834
|
+
};
|
|
2835
|
+
}
|
|
2836
|
+
function parseMetricRow(row) {
|
|
2837
|
+
return {
|
|
2838
|
+
id: row["id"],
|
|
2839
|
+
run_id: row["run_id"],
|
|
2840
|
+
metric_type: row["metric_type"],
|
|
2841
|
+
value: row["value"],
|
|
2842
|
+
baseline: row["baseline"] != null ? row["baseline"] : null,
|
|
2843
|
+
created_at: row["created_at"]
|
|
2844
|
+
};
|
|
2845
|
+
}
|
|
2846
|
+
function parseEventRow(row) {
|
|
2847
|
+
return {
|
|
2848
|
+
id: row["id"],
|
|
2849
|
+
event_type: row["event_type"],
|
|
2850
|
+
memory_id: row["memory_id"] || null,
|
|
2851
|
+
agent_id: row["agent_id"] || null,
|
|
2852
|
+
project_id: row["project_id"] || null,
|
|
2853
|
+
session_id: row["session_id"] || null,
|
|
2854
|
+
query: row["query"] || null,
|
|
2855
|
+
importance_at_time: row["importance_at_time"] != null ? row["importance_at_time"] : null,
|
|
2856
|
+
metadata: JSON.parse(row["metadata"] || "{}"),
|
|
2857
|
+
created_at: row["created_at"]
|
|
2858
|
+
};
|
|
2859
|
+
}
|
|
2860
|
+
function createSynthesisRun(input, db) {
|
|
2861
|
+
const d = db || getDatabase();
|
|
2862
|
+
const id = shortUuid();
|
|
2863
|
+
const timestamp = now();
|
|
2864
|
+
d.run(`INSERT INTO synthesis_runs (id, triggered_by, project_id, agent_id, corpus_size, proposals_generated, proposals_accepted, proposals_rejected, status, started_at)
|
|
2865
|
+
VALUES (?, ?, ?, ?, ?, 0, 0, 0, 'pending', ?)`, [
|
|
2866
|
+
id,
|
|
2867
|
+
input.triggered_by,
|
|
2868
|
+
input.project_id ?? null,
|
|
2869
|
+
input.agent_id ?? null,
|
|
2870
|
+
input.corpus_size ?? 0,
|
|
2871
|
+
timestamp
|
|
2872
|
+
]);
|
|
2873
|
+
return getSynthesisRun(id, d);
|
|
2874
|
+
}
|
|
2875
|
+
function getSynthesisRun(id, db) {
|
|
2876
|
+
const d = db || getDatabase();
|
|
2877
|
+
const row = d.query("SELECT * FROM synthesis_runs WHERE id = ?").get(id);
|
|
2878
|
+
if (!row)
|
|
2879
|
+
return null;
|
|
2880
|
+
return parseRunRow(row);
|
|
2881
|
+
}
|
|
2882
|
+
function listSynthesisRuns(filter, db) {
|
|
2883
|
+
const d = db || getDatabase();
|
|
2884
|
+
const conditions = [];
|
|
2885
|
+
const params = [];
|
|
2886
|
+
if (filter.project_id !== undefined) {
|
|
2887
|
+
if (filter.project_id === null) {
|
|
2888
|
+
conditions.push("project_id IS NULL");
|
|
2889
|
+
} else {
|
|
2890
|
+
conditions.push("project_id = ?");
|
|
2891
|
+
params.push(filter.project_id);
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
if (filter.status) {
|
|
2895
|
+
conditions.push("status = ?");
|
|
2896
|
+
params.push(filter.status);
|
|
2897
|
+
}
|
|
2898
|
+
let sql = "SELECT * FROM synthesis_runs";
|
|
2899
|
+
if (conditions.length > 0) {
|
|
2900
|
+
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
2901
|
+
}
|
|
2902
|
+
sql += " ORDER BY started_at DESC";
|
|
2903
|
+
if (filter.limit) {
|
|
2904
|
+
sql += " LIMIT ?";
|
|
2905
|
+
params.push(filter.limit);
|
|
2906
|
+
}
|
|
2907
|
+
const rows = d.query(sql).all(...params);
|
|
2908
|
+
return rows.map(parseRunRow);
|
|
2909
|
+
}
|
|
2910
|
+
function updateSynthesisRun(id, updates, db) {
|
|
2911
|
+
const d = db || getDatabase();
|
|
2912
|
+
const sets = [];
|
|
2913
|
+
const params = [];
|
|
2914
|
+
if (updates.status !== undefined) {
|
|
2915
|
+
sets.push("status = ?");
|
|
2916
|
+
params.push(updates.status);
|
|
2917
|
+
}
|
|
2918
|
+
if (updates.error !== undefined) {
|
|
2919
|
+
sets.push("error = ?");
|
|
2920
|
+
params.push(updates.error);
|
|
2921
|
+
}
|
|
2922
|
+
if (updates.corpus_size !== undefined) {
|
|
2923
|
+
sets.push("corpus_size = ?");
|
|
2924
|
+
params.push(updates.corpus_size);
|
|
2925
|
+
}
|
|
2926
|
+
if (updates.proposals_generated !== undefined) {
|
|
2927
|
+
sets.push("proposals_generated = ?");
|
|
2928
|
+
params.push(updates.proposals_generated);
|
|
2929
|
+
}
|
|
2930
|
+
if (updates.proposals_accepted !== undefined) {
|
|
2931
|
+
sets.push("proposals_accepted = ?");
|
|
2932
|
+
params.push(updates.proposals_accepted);
|
|
2933
|
+
}
|
|
2934
|
+
if (updates.proposals_rejected !== undefined) {
|
|
2935
|
+
sets.push("proposals_rejected = ?");
|
|
2936
|
+
params.push(updates.proposals_rejected);
|
|
2937
|
+
}
|
|
2938
|
+
if (updates.completed_at !== undefined) {
|
|
2939
|
+
sets.push("completed_at = ?");
|
|
2940
|
+
params.push(updates.completed_at);
|
|
2941
|
+
}
|
|
2942
|
+
if (sets.length === 0)
|
|
2943
|
+
return getSynthesisRun(id, d);
|
|
2944
|
+
params.push(id);
|
|
2945
|
+
d.run(`UPDATE synthesis_runs SET ${sets.join(", ")} WHERE id = ?`, params);
|
|
2946
|
+
return getSynthesisRun(id, d);
|
|
2947
|
+
}
|
|
2948
|
+
function createProposal(input, db) {
|
|
2949
|
+
const d = db || getDatabase();
|
|
2950
|
+
const id = shortUuid();
|
|
2951
|
+
const timestamp = now();
|
|
2952
|
+
d.run(`INSERT INTO synthesis_proposals (id, run_id, proposal_type, memory_ids, target_memory_id, proposed_changes, reasoning, confidence, status, created_at)
|
|
2953
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`, [
|
|
2954
|
+
id,
|
|
2955
|
+
input.run_id,
|
|
2956
|
+
input.proposal_type,
|
|
2957
|
+
JSON.stringify(input.memory_ids),
|
|
2958
|
+
input.target_memory_id ?? null,
|
|
2959
|
+
JSON.stringify(input.proposed_changes),
|
|
2960
|
+
input.reasoning ?? null,
|
|
2961
|
+
input.confidence,
|
|
2962
|
+
timestamp
|
|
2963
|
+
]);
|
|
2964
|
+
return getProposal(id, d);
|
|
2965
|
+
}
|
|
2966
|
+
function getProposal(id, db) {
|
|
2967
|
+
const d = db || getDatabase();
|
|
2968
|
+
const row = d.query("SELECT * FROM synthesis_proposals WHERE id = ?").get(id);
|
|
2969
|
+
if (!row)
|
|
2970
|
+
return null;
|
|
2971
|
+
return parseProposalRow(row);
|
|
2972
|
+
}
|
|
2973
|
+
function listProposals(run_id, filter, db) {
|
|
2974
|
+
const d = db || getDatabase();
|
|
2975
|
+
const params = [run_id];
|
|
2976
|
+
let sql = "SELECT * FROM synthesis_proposals WHERE run_id = ?";
|
|
2977
|
+
if (filter?.status) {
|
|
2978
|
+
sql += " AND status = ?";
|
|
2979
|
+
params.push(filter.status);
|
|
2980
|
+
}
|
|
2981
|
+
sql += " ORDER BY created_at ASC";
|
|
2982
|
+
const rows = d.query(sql).all(...params);
|
|
2983
|
+
return rows.map(parseProposalRow);
|
|
2984
|
+
}
|
|
2985
|
+
function updateProposal(id, updates, db) {
|
|
2986
|
+
const d = db || getDatabase();
|
|
2987
|
+
const sets = [];
|
|
2988
|
+
const params = [];
|
|
2989
|
+
if (updates.status !== undefined) {
|
|
2990
|
+
sets.push("status = ?");
|
|
2991
|
+
params.push(updates.status);
|
|
2992
|
+
}
|
|
2993
|
+
if (updates.executed_at !== undefined) {
|
|
2994
|
+
sets.push("executed_at = ?");
|
|
2995
|
+
params.push(updates.executed_at);
|
|
2996
|
+
}
|
|
2997
|
+
if (updates.rollback_data !== undefined) {
|
|
2998
|
+
sets.push("rollback_data = ?");
|
|
2999
|
+
params.push(JSON.stringify(updates.rollback_data));
|
|
3000
|
+
}
|
|
3001
|
+
if (sets.length === 0)
|
|
3002
|
+
return getProposal(id, d);
|
|
3003
|
+
params.push(id);
|
|
3004
|
+
d.run(`UPDATE synthesis_proposals SET ${sets.join(", ")} WHERE id = ?`, params);
|
|
3005
|
+
return getProposal(id, d);
|
|
3006
|
+
}
|
|
3007
|
+
function createMetric(input, db) {
|
|
3008
|
+
const d = db || getDatabase();
|
|
3009
|
+
const id = shortUuid();
|
|
3010
|
+
const timestamp = now();
|
|
3011
|
+
d.run(`INSERT INTO synthesis_metrics (id, run_id, metric_type, value, baseline, created_at)
|
|
3012
|
+
VALUES (?, ?, ?, ?, ?, ?)`, [id, input.run_id, input.metric_type, input.value, input.baseline ?? null, timestamp]);
|
|
3013
|
+
return { id, run_id: input.run_id, metric_type: input.metric_type, value: input.value, baseline: input.baseline ?? null, created_at: timestamp };
|
|
3014
|
+
}
|
|
3015
|
+
function listMetrics(run_id, db) {
|
|
3016
|
+
const d = db || getDatabase();
|
|
3017
|
+
const rows = d.query("SELECT * FROM synthesis_metrics WHERE run_id = ? ORDER BY created_at ASC").all(run_id);
|
|
3018
|
+
return rows.map(parseMetricRow);
|
|
3019
|
+
}
|
|
3020
|
+
function recordSynthesisEvent(input, db) {
|
|
3021
|
+
try {
|
|
3022
|
+
const d = db || getDatabase();
|
|
3023
|
+
const id = shortUuid();
|
|
3024
|
+
const timestamp = now();
|
|
3025
|
+
d.run(`INSERT INTO synthesis_events (id, event_type, memory_id, agent_id, project_id, session_id, query, importance_at_time, metadata, created_at)
|
|
3026
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
3027
|
+
id,
|
|
3028
|
+
input.event_type,
|
|
3029
|
+
input.memory_id ?? null,
|
|
3030
|
+
input.agent_id ?? null,
|
|
3031
|
+
input.project_id ?? null,
|
|
3032
|
+
input.session_id ?? null,
|
|
3033
|
+
input.query ?? null,
|
|
3034
|
+
input.importance_at_time ?? null,
|
|
3035
|
+
JSON.stringify(input.metadata ?? {}),
|
|
3036
|
+
timestamp
|
|
3037
|
+
]);
|
|
3038
|
+
} catch {}
|
|
3039
|
+
}
|
|
3040
|
+
function listSynthesisEvents(filter, db) {
|
|
3041
|
+
const d = db || getDatabase();
|
|
3042
|
+
const conditions = [];
|
|
3043
|
+
const params = [];
|
|
3044
|
+
if (filter.memory_id) {
|
|
3045
|
+
conditions.push("memory_id = ?");
|
|
3046
|
+
params.push(filter.memory_id);
|
|
3047
|
+
}
|
|
3048
|
+
if (filter.project_id) {
|
|
3049
|
+
conditions.push("project_id = ?");
|
|
3050
|
+
params.push(filter.project_id);
|
|
3051
|
+
}
|
|
3052
|
+
if (filter.event_type) {
|
|
3053
|
+
conditions.push("event_type = ?");
|
|
3054
|
+
params.push(filter.event_type);
|
|
3055
|
+
}
|
|
3056
|
+
if (filter.since) {
|
|
3057
|
+
conditions.push("created_at >= ?");
|
|
3058
|
+
params.push(filter.since);
|
|
3059
|
+
}
|
|
3060
|
+
let sql = "SELECT * FROM synthesis_events";
|
|
3061
|
+
if (conditions.length > 0) {
|
|
3062
|
+
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
3063
|
+
}
|
|
3064
|
+
sql += " ORDER BY created_at DESC";
|
|
3065
|
+
if (filter.limit) {
|
|
3066
|
+
sql += " LIMIT ?";
|
|
3067
|
+
params.push(filter.limit);
|
|
3068
|
+
}
|
|
3069
|
+
const rows = d.query(sql).all(...params);
|
|
3070
|
+
return rows.map(parseEventRow);
|
|
3071
|
+
}
|
|
3072
|
+
var init_synthesis = __esm(() => {
|
|
3073
|
+
init_database();
|
|
3074
|
+
});
|
|
3075
|
+
|
|
2719
3076
|
// src/lib/built-in-hooks.ts
|
|
2720
3077
|
var exports_built_in_hooks = {};
|
|
2721
3078
|
__export(exports_built_in_hooks, {
|
|
@@ -2816,6 +3173,41 @@ var init_built_in_hooks = __esm(() => {
|
|
|
2816
3173
|
} catch {}
|
|
2817
3174
|
}
|
|
2818
3175
|
});
|
|
3176
|
+
hookRegistry.register({
|
|
3177
|
+
type: "PostMemorySave",
|
|
3178
|
+
blocking: false,
|
|
3179
|
+
builtin: true,
|
|
3180
|
+
priority: 200,
|
|
3181
|
+
description: "Record memory save event for synthesis analytics",
|
|
3182
|
+
handler: async (ctx) => {
|
|
3183
|
+
const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
|
|
3184
|
+
recordSynthesisEvent2({
|
|
3185
|
+
event_type: "saved",
|
|
3186
|
+
memory_id: ctx.memory.id,
|
|
3187
|
+
agent_id: ctx.agentId,
|
|
3188
|
+
project_id: ctx.projectId,
|
|
3189
|
+
session_id: ctx.sessionId,
|
|
3190
|
+
importance_at_time: ctx.memory.importance
|
|
3191
|
+
});
|
|
3192
|
+
}
|
|
3193
|
+
});
|
|
3194
|
+
hookRegistry.register({
|
|
3195
|
+
type: "PostMemoryInject",
|
|
3196
|
+
blocking: false,
|
|
3197
|
+
builtin: true,
|
|
3198
|
+
priority: 200,
|
|
3199
|
+
description: "Record injection event for synthesis analytics",
|
|
3200
|
+
handler: async (ctx) => {
|
|
3201
|
+
const { recordSynthesisEvent: recordSynthesisEvent2 } = await Promise.resolve().then(() => (init_synthesis(), exports_synthesis));
|
|
3202
|
+
recordSynthesisEvent2({
|
|
3203
|
+
event_type: "injected",
|
|
3204
|
+
agent_id: ctx.agentId,
|
|
3205
|
+
project_id: ctx.projectId,
|
|
3206
|
+
session_id: ctx.sessionId,
|
|
3207
|
+
metadata: { count: ctx.memoriesCount, format: ctx.format }
|
|
3208
|
+
});
|
|
3209
|
+
}
|
|
3210
|
+
});
|
|
2819
3211
|
});
|
|
2820
3212
|
|
|
2821
3213
|
// src/mcp/index.ts
|
|
@@ -7198,6 +7590,910 @@ var FORMAT_UNITS = [
|
|
|
7198
7590
|
init_hooks();
|
|
7199
7591
|
init_built_in_hooks();
|
|
7200
7592
|
init_webhook_hooks();
|
|
7593
|
+
|
|
7594
|
+
// src/lib/synthesis/index.ts
|
|
7595
|
+
init_database();
|
|
7596
|
+
init_synthesis();
|
|
7597
|
+
|
|
7598
|
+
// src/lib/synthesis/corpus-builder.ts
|
|
7599
|
+
init_database();
|
|
7600
|
+
init_memories();
|
|
7601
|
+
init_synthesis();
|
|
7602
|
+
function extractTerms(text) {
|
|
7603
|
+
const stopWords = new Set([
|
|
7604
|
+
"a",
|
|
7605
|
+
"an",
|
|
7606
|
+
"the",
|
|
7607
|
+
"is",
|
|
7608
|
+
"it",
|
|
7609
|
+
"in",
|
|
7610
|
+
"of",
|
|
7611
|
+
"for",
|
|
7612
|
+
"to",
|
|
7613
|
+
"and",
|
|
7614
|
+
"or",
|
|
7615
|
+
"but",
|
|
7616
|
+
"not",
|
|
7617
|
+
"with",
|
|
7618
|
+
"this",
|
|
7619
|
+
"that",
|
|
7620
|
+
"are",
|
|
7621
|
+
"was",
|
|
7622
|
+
"be",
|
|
7623
|
+
"by",
|
|
7624
|
+
"at",
|
|
7625
|
+
"as",
|
|
7626
|
+
"on",
|
|
7627
|
+
"has",
|
|
7628
|
+
"have",
|
|
7629
|
+
"had",
|
|
7630
|
+
"do",
|
|
7631
|
+
"did",
|
|
7632
|
+
"does",
|
|
7633
|
+
"will",
|
|
7634
|
+
"would",
|
|
7635
|
+
"can",
|
|
7636
|
+
"could",
|
|
7637
|
+
"should",
|
|
7638
|
+
"may",
|
|
7639
|
+
"might",
|
|
7640
|
+
"shall",
|
|
7641
|
+
"from",
|
|
7642
|
+
"into",
|
|
7643
|
+
"then",
|
|
7644
|
+
"than",
|
|
7645
|
+
"so",
|
|
7646
|
+
"if",
|
|
7647
|
+
"up",
|
|
7648
|
+
"out",
|
|
7649
|
+
"about",
|
|
7650
|
+
"its",
|
|
7651
|
+
"my",
|
|
7652
|
+
"we",
|
|
7653
|
+
"i",
|
|
7654
|
+
"you"
|
|
7655
|
+
]);
|
|
7656
|
+
return new Set(text.toLowerCase().replace(/[^a-z0-9\s\-_]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w)));
|
|
7657
|
+
}
|
|
7658
|
+
function jaccardSimilarity(a, b) {
|
|
7659
|
+
if (a.size === 0 && b.size === 0)
|
|
7660
|
+
return 0;
|
|
7661
|
+
const intersection = new Set([...a].filter((x) => b.has(x)));
|
|
7662
|
+
const union = new Set([...a, ...b]);
|
|
7663
|
+
return intersection.size / union.size;
|
|
7664
|
+
}
|
|
7665
|
+
function isStale(memory) {
|
|
7666
|
+
if (memory.status !== "active")
|
|
7667
|
+
return false;
|
|
7668
|
+
if (memory.importance >= 7)
|
|
7669
|
+
return false;
|
|
7670
|
+
if (!memory.accessed_at)
|
|
7671
|
+
return true;
|
|
7672
|
+
const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
|
|
7673
|
+
return new Date(memory.accessed_at).getTime() < thirtyDaysAgo;
|
|
7674
|
+
}
|
|
7675
|
+
async function buildCorpus(options) {
|
|
7676
|
+
const d = options.db || getDatabase();
|
|
7677
|
+
const limit = options.limit ?? 500;
|
|
7678
|
+
const projectId = options.projectId ?? null;
|
|
7679
|
+
const memories = listMemories({
|
|
7680
|
+
status: "active",
|
|
7681
|
+
project_id: options.projectId,
|
|
7682
|
+
agent_id: options.agentId,
|
|
7683
|
+
limit
|
|
7684
|
+
}, d);
|
|
7685
|
+
const recallEvents = listSynthesisEvents({
|
|
7686
|
+
event_type: "recalled",
|
|
7687
|
+
project_id: options.projectId
|
|
7688
|
+
}, d);
|
|
7689
|
+
const recallCounts = new Map;
|
|
7690
|
+
const lastRecalledMap = new Map;
|
|
7691
|
+
for (const event of recallEvents) {
|
|
7692
|
+
if (!event.memory_id)
|
|
7693
|
+
continue;
|
|
7694
|
+
recallCounts.set(event.memory_id, (recallCounts.get(event.memory_id) ?? 0) + 1);
|
|
7695
|
+
const existing = lastRecalledMap.get(event.memory_id);
|
|
7696
|
+
if (!existing || event.created_at > existing) {
|
|
7697
|
+
lastRecalledMap.set(event.memory_id, event.created_at);
|
|
7698
|
+
}
|
|
7699
|
+
}
|
|
7700
|
+
const searchEvents = listSynthesisEvents({
|
|
7701
|
+
event_type: "searched",
|
|
7702
|
+
project_id: options.projectId
|
|
7703
|
+
}, d);
|
|
7704
|
+
const searchHits = new Map;
|
|
7705
|
+
for (const event of searchEvents) {
|
|
7706
|
+
if (!event.memory_id)
|
|
7707
|
+
continue;
|
|
7708
|
+
searchHits.set(event.memory_id, (searchHits.get(event.memory_id) ?? 0) + 1);
|
|
7709
|
+
}
|
|
7710
|
+
const termSets = new Map;
|
|
7711
|
+
for (const m of memories) {
|
|
7712
|
+
termSets.set(m.id, extractTerms(`${m.key} ${m.value} ${m.summary ?? ""}`));
|
|
7713
|
+
}
|
|
7714
|
+
const duplicateCandidates = [];
|
|
7715
|
+
const similarityThreshold = 0.5;
|
|
7716
|
+
const similarIds = new Map;
|
|
7717
|
+
for (let i = 0;i < memories.length; i++) {
|
|
7718
|
+
const a = memories[i];
|
|
7719
|
+
const termsA = termSets.get(a.id);
|
|
7720
|
+
const aSimIds = [];
|
|
7721
|
+
for (let j = i + 1;j < memories.length; j++) {
|
|
7722
|
+
const b = memories[j];
|
|
7723
|
+
const termsB = termSets.get(b.id);
|
|
7724
|
+
const sim = jaccardSimilarity(termsA, termsB);
|
|
7725
|
+
if (sim >= similarityThreshold) {
|
|
7726
|
+
duplicateCandidates.push({ a, b, similarity: sim });
|
|
7727
|
+
aSimIds.push(b.id);
|
|
7728
|
+
const bSimIds = similarIds.get(b.id) ?? [];
|
|
7729
|
+
bSimIds.push(a.id);
|
|
7730
|
+
similarIds.set(b.id, bSimIds);
|
|
7731
|
+
}
|
|
7732
|
+
}
|
|
7733
|
+
if (aSimIds.length > 0) {
|
|
7734
|
+
const existing = similarIds.get(a.id) ?? [];
|
|
7735
|
+
similarIds.set(a.id, [...existing, ...aSimIds]);
|
|
7736
|
+
}
|
|
7737
|
+
}
|
|
7738
|
+
duplicateCandidates.sort((a, b) => b.similarity - a.similarity);
|
|
7739
|
+
const items = memories.map((memory) => ({
|
|
7740
|
+
memory,
|
|
7741
|
+
recallCount: recallCounts.get(memory.id) ?? 0,
|
|
7742
|
+
lastRecalled: lastRecalledMap.get(memory.id) ?? null,
|
|
7743
|
+
searchHits: searchHits.get(memory.id) ?? 0,
|
|
7744
|
+
similarMemoryIds: similarIds.get(memory.id) ?? []
|
|
7745
|
+
}));
|
|
7746
|
+
const staleMemories = memories.filter(isStale);
|
|
7747
|
+
const lowImportanceHighRecall = memories.filter((m) => m.importance < 5 && (recallCounts.get(m.id) ?? 0) > 3);
|
|
7748
|
+
const highImportanceLowRecall = memories.filter((m) => m.importance > 7 && (recallCounts.get(m.id) ?? 0) === 0);
|
|
7749
|
+
return {
|
|
7750
|
+
projectId,
|
|
7751
|
+
totalMemories: memories.length,
|
|
7752
|
+
items,
|
|
7753
|
+
staleMemories,
|
|
7754
|
+
duplicateCandidates,
|
|
7755
|
+
lowImportanceHighRecall,
|
|
7756
|
+
highImportanceLowRecall,
|
|
7757
|
+
generatedAt: now()
|
|
7758
|
+
};
|
|
7759
|
+
}
|
|
7760
|
+
|
|
7761
|
+
// src/lib/synthesis/llm-analyzer.ts
|
|
7762
|
+
init_registry();
|
|
7763
|
+
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.";
|
|
7764
|
+
function buildCorpusPrompt(corpus, maxProposals) {
|
|
7765
|
+
const lines = [];
|
|
7766
|
+
lines.push(`## Memory Corpus Analysis`);
|
|
7767
|
+
lines.push(`Project: ${corpus.projectId ?? "(global)"}`);
|
|
7768
|
+
lines.push(`Total active memories: ${corpus.totalMemories}`);
|
|
7769
|
+
lines.push(`Analysis generated at: ${corpus.generatedAt}`);
|
|
7770
|
+
lines.push("");
|
|
7771
|
+
if (corpus.staleMemories.length > 0) {
|
|
7772
|
+
lines.push(`## Stale Memories (not accessed in 30+ days, importance < 7)`);
|
|
7773
|
+
lines.push(`Count: ${corpus.staleMemories.length}`);
|
|
7774
|
+
for (const m of corpus.staleMemories.slice(0, 30)) {
|
|
7775
|
+
const accessed = m.accessed_at ?? "never";
|
|
7776
|
+
lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} lastAccessed=${accessed}`);
|
|
7777
|
+
lines.push(` value: ${m.value.slice(0, 120)}`);
|
|
7778
|
+
}
|
|
7779
|
+
lines.push("");
|
|
7780
|
+
}
|
|
7781
|
+
if (corpus.duplicateCandidates.length > 0) {
|
|
7782
|
+
lines.push(`## Potential Duplicates (term overlap \u2265 50%)`);
|
|
7783
|
+
lines.push(`Count: ${corpus.duplicateCandidates.length} pairs`);
|
|
7784
|
+
for (const { a, b, similarity } of corpus.duplicateCandidates.slice(0, 20)) {
|
|
7785
|
+
lines.push(`- similarity=${similarity.toFixed(2)}`);
|
|
7786
|
+
lines.push(` A id:${a.id} key="${a.key}" importance=${a.importance}: ${a.value.slice(0, 80)}`);
|
|
7787
|
+
lines.push(` B id:${b.id} key="${b.key}" importance=${b.importance}: ${b.value.slice(0, 80)}`);
|
|
7788
|
+
}
|
|
7789
|
+
lines.push("");
|
|
7790
|
+
}
|
|
7791
|
+
if (corpus.lowImportanceHighRecall.length > 0) {
|
|
7792
|
+
lines.push(`## Low Importance But High Recall (candidates for importance promotion)`);
|
|
7793
|
+
for (const m of corpus.lowImportanceHighRecall.slice(0, 20)) {
|
|
7794
|
+
lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance} recall_count=${m.access_count}`);
|
|
7795
|
+
}
|
|
7796
|
+
lines.push("");
|
|
7797
|
+
}
|
|
7798
|
+
if (corpus.highImportanceLowRecall.length > 0) {
|
|
7799
|
+
lines.push(`## High Importance But Never Recalled (may need value update)`);
|
|
7800
|
+
for (const m of corpus.highImportanceLowRecall.slice(0, 20)) {
|
|
7801
|
+
lines.push(`- id:${m.id} key="${m.key}" importance=${m.importance}: ${m.value.slice(0, 80)}`);
|
|
7802
|
+
}
|
|
7803
|
+
lines.push("");
|
|
7804
|
+
}
|
|
7805
|
+
lines.push(`## Instructions`);
|
|
7806
|
+
lines.push(`Generate up to ${maxProposals} proposals as a JSON array. Each proposal must have:`);
|
|
7807
|
+
lines.push(` - type: "merge" | "archive" | "promote" | "update_value" | "add_tag" | "remove_duplicate"`);
|
|
7808
|
+
lines.push(` - memory_ids: string[] (IDs this proposal acts on)`);
|
|
7809
|
+
lines.push(` - target_memory_id: string (optional \u2014 used for merge/remove_duplicate)`);
|
|
7810
|
+
lines.push(` - proposed_changes: object (e.g. {new_importance:8} or {new_value:"..."} or {tags:["x"]})`);
|
|
7811
|
+
lines.push(` - reasoning: string (one sentence)`);
|
|
7812
|
+
lines.push(` - confidence: number 0.0-1.0`);
|
|
7813
|
+
lines.push("");
|
|
7814
|
+
lines.push(`Return ONLY the JSON array. No markdown, no explanation.`);
|
|
7815
|
+
return lines.join(`
|
|
7816
|
+
`);
|
|
7817
|
+
}
|
|
7818
|
+
async function analyzeCorpus(corpus, options) {
|
|
7819
|
+
const startMs = Date.now();
|
|
7820
|
+
const maxProposals = options?.maxProposals ?? 20;
|
|
7821
|
+
const empty = {
|
|
7822
|
+
proposals: [],
|
|
7823
|
+
summary: "No LLM provider available.",
|
|
7824
|
+
analysisDurationMs: 0
|
|
7825
|
+
};
|
|
7826
|
+
let provider = options?.provider ? providerRegistry.getProvider(options.provider) : providerRegistry.getAvailable();
|
|
7827
|
+
if (!provider) {
|
|
7828
|
+
return { ...empty, analysisDurationMs: Date.now() - startMs };
|
|
7829
|
+
}
|
|
7830
|
+
const userPrompt = buildCorpusPrompt(corpus, maxProposals);
|
|
7831
|
+
try {
|
|
7832
|
+
const rawResponse = await callProviderRaw(provider, SYNTHESIS_SYSTEM_PROMPT, userPrompt);
|
|
7833
|
+
if (!rawResponse) {
|
|
7834
|
+
return { ...empty, analysisDurationMs: Date.now() - startMs };
|
|
7835
|
+
}
|
|
7836
|
+
const parsed = parseProposalsResponse(rawResponse);
|
|
7837
|
+
const analysisDurationMs = Date.now() - startMs;
|
|
7838
|
+
const validProposals = parsed.slice(0, maxProposals);
|
|
7839
|
+
return {
|
|
7840
|
+
proposals: validProposals,
|
|
7841
|
+
summary: buildSummary(corpus, validProposals.length),
|
|
7842
|
+
analysisDurationMs
|
|
7843
|
+
};
|
|
7844
|
+
} catch {
|
|
7845
|
+
return { ...empty, analysisDurationMs: Date.now() - startMs };
|
|
7846
|
+
}
|
|
7847
|
+
}
|
|
7848
|
+
async function callProviderRaw(provider, systemPrompt, userPrompt) {
|
|
7849
|
+
if (!provider)
|
|
7850
|
+
return null;
|
|
7851
|
+
const { config, name } = provider;
|
|
7852
|
+
if (!config.apiKey)
|
|
7853
|
+
return null;
|
|
7854
|
+
const timeoutMs = config.timeoutMs ?? 30000;
|
|
7855
|
+
try {
|
|
7856
|
+
if (name === "anthropic") {
|
|
7857
|
+
return await callAnthropic(config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
|
|
7858
|
+
} else if (name === "openai" || name === "cerebras" || name === "grok") {
|
|
7859
|
+
return await callOpenAICompat(name, config.apiKey, config.model, systemPrompt, userPrompt, timeoutMs);
|
|
7860
|
+
}
|
|
7861
|
+
} catch {}
|
|
7862
|
+
return null;
|
|
7863
|
+
}
|
|
7864
|
+
async function callAnthropic(apiKey, model, systemPrompt, userPrompt, timeoutMs) {
|
|
7865
|
+
const response = await fetch("https://api.anthropic.com/v1/messages", {
|
|
7866
|
+
method: "POST",
|
|
7867
|
+
headers: {
|
|
7868
|
+
"x-api-key": apiKey,
|
|
7869
|
+
"anthropic-version": "2023-06-01",
|
|
7870
|
+
"content-type": "application/json"
|
|
7871
|
+
},
|
|
7872
|
+
body: JSON.stringify({
|
|
7873
|
+
model,
|
|
7874
|
+
max_tokens: 2048,
|
|
7875
|
+
system: systemPrompt,
|
|
7876
|
+
messages: [{ role: "user", content: userPrompt }]
|
|
7877
|
+
}),
|
|
7878
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
7879
|
+
});
|
|
7880
|
+
if (!response.ok)
|
|
7881
|
+
return null;
|
|
7882
|
+
const data = await response.json();
|
|
7883
|
+
return data.content?.[0]?.text ?? null;
|
|
7884
|
+
}
|
|
7885
|
+
function getBaseUrlForProvider(providerName) {
|
|
7886
|
+
switch (providerName) {
|
|
7887
|
+
case "openai":
|
|
7888
|
+
return "https://api.openai.com/v1";
|
|
7889
|
+
case "cerebras":
|
|
7890
|
+
return "https://api.cerebras.ai/v1";
|
|
7891
|
+
case "grok":
|
|
7892
|
+
return "https://api.x.ai/v1";
|
|
7893
|
+
default:
|
|
7894
|
+
return "https://api.openai.com/v1";
|
|
7895
|
+
}
|
|
7896
|
+
}
|
|
7897
|
+
async function callOpenAICompat(providerName, apiKey, model, systemPrompt, userPrompt, timeoutMs) {
|
|
7898
|
+
const baseUrl = getBaseUrlForProvider(providerName);
|
|
7899
|
+
const response = await fetch(`${baseUrl}/chat/completions`, {
|
|
7900
|
+
method: "POST",
|
|
7901
|
+
headers: {
|
|
7902
|
+
authorization: `Bearer ${apiKey}`,
|
|
7903
|
+
"content-type": "application/json"
|
|
7904
|
+
},
|
|
7905
|
+
body: JSON.stringify({
|
|
7906
|
+
model,
|
|
7907
|
+
max_tokens: 2048,
|
|
7908
|
+
temperature: 0,
|
|
7909
|
+
messages: [
|
|
7910
|
+
{ role: "system", content: systemPrompt },
|
|
7911
|
+
{ role: "user", content: userPrompt }
|
|
7912
|
+
]
|
|
7913
|
+
}),
|
|
7914
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
7915
|
+
});
|
|
7916
|
+
if (!response.ok)
|
|
7917
|
+
return null;
|
|
7918
|
+
const data = await response.json();
|
|
7919
|
+
return data.choices?.[0]?.message?.content ?? null;
|
|
7920
|
+
}
|
|
7921
|
+
function parseProposalsResponse(raw) {
|
|
7922
|
+
try {
|
|
7923
|
+
const cleaned = raw.replace(/^```(?:json)?\s*/m, "").replace(/\s*```$/m, "").trim();
|
|
7924
|
+
const parsed = JSON.parse(cleaned);
|
|
7925
|
+
if (!Array.isArray(parsed))
|
|
7926
|
+
return [];
|
|
7927
|
+
const validTypes = new Set([
|
|
7928
|
+
"merge",
|
|
7929
|
+
"archive",
|
|
7930
|
+
"promote",
|
|
7931
|
+
"update_value",
|
|
7932
|
+
"add_tag",
|
|
7933
|
+
"remove_duplicate"
|
|
7934
|
+
]);
|
|
7935
|
+
return parsed.filter((item) => {
|
|
7936
|
+
if (!item || typeof item !== "object")
|
|
7937
|
+
return false;
|
|
7938
|
+
const p = item;
|
|
7939
|
+
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";
|
|
7940
|
+
}).map((p) => ({
|
|
7941
|
+
type: p.type,
|
|
7942
|
+
memory_ids: p.memory_ids.filter((id) => typeof id === "string"),
|
|
7943
|
+
target_memory_id: typeof p.target_memory_id === "string" ? p.target_memory_id : undefined,
|
|
7944
|
+
proposed_changes: p.proposed_changes ?? {},
|
|
7945
|
+
reasoning: p.reasoning,
|
|
7946
|
+
confidence: Math.max(0, Math.min(1, p.confidence))
|
|
7947
|
+
}));
|
|
7948
|
+
} catch {
|
|
7949
|
+
return [];
|
|
7950
|
+
}
|
|
7951
|
+
}
|
|
7952
|
+
function buildSummary(corpus, proposalCount) {
|
|
7953
|
+
return `Analyzed ${corpus.totalMemories} memories. ` + `Found ${corpus.staleMemories.length} stale, ` + `${corpus.duplicateCandidates.length} duplicate pairs. ` + `Generated ${proposalCount} proposals.`;
|
|
7954
|
+
}
|
|
7955
|
+
|
|
7956
|
+
// src/lib/synthesis/validator.ts
|
|
7957
|
+
var DEFAULT_SAFETY_CONFIG = {
|
|
7958
|
+
maxArchivePercent: 20,
|
|
7959
|
+
maxMergePercent: 30,
|
|
7960
|
+
minConfidence: 0.6,
|
|
7961
|
+
protectPinned: true,
|
|
7962
|
+
protectHighImportance: 9
|
|
7963
|
+
};
|
|
7964
|
+
function validateProposals(proposals, corpus, config) {
|
|
7965
|
+
const cfg = { ...DEFAULT_SAFETY_CONFIG, ...config };
|
|
7966
|
+
const memoryMap = new Map(corpus.items.map((item) => [item.memory.id, item.memory]));
|
|
7967
|
+
const rejectedProposals = [];
|
|
7968
|
+
const warnings = [];
|
|
7969
|
+
let archiveCount = 0;
|
|
7970
|
+
let mergeCount = 0;
|
|
7971
|
+
for (const proposal of proposals) {
|
|
7972
|
+
if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
|
|
7973
|
+
archiveCount++;
|
|
7974
|
+
}
|
|
7975
|
+
if (proposal.type === "merge") {
|
|
7976
|
+
mergeCount++;
|
|
7977
|
+
}
|
|
7978
|
+
}
|
|
7979
|
+
const corpusSize = corpus.totalMemories;
|
|
7980
|
+
const archivePercent = corpusSize > 0 ? archiveCount / corpusSize * 100 : 0;
|
|
7981
|
+
const mergePercent = corpusSize > 0 ? mergeCount / corpusSize * 100 : 0;
|
|
7982
|
+
if (archivePercent > cfg.maxArchivePercent) {
|
|
7983
|
+
warnings.push(`Archive proposals (${archiveCount}) exceed ${cfg.maxArchivePercent}% of corpus (${archivePercent.toFixed(1)}%). Some will be rejected.`);
|
|
7984
|
+
}
|
|
7985
|
+
if (mergePercent > cfg.maxMergePercent) {
|
|
7986
|
+
warnings.push(`Merge proposals (${mergeCount}) exceed ${cfg.maxMergePercent}% of corpus (${mergePercent.toFixed(1)}%). Some will be rejected.`);
|
|
7987
|
+
}
|
|
7988
|
+
let remainingArchiveSlots = Math.floor(cfg.maxArchivePercent / 100 * corpusSize);
|
|
7989
|
+
let remainingMergeSlots = Math.floor(cfg.maxMergePercent / 100 * corpusSize);
|
|
7990
|
+
for (let i = 0;i < proposals.length; i++) {
|
|
7991
|
+
const proposal = proposals[i];
|
|
7992
|
+
const proposalRef = `proposal[${i}]`;
|
|
7993
|
+
if (proposal.confidence < cfg.minConfidence) {
|
|
7994
|
+
rejectedProposals.push({
|
|
7995
|
+
proposalId: proposalRef,
|
|
7996
|
+
reason: `Confidence ${proposal.confidence.toFixed(2)} below minimum ${cfg.minConfidence}`
|
|
7997
|
+
});
|
|
7998
|
+
continue;
|
|
7999
|
+
}
|
|
8000
|
+
const missingIds = proposal.memory_ids.filter((id) => !memoryMap.has(id));
|
|
8001
|
+
if (missingIds.length > 0) {
|
|
8002
|
+
rejectedProposals.push({
|
|
8003
|
+
proposalId: proposalRef,
|
|
8004
|
+
reason: `References unknown memory IDs: ${missingIds.join(", ")}`
|
|
8005
|
+
});
|
|
8006
|
+
continue;
|
|
8007
|
+
}
|
|
8008
|
+
if (cfg.protectPinned) {
|
|
8009
|
+
const pinnedIds = proposal.memory_ids.filter((id) => {
|
|
8010
|
+
const m = memoryMap.get(id);
|
|
8011
|
+
return m?.pinned === true;
|
|
8012
|
+
});
|
|
8013
|
+
if (pinnedIds.length > 0) {
|
|
8014
|
+
rejectedProposals.push({
|
|
8015
|
+
proposalId: proposalRef,
|
|
8016
|
+
reason: `Attempts to modify pinned memories: ${pinnedIds.join(", ")}`
|
|
8017
|
+
});
|
|
8018
|
+
continue;
|
|
8019
|
+
}
|
|
8020
|
+
}
|
|
8021
|
+
if (proposal.type === "archive" || proposal.type === "remove_duplicate" || proposal.type === "merge") {
|
|
8022
|
+
const highImportanceIds = proposal.memory_ids.filter((id) => {
|
|
8023
|
+
const m = memoryMap.get(id);
|
|
8024
|
+
return m && m.importance >= cfg.protectHighImportance;
|
|
8025
|
+
});
|
|
8026
|
+
if (highImportanceIds.length > 0) {
|
|
8027
|
+
rejectedProposals.push({
|
|
8028
|
+
proposalId: proposalRef,
|
|
8029
|
+
reason: `Attempts to archive/merge memories with importance \u2265 ${cfg.protectHighImportance}: ${highImportanceIds.join(", ")}`
|
|
8030
|
+
});
|
|
8031
|
+
continue;
|
|
8032
|
+
}
|
|
8033
|
+
}
|
|
8034
|
+
if (proposal.type === "archive" || proposal.type === "remove_duplicate") {
|
|
8035
|
+
if (remainingArchiveSlots <= 0) {
|
|
8036
|
+
rejectedProposals.push({
|
|
8037
|
+
proposalId: proposalRef,
|
|
8038
|
+
reason: `Archive quota exhausted (max ${cfg.maxArchivePercent}% of corpus)`
|
|
8039
|
+
});
|
|
8040
|
+
continue;
|
|
8041
|
+
}
|
|
8042
|
+
remainingArchiveSlots--;
|
|
8043
|
+
}
|
|
8044
|
+
if (proposal.type === "merge") {
|
|
8045
|
+
if (remainingMergeSlots <= 0) {
|
|
8046
|
+
rejectedProposals.push({
|
|
8047
|
+
proposalId: proposalRef,
|
|
8048
|
+
reason: `Merge quota exhausted (max ${cfg.maxMergePercent}% of corpus)`
|
|
8049
|
+
});
|
|
8050
|
+
continue;
|
|
8051
|
+
}
|
|
8052
|
+
remainingMergeSlots--;
|
|
8053
|
+
}
|
|
8054
|
+
if (proposal.target_memory_id && !memoryMap.has(proposal.target_memory_id)) {
|
|
8055
|
+
rejectedProposals.push({
|
|
8056
|
+
proposalId: proposalRef,
|
|
8057
|
+
reason: `target_memory_id "${proposal.target_memory_id}" does not exist in corpus`
|
|
8058
|
+
});
|
|
8059
|
+
continue;
|
|
8060
|
+
}
|
|
8061
|
+
}
|
|
8062
|
+
return {
|
|
8063
|
+
valid: rejectedProposals.length === 0,
|
|
8064
|
+
rejectedProposals,
|
|
8065
|
+
warnings
|
|
8066
|
+
};
|
|
8067
|
+
}
|
|
8068
|
+
|
|
8069
|
+
// src/lib/synthesis/executor.ts
|
|
8070
|
+
init_database();
|
|
8071
|
+
init_memories();
|
|
8072
|
+
init_synthesis();
|
|
8073
|
+
async function executeProposals(runId, proposals, db) {
|
|
8074
|
+
const d = db || getDatabase();
|
|
8075
|
+
let executed = 0;
|
|
8076
|
+
let failed = 0;
|
|
8077
|
+
const rollbackData = {};
|
|
8078
|
+
for (const proposal of proposals) {
|
|
8079
|
+
try {
|
|
8080
|
+
const rollback = executeProposal(proposal, d);
|
|
8081
|
+
updateProposal(proposal.id, {
|
|
8082
|
+
status: "accepted",
|
|
8083
|
+
executed_at: now(),
|
|
8084
|
+
rollback_data: rollback
|
|
8085
|
+
}, d);
|
|
8086
|
+
rollbackData[proposal.id] = rollback;
|
|
8087
|
+
executed++;
|
|
8088
|
+
} catch (err) {
|
|
8089
|
+
try {
|
|
8090
|
+
updateProposal(proposal.id, { status: "rejected" }, d);
|
|
8091
|
+
} catch {}
|
|
8092
|
+
failed++;
|
|
8093
|
+
}
|
|
8094
|
+
}
|
|
8095
|
+
return { runId, executed, failed, rollbackData };
|
|
8096
|
+
}
|
|
8097
|
+
function executeProposal(proposal, d) {
|
|
8098
|
+
let rollbackData = {};
|
|
8099
|
+
d.transaction(() => {
|
|
8100
|
+
switch (proposal.proposal_type) {
|
|
8101
|
+
case "archive":
|
|
8102
|
+
rollbackData = executeArchive(proposal, d);
|
|
8103
|
+
break;
|
|
8104
|
+
case "promote":
|
|
8105
|
+
rollbackData = executePromote(proposal, d);
|
|
8106
|
+
break;
|
|
8107
|
+
case "update_value":
|
|
8108
|
+
rollbackData = executeUpdateValue(proposal, d);
|
|
8109
|
+
break;
|
|
8110
|
+
case "add_tag":
|
|
8111
|
+
rollbackData = executeAddTag(proposal, d);
|
|
8112
|
+
break;
|
|
8113
|
+
case "merge":
|
|
8114
|
+
rollbackData = executeMerge(proposal, d);
|
|
8115
|
+
break;
|
|
8116
|
+
case "remove_duplicate":
|
|
8117
|
+
rollbackData = executeRemoveDuplicate(proposal, d);
|
|
8118
|
+
break;
|
|
8119
|
+
default:
|
|
8120
|
+
throw new Error(`Unknown proposal type: ${proposal.proposal_type}`);
|
|
8121
|
+
}
|
|
8122
|
+
})();
|
|
8123
|
+
return rollbackData;
|
|
8124
|
+
}
|
|
8125
|
+
function executeArchive(proposal, d) {
|
|
8126
|
+
const rollback = {};
|
|
8127
|
+
for (const memId of proposal.memory_ids) {
|
|
8128
|
+
const mem = getMemory(memId, d);
|
|
8129
|
+
if (!mem)
|
|
8130
|
+
continue;
|
|
8131
|
+
rollback[memId] = mem.status;
|
|
8132
|
+
d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
|
|
8133
|
+
}
|
|
8134
|
+
return { old_status: rollback };
|
|
8135
|
+
}
|
|
8136
|
+
function executePromote(proposal, d) {
|
|
8137
|
+
const newImportance = proposal.proposed_changes["new_importance"];
|
|
8138
|
+
if (typeof newImportance !== "number") {
|
|
8139
|
+
throw new Error("promote proposal missing new_importance in proposed_changes");
|
|
8140
|
+
}
|
|
8141
|
+
const rollback = {};
|
|
8142
|
+
for (const memId of proposal.memory_ids) {
|
|
8143
|
+
const mem = getMemory(memId, d);
|
|
8144
|
+
if (!mem)
|
|
8145
|
+
continue;
|
|
8146
|
+
rollback[memId] = mem.importance;
|
|
8147
|
+
d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [Math.max(1, Math.min(10, Math.round(newImportance))), now(), memId]);
|
|
8148
|
+
}
|
|
8149
|
+
return { old_importance: rollback };
|
|
8150
|
+
}
|
|
8151
|
+
function executeUpdateValue(proposal, d) {
|
|
8152
|
+
const newValue = proposal.proposed_changes["new_value"];
|
|
8153
|
+
if (typeof newValue !== "string") {
|
|
8154
|
+
throw new Error("update_value proposal missing new_value in proposed_changes");
|
|
8155
|
+
}
|
|
8156
|
+
const rollback = {};
|
|
8157
|
+
const memId = proposal.memory_ids[0];
|
|
8158
|
+
if (!memId)
|
|
8159
|
+
throw new Error("update_value proposal has no memory_ids");
|
|
8160
|
+
const mem = getMemory(memId, d);
|
|
8161
|
+
if (!mem)
|
|
8162
|
+
throw new Error(`Memory ${memId} not found`);
|
|
8163
|
+
rollback[memId] = { value: mem.value, version: mem.version };
|
|
8164
|
+
d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [newValue, now(), memId]);
|
|
8165
|
+
return { old_state: rollback };
|
|
8166
|
+
}
|
|
8167
|
+
function executeAddTag(proposal, d) {
|
|
8168
|
+
const tagsToAdd = proposal.proposed_changes["tags"];
|
|
8169
|
+
if (!Array.isArray(tagsToAdd)) {
|
|
8170
|
+
throw new Error("add_tag proposal missing tags array in proposed_changes");
|
|
8171
|
+
}
|
|
8172
|
+
const rollback = {};
|
|
8173
|
+
for (const memId of proposal.memory_ids) {
|
|
8174
|
+
const mem = getMemory(memId, d);
|
|
8175
|
+
if (!mem)
|
|
8176
|
+
continue;
|
|
8177
|
+
rollback[memId] = [...mem.tags];
|
|
8178
|
+
const newTags = Array.from(new Set([...mem.tags, ...tagsToAdd]));
|
|
8179
|
+
d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(newTags), now(), memId]);
|
|
8180
|
+
const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
|
|
8181
|
+
for (const tag of tagsToAdd) {
|
|
8182
|
+
insertTag.run(memId, tag);
|
|
8183
|
+
}
|
|
8184
|
+
}
|
|
8185
|
+
return { old_tags: rollback };
|
|
8186
|
+
}
|
|
8187
|
+
function executeMerge(proposal, d) {
|
|
8188
|
+
const targetId = proposal.target_memory_id;
|
|
8189
|
+
if (!targetId)
|
|
8190
|
+
throw new Error("merge proposal missing target_memory_id");
|
|
8191
|
+
const target = getMemory(targetId, d);
|
|
8192
|
+
if (!target)
|
|
8193
|
+
throw new Error(`Target memory ${targetId} not found`);
|
|
8194
|
+
const rollback = {
|
|
8195
|
+
target_old_value: target.value,
|
|
8196
|
+
target_old_version: target.version,
|
|
8197
|
+
archived_memories: {}
|
|
8198
|
+
};
|
|
8199
|
+
const sourceValues = [];
|
|
8200
|
+
for (const memId of proposal.memory_ids) {
|
|
8201
|
+
if (memId === targetId)
|
|
8202
|
+
continue;
|
|
8203
|
+
const mem = getMemory(memId, d);
|
|
8204
|
+
if (!mem)
|
|
8205
|
+
continue;
|
|
8206
|
+
sourceValues.push(mem.value);
|
|
8207
|
+
rollback.archived_memories[memId] = mem.status;
|
|
8208
|
+
}
|
|
8209
|
+
const mergedValue = proposal.proposed_changes["merged_value"] ?? [target.value, ...sourceValues].join(`
|
|
8210
|
+
---
|
|
8211
|
+
`);
|
|
8212
|
+
d.run("UPDATE memories SET value = ?, version = version + 1, updated_at = ? WHERE id = ?", [mergedValue, now(), targetId]);
|
|
8213
|
+
for (const memId of proposal.memory_ids) {
|
|
8214
|
+
if (memId === targetId)
|
|
8215
|
+
continue;
|
|
8216
|
+
d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), memId]);
|
|
8217
|
+
}
|
|
8218
|
+
return rollback;
|
|
8219
|
+
}
|
|
8220
|
+
function executeRemoveDuplicate(proposal, d) {
|
|
8221
|
+
const memories = proposal.memory_ids.map((id) => getMemory(id, d)).filter((m) => m !== null);
|
|
8222
|
+
if (memories.length < 2) {
|
|
8223
|
+
throw new Error("remove_duplicate requires at least 2 memories");
|
|
8224
|
+
}
|
|
8225
|
+
memories.sort((a, b) => b.importance - a.importance || a.created_at.localeCompare(b.created_at));
|
|
8226
|
+
const keepId = proposal.target_memory_id ?? memories[0].id;
|
|
8227
|
+
const rollback = {};
|
|
8228
|
+
for (const mem of memories) {
|
|
8229
|
+
if (mem.id === keepId)
|
|
8230
|
+
continue;
|
|
8231
|
+
rollback[mem.id] = mem.status;
|
|
8232
|
+
d.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", [now(), mem.id]);
|
|
8233
|
+
}
|
|
8234
|
+
return { old_status: rollback, kept_id: keepId };
|
|
8235
|
+
}
|
|
8236
|
+
async function rollbackRun(runId, db) {
|
|
8237
|
+
const d = db || getDatabase();
|
|
8238
|
+
const proposals = listProposals(runId, { status: "accepted" }, d);
|
|
8239
|
+
let rolledBack = 0;
|
|
8240
|
+
const errors2 = [];
|
|
8241
|
+
for (const proposal of proposals) {
|
|
8242
|
+
try {
|
|
8243
|
+
rollbackProposal(proposal, d);
|
|
8244
|
+
updateProposal(proposal.id, { status: "rolled_back" }, d);
|
|
8245
|
+
rolledBack++;
|
|
8246
|
+
} catch (err) {
|
|
8247
|
+
errors2.push(`Proposal ${proposal.id} (${proposal.proposal_type}): ${err instanceof Error ? err.message : String(err)}`);
|
|
8248
|
+
}
|
|
8249
|
+
}
|
|
8250
|
+
return { rolled_back: rolledBack, errors: errors2 };
|
|
8251
|
+
}
|
|
8252
|
+
function rollbackProposal(proposal, d) {
|
|
8253
|
+
const rb = proposal.rollback_data;
|
|
8254
|
+
if (!rb)
|
|
8255
|
+
return;
|
|
8256
|
+
d.transaction(() => {
|
|
8257
|
+
switch (proposal.proposal_type) {
|
|
8258
|
+
case "archive":
|
|
8259
|
+
case "remove_duplicate": {
|
|
8260
|
+
const oldStatus = rb["old_status"];
|
|
8261
|
+
if (!oldStatus)
|
|
8262
|
+
break;
|
|
8263
|
+
for (const [memId, status] of Object.entries(oldStatus)) {
|
|
8264
|
+
d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
|
|
8265
|
+
}
|
|
8266
|
+
break;
|
|
8267
|
+
}
|
|
8268
|
+
case "promote": {
|
|
8269
|
+
const oldImportance = rb["old_importance"];
|
|
8270
|
+
if (!oldImportance)
|
|
8271
|
+
break;
|
|
8272
|
+
for (const [memId, importance] of Object.entries(oldImportance)) {
|
|
8273
|
+
d.run("UPDATE memories SET importance = ?, updated_at = ? WHERE id = ?", [importance, now(), memId]);
|
|
8274
|
+
}
|
|
8275
|
+
break;
|
|
8276
|
+
}
|
|
8277
|
+
case "update_value": {
|
|
8278
|
+
const oldState = rb["old_state"];
|
|
8279
|
+
if (!oldState)
|
|
8280
|
+
break;
|
|
8281
|
+
for (const [memId, state] of Object.entries(oldState)) {
|
|
8282
|
+
d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [state.value, state.version, now(), memId]);
|
|
8283
|
+
}
|
|
8284
|
+
break;
|
|
8285
|
+
}
|
|
8286
|
+
case "add_tag": {
|
|
8287
|
+
const oldTags = rb["old_tags"];
|
|
8288
|
+
if (!oldTags)
|
|
8289
|
+
break;
|
|
8290
|
+
for (const [memId, tags] of Object.entries(oldTags)) {
|
|
8291
|
+
d.run("UPDATE memories SET tags = ?, updated_at = ? WHERE id = ?", [JSON.stringify(tags), now(), memId]);
|
|
8292
|
+
d.run("DELETE FROM memory_tags WHERE memory_id = ?", [memId]);
|
|
8293
|
+
const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
|
|
8294
|
+
for (const tag of tags) {
|
|
8295
|
+
insertTag.run(memId, tag);
|
|
8296
|
+
}
|
|
8297
|
+
}
|
|
8298
|
+
break;
|
|
8299
|
+
}
|
|
8300
|
+
case "merge": {
|
|
8301
|
+
const targetOldValue = rb["target_old_value"];
|
|
8302
|
+
const targetOldVersion = rb["target_old_version"];
|
|
8303
|
+
const archivedMemories = rb["archived_memories"];
|
|
8304
|
+
const targetId = proposal.target_memory_id;
|
|
8305
|
+
if (targetId && targetOldValue !== undefined && targetOldVersion !== undefined) {
|
|
8306
|
+
d.run("UPDATE memories SET value = ?, version = ?, updated_at = ? WHERE id = ?", [targetOldValue, targetOldVersion, now(), targetId]);
|
|
8307
|
+
}
|
|
8308
|
+
if (archivedMemories) {
|
|
8309
|
+
for (const [memId, status] of Object.entries(archivedMemories)) {
|
|
8310
|
+
d.run("UPDATE memories SET status = ?, updated_at = ? WHERE id = ?", [status, now(), memId]);
|
|
8311
|
+
}
|
|
8312
|
+
}
|
|
8313
|
+
break;
|
|
8314
|
+
}
|
|
8315
|
+
default:
|
|
8316
|
+
break;
|
|
8317
|
+
}
|
|
8318
|
+
})();
|
|
8319
|
+
}
|
|
8320
|
+
|
|
8321
|
+
// src/lib/synthesis/metrics.ts
|
|
8322
|
+
init_database();
|
|
8323
|
+
init_synthesis();
|
|
8324
|
+
init_memories();
|
|
8325
|
+
async function measureEffectiveness(runId, preCorpus, db) {
|
|
8326
|
+
const d = db || getDatabase();
|
|
8327
|
+
const postMemories = listMemories({
|
|
8328
|
+
status: "active",
|
|
8329
|
+
project_id: preCorpus.projectId ?? undefined
|
|
8330
|
+
}, d);
|
|
8331
|
+
const postCount = postMemories.length;
|
|
8332
|
+
const preCount = preCorpus.totalMemories;
|
|
8333
|
+
const corpusReduction = preCount > 0 ? (preCount - postCount) / preCount * 100 : 0;
|
|
8334
|
+
const preAvgImportance = preCorpus.items.length > 0 ? preCorpus.items.reduce((sum, i) => sum + i.memory.importance, 0) / preCorpus.items.length : 0;
|
|
8335
|
+
const postAvgImportance = postMemories.length > 0 ? postMemories.reduce((sum, m) => sum + m.importance, 0) / postMemories.length : 0;
|
|
8336
|
+
const importanceDrift = postAvgImportance - preAvgImportance;
|
|
8337
|
+
const preDuplicatePairs = preCorpus.duplicateCandidates.length;
|
|
8338
|
+
const acceptedProposals = listProposals(runId, { status: "accepted" }, d);
|
|
8339
|
+
const deduplicationProposals = acceptedProposals.filter((p) => p.proposal_type === "remove_duplicate" || p.proposal_type === "merge");
|
|
8340
|
+
const deduplicationRate = preDuplicatePairs > 0 ? deduplicationProposals.length / preDuplicatePairs * 100 : 0;
|
|
8341
|
+
const recallWeight = {
|
|
8342
|
+
corpusReduction: 0.3,
|
|
8343
|
+
importanceDrift: 0.4,
|
|
8344
|
+
deduplicationRate: 0.3
|
|
8345
|
+
};
|
|
8346
|
+
const estimatedRecallImprovement = Math.max(0, Math.min(100, corpusReduction * recallWeight.corpusReduction + Math.max(0, importanceDrift * 10) * recallWeight.importanceDrift + deduplicationRate * recallWeight.deduplicationRate));
|
|
8347
|
+
const metricDefs = [
|
|
8348
|
+
{ metric_type: "corpus_reduction_pct", value: corpusReduction, baseline: 0 },
|
|
8349
|
+
{ metric_type: "importance_drift", value: importanceDrift, baseline: 0 },
|
|
8350
|
+
{ metric_type: "deduplication_rate_pct", value: deduplicationRate, baseline: 0 },
|
|
8351
|
+
{ metric_type: "estimated_recall_improvement_pct", value: estimatedRecallImprovement, baseline: 0 },
|
|
8352
|
+
{ metric_type: "pre_corpus_size", value: preCount, baseline: preCount },
|
|
8353
|
+
{ metric_type: "post_corpus_size", value: postCount, baseline: preCount },
|
|
8354
|
+
{ metric_type: "proposals_accepted", value: acceptedProposals.length, baseline: 0 },
|
|
8355
|
+
{ metric_type: "pre_avg_importance", value: preAvgImportance, baseline: preAvgImportance },
|
|
8356
|
+
{ metric_type: "post_avg_importance", value: postAvgImportance, baseline: preAvgImportance }
|
|
8357
|
+
];
|
|
8358
|
+
for (const def of metricDefs) {
|
|
8359
|
+
createMetric({
|
|
8360
|
+
run_id: runId,
|
|
8361
|
+
metric_type: def.metric_type,
|
|
8362
|
+
value: def.value,
|
|
8363
|
+
baseline: def.baseline ?? null
|
|
8364
|
+
}, d);
|
|
8365
|
+
}
|
|
8366
|
+
const metrics = listMetrics(runId, d);
|
|
8367
|
+
return {
|
|
8368
|
+
runId,
|
|
8369
|
+
corpusReduction,
|
|
8370
|
+
importanceDrift,
|
|
8371
|
+
deduplicationRate,
|
|
8372
|
+
estimatedRecallImprovement,
|
|
8373
|
+
metrics
|
|
8374
|
+
};
|
|
8375
|
+
}
|
|
8376
|
+
|
|
8377
|
+
// src/lib/synthesis/index.ts
|
|
8378
|
+
async function runSynthesis(options = {}) {
|
|
8379
|
+
const d = options.db || getDatabase();
|
|
8380
|
+
const projectId = options.projectId ?? null;
|
|
8381
|
+
const agentId = options.agentId ?? null;
|
|
8382
|
+
const dryRun = options.dryRun ?? false;
|
|
8383
|
+
const run = createSynthesisRun({
|
|
8384
|
+
triggered_by: "manual",
|
|
8385
|
+
project_id: projectId,
|
|
8386
|
+
agent_id: agentId
|
|
8387
|
+
}, d);
|
|
8388
|
+
updateSynthesisRun(run.id, { status: "running" }, d);
|
|
8389
|
+
try {
|
|
8390
|
+
const corpus = await buildCorpus({
|
|
8391
|
+
projectId: projectId ?? undefined,
|
|
8392
|
+
agentId: agentId ?? undefined,
|
|
8393
|
+
db: d
|
|
8394
|
+
});
|
|
8395
|
+
updateSynthesisRun(run.id, { corpus_size: corpus.totalMemories }, d);
|
|
8396
|
+
const analysisResult = await analyzeCorpus(corpus, {
|
|
8397
|
+
provider: options.provider,
|
|
8398
|
+
maxProposals: options.maxProposals ?? 20
|
|
8399
|
+
});
|
|
8400
|
+
const validation = validateProposals(analysisResult.proposals, corpus, options.safetyConfig);
|
|
8401
|
+
const rejectedIndices = new Set(validation.rejectedProposals.map((r) => {
|
|
8402
|
+
const match = r.proposalId.match(/\[(\d+)\]/);
|
|
8403
|
+
return match ? parseInt(match[1], 10) : -1;
|
|
8404
|
+
}));
|
|
8405
|
+
const validProposals = analysisResult.proposals.filter((_, idx) => !rejectedIndices.has(idx));
|
|
8406
|
+
const savedProposals = [];
|
|
8407
|
+
for (const p of validProposals) {
|
|
8408
|
+
const saved = createProposal({
|
|
8409
|
+
run_id: run.id,
|
|
8410
|
+
proposal_type: p.type,
|
|
8411
|
+
memory_ids: p.memory_ids,
|
|
8412
|
+
target_memory_id: p.target_memory_id ?? null,
|
|
8413
|
+
proposed_changes: p.proposed_changes,
|
|
8414
|
+
reasoning: p.reasoning,
|
|
8415
|
+
confidence: p.confidence
|
|
8416
|
+
}, d);
|
|
8417
|
+
savedProposals.push(saved);
|
|
8418
|
+
}
|
|
8419
|
+
updateSynthesisRun(run.id, {
|
|
8420
|
+
proposals_generated: analysisResult.proposals.length,
|
|
8421
|
+
proposals_rejected: validation.rejectedProposals.length
|
|
8422
|
+
}, d);
|
|
8423
|
+
let executedCount = 0;
|
|
8424
|
+
if (!dryRun && savedProposals.length > 0) {
|
|
8425
|
+
const execResult = await executeProposals(run.id, savedProposals, d);
|
|
8426
|
+
executedCount = execResult.executed;
|
|
8427
|
+
updateSynthesisRun(run.id, {
|
|
8428
|
+
proposals_accepted: execResult.executed,
|
|
8429
|
+
proposals_rejected: validation.rejectedProposals.length + execResult.failed,
|
|
8430
|
+
status: "completed",
|
|
8431
|
+
completed_at: now()
|
|
8432
|
+
}, d);
|
|
8433
|
+
} else {
|
|
8434
|
+
updateSynthesisRun(run.id, {
|
|
8435
|
+
status: "completed",
|
|
8436
|
+
completed_at: now()
|
|
8437
|
+
}, d);
|
|
8438
|
+
}
|
|
8439
|
+
let effectivenessReport = null;
|
|
8440
|
+
if (!dryRun && executedCount > 0) {
|
|
8441
|
+
try {
|
|
8442
|
+
effectivenessReport = await measureEffectiveness(run.id, corpus, d);
|
|
8443
|
+
} catch {}
|
|
8444
|
+
}
|
|
8445
|
+
const finalRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
|
|
8446
|
+
const finalProposals = listProposals(run.id, undefined, d);
|
|
8447
|
+
return {
|
|
8448
|
+
run: finalRun,
|
|
8449
|
+
proposals: finalProposals,
|
|
8450
|
+
executed: executedCount,
|
|
8451
|
+
metrics: effectivenessReport,
|
|
8452
|
+
dryRun
|
|
8453
|
+
};
|
|
8454
|
+
} catch (err) {
|
|
8455
|
+
updateSynthesisRun(run.id, {
|
|
8456
|
+
status: "failed",
|
|
8457
|
+
error: err instanceof Error ? err.message : String(err),
|
|
8458
|
+
completed_at: now()
|
|
8459
|
+
}, d);
|
|
8460
|
+
const failedRun = listSynthesisRuns({ project_id: projectId, limit: 1 }, d)[0] ?? run;
|
|
8461
|
+
return {
|
|
8462
|
+
run: failedRun,
|
|
8463
|
+
proposals: [],
|
|
8464
|
+
executed: 0,
|
|
8465
|
+
metrics: null,
|
|
8466
|
+
dryRun
|
|
8467
|
+
};
|
|
8468
|
+
}
|
|
8469
|
+
}
|
|
8470
|
+
async function rollbackSynthesis(runId, db) {
|
|
8471
|
+
const d = db || getDatabase();
|
|
8472
|
+
const result = await rollbackRun(runId, d);
|
|
8473
|
+
if (result.errors.length === 0) {
|
|
8474
|
+
updateSynthesisRun(runId, { status: "rolled_back", completed_at: now() }, d);
|
|
8475
|
+
}
|
|
8476
|
+
return result;
|
|
8477
|
+
}
|
|
8478
|
+
function getSynthesisStatus(runId, projectId, db) {
|
|
8479
|
+
const d = db || getDatabase();
|
|
8480
|
+
if (runId) {
|
|
8481
|
+
const recentRuns2 = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
|
|
8482
|
+
const specificRun = recentRuns2.find((r) => r.id === runId) ?? null;
|
|
8483
|
+
return {
|
|
8484
|
+
lastRun: specificRun ?? recentRuns2[0] ?? null,
|
|
8485
|
+
recentRuns: recentRuns2
|
|
8486
|
+
};
|
|
8487
|
+
}
|
|
8488
|
+
const recentRuns = listSynthesisRuns({ project_id: projectId ?? null, limit: 10 }, d);
|
|
8489
|
+
return {
|
|
8490
|
+
lastRun: recentRuns[0] ?? null,
|
|
8491
|
+
recentRuns
|
|
8492
|
+
};
|
|
8493
|
+
}
|
|
8494
|
+
|
|
8495
|
+
// src/mcp/index.ts
|
|
8496
|
+
init_synthesis();
|
|
7201
8497
|
init_auto_memory();
|
|
7202
8498
|
init_registry();
|
|
7203
8499
|
import { createRequire } from "module";
|
|
@@ -8006,6 +9302,58 @@ server.tool("webhook_update", "Enable, disable, or update a persisted webhook ho
|
|
|
8006
9302
|
return { content: [{ type: "text", text: formatError(e) }], isError: true };
|
|
8007
9303
|
}
|
|
8008
9304
|
});
|
|
9305
|
+
server.tool("memory_synthesize", "Run ALMA synthesis: analyze memory corpus, find redundancies, propose and apply consolidations.", {
|
|
9306
|
+
project_id: exports_external.string().optional(),
|
|
9307
|
+
agent_id: exports_external.string().optional(),
|
|
9308
|
+
dry_run: exports_external.boolean().optional(),
|
|
9309
|
+
max_proposals: exports_external.coerce.number().optional(),
|
|
9310
|
+
provider: exports_external.string().optional()
|
|
9311
|
+
}, async (args) => {
|
|
9312
|
+
try {
|
|
9313
|
+
const result = await runSynthesis({
|
|
9314
|
+
projectId: args.project_id,
|
|
9315
|
+
agentId: args.agent_id,
|
|
9316
|
+
dryRun: args.dry_run ?? false,
|
|
9317
|
+
maxProposals: args.max_proposals,
|
|
9318
|
+
provider: args.provider
|
|
9319
|
+
});
|
|
9320
|
+
return { content: [{ type: "text", text: JSON.stringify({
|
|
9321
|
+
run_id: result.run.id,
|
|
9322
|
+
status: result.run.status,
|
|
9323
|
+
corpus_size: result.run.corpus_size,
|
|
9324
|
+
proposals_generated: result.run.proposals_generated,
|
|
9325
|
+
proposals_accepted: result.run.proposals_accepted,
|
|
9326
|
+
dry_run: result.dryRun,
|
|
9327
|
+
metrics: result.metrics ? { corpus_reduction: result.metrics.corpusReduction, deduplication_rate: result.metrics.deduplicationRate } : null
|
|
9328
|
+
}, null, 2) }] };
|
|
9329
|
+
} catch (e) {
|
|
9330
|
+
return { content: [{ type: "text", text: formatError(e) }], isError: true };
|
|
9331
|
+
}
|
|
9332
|
+
});
|
|
9333
|
+
server.tool("memory_synthesis_status", "Get the status of synthesis runs.", { project_id: exports_external.string().optional(), run_id: exports_external.string().optional() }, async (args) => {
|
|
9334
|
+
try {
|
|
9335
|
+
const status = getSynthesisStatus(args.run_id, args.project_id);
|
|
9336
|
+
return { content: [{ type: "text", text: JSON.stringify(status, null, 2) }] };
|
|
9337
|
+
} catch (e) {
|
|
9338
|
+
return { content: [{ type: "text", text: formatError(e) }], isError: true };
|
|
9339
|
+
}
|
|
9340
|
+
});
|
|
9341
|
+
server.tool("memory_synthesis_history", "List past synthesis runs.", { project_id: exports_external.string().optional(), limit: exports_external.coerce.number().optional() }, async (args) => {
|
|
9342
|
+
try {
|
|
9343
|
+
const runs = listSynthesisRuns({ project_id: args.project_id, limit: args.limit ?? 20 });
|
|
9344
|
+
return { content: [{ type: "text", text: JSON.stringify(runs, null, 2) }] };
|
|
9345
|
+
} catch (e) {
|
|
9346
|
+
return { content: [{ type: "text", text: formatError(e) }], isError: true };
|
|
9347
|
+
}
|
|
9348
|
+
});
|
|
9349
|
+
server.tool("memory_synthesis_rollback", "Roll back a synthesis run, reversing all applied proposals.", { run_id: exports_external.string() }, async (args) => {
|
|
9350
|
+
try {
|
|
9351
|
+
const result = await rollbackSynthesis(args.run_id);
|
|
9352
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
9353
|
+
} catch (e) {
|
|
9354
|
+
return { content: [{ type: "text", text: formatError(e) }], isError: true };
|
|
9355
|
+
}
|
|
9356
|
+
});
|
|
8009
9357
|
server.tool("register_agent", "Register an agent. Idempotent \u2014 same name returns existing agent.", {
|
|
8010
9358
|
name: exports_external.string(),
|
|
8011
9359
|
session_id: exports_external.string().optional(),
|