claude-memory-layer 1.0.8 → 1.0.9
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/.claude/settings.local.json +7 -1
- package/.claude-memory/test.sqlite +0 -0
- package/.history/package_20260202114053.json +49 -0
- package/HANDOFF.md +92 -0
- package/dist/cli/index.js +1150 -71
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +1033 -47
- package/dist/core/index.js.map +4 -4
- package/dist/hooks/post-tool-use.js +5589 -0
- package/dist/hooks/post-tool-use.js.map +7 -0
- package/dist/hooks/session-end.js +1117 -64
- package/dist/hooks/session-end.js.map +4 -4
- package/dist/hooks/session-start.js +1112 -63
- package/dist/hooks/session-start.js.map +4 -4
- package/dist/hooks/stop.js +1117 -64
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +1151 -67
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +1145 -70
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +1145 -70
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +1122 -65
- package/dist/services/memory-service.js.map +4 -4
- package/dist/ui/app.js +304 -0
- package/dist/ui/index.html +195 -1188
- package/dist/ui/style.css +595 -0
- package/package.json +3 -1
- package/scripts/build.ts +2 -0
- package/src/core/event-store.ts +18 -0
- package/src/core/index.ts +3 -0
- package/src/core/retriever.ts +4 -1
- package/src/core/sqlite-event-store.ts +849 -0
- package/src/core/sqlite-wrapper.ts +108 -0
- package/src/core/sync-worker.ts +228 -0
- package/src/core/vector-worker.ts +44 -14
- package/src/hooks/user-prompt-submit.ts +53 -4
- package/src/server/api/stats.ts +37 -7
- package/src/services/memory-service.ts +168 -39
- package/src/ui/app.js +304 -0
- package/src/ui/index.html +195 -1188
- package/src/ui/style.css +595 -0
- package/test_access.js +49 -0
package/dist/server/api/index.js
CHANGED
|
@@ -706,26 +706,975 @@ var EventStore = class {
|
|
|
706
706
|
tags: row.tags ? JSON.parse(row.tags) : void 0
|
|
707
707
|
}));
|
|
708
708
|
}
|
|
709
|
+
/**
|
|
710
|
+
* Increment access count for events (stub for compatibility)
|
|
711
|
+
*/
|
|
712
|
+
async incrementAccessCount(eventIds) {
|
|
713
|
+
return Promise.resolve();
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Get most accessed memories (stub for compatibility)
|
|
717
|
+
*/
|
|
718
|
+
async getMostAccessed(limit = 10) {
|
|
719
|
+
return [];
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Close database connection
|
|
723
|
+
*/
|
|
724
|
+
async close() {
|
|
725
|
+
await dbClose(this.db);
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Convert database row to MemoryEvent
|
|
729
|
+
*/
|
|
730
|
+
rowToEvent(row) {
|
|
731
|
+
return {
|
|
732
|
+
id: row.id,
|
|
733
|
+
eventType: row.event_type,
|
|
734
|
+
sessionId: row.session_id,
|
|
735
|
+
timestamp: toDate(row.timestamp),
|
|
736
|
+
content: row.content,
|
|
737
|
+
canonicalKey: row.canonical_key,
|
|
738
|
+
dedupeKey: row.dedupe_key,
|
|
739
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : void 0
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
|
|
744
|
+
// src/core/sqlite-event-store.ts
|
|
745
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
746
|
+
|
|
747
|
+
// src/core/sqlite-wrapper.ts
|
|
748
|
+
import Database from "better-sqlite3";
|
|
749
|
+
function createSQLiteDatabase(path2, options) {
|
|
750
|
+
const db = new Database(path2, {
|
|
751
|
+
readonly: options?.readonly ?? false
|
|
752
|
+
});
|
|
753
|
+
if (!options?.readonly && (options?.walMode ?? true)) {
|
|
754
|
+
db.pragma("journal_mode = WAL");
|
|
755
|
+
db.pragma("synchronous = NORMAL");
|
|
756
|
+
db.pragma("busy_timeout = 5000");
|
|
757
|
+
}
|
|
758
|
+
return db;
|
|
759
|
+
}
|
|
760
|
+
function sqliteRun(db, sql, params = []) {
|
|
761
|
+
const stmt = db.prepare(sql);
|
|
762
|
+
return stmt.run(...params);
|
|
763
|
+
}
|
|
764
|
+
function sqliteAll(db, sql, params = []) {
|
|
765
|
+
const stmt = db.prepare(sql);
|
|
766
|
+
return stmt.all(...params);
|
|
767
|
+
}
|
|
768
|
+
function sqliteGet(db, sql, params = []) {
|
|
769
|
+
const stmt = db.prepare(sql);
|
|
770
|
+
return stmt.get(...params);
|
|
771
|
+
}
|
|
772
|
+
function sqliteExec(db, sql) {
|
|
773
|
+
db.exec(sql);
|
|
774
|
+
}
|
|
775
|
+
function sqliteClose(db) {
|
|
776
|
+
db.close();
|
|
777
|
+
}
|
|
778
|
+
function toDateFromSQLite(value) {
|
|
779
|
+
if (value instanceof Date)
|
|
780
|
+
return value;
|
|
781
|
+
if (typeof value === "string")
|
|
782
|
+
return new Date(value);
|
|
783
|
+
if (typeof value === "number")
|
|
784
|
+
return new Date(value);
|
|
785
|
+
return new Date(String(value));
|
|
786
|
+
}
|
|
787
|
+
function toSQLiteTimestamp(date) {
|
|
788
|
+
return date.toISOString();
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// src/core/sqlite-event-store.ts
|
|
792
|
+
var SQLiteEventStore = class {
|
|
793
|
+
constructor(dbPath, options) {
|
|
794
|
+
this.dbPath = dbPath;
|
|
795
|
+
this.readOnly = options?.readonly ?? false;
|
|
796
|
+
this.db = createSQLiteDatabase(dbPath, {
|
|
797
|
+
readonly: this.readOnly,
|
|
798
|
+
walMode: !this.readOnly
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
db;
|
|
802
|
+
initialized = false;
|
|
803
|
+
readOnly;
|
|
804
|
+
/**
|
|
805
|
+
* Initialize database schema
|
|
806
|
+
*/
|
|
807
|
+
async initialize() {
|
|
808
|
+
if (this.initialized)
|
|
809
|
+
return;
|
|
810
|
+
if (this.readOnly) {
|
|
811
|
+
this.initialized = true;
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
sqliteExec(this.db, `
|
|
815
|
+
-- L0 EventStore: Single Source of Truth (immutable, append-only)
|
|
816
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
817
|
+
id TEXT PRIMARY KEY,
|
|
818
|
+
event_type TEXT NOT NULL,
|
|
819
|
+
session_id TEXT NOT NULL,
|
|
820
|
+
timestamp TEXT NOT NULL,
|
|
821
|
+
content TEXT NOT NULL,
|
|
822
|
+
canonical_key TEXT NOT NULL,
|
|
823
|
+
dedupe_key TEXT UNIQUE,
|
|
824
|
+
metadata TEXT,
|
|
825
|
+
access_count INTEGER DEFAULT 0,
|
|
826
|
+
last_accessed_at TEXT
|
|
827
|
+
);
|
|
828
|
+
|
|
829
|
+
-- Dedup table for idempotency
|
|
830
|
+
CREATE TABLE IF NOT EXISTS event_dedup (
|
|
831
|
+
dedupe_key TEXT PRIMARY KEY,
|
|
832
|
+
event_id TEXT NOT NULL,
|
|
833
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
834
|
+
);
|
|
835
|
+
|
|
836
|
+
-- Session metadata
|
|
837
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
838
|
+
id TEXT PRIMARY KEY,
|
|
839
|
+
started_at TEXT NOT NULL,
|
|
840
|
+
ended_at TEXT,
|
|
841
|
+
project_path TEXT,
|
|
842
|
+
summary TEXT,
|
|
843
|
+
tags TEXT
|
|
844
|
+
);
|
|
845
|
+
|
|
846
|
+
-- Insights (derived data, rebuildable)
|
|
847
|
+
CREATE TABLE IF NOT EXISTS insights (
|
|
848
|
+
id TEXT PRIMARY KEY,
|
|
849
|
+
insight_type TEXT NOT NULL,
|
|
850
|
+
content TEXT NOT NULL,
|
|
851
|
+
canonical_key TEXT NOT NULL,
|
|
852
|
+
confidence REAL,
|
|
853
|
+
source_events TEXT,
|
|
854
|
+
created_at TEXT,
|
|
855
|
+
last_updated TEXT
|
|
856
|
+
);
|
|
857
|
+
|
|
858
|
+
-- Embedding Outbox (Single-Writer Pattern)
|
|
859
|
+
CREATE TABLE IF NOT EXISTS embedding_outbox (
|
|
860
|
+
id TEXT PRIMARY KEY,
|
|
861
|
+
event_id TEXT NOT NULL,
|
|
862
|
+
content TEXT NOT NULL,
|
|
863
|
+
status TEXT DEFAULT 'pending',
|
|
864
|
+
retry_count INTEGER DEFAULT 0,
|
|
865
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
866
|
+
processed_at TEXT,
|
|
867
|
+
error_message TEXT
|
|
868
|
+
);
|
|
869
|
+
|
|
870
|
+
-- Projection offset tracking
|
|
871
|
+
CREATE TABLE IF NOT EXISTS projection_offsets (
|
|
872
|
+
projection_name TEXT PRIMARY KEY,
|
|
873
|
+
last_event_id TEXT,
|
|
874
|
+
last_timestamp TEXT,
|
|
875
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
876
|
+
);
|
|
877
|
+
|
|
878
|
+
-- Memory level tracking
|
|
879
|
+
CREATE TABLE IF NOT EXISTS memory_levels (
|
|
880
|
+
event_id TEXT PRIMARY KEY,
|
|
881
|
+
level TEXT NOT NULL DEFAULT 'L0',
|
|
882
|
+
promoted_at TEXT DEFAULT (datetime('now'))
|
|
883
|
+
);
|
|
884
|
+
|
|
885
|
+
-- Entries (immutable memory units)
|
|
886
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
887
|
+
entry_id TEXT PRIMARY KEY,
|
|
888
|
+
created_ts TEXT NOT NULL,
|
|
889
|
+
entry_type TEXT NOT NULL,
|
|
890
|
+
title TEXT NOT NULL,
|
|
891
|
+
content_json TEXT NOT NULL,
|
|
892
|
+
stage TEXT NOT NULL DEFAULT 'raw',
|
|
893
|
+
status TEXT DEFAULT 'active',
|
|
894
|
+
superseded_by TEXT,
|
|
895
|
+
build_id TEXT,
|
|
896
|
+
evidence_json TEXT,
|
|
897
|
+
canonical_key TEXT,
|
|
898
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
899
|
+
);
|
|
900
|
+
|
|
901
|
+
-- Entities (task/condition/artifact)
|
|
902
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
903
|
+
entity_id TEXT PRIMARY KEY,
|
|
904
|
+
entity_type TEXT NOT NULL,
|
|
905
|
+
canonical_key TEXT NOT NULL,
|
|
906
|
+
title TEXT NOT NULL,
|
|
907
|
+
stage TEXT NOT NULL DEFAULT 'raw',
|
|
908
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
909
|
+
current_json TEXT NOT NULL,
|
|
910
|
+
title_norm TEXT,
|
|
911
|
+
search_text TEXT,
|
|
912
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
913
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
914
|
+
);
|
|
915
|
+
|
|
916
|
+
-- Entity aliases for canonical key lookup
|
|
917
|
+
CREATE TABLE IF NOT EXISTS entity_aliases (
|
|
918
|
+
entity_type TEXT NOT NULL,
|
|
919
|
+
canonical_key TEXT NOT NULL,
|
|
920
|
+
entity_id TEXT NOT NULL,
|
|
921
|
+
is_primary INTEGER DEFAULT 0,
|
|
922
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
923
|
+
PRIMARY KEY(entity_type, canonical_key)
|
|
924
|
+
);
|
|
925
|
+
|
|
926
|
+
-- Edges (relationships between entries/entities)
|
|
927
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
928
|
+
edge_id TEXT PRIMARY KEY,
|
|
929
|
+
src_type TEXT NOT NULL,
|
|
930
|
+
src_id TEXT NOT NULL,
|
|
931
|
+
rel_type TEXT NOT NULL,
|
|
932
|
+
dst_type TEXT NOT NULL,
|
|
933
|
+
dst_id TEXT NOT NULL,
|
|
934
|
+
meta_json TEXT,
|
|
935
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
936
|
+
);
|
|
937
|
+
|
|
938
|
+
-- Vector Outbox V2 Table
|
|
939
|
+
CREATE TABLE IF NOT EXISTS vector_outbox (
|
|
940
|
+
job_id TEXT PRIMARY KEY,
|
|
941
|
+
item_kind TEXT NOT NULL,
|
|
942
|
+
item_id TEXT NOT NULL,
|
|
943
|
+
embedding_version TEXT NOT NULL,
|
|
944
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
945
|
+
retry_count INTEGER DEFAULT 0,
|
|
946
|
+
error TEXT,
|
|
947
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
948
|
+
updated_at TEXT DEFAULT (datetime('now')),
|
|
949
|
+
UNIQUE(item_kind, item_id, embedding_version)
|
|
950
|
+
);
|
|
951
|
+
|
|
952
|
+
-- Build Runs
|
|
953
|
+
CREATE TABLE IF NOT EXISTS build_runs (
|
|
954
|
+
build_id TEXT PRIMARY KEY,
|
|
955
|
+
started_at TEXT NOT NULL,
|
|
956
|
+
finished_at TEXT,
|
|
957
|
+
extractor_model TEXT NOT NULL,
|
|
958
|
+
extractor_prompt_hash TEXT NOT NULL,
|
|
959
|
+
embedder_model TEXT NOT NULL,
|
|
960
|
+
embedding_version TEXT NOT NULL,
|
|
961
|
+
idris_version TEXT NOT NULL,
|
|
962
|
+
schema_version TEXT NOT NULL,
|
|
963
|
+
status TEXT NOT NULL DEFAULT 'running',
|
|
964
|
+
error TEXT
|
|
965
|
+
);
|
|
966
|
+
|
|
967
|
+
-- Pipeline Metrics
|
|
968
|
+
CREATE TABLE IF NOT EXISTS pipeline_metrics (
|
|
969
|
+
id TEXT PRIMARY KEY,
|
|
970
|
+
ts TEXT NOT NULL,
|
|
971
|
+
stage TEXT NOT NULL,
|
|
972
|
+
latency_ms REAL NOT NULL,
|
|
973
|
+
success INTEGER NOT NULL,
|
|
974
|
+
error TEXT,
|
|
975
|
+
session_id TEXT
|
|
976
|
+
);
|
|
977
|
+
|
|
978
|
+
-- Working Set table (active memory window)
|
|
979
|
+
CREATE TABLE IF NOT EXISTS working_set (
|
|
980
|
+
id TEXT PRIMARY KEY,
|
|
981
|
+
event_id TEXT NOT NULL,
|
|
982
|
+
added_at TEXT DEFAULT (datetime('now')),
|
|
983
|
+
relevance_score REAL DEFAULT 1.0,
|
|
984
|
+
topics TEXT,
|
|
985
|
+
expires_at TEXT
|
|
986
|
+
);
|
|
987
|
+
|
|
988
|
+
-- Consolidated Memories table (long-term integrated memories)
|
|
989
|
+
CREATE TABLE IF NOT EXISTS consolidated_memories (
|
|
990
|
+
memory_id TEXT PRIMARY KEY,
|
|
991
|
+
summary TEXT NOT NULL,
|
|
992
|
+
topics TEXT,
|
|
993
|
+
source_events TEXT,
|
|
994
|
+
confidence REAL DEFAULT 0.5,
|
|
995
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
996
|
+
accessed_at TEXT,
|
|
997
|
+
access_count INTEGER DEFAULT 0
|
|
998
|
+
);
|
|
999
|
+
|
|
1000
|
+
-- Continuity Log table (tracks context transitions)
|
|
1001
|
+
CREATE TABLE IF NOT EXISTS continuity_log (
|
|
1002
|
+
log_id TEXT PRIMARY KEY,
|
|
1003
|
+
from_context_id TEXT,
|
|
1004
|
+
to_context_id TEXT,
|
|
1005
|
+
continuity_score REAL,
|
|
1006
|
+
transition_type TEXT,
|
|
1007
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
1008
|
+
);
|
|
1009
|
+
|
|
1010
|
+
-- Endless Mode Config table
|
|
1011
|
+
CREATE TABLE IF NOT EXISTS endless_config (
|
|
1012
|
+
key TEXT PRIMARY KEY,
|
|
1013
|
+
value TEXT,
|
|
1014
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
1015
|
+
);
|
|
1016
|
+
|
|
1017
|
+
-- Sync position tracking (for SQLite -> DuckDB sync)
|
|
1018
|
+
CREATE TABLE IF NOT EXISTS sync_positions (
|
|
1019
|
+
target_name TEXT PRIMARY KEY,
|
|
1020
|
+
last_event_id TEXT,
|
|
1021
|
+
last_timestamp TEXT,
|
|
1022
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
1023
|
+
);
|
|
1024
|
+
|
|
1025
|
+
-- Create indexes
|
|
1026
|
+
CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
|
|
1027
|
+
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
|
1028
|
+
CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type);
|
|
1029
|
+
CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage);
|
|
1030
|
+
CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key);
|
|
1031
|
+
CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key);
|
|
1032
|
+
CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status);
|
|
1033
|
+
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type);
|
|
1034
|
+
CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type);
|
|
1035
|
+
CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type);
|
|
1036
|
+
CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status);
|
|
1037
|
+
CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at);
|
|
1038
|
+
CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score);
|
|
1039
|
+
CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
|
|
1040
|
+
CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
|
|
1041
|
+
CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
|
|
1042
|
+
`);
|
|
1043
|
+
const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
|
|
1044
|
+
const columnNames = tableInfo.map((col) => col.name);
|
|
1045
|
+
if (!columnNames.includes("access_count")) {
|
|
1046
|
+
try {
|
|
1047
|
+
sqliteExec(this.db, `
|
|
1048
|
+
ALTER TABLE events ADD COLUMN access_count INTEGER DEFAULT 0;
|
|
1049
|
+
`);
|
|
1050
|
+
} catch (err) {
|
|
1051
|
+
console.error("Error adding access_count column:", err);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
if (!columnNames.includes("last_accessed_at")) {
|
|
1055
|
+
try {
|
|
1056
|
+
sqliteExec(this.db, `
|
|
1057
|
+
ALTER TABLE events ADD COLUMN last_accessed_at TEXT;
|
|
1058
|
+
`);
|
|
1059
|
+
} catch (err) {
|
|
1060
|
+
console.error("Error adding last_accessed_at column:", err);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
try {
|
|
1064
|
+
sqliteExec(this.db, `
|
|
1065
|
+
CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
|
|
1066
|
+
`);
|
|
1067
|
+
} catch (err) {
|
|
1068
|
+
}
|
|
1069
|
+
try {
|
|
1070
|
+
sqliteExec(this.db, `
|
|
1071
|
+
CREATE INDEX IF NOT EXISTS idx_events_last_accessed ON events(last_accessed_at DESC);
|
|
1072
|
+
`);
|
|
1073
|
+
} catch (err) {
|
|
1074
|
+
}
|
|
1075
|
+
this.initialized = true;
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Append event to store (Append-only, Idempotent)
|
|
1079
|
+
*/
|
|
1080
|
+
async append(input) {
|
|
1081
|
+
await this.initialize();
|
|
1082
|
+
const canonicalKey = makeCanonicalKey(input.content);
|
|
1083
|
+
const dedupeKey = makeDedupeKey(input.content, input.sessionId);
|
|
1084
|
+
const existing = sqliteGet(
|
|
1085
|
+
this.db,
|
|
1086
|
+
`SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
|
|
1087
|
+
[dedupeKey]
|
|
1088
|
+
);
|
|
1089
|
+
if (existing) {
|
|
1090
|
+
return {
|
|
1091
|
+
success: true,
|
|
1092
|
+
eventId: existing.event_id,
|
|
1093
|
+
isDuplicate: true
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
const id = randomUUID2();
|
|
1097
|
+
const timestamp = toSQLiteTimestamp(input.timestamp);
|
|
1098
|
+
try {
|
|
1099
|
+
const insertEvent = this.db.prepare(`
|
|
1100
|
+
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
|
|
1101
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1102
|
+
`);
|
|
1103
|
+
const insertDedup = this.db.prepare(`
|
|
1104
|
+
INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
|
|
1105
|
+
`);
|
|
1106
|
+
const insertLevel = this.db.prepare(`
|
|
1107
|
+
INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')
|
|
1108
|
+
`);
|
|
1109
|
+
const transaction = this.db.transaction(() => {
|
|
1110
|
+
insertEvent.run(
|
|
1111
|
+
id,
|
|
1112
|
+
input.eventType,
|
|
1113
|
+
input.sessionId,
|
|
1114
|
+
timestamp,
|
|
1115
|
+
input.content,
|
|
1116
|
+
canonicalKey,
|
|
1117
|
+
dedupeKey,
|
|
1118
|
+
JSON.stringify(input.metadata || {})
|
|
1119
|
+
);
|
|
1120
|
+
insertDedup.run(dedupeKey, id);
|
|
1121
|
+
insertLevel.run(id);
|
|
1122
|
+
});
|
|
1123
|
+
transaction();
|
|
1124
|
+
return { success: true, eventId: id, isDuplicate: false };
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
return {
|
|
1127
|
+
success: false,
|
|
1128
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Get events by session ID
|
|
1134
|
+
*/
|
|
1135
|
+
async getSessionEvents(sessionId) {
|
|
1136
|
+
await this.initialize();
|
|
1137
|
+
const rows = sqliteAll(
|
|
1138
|
+
this.db,
|
|
1139
|
+
`SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
|
|
1140
|
+
[sessionId]
|
|
1141
|
+
);
|
|
1142
|
+
return rows.map(this.rowToEvent);
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Get recent events
|
|
1146
|
+
*/
|
|
1147
|
+
async getRecentEvents(limit = 100) {
|
|
1148
|
+
await this.initialize();
|
|
1149
|
+
const rows = sqliteAll(
|
|
1150
|
+
this.db,
|
|
1151
|
+
`SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
|
|
1152
|
+
[limit]
|
|
1153
|
+
);
|
|
1154
|
+
return rows.map(this.rowToEvent);
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* Get event by ID
|
|
1158
|
+
*/
|
|
1159
|
+
async getEvent(id) {
|
|
1160
|
+
await this.initialize();
|
|
1161
|
+
const row = sqliteGet(
|
|
1162
|
+
this.db,
|
|
1163
|
+
`SELECT * FROM events WHERE id = ?`,
|
|
1164
|
+
[id]
|
|
1165
|
+
);
|
|
1166
|
+
if (!row)
|
|
1167
|
+
return null;
|
|
1168
|
+
return this.rowToEvent(row);
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Get events since a timestamp (for sync)
|
|
1172
|
+
*/
|
|
1173
|
+
async getEventsSince(timestamp, limit = 1e3) {
|
|
1174
|
+
await this.initialize();
|
|
1175
|
+
const rows = sqliteAll(
|
|
1176
|
+
this.db,
|
|
1177
|
+
`SELECT * FROM events WHERE timestamp > ? ORDER BY timestamp ASC LIMIT ?`,
|
|
1178
|
+
[timestamp, limit]
|
|
1179
|
+
);
|
|
1180
|
+
return rows.map(this.rowToEvent);
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Create or update session
|
|
1184
|
+
*/
|
|
1185
|
+
async upsertSession(session) {
|
|
1186
|
+
await this.initialize();
|
|
1187
|
+
const existing = sqliteGet(
|
|
1188
|
+
this.db,
|
|
1189
|
+
`SELECT id FROM sessions WHERE id = ?`,
|
|
1190
|
+
[session.id]
|
|
1191
|
+
);
|
|
1192
|
+
if (!existing) {
|
|
1193
|
+
sqliteRun(
|
|
1194
|
+
this.db,
|
|
1195
|
+
`INSERT INTO sessions (id, started_at, project_path, tags)
|
|
1196
|
+
VALUES (?, ?, ?, ?)`,
|
|
1197
|
+
[
|
|
1198
|
+
session.id,
|
|
1199
|
+
toSQLiteTimestamp(session.startedAt || /* @__PURE__ */ new Date()),
|
|
1200
|
+
session.projectPath || null,
|
|
1201
|
+
JSON.stringify(session.tags || [])
|
|
1202
|
+
]
|
|
1203
|
+
);
|
|
1204
|
+
} else {
|
|
1205
|
+
const updates = [];
|
|
1206
|
+
const values = [];
|
|
1207
|
+
if (session.endedAt) {
|
|
1208
|
+
updates.push("ended_at = ?");
|
|
1209
|
+
values.push(toSQLiteTimestamp(session.endedAt));
|
|
1210
|
+
}
|
|
1211
|
+
if (session.summary) {
|
|
1212
|
+
updates.push("summary = ?");
|
|
1213
|
+
values.push(session.summary);
|
|
1214
|
+
}
|
|
1215
|
+
if (session.tags) {
|
|
1216
|
+
updates.push("tags = ?");
|
|
1217
|
+
values.push(JSON.stringify(session.tags));
|
|
1218
|
+
}
|
|
1219
|
+
if (updates.length > 0) {
|
|
1220
|
+
values.push(session.id);
|
|
1221
|
+
sqliteRun(
|
|
1222
|
+
this.db,
|
|
1223
|
+
`UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
|
|
1224
|
+
values
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Get session by ID
|
|
1231
|
+
*/
|
|
1232
|
+
async getSession(id) {
|
|
1233
|
+
await this.initialize();
|
|
1234
|
+
const row = sqliteGet(
|
|
1235
|
+
this.db,
|
|
1236
|
+
`SELECT * FROM sessions WHERE id = ?`,
|
|
1237
|
+
[id]
|
|
1238
|
+
);
|
|
1239
|
+
if (!row)
|
|
1240
|
+
return null;
|
|
1241
|
+
return {
|
|
1242
|
+
id: row.id,
|
|
1243
|
+
startedAt: toDateFromSQLite(row.started_at),
|
|
1244
|
+
endedAt: row.ended_at ? toDateFromSQLite(row.ended_at) : void 0,
|
|
1245
|
+
projectPath: row.project_path,
|
|
1246
|
+
summary: row.summary,
|
|
1247
|
+
tags: row.tags ? JSON.parse(row.tags) : void 0
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Get all sessions
|
|
1252
|
+
*/
|
|
1253
|
+
async getAllSessions() {
|
|
1254
|
+
await this.initialize();
|
|
1255
|
+
const rows = sqliteAll(
|
|
1256
|
+
this.db,
|
|
1257
|
+
`SELECT * FROM sessions ORDER BY started_at DESC`
|
|
1258
|
+
);
|
|
1259
|
+
return rows.map((row) => ({
|
|
1260
|
+
id: row.id,
|
|
1261
|
+
startedAt: toDateFromSQLite(row.started_at),
|
|
1262
|
+
endedAt: row.ended_at ? toDateFromSQLite(row.ended_at) : void 0,
|
|
1263
|
+
projectPath: row.project_path,
|
|
1264
|
+
summary: row.summary,
|
|
1265
|
+
tags: row.tags ? JSON.parse(row.tags) : void 0
|
|
1266
|
+
}));
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Add to embedding outbox
|
|
1270
|
+
*/
|
|
1271
|
+
async enqueueForEmbedding(eventId, content) {
|
|
1272
|
+
await this.initialize();
|
|
1273
|
+
const id = randomUUID2();
|
|
1274
|
+
sqliteRun(
|
|
1275
|
+
this.db,
|
|
1276
|
+
`INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
|
|
1277
|
+
VALUES (?, ?, ?, 'pending', 0)`,
|
|
1278
|
+
[id, eventId, content]
|
|
1279
|
+
);
|
|
1280
|
+
return id;
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Get pending outbox items
|
|
1284
|
+
*/
|
|
1285
|
+
async getPendingOutboxItems(limit = 32) {
|
|
1286
|
+
await this.initialize();
|
|
1287
|
+
const pending = sqliteAll(
|
|
1288
|
+
this.db,
|
|
1289
|
+
`SELECT * FROM embedding_outbox
|
|
1290
|
+
WHERE status = 'pending'
|
|
1291
|
+
ORDER BY created_at
|
|
1292
|
+
LIMIT ?`,
|
|
1293
|
+
[limit]
|
|
1294
|
+
);
|
|
1295
|
+
if (pending.length === 0)
|
|
1296
|
+
return [];
|
|
1297
|
+
const ids = pending.map((r) => r.id);
|
|
1298
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1299
|
+
sqliteRun(
|
|
1300
|
+
this.db,
|
|
1301
|
+
`UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
|
|
1302
|
+
ids
|
|
1303
|
+
);
|
|
1304
|
+
return pending.map((row) => ({
|
|
1305
|
+
id: row.id,
|
|
1306
|
+
eventId: row.event_id,
|
|
1307
|
+
content: row.content,
|
|
1308
|
+
status: "processing",
|
|
1309
|
+
retryCount: row.retry_count,
|
|
1310
|
+
createdAt: toDateFromSQLite(row.created_at),
|
|
1311
|
+
errorMessage: row.error_message
|
|
1312
|
+
}));
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* Mark outbox items as done
|
|
1316
|
+
*/
|
|
1317
|
+
async completeOutboxItems(ids) {
|
|
1318
|
+
if (ids.length === 0)
|
|
1319
|
+
return;
|
|
1320
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1321
|
+
sqliteRun(
|
|
1322
|
+
this.db,
|
|
1323
|
+
`DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
|
|
1324
|
+
ids
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
/**
|
|
1328
|
+
* Mark outbox items as failed
|
|
1329
|
+
*/
|
|
1330
|
+
async failOutboxItems(ids, error) {
|
|
1331
|
+
if (ids.length === 0)
|
|
1332
|
+
return;
|
|
1333
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1334
|
+
sqliteRun(
|
|
1335
|
+
this.db,
|
|
1336
|
+
`UPDATE embedding_outbox
|
|
1337
|
+
SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
|
|
1338
|
+
retry_count = retry_count + 1,
|
|
1339
|
+
error_message = ?
|
|
1340
|
+
WHERE id IN (${placeholders})`,
|
|
1341
|
+
[error, ...ids]
|
|
1342
|
+
);
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Update memory level
|
|
1346
|
+
*/
|
|
1347
|
+
async updateMemoryLevel(eventId, level) {
|
|
1348
|
+
await this.initialize();
|
|
1349
|
+
sqliteRun(
|
|
1350
|
+
this.db,
|
|
1351
|
+
`UPDATE memory_levels SET level = ?, promoted_at = datetime('now') WHERE event_id = ?`,
|
|
1352
|
+
[level, eventId]
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Get memory level statistics
|
|
1357
|
+
*/
|
|
1358
|
+
async getLevelStats() {
|
|
1359
|
+
await this.initialize();
|
|
1360
|
+
const rows = sqliteAll(
|
|
1361
|
+
this.db,
|
|
1362
|
+
`SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
|
|
1363
|
+
);
|
|
1364
|
+
return rows;
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* Get events by memory level
|
|
1368
|
+
*/
|
|
1369
|
+
async getEventsByLevel(level, options) {
|
|
1370
|
+
await this.initialize();
|
|
1371
|
+
const limit = options?.limit || 50;
|
|
1372
|
+
const offset = options?.offset || 0;
|
|
1373
|
+
const rows = sqliteAll(
|
|
1374
|
+
this.db,
|
|
1375
|
+
`SELECT e.* FROM events e
|
|
1376
|
+
INNER JOIN memory_levels ml ON e.id = ml.event_id
|
|
1377
|
+
WHERE ml.level = ?
|
|
1378
|
+
ORDER BY e.timestamp DESC
|
|
1379
|
+
LIMIT ? OFFSET ?`,
|
|
1380
|
+
[level, limit, offset]
|
|
1381
|
+
);
|
|
1382
|
+
return rows.map((row) => this.rowToEvent(row));
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Get memory level for a specific event
|
|
1386
|
+
*/
|
|
1387
|
+
async getEventLevel(eventId) {
|
|
1388
|
+
await this.initialize();
|
|
1389
|
+
const row = sqliteGet(
|
|
1390
|
+
this.db,
|
|
1391
|
+
`SELECT level FROM memory_levels WHERE event_id = ?`,
|
|
1392
|
+
[eventId]
|
|
1393
|
+
);
|
|
1394
|
+
return row ? row.level : null;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Get sync position for a target
|
|
1398
|
+
*/
|
|
1399
|
+
async getSyncPosition(targetName) {
|
|
1400
|
+
await this.initialize();
|
|
1401
|
+
const row = sqliteGet(
|
|
1402
|
+
this.db,
|
|
1403
|
+
`SELECT last_event_id, last_timestamp FROM sync_positions WHERE target_name = ?`,
|
|
1404
|
+
[targetName]
|
|
1405
|
+
);
|
|
1406
|
+
return {
|
|
1407
|
+
lastEventId: row?.last_event_id ?? null,
|
|
1408
|
+
lastTimestamp: row?.last_timestamp ?? null
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* Update sync position for a target
|
|
1413
|
+
*/
|
|
1414
|
+
async updateSyncPosition(targetName, lastEventId, lastTimestamp) {
|
|
1415
|
+
await this.initialize();
|
|
1416
|
+
sqliteRun(
|
|
1417
|
+
this.db,
|
|
1418
|
+
`INSERT OR REPLACE INTO sync_positions (target_name, last_event_id, last_timestamp, updated_at)
|
|
1419
|
+
VALUES (?, ?, ?, datetime('now'))`,
|
|
1420
|
+
[targetName, lastEventId, lastTimestamp]
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Get config value for endless mode
|
|
1425
|
+
*/
|
|
1426
|
+
async getEndlessConfig(key) {
|
|
1427
|
+
await this.initialize();
|
|
1428
|
+
const row = sqliteGet(
|
|
1429
|
+
this.db,
|
|
1430
|
+
`SELECT value FROM endless_config WHERE key = ?`,
|
|
1431
|
+
[key]
|
|
1432
|
+
);
|
|
1433
|
+
if (!row)
|
|
1434
|
+
return null;
|
|
1435
|
+
return JSON.parse(row.value);
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Set config value for endless mode
|
|
1439
|
+
*/
|
|
1440
|
+
async setEndlessConfig(key, value) {
|
|
1441
|
+
await this.initialize();
|
|
1442
|
+
sqliteRun(
|
|
1443
|
+
this.db,
|
|
1444
|
+
`INSERT OR REPLACE INTO endless_config (key, value, updated_at)
|
|
1445
|
+
VALUES (?, ?, datetime('now'))`,
|
|
1446
|
+
[key, JSON.stringify(value)]
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Increment access count for events
|
|
1451
|
+
*/
|
|
1452
|
+
async incrementAccessCount(eventIds) {
|
|
1453
|
+
if (eventIds.length === 0 || this.readOnly)
|
|
1454
|
+
return;
|
|
1455
|
+
await this.initialize();
|
|
1456
|
+
const placeholders = eventIds.map(() => "?").join(",");
|
|
1457
|
+
const currentTime = toSQLiteTimestamp(/* @__PURE__ */ new Date());
|
|
1458
|
+
sqliteRun(
|
|
1459
|
+
this.db,
|
|
1460
|
+
`UPDATE events
|
|
1461
|
+
SET access_count = access_count + 1,
|
|
1462
|
+
last_accessed_at = ?
|
|
1463
|
+
WHERE id IN (${placeholders})`,
|
|
1464
|
+
[currentTime, ...eventIds]
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Get most accessed memories
|
|
1469
|
+
*/
|
|
1470
|
+
async getMostAccessed(limit = 10) {
|
|
1471
|
+
await this.initialize();
|
|
1472
|
+
const rows = sqliteAll(
|
|
1473
|
+
this.db,
|
|
1474
|
+
`SELECT * FROM events
|
|
1475
|
+
WHERE access_count > 0
|
|
1476
|
+
ORDER BY access_count DESC, last_accessed_at DESC
|
|
1477
|
+
LIMIT ?`,
|
|
1478
|
+
[limit]
|
|
1479
|
+
);
|
|
1480
|
+
return rows.map((row) => this.rowToEvent(row));
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1483
|
+
* Get database instance for direct access
|
|
1484
|
+
*/
|
|
1485
|
+
getDatabase() {
|
|
1486
|
+
return this.db;
|
|
1487
|
+
}
|
|
709
1488
|
/**
|
|
710
1489
|
* Close database connection
|
|
711
1490
|
*/
|
|
712
1491
|
async close() {
|
|
713
|
-
|
|
1492
|
+
sqliteClose(this.db);
|
|
714
1493
|
}
|
|
715
1494
|
/**
|
|
716
1495
|
* Convert database row to MemoryEvent
|
|
717
1496
|
*/
|
|
718
1497
|
rowToEvent(row) {
|
|
719
|
-
|
|
1498
|
+
const event = {
|
|
720
1499
|
id: row.id,
|
|
721
1500
|
eventType: row.event_type,
|
|
722
1501
|
sessionId: row.session_id,
|
|
723
|
-
timestamp:
|
|
1502
|
+
timestamp: toDateFromSQLite(row.timestamp),
|
|
724
1503
|
content: row.content,
|
|
725
1504
|
canonicalKey: row.canonical_key,
|
|
726
1505
|
dedupeKey: row.dedupe_key,
|
|
727
1506
|
metadata: row.metadata ? JSON.parse(row.metadata) : void 0
|
|
728
1507
|
};
|
|
1508
|
+
if (row.access_count !== void 0) {
|
|
1509
|
+
event.access_count = row.access_count;
|
|
1510
|
+
}
|
|
1511
|
+
if (row.last_accessed_at !== void 0) {
|
|
1512
|
+
event.last_accessed_at = row.last_accessed_at;
|
|
1513
|
+
}
|
|
1514
|
+
return event;
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
|
|
1518
|
+
// src/core/sync-worker.ts
|
|
1519
|
+
var DEFAULT_CONFIG = {
|
|
1520
|
+
intervalMs: 3e4,
|
|
1521
|
+
batchSize: 500,
|
|
1522
|
+
maxRetries: 3,
|
|
1523
|
+
retryDelayMs: 5e3
|
|
1524
|
+
};
|
|
1525
|
+
var SyncWorker = class {
|
|
1526
|
+
constructor(sqliteStore, duckdbStore, config) {
|
|
1527
|
+
this.sqliteStore = sqliteStore;
|
|
1528
|
+
this.duckdbStore = duckdbStore;
|
|
1529
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
1530
|
+
}
|
|
1531
|
+
config;
|
|
1532
|
+
intervalHandle = null;
|
|
1533
|
+
running = false;
|
|
1534
|
+
stats = {
|
|
1535
|
+
lastSyncAt: null,
|
|
1536
|
+
eventsSynced: 0,
|
|
1537
|
+
sessionsSynced: 0,
|
|
1538
|
+
errors: 0,
|
|
1539
|
+
status: "idle"
|
|
1540
|
+
};
|
|
1541
|
+
/**
|
|
1542
|
+
* Start the sync worker
|
|
1543
|
+
*/
|
|
1544
|
+
start() {
|
|
1545
|
+
if (this.running)
|
|
1546
|
+
return;
|
|
1547
|
+
this.running = true;
|
|
1548
|
+
this.stats.status = "idle";
|
|
1549
|
+
this.syncNow().catch((err) => {
|
|
1550
|
+
console.error("[SyncWorker] Initial sync failed:", err);
|
|
1551
|
+
});
|
|
1552
|
+
this.intervalHandle = setInterval(() => {
|
|
1553
|
+
this.syncNow().catch((err) => {
|
|
1554
|
+
console.error("[SyncWorker] Periodic sync failed:", err);
|
|
1555
|
+
});
|
|
1556
|
+
}, this.config.intervalMs);
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Stop the sync worker
|
|
1560
|
+
*/
|
|
1561
|
+
stop() {
|
|
1562
|
+
this.running = false;
|
|
1563
|
+
this.stats.status = "stopped";
|
|
1564
|
+
if (this.intervalHandle) {
|
|
1565
|
+
clearInterval(this.intervalHandle);
|
|
1566
|
+
this.intervalHandle = null;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
/**
|
|
1570
|
+
* Trigger immediate sync
|
|
1571
|
+
*/
|
|
1572
|
+
async syncNow() {
|
|
1573
|
+
if (this.stats.status === "syncing") {
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
this.stats.status = "syncing";
|
|
1577
|
+
try {
|
|
1578
|
+
await this.syncEvents();
|
|
1579
|
+
await this.syncSessions();
|
|
1580
|
+
this.stats.lastSyncAt = /* @__PURE__ */ new Date();
|
|
1581
|
+
this.stats.status = "idle";
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
this.stats.errors++;
|
|
1584
|
+
this.stats.status = "error";
|
|
1585
|
+
throw error;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Sync events from SQLite to DuckDB
|
|
1590
|
+
*/
|
|
1591
|
+
async syncEvents() {
|
|
1592
|
+
const targetName = "duckdb_analytics";
|
|
1593
|
+
const position = await this.sqliteStore.getSyncPosition(targetName);
|
|
1594
|
+
const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
|
|
1595
|
+
let hasMore = true;
|
|
1596
|
+
let totalSynced = 0;
|
|
1597
|
+
while (hasMore) {
|
|
1598
|
+
const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
|
|
1599
|
+
if (events.length === 0) {
|
|
1600
|
+
hasMore = false;
|
|
1601
|
+
break;
|
|
1602
|
+
}
|
|
1603
|
+
await this.retryWithBackoff(async () => {
|
|
1604
|
+
for (const event of events) {
|
|
1605
|
+
await this.insertEventToDuckDB(event);
|
|
1606
|
+
}
|
|
1607
|
+
});
|
|
1608
|
+
totalSynced += events.length;
|
|
1609
|
+
const lastEvent = events[events.length - 1];
|
|
1610
|
+
await this.sqliteStore.updateSyncPosition(
|
|
1611
|
+
targetName,
|
|
1612
|
+
lastEvent.id,
|
|
1613
|
+
lastEvent.timestamp.toISOString()
|
|
1614
|
+
);
|
|
1615
|
+
hasMore = events.length === this.config.batchSize;
|
|
1616
|
+
}
|
|
1617
|
+
this.stats.eventsSynced += totalSynced;
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Sync sessions from SQLite to DuckDB
|
|
1621
|
+
*/
|
|
1622
|
+
async syncSessions() {
|
|
1623
|
+
const sessions = await this.sqliteStore.getAllSessions();
|
|
1624
|
+
for (const session of sessions) {
|
|
1625
|
+
await this.retryWithBackoff(async () => {
|
|
1626
|
+
await this.duckdbStore.upsertSession(session);
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
this.stats.sessionsSynced = sessions.length;
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* Insert a single event into DuckDB
|
|
1633
|
+
*/
|
|
1634
|
+
async insertEventToDuckDB(event) {
|
|
1635
|
+
await this.duckdbStore.append({
|
|
1636
|
+
eventType: event.eventType,
|
|
1637
|
+
sessionId: event.sessionId,
|
|
1638
|
+
timestamp: event.timestamp,
|
|
1639
|
+
content: event.content,
|
|
1640
|
+
metadata: event.metadata
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Retry operation with exponential backoff
|
|
1645
|
+
*/
|
|
1646
|
+
async retryWithBackoff(fn) {
|
|
1647
|
+
let lastError = null;
|
|
1648
|
+
for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
|
|
1649
|
+
try {
|
|
1650
|
+
return await fn();
|
|
1651
|
+
} catch (error) {
|
|
1652
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1653
|
+
if (attempt < this.config.maxRetries - 1) {
|
|
1654
|
+
const delay = this.config.retryDelayMs * Math.pow(2, attempt);
|
|
1655
|
+
await this.sleep(delay);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
throw lastError;
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Sleep utility
|
|
1663
|
+
*/
|
|
1664
|
+
sleep(ms) {
|
|
1665
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Get sync statistics
|
|
1669
|
+
*/
|
|
1670
|
+
getStats() {
|
|
1671
|
+
return { ...this.stats };
|
|
1672
|
+
}
|
|
1673
|
+
/**
|
|
1674
|
+
* Check if worker is running
|
|
1675
|
+
*/
|
|
1676
|
+
isRunning() {
|
|
1677
|
+
return this.running;
|
|
729
1678
|
}
|
|
730
1679
|
};
|
|
731
1680
|
|
|
@@ -957,7 +1906,7 @@ function getDefaultEmbedder() {
|
|
|
957
1906
|
}
|
|
958
1907
|
|
|
959
1908
|
// src/core/vector-outbox.ts
|
|
960
|
-
var
|
|
1909
|
+
var DEFAULT_CONFIG2 = {
|
|
961
1910
|
embeddingVersion: "v1",
|
|
962
1911
|
maxRetries: 3,
|
|
963
1912
|
stuckThresholdMs: 5 * 60 * 1e3,
|
|
@@ -966,7 +1915,7 @@ var DEFAULT_CONFIG = {
|
|
|
966
1915
|
};
|
|
967
1916
|
|
|
968
1917
|
// src/core/vector-worker.ts
|
|
969
|
-
var
|
|
1918
|
+
var DEFAULT_CONFIG3 = {
|
|
970
1919
|
batchSize: 32,
|
|
971
1920
|
pollIntervalMs: 1e3,
|
|
972
1921
|
maxRetries: 3
|
|
@@ -977,12 +1926,13 @@ var VectorWorker = class {
|
|
|
977
1926
|
embedder;
|
|
978
1927
|
config;
|
|
979
1928
|
running = false;
|
|
1929
|
+
stopping = false;
|
|
980
1930
|
pollTimeout = null;
|
|
981
1931
|
constructor(eventStore, vectorStore, embedder, config = {}) {
|
|
982
1932
|
this.eventStore = eventStore;
|
|
983
1933
|
this.vectorStore = vectorStore;
|
|
984
1934
|
this.embedder = embedder;
|
|
985
|
-
this.config = { ...
|
|
1935
|
+
this.config = { ...DEFAULT_CONFIG3, ...config };
|
|
986
1936
|
}
|
|
987
1937
|
/**
|
|
988
1938
|
* Start the worker polling loop
|
|
@@ -991,6 +1941,7 @@ var VectorWorker = class {
|
|
|
991
1941
|
if (this.running)
|
|
992
1942
|
return;
|
|
993
1943
|
this.running = true;
|
|
1944
|
+
this.stopping = false;
|
|
994
1945
|
this.poll();
|
|
995
1946
|
}
|
|
996
1947
|
/**
|
|
@@ -998,6 +1949,7 @@ var VectorWorker = class {
|
|
|
998
1949
|
*/
|
|
999
1950
|
stop() {
|
|
1000
1951
|
this.running = false;
|
|
1952
|
+
this.stopping = true;
|
|
1001
1953
|
if (this.pollTimeout) {
|
|
1002
1954
|
clearTimeout(this.pollTimeout);
|
|
1003
1955
|
this.pollTimeout = null;
|
|
@@ -1047,9 +1999,15 @@ var VectorWorker = class {
|
|
|
1047
1999
|
}
|
|
1048
2000
|
return successful.length;
|
|
1049
2001
|
} catch (error) {
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
2002
|
+
if (!this.stopping) {
|
|
2003
|
+
try {
|
|
2004
|
+
const allIds = items.map((i) => i.id);
|
|
2005
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2006
|
+
await this.eventStore.failOutboxItems(allIds, errorMessage);
|
|
2007
|
+
} catch (failError) {
|
|
2008
|
+
console.warn("Could not mark outbox items as failed (database may be closed)");
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
1053
2011
|
throw error;
|
|
1054
2012
|
}
|
|
1055
2013
|
}
|
|
@@ -1057,14 +2015,18 @@ var VectorWorker = class {
|
|
|
1057
2015
|
* Poll for new items
|
|
1058
2016
|
*/
|
|
1059
2017
|
async poll() {
|
|
1060
|
-
if (!this.running)
|
|
2018
|
+
if (!this.running || this.stopping)
|
|
1061
2019
|
return;
|
|
1062
2020
|
try {
|
|
1063
2021
|
await this.processBatch();
|
|
1064
2022
|
} catch (error) {
|
|
1065
|
-
|
|
2023
|
+
if (!this.stopping) {
|
|
2024
|
+
console.error("Vector worker error:", error);
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
if (this.running && !this.stopping) {
|
|
2028
|
+
this.pollTimeout = setTimeout(() => this.poll(), this.config.pollIntervalMs);
|
|
1066
2029
|
}
|
|
1067
|
-
this.pollTimeout = setTimeout(() => this.poll(), this.config.pollIntervalMs);
|
|
1068
2030
|
}
|
|
1069
2031
|
/**
|
|
1070
2032
|
* Process all pending items (blocking)
|
|
@@ -1091,7 +2053,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
|
|
|
1091
2053
|
}
|
|
1092
2054
|
|
|
1093
2055
|
// src/core/matcher.ts
|
|
1094
|
-
var
|
|
2056
|
+
var DEFAULT_CONFIG4 = {
|
|
1095
2057
|
weights: {
|
|
1096
2058
|
semanticSimilarity: 0.4,
|
|
1097
2059
|
ftsScore: 0.25,
|
|
@@ -1106,9 +2068,9 @@ var Matcher = class {
|
|
|
1106
2068
|
config;
|
|
1107
2069
|
constructor(config = {}) {
|
|
1108
2070
|
this.config = {
|
|
1109
|
-
...
|
|
2071
|
+
...DEFAULT_CONFIG4,
|
|
1110
2072
|
...config,
|
|
1111
|
-
weights: { ...
|
|
2073
|
+
weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
|
|
1112
2074
|
};
|
|
1113
2075
|
}
|
|
1114
2076
|
/**
|
|
@@ -1816,7 +2778,7 @@ function createSharedEventStore(dbPath) {
|
|
|
1816
2778
|
}
|
|
1817
2779
|
|
|
1818
2780
|
// src/core/shared-store.ts
|
|
1819
|
-
import { randomUUID as
|
|
2781
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
1820
2782
|
var SharedStore = class {
|
|
1821
2783
|
constructor(sharedEventStore) {
|
|
1822
2784
|
this.sharedEventStore = sharedEventStore;
|
|
@@ -1828,7 +2790,7 @@ var SharedStore = class {
|
|
|
1828
2790
|
* Promote a verified troubleshooting entry to shared storage
|
|
1829
2791
|
*/
|
|
1830
2792
|
async promoteEntry(input) {
|
|
1831
|
-
const entryId =
|
|
2793
|
+
const entryId = randomUUID3();
|
|
1832
2794
|
await dbRun(
|
|
1833
2795
|
this.db,
|
|
1834
2796
|
`INSERT INTO shared_troubleshooting (
|
|
@@ -2193,7 +3155,7 @@ function createSharedVectorStore(dbPath) {
|
|
|
2193
3155
|
}
|
|
2194
3156
|
|
|
2195
3157
|
// src/core/shared-promoter.ts
|
|
2196
|
-
import { randomUUID as
|
|
3158
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
2197
3159
|
var SharedPromoter = class {
|
|
2198
3160
|
constructor(sharedStore, sharedVectorStore, embedder, config) {
|
|
2199
3161
|
this.sharedStore = sharedStore;
|
|
@@ -2261,7 +3223,7 @@ var SharedPromoter = class {
|
|
|
2261
3223
|
const embeddingContent = this.createEmbeddingContent(input);
|
|
2262
3224
|
const embedding = await this.embedder.embed(embeddingContent);
|
|
2263
3225
|
await this.sharedVectorStore.upsert({
|
|
2264
|
-
id:
|
|
3226
|
+
id: randomUUID4(),
|
|
2265
3227
|
entryId,
|
|
2266
3228
|
entryType: "troubleshooting",
|
|
2267
3229
|
content: embeddingContent,
|
|
@@ -2401,7 +3363,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
|
|
|
2401
3363
|
}
|
|
2402
3364
|
|
|
2403
3365
|
// src/core/working-set-store.ts
|
|
2404
|
-
import { randomUUID as
|
|
3366
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
2405
3367
|
var WorkingSetStore = class {
|
|
2406
3368
|
constructor(eventStore, config) {
|
|
2407
3369
|
this.eventStore = eventStore;
|
|
@@ -2422,7 +3384,7 @@ var WorkingSetStore = class {
|
|
|
2422
3384
|
`INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
|
|
2423
3385
|
VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
|
|
2424
3386
|
[
|
|
2425
|
-
|
|
3387
|
+
randomUUID5(),
|
|
2426
3388
|
eventId,
|
|
2427
3389
|
relevanceScore,
|
|
2428
3390
|
JSON.stringify(topics || []),
|
|
@@ -2606,7 +3568,7 @@ function createWorkingSetStore(eventStore, config) {
|
|
|
2606
3568
|
}
|
|
2607
3569
|
|
|
2608
3570
|
// src/core/consolidated-store.ts
|
|
2609
|
-
import { randomUUID as
|
|
3571
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
2610
3572
|
var ConsolidatedStore = class {
|
|
2611
3573
|
constructor(eventStore) {
|
|
2612
3574
|
this.eventStore = eventStore;
|
|
@@ -2618,7 +3580,7 @@ var ConsolidatedStore = class {
|
|
|
2618
3580
|
* Create a new consolidated memory
|
|
2619
3581
|
*/
|
|
2620
3582
|
async create(input) {
|
|
2621
|
-
const memoryId =
|
|
3583
|
+
const memoryId = randomUUID6();
|
|
2622
3584
|
await dbRun(
|
|
2623
3585
|
this.db,
|
|
2624
3586
|
`INSERT INTO consolidated_memories
|
|
@@ -3145,7 +4107,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
|
|
|
3145
4107
|
}
|
|
3146
4108
|
|
|
3147
4109
|
// src/core/continuity-manager.ts
|
|
3148
|
-
import { randomUUID as
|
|
4110
|
+
import { randomUUID as randomUUID7 } from "crypto";
|
|
3149
4111
|
var ContinuityManager = class {
|
|
3150
4112
|
constructor(eventStore, config) {
|
|
3151
4113
|
this.eventStore = eventStore;
|
|
@@ -3299,7 +4261,7 @@ var ContinuityManager = class {
|
|
|
3299
4261
|
`INSERT INTO continuity_log
|
|
3300
4262
|
(log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
|
|
3301
4263
|
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
|
3302
|
-
[
|
|
4264
|
+
[randomUUID7(), previous.id, current.id, score, type]
|
|
3303
4265
|
);
|
|
3304
4266
|
}
|
|
3305
4267
|
/**
|
|
@@ -3408,7 +4370,7 @@ function createContinuityManager(eventStore, config) {
|
|
|
3408
4370
|
}
|
|
3409
4371
|
|
|
3410
4372
|
// src/core/graduation-worker.ts
|
|
3411
|
-
var
|
|
4373
|
+
var DEFAULT_CONFIG5 = {
|
|
3412
4374
|
evaluationIntervalMs: 3e5,
|
|
3413
4375
|
// 5 minutes
|
|
3414
4376
|
batchSize: 50,
|
|
@@ -3416,7 +4378,7 @@ var DEFAULT_CONFIG4 = {
|
|
|
3416
4378
|
// 1 hour cooldown between evaluations
|
|
3417
4379
|
};
|
|
3418
4380
|
var GraduationWorker = class {
|
|
3419
|
-
constructor(eventStore, graduation, config =
|
|
4381
|
+
constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
|
|
3420
4382
|
this.eventStore = eventStore;
|
|
3421
4383
|
this.graduation = graduation;
|
|
3422
4384
|
this.config = config;
|
|
@@ -3524,7 +4486,7 @@ function createGraduationWorker(eventStore, graduation, config) {
|
|
|
3524
4486
|
return new GraduationWorker(
|
|
3525
4487
|
eventStore,
|
|
3526
4488
|
graduation,
|
|
3527
|
-
{ ...
|
|
4489
|
+
{ ...DEFAULT_CONFIG5, ...config }
|
|
3528
4490
|
);
|
|
3529
4491
|
}
|
|
3530
4492
|
|
|
@@ -3548,7 +4510,11 @@ function getProjectStoragePath(projectPath) {
|
|
|
3548
4510
|
var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-registry.json");
|
|
3549
4511
|
var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
|
|
3550
4512
|
var MemoryService = class {
|
|
3551
|
-
|
|
4513
|
+
// Primary store: SQLite (WAL mode) - for hooks, always available
|
|
4514
|
+
sqliteStore;
|
|
4515
|
+
// Analytics store: DuckDB - for server reads (optional, synced from SQLite)
|
|
4516
|
+
analyticsStore;
|
|
4517
|
+
syncWorker = null;
|
|
3552
4518
|
vectorStore;
|
|
3553
4519
|
embedder;
|
|
3554
4520
|
matcher;
|
|
@@ -3579,17 +4545,39 @@ var MemoryService = class {
|
|
|
3579
4545
|
}
|
|
3580
4546
|
this.projectHash = config.projectHash || null;
|
|
3581
4547
|
this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
|
|
3582
|
-
this.
|
|
4548
|
+
this.sqliteStore = new SQLiteEventStore(
|
|
4549
|
+
path.join(storagePath, "events.sqlite"),
|
|
4550
|
+
{ readonly: this.readOnly }
|
|
4551
|
+
);
|
|
4552
|
+
const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
|
|
4553
|
+
if (!analyticsEnabled) {
|
|
4554
|
+
this.analyticsStore = null;
|
|
4555
|
+
} else if (this.readOnly) {
|
|
4556
|
+
try {
|
|
4557
|
+
this.analyticsStore = new EventStore(
|
|
4558
|
+
path.join(storagePath, "analytics.duckdb"),
|
|
4559
|
+
{ readOnly: true }
|
|
4560
|
+
);
|
|
4561
|
+
} catch {
|
|
4562
|
+
this.analyticsStore = null;
|
|
4563
|
+
}
|
|
4564
|
+
} else {
|
|
4565
|
+
this.analyticsStore = new EventStore(
|
|
4566
|
+
path.join(storagePath, "analytics.duckdb"),
|
|
4567
|
+
{ readOnly: false }
|
|
4568
|
+
);
|
|
4569
|
+
}
|
|
3583
4570
|
this.vectorStore = new VectorStore(path.join(storagePath, "vectors"));
|
|
3584
4571
|
this.embedder = config.embeddingModel ? new Embedder(config.embeddingModel) : getDefaultEmbedder();
|
|
3585
4572
|
this.matcher = getDefaultMatcher();
|
|
3586
4573
|
this.retriever = createRetriever(
|
|
3587
|
-
this.
|
|
4574
|
+
this.sqliteStore,
|
|
4575
|
+
// Interface compatible
|
|
3588
4576
|
this.vectorStore,
|
|
3589
4577
|
this.embedder,
|
|
3590
4578
|
this.matcher
|
|
3591
4579
|
);
|
|
3592
|
-
this.graduation = createGraduationPipeline(this.
|
|
4580
|
+
this.graduation = createGraduationPipeline(this.sqliteStore);
|
|
3593
4581
|
}
|
|
3594
4582
|
/**
|
|
3595
4583
|
* Initialize all components
|
|
@@ -3597,23 +4585,38 @@ var MemoryService = class {
|
|
|
3597
4585
|
async initialize() {
|
|
3598
4586
|
if (this.initialized)
|
|
3599
4587
|
return;
|
|
3600
|
-
await this.
|
|
4588
|
+
await this.sqliteStore.initialize();
|
|
4589
|
+
if (this.analyticsStore) {
|
|
4590
|
+
try {
|
|
4591
|
+
await this.analyticsStore.initialize();
|
|
4592
|
+
} catch (error) {
|
|
4593
|
+
console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
|
|
4594
|
+
}
|
|
4595
|
+
}
|
|
3601
4596
|
await this.vectorStore.initialize();
|
|
3602
4597
|
await this.embedder.initialize();
|
|
3603
4598
|
if (!this.readOnly) {
|
|
3604
4599
|
this.vectorWorker = createVectorWorker(
|
|
3605
|
-
this.
|
|
4600
|
+
this.sqliteStore,
|
|
3606
4601
|
this.vectorStore,
|
|
3607
4602
|
this.embedder
|
|
3608
4603
|
);
|
|
3609
4604
|
this.vectorWorker.start();
|
|
3610
4605
|
this.retriever.setGraduationPipeline(this.graduation);
|
|
3611
4606
|
this.graduationWorker = createGraduationWorker(
|
|
3612
|
-
this.
|
|
4607
|
+
this.sqliteStore,
|
|
3613
4608
|
this.graduation
|
|
3614
4609
|
);
|
|
3615
4610
|
this.graduationWorker.start();
|
|
3616
|
-
|
|
4611
|
+
if (this.analyticsStore) {
|
|
4612
|
+
this.syncWorker = new SyncWorker(
|
|
4613
|
+
this.sqliteStore,
|
|
4614
|
+
this.analyticsStore,
|
|
4615
|
+
{ intervalMs: 3e4, batchSize: 500 }
|
|
4616
|
+
);
|
|
4617
|
+
this.syncWorker.start();
|
|
4618
|
+
}
|
|
4619
|
+
const savedMode = await this.sqliteStore.getEndlessConfig("mode");
|
|
3617
4620
|
if (savedMode === "endless") {
|
|
3618
4621
|
this.endlessMode = "endless";
|
|
3619
4622
|
await this.initializeEndlessMode();
|
|
@@ -3654,7 +4657,7 @@ var MemoryService = class {
|
|
|
3654
4657
|
*/
|
|
3655
4658
|
async startSession(sessionId, projectPath) {
|
|
3656
4659
|
await this.initialize();
|
|
3657
|
-
await this.
|
|
4660
|
+
await this.sqliteStore.upsertSession({
|
|
3658
4661
|
id: sessionId,
|
|
3659
4662
|
startedAt: /* @__PURE__ */ new Date(),
|
|
3660
4663
|
projectPath
|
|
@@ -3665,7 +4668,7 @@ var MemoryService = class {
|
|
|
3665
4668
|
*/
|
|
3666
4669
|
async endSession(sessionId, summary) {
|
|
3667
4670
|
await this.initialize();
|
|
3668
|
-
await this.
|
|
4671
|
+
await this.sqliteStore.upsertSession({
|
|
3669
4672
|
id: sessionId,
|
|
3670
4673
|
endedAt: /* @__PURE__ */ new Date(),
|
|
3671
4674
|
summary
|
|
@@ -3676,7 +4679,7 @@ var MemoryService = class {
|
|
|
3676
4679
|
*/
|
|
3677
4680
|
async storeUserPrompt(sessionId, content, metadata) {
|
|
3678
4681
|
await this.initialize();
|
|
3679
|
-
const result = await this.
|
|
4682
|
+
const result = await this.sqliteStore.append({
|
|
3680
4683
|
eventType: "user_prompt",
|
|
3681
4684
|
sessionId,
|
|
3682
4685
|
timestamp: /* @__PURE__ */ new Date(),
|
|
@@ -3684,7 +4687,7 @@ var MemoryService = class {
|
|
|
3684
4687
|
metadata
|
|
3685
4688
|
});
|
|
3686
4689
|
if (result.success && !result.isDuplicate) {
|
|
3687
|
-
await this.
|
|
4690
|
+
await this.sqliteStore.enqueueForEmbedding(result.eventId, content);
|
|
3688
4691
|
}
|
|
3689
4692
|
return result;
|
|
3690
4693
|
}
|
|
@@ -3693,7 +4696,7 @@ var MemoryService = class {
|
|
|
3693
4696
|
*/
|
|
3694
4697
|
async storeAgentResponse(sessionId, content, metadata) {
|
|
3695
4698
|
await this.initialize();
|
|
3696
|
-
const result = await this.
|
|
4699
|
+
const result = await this.sqliteStore.append({
|
|
3697
4700
|
eventType: "agent_response",
|
|
3698
4701
|
sessionId,
|
|
3699
4702
|
timestamp: /* @__PURE__ */ new Date(),
|
|
@@ -3701,7 +4704,7 @@ var MemoryService = class {
|
|
|
3701
4704
|
metadata
|
|
3702
4705
|
});
|
|
3703
4706
|
if (result.success && !result.isDuplicate) {
|
|
3704
|
-
await this.
|
|
4707
|
+
await this.sqliteStore.enqueueForEmbedding(result.eventId, content);
|
|
3705
4708
|
}
|
|
3706
4709
|
return result;
|
|
3707
4710
|
}
|
|
@@ -3710,14 +4713,14 @@ var MemoryService = class {
|
|
|
3710
4713
|
*/
|
|
3711
4714
|
async storeSessionSummary(sessionId, summary) {
|
|
3712
4715
|
await this.initialize();
|
|
3713
|
-
const result = await this.
|
|
4716
|
+
const result = await this.sqliteStore.append({
|
|
3714
4717
|
eventType: "session_summary",
|
|
3715
4718
|
sessionId,
|
|
3716
4719
|
timestamp: /* @__PURE__ */ new Date(),
|
|
3717
4720
|
content: summary
|
|
3718
4721
|
});
|
|
3719
4722
|
if (result.success && !result.isDuplicate) {
|
|
3720
|
-
await this.
|
|
4723
|
+
await this.sqliteStore.enqueueForEmbedding(result.eventId, summary);
|
|
3721
4724
|
}
|
|
3722
4725
|
return result;
|
|
3723
4726
|
}
|
|
@@ -3727,7 +4730,7 @@ var MemoryService = class {
|
|
|
3727
4730
|
async storeToolObservation(sessionId, payload) {
|
|
3728
4731
|
await this.initialize();
|
|
3729
4732
|
const content = JSON.stringify(payload);
|
|
3730
|
-
const result = await this.
|
|
4733
|
+
const result = await this.sqliteStore.append({
|
|
3731
4734
|
eventType: "tool_observation",
|
|
3732
4735
|
sessionId,
|
|
3733
4736
|
timestamp: /* @__PURE__ */ new Date(),
|
|
@@ -3743,7 +4746,7 @@ var MemoryService = class {
|
|
|
3743
4746
|
payload.metadata || {},
|
|
3744
4747
|
payload.success
|
|
3745
4748
|
);
|
|
3746
|
-
await this.
|
|
4749
|
+
await this.sqliteStore.enqueueForEmbedding(result.eventId, embeddingContent);
|
|
3747
4750
|
}
|
|
3748
4751
|
return result;
|
|
3749
4752
|
}
|
|
@@ -3769,21 +4772,21 @@ var MemoryService = class {
|
|
|
3769
4772
|
*/
|
|
3770
4773
|
async getSessionHistory(sessionId) {
|
|
3771
4774
|
await this.initialize();
|
|
3772
|
-
return this.
|
|
4775
|
+
return this.sqliteStore.getSessionEvents(sessionId);
|
|
3773
4776
|
}
|
|
3774
4777
|
/**
|
|
3775
4778
|
* Get recent events
|
|
3776
4779
|
*/
|
|
3777
4780
|
async getRecentEvents(limit = 100) {
|
|
3778
4781
|
await this.initialize();
|
|
3779
|
-
return this.
|
|
4782
|
+
return this.sqliteStore.getRecentEvents(limit);
|
|
3780
4783
|
}
|
|
3781
4784
|
/**
|
|
3782
4785
|
* Get memory statistics
|
|
3783
4786
|
*/
|
|
3784
4787
|
async getStats() {
|
|
3785
4788
|
await this.initialize();
|
|
3786
|
-
const recentEvents = await this.
|
|
4789
|
+
const recentEvents = await this.sqliteStore.getRecentEvents(1e4);
|
|
3787
4790
|
const vectorCount = await this.vectorStore.count();
|
|
3788
4791
|
const levelStats = await this.graduation.getStats();
|
|
3789
4792
|
return {
|
|
@@ -3806,14 +4809,14 @@ var MemoryService = class {
|
|
|
3806
4809
|
*/
|
|
3807
4810
|
async getEventsByLevel(level, options) {
|
|
3808
4811
|
await this.initialize();
|
|
3809
|
-
return this.
|
|
4812
|
+
return this.sqliteStore.getEventsByLevel(level, options);
|
|
3810
4813
|
}
|
|
3811
4814
|
/**
|
|
3812
4815
|
* Get memory level for a specific event
|
|
3813
4816
|
*/
|
|
3814
4817
|
async getEventLevel(eventId) {
|
|
3815
4818
|
await this.initialize();
|
|
3816
|
-
return this.
|
|
4819
|
+
return this.sqliteStore.getEventLevel(eventId);
|
|
3817
4820
|
}
|
|
3818
4821
|
/**
|
|
3819
4822
|
* Format retrieval results as context for Claude
|
|
@@ -3907,21 +4910,21 @@ var MemoryService = class {
|
|
|
3907
4910
|
*/
|
|
3908
4911
|
async initializeEndlessMode() {
|
|
3909
4912
|
const config = await this.getEndlessConfig();
|
|
3910
|
-
this.workingSetStore = createWorkingSetStore(this.
|
|
3911
|
-
this.consolidatedStore = createConsolidatedStore(this.
|
|
4913
|
+
this.workingSetStore = createWorkingSetStore(this.sqliteStore, config);
|
|
4914
|
+
this.consolidatedStore = createConsolidatedStore(this.sqliteStore);
|
|
3912
4915
|
this.consolidationWorker = createConsolidationWorker(
|
|
3913
4916
|
this.workingSetStore,
|
|
3914
4917
|
this.consolidatedStore,
|
|
3915
4918
|
config
|
|
3916
4919
|
);
|
|
3917
|
-
this.continuityManager = createContinuityManager(this.
|
|
4920
|
+
this.continuityManager = createContinuityManager(this.sqliteStore, config);
|
|
3918
4921
|
this.consolidationWorker.start();
|
|
3919
4922
|
}
|
|
3920
4923
|
/**
|
|
3921
4924
|
* Get Endless Mode configuration
|
|
3922
4925
|
*/
|
|
3923
4926
|
async getEndlessConfig() {
|
|
3924
|
-
const savedConfig = await this.
|
|
4927
|
+
const savedConfig = await this.sqliteStore.getEndlessConfig("config");
|
|
3925
4928
|
return savedConfig || this.getDefaultEndlessConfig();
|
|
3926
4929
|
}
|
|
3927
4930
|
/**
|
|
@@ -3930,7 +4933,7 @@ var MemoryService = class {
|
|
|
3930
4933
|
async setEndlessConfig(config) {
|
|
3931
4934
|
const current = await this.getEndlessConfig();
|
|
3932
4935
|
const merged = { ...current, ...config };
|
|
3933
|
-
await this.
|
|
4936
|
+
await this.sqliteStore.setEndlessConfig("config", merged);
|
|
3934
4937
|
}
|
|
3935
4938
|
/**
|
|
3936
4939
|
* Set memory mode (session or endless)
|
|
@@ -3940,7 +4943,7 @@ var MemoryService = class {
|
|
|
3940
4943
|
if (mode === this.endlessMode)
|
|
3941
4944
|
return;
|
|
3942
4945
|
this.endlessMode = mode;
|
|
3943
|
-
await this.
|
|
4946
|
+
await this.sqliteStore.setEndlessConfig("mode", mode);
|
|
3944
4947
|
if (mode === "endless") {
|
|
3945
4948
|
await this.initializeEndlessMode();
|
|
3946
4949
|
} else {
|
|
@@ -3998,12 +5001,49 @@ var MemoryService = class {
|
|
|
3998
5001
|
return this.consolidatedStore.getAll({ limit });
|
|
3999
5002
|
}
|
|
4000
5003
|
/**
|
|
4001
|
-
*
|
|
5004
|
+
* Increment access count for memories that were used in prompts
|
|
5005
|
+
*/
|
|
5006
|
+
async incrementMemoryAccess(eventIds) {
|
|
5007
|
+
if (eventIds.length === 0)
|
|
5008
|
+
return;
|
|
5009
|
+
if (this.sqliteStore) {
|
|
5010
|
+
await this.sqliteStore.incrementAccessCount(eventIds);
|
|
5011
|
+
} else if (this.eventStore) {
|
|
5012
|
+
await this.eventStore.incrementAccessCount(eventIds);
|
|
5013
|
+
}
|
|
5014
|
+
}
|
|
5015
|
+
/**
|
|
5016
|
+
* Get most accessed memories from events
|
|
4002
5017
|
*/
|
|
4003
5018
|
async getMostAccessedMemories(limit = 10) {
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
5019
|
+
console.log("[getMostAccessedMemories] sqliteStore available:", !!this.sqliteStore);
|
|
5020
|
+
if (this.sqliteStore) {
|
|
5021
|
+
const events = await this.sqliteStore.getMostAccessed(limit);
|
|
5022
|
+
console.log("[getMostAccessedMemories] Got events from SQLite:", events.length);
|
|
5023
|
+
return events.map((event) => ({
|
|
5024
|
+
memoryId: event.id,
|
|
5025
|
+
summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
|
|
5026
|
+
topics: [],
|
|
5027
|
+
// Could extract topics from content if needed
|
|
5028
|
+
accessCount: event.access_count || 0,
|
|
5029
|
+
lastAccessed: event.last_accessed_at || null,
|
|
5030
|
+
confidence: 1,
|
|
5031
|
+
createdAt: event.timestamp
|
|
5032
|
+
}));
|
|
5033
|
+
}
|
|
5034
|
+
if (this.consolidatedStore) {
|
|
5035
|
+
const consolidated = await this.consolidatedStore.getMostAccessed(limit);
|
|
5036
|
+
return consolidated.map((m) => ({
|
|
5037
|
+
memoryId: m.memoryId,
|
|
5038
|
+
summary: m.summary,
|
|
5039
|
+
topics: m.topics,
|
|
5040
|
+
accessCount: m.accessCount,
|
|
5041
|
+
lastAccessed: m.accessedAt,
|
|
5042
|
+
confidence: m.confidence,
|
|
5043
|
+
createdAt: m.createdAt
|
|
5044
|
+
}));
|
|
5045
|
+
}
|
|
5046
|
+
return [];
|
|
4007
5047
|
}
|
|
4008
5048
|
/**
|
|
4009
5049
|
* Mark a consolidated memory as accessed
|
|
@@ -4128,10 +5168,16 @@ var MemoryService = class {
|
|
|
4128
5168
|
if (this.vectorWorker) {
|
|
4129
5169
|
this.vectorWorker.stop();
|
|
4130
5170
|
}
|
|
5171
|
+
if (this.syncWorker) {
|
|
5172
|
+
this.syncWorker.stop();
|
|
5173
|
+
}
|
|
4131
5174
|
if (this.sharedEventStore) {
|
|
4132
5175
|
await this.sharedEventStore.close();
|
|
4133
5176
|
}
|
|
4134
|
-
await this.
|
|
5177
|
+
await this.sqliteStore.close();
|
|
5178
|
+
if (this.analyticsStore) {
|
|
5179
|
+
await this.analyticsStore.close();
|
|
5180
|
+
}
|
|
4135
5181
|
}
|
|
4136
5182
|
/**
|
|
4137
5183
|
* Expand ~ to home directory
|
|
@@ -4147,7 +5193,11 @@ var serviceCache = /* @__PURE__ */ new Map();
|
|
|
4147
5193
|
function getReadOnlyMemoryService() {
|
|
4148
5194
|
return new MemoryService({
|
|
4149
5195
|
storagePath: "~/.claude-code/memory",
|
|
4150
|
-
readOnly: true
|
|
5196
|
+
readOnly: true,
|
|
5197
|
+
analyticsEnabled: false,
|
|
5198
|
+
// Use SQLite for reads (WAL supports concurrent readers)
|
|
5199
|
+
sharedStoreConfig: { enabled: false }
|
|
5200
|
+
// Skip shared store for now
|
|
4151
5201
|
});
|
|
4152
5202
|
}
|
|
4153
5203
|
function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
|
|
@@ -4157,7 +5207,10 @@ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
|
|
|
4157
5207
|
serviceCache.set(hash, new MemoryService({
|
|
4158
5208
|
storagePath,
|
|
4159
5209
|
projectHash: hash,
|
|
4160
|
-
|
|
5210
|
+
// Override shared store config - hooks don't need DuckDB
|
|
5211
|
+
sharedStoreConfig: sharedStoreConfig ?? { enabled: false },
|
|
5212
|
+
analyticsEnabled: false
|
|
5213
|
+
// Hooks don't need DuckDB
|
|
4161
5214
|
}));
|
|
4162
5215
|
}
|
|
4163
5216
|
return serviceCache.get(hash);
|
|
@@ -4453,6 +5506,7 @@ statsRouter.get("/levels/:level", async (c) => {
|
|
|
4453
5506
|
const { level } = c.req.param();
|
|
4454
5507
|
const limit = parseInt(c.req.query("limit") || "20", 10);
|
|
4455
5508
|
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
5509
|
+
const sort = c.req.query("sort") || "recent";
|
|
4456
5510
|
const validLevels = ["L0", "L1", "L2", "L3", "L4"];
|
|
4457
5511
|
if (!validLevels.includes(level)) {
|
|
4458
5512
|
return c.json({ error: `Invalid level. Must be one of: ${validLevels.join(", ")}` }, 400);
|
|
@@ -4460,9 +5514,27 @@ statsRouter.get("/levels/:level", async (c) => {
|
|
|
4460
5514
|
const memoryService = getReadOnlyMemoryService();
|
|
4461
5515
|
try {
|
|
4462
5516
|
await memoryService.initialize();
|
|
4463
|
-
|
|
5517
|
+
let events = await memoryService.getEventsByLevel(level, { limit: limit * 2, offset });
|
|
4464
5518
|
const stats = await memoryService.getStats();
|
|
4465
5519
|
const levelStat = stats.levelStats.find((s) => s.level === level);
|
|
5520
|
+
if (sort === "accessed") {
|
|
5521
|
+
const sqliteStore = memoryService.sqliteEventStore;
|
|
5522
|
+
if (sqliteStore) {
|
|
5523
|
+
const eventIds = events.map((e) => e.id);
|
|
5524
|
+
const accessedEvents = await sqliteStore.getMostAccessed(1e3);
|
|
5525
|
+
const accessMap = new Map(accessedEvents.map((e) => [e.id, e.access_count || 0]));
|
|
5526
|
+
events = events.map((e) => ({
|
|
5527
|
+
...e,
|
|
5528
|
+
accessCount: accessMap.get(e.id) || 0
|
|
5529
|
+
}));
|
|
5530
|
+
events.sort((a, b) => b.accessCount - a.accessCount);
|
|
5531
|
+
}
|
|
5532
|
+
} else if (sort === "oldest") {
|
|
5533
|
+
events.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
|
5534
|
+
} else {
|
|
5535
|
+
events.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
|
|
5536
|
+
}
|
|
5537
|
+
events = events.slice(0, limit);
|
|
4466
5538
|
return c.json({
|
|
4467
5539
|
level,
|
|
4468
5540
|
events: events.map((e) => ({
|
|
@@ -4471,7 +5543,8 @@ statsRouter.get("/levels/:level", async (c) => {
|
|
|
4471
5543
|
sessionId: e.sessionId,
|
|
4472
5544
|
timestamp: e.timestamp.toISOString(),
|
|
4473
5545
|
content: e.content.slice(0, 500) + (e.content.length > 500 ? "..." : ""),
|
|
4474
|
-
metadata: e.metadata
|
|
5546
|
+
metadata: e.metadata,
|
|
5547
|
+
accessCount: e.accessCount || 0
|
|
4475
5548
|
})),
|
|
4476
5549
|
total: levelStat?.count || 0,
|
|
4477
5550
|
limit,
|
|
@@ -4529,24 +5602,26 @@ statsRouter.get("/", async (c) => {
|
|
|
4529
5602
|
});
|
|
4530
5603
|
statsRouter.get("/most-accessed", async (c) => {
|
|
4531
5604
|
const limit = parseInt(c.req.query("limit") || "10", 10);
|
|
4532
|
-
const
|
|
4533
|
-
const memoryService = getMemoryServiceForProject(projectPath);
|
|
5605
|
+
const memoryService = getReadOnlyMemoryService();
|
|
4534
5606
|
try {
|
|
4535
5607
|
await memoryService.initialize();
|
|
5608
|
+
console.log("[most-accessed] Fetching most accessed memories, limit:", limit);
|
|
4536
5609
|
const memories = await memoryService.getMostAccessedMemories(limit);
|
|
5610
|
+
console.log("[most-accessed] Got memories:", memories.length);
|
|
4537
5611
|
return c.json({
|
|
4538
5612
|
memories: memories.map((m) => ({
|
|
4539
5613
|
memoryId: m.memoryId,
|
|
4540
5614
|
summary: m.summary,
|
|
4541
5615
|
topics: m.topics,
|
|
4542
5616
|
accessCount: m.accessCount,
|
|
4543
|
-
lastAccessed: m.
|
|
5617
|
+
lastAccessed: m.lastAccessed || null,
|
|
4544
5618
|
confidence: m.confidence,
|
|
4545
|
-
createdAt: m.createdAt.toISOString()
|
|
5619
|
+
createdAt: m.createdAt instanceof Date ? m.createdAt.toISOString() : m.createdAt
|
|
4546
5620
|
})),
|
|
4547
5621
|
total: memories.length
|
|
4548
5622
|
});
|
|
4549
5623
|
} catch (error) {
|
|
5624
|
+
console.error("[most-accessed] Error:", error);
|
|
4550
5625
|
return c.json({
|
|
4551
5626
|
memories: [],
|
|
4552
5627
|
total: 0,
|