n3memorycore-free-codex 1.9.2__py3-none-any.whl

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.
@@ -0,0 +1,429 @@
1
+ """DB layer: schema, CRUD, PRAGMAs, migrations (SQLite + sqlite-vec + FTS5)."""
2
+ import re
3
+ import sqlite3
4
+ import struct
5
+ from datetime import datetime, timezone
6
+
7
+ from ..paths import DB_PATH
8
+
9
+ EMBED_DIM = 768
10
+ FTS_TEXT_RULES = "2"
11
+ BUSY_TIMEOUT_SECONDS = 10
12
+ _FTS_MAX_TERMS = 40 # guards FTS5 against huge inputs
13
+
14
+ _FTS_PUNCT_RE = re.compile(r'[「」『』【】()()\[\]{}<>〈〉《》・、。,.!!??;;::\-―─…\'\"“”‘’]')
15
+ _FTS_CTRL_RE = re.compile(r'[\x00-\x1f\x7f]')
16
+ _CJK_CHAR_RE = re.compile(r'[々-〇぀-ヿ㐀-鿿豈-﫿가-힯]')
17
+ _CJK_RUN_RE = re.compile(r'([々-〇぀-ヿ㐀-鿿豈-﫿가-힯]+)')
18
+ _HIRAGANA_ONLY_RE = re.compile(r'^[぀-ゟー]+$')
19
+
20
+
21
+ # English function words (articles, pronouns, auxiliaries, question words, ...). They are in most
22
+ # English records, so a query made of them matched almost everything: "Who is the CEO of the
23
+ # company?" filled Top matches with 20 unrelated rows through `the` / `of` / `is`. Dropped from the
24
+ # keyword terms when config "fts_stopwords" is true (disabled by default).
25
+ EN_STOPWORDS = frozenset("""
26
+ a an the and or but if of to in on at by for with from as into onto about over under than then
27
+ so too very just is are was were be been being am do does did done have has had having it its
28
+ this that these those there here what which who whom whose when where why how i we you he she
29
+ they me us our ours your yours my mine their theirs his her hers them not no can could should
30
+ would will shall may might must also any some all each such only own same other more most
31
+ get got please tell know let lets
32
+ """.split())
33
+
34
+
35
+ def _drop_stopwords(terms):
36
+ kept = [t for t in terms if t.lower() not in EN_STOPWORDS]
37
+ return kept or terms # a query made only of function words is searched as typed
38
+
39
+
40
+ _FTS_ROLE_PREFIX_RE = re.compile(r'^\[(?:user|claude)(?: \d+/\d+)?\] ?')
41
+
42
+
43
+ def fts_index_text(content: str) -> str:
44
+ return _FTS_ROLE_PREFIX_RE.sub("", content, count=1).replace("[code omitted]", " ")
45
+
46
+
47
+ def strip_fts_punctuation(text: str) -> str:
48
+ cleaned = _FTS_PUNCT_RE.sub('', text)
49
+ return re.sub(r'\s+', ' ', cleaned).strip()
50
+
51
+
52
+ def fts_terms(query: str, stopwords: bool = False) -> list:
53
+ """The trigram search terms of ``query`` (in order, de-duplicated, at most 40)."""
54
+ terms, seen = [], set()
55
+ for word in _FTS_PUNCT_RE.sub(' ', _FTS_CTRL_RE.sub(' ', query or '')).split():
56
+ if len(word) > 3 and _CJK_CHAR_RE.search(word):
57
+ grams = [word[i:i + 3] for i in range(len(word) - 2)]
58
+ grams = [g for g in grams if not _HIRAGANA_ONLY_RE.match(g)]
59
+ elif len(word) >= 3:
60
+ grams = [word]
61
+ else:
62
+ grams = []
63
+ for g in grams:
64
+ if g not in seen:
65
+ seen.add(g)
66
+ terms.append(g)
67
+ if stopwords:
68
+ terms = _drop_stopwords(terms)
69
+ return terms[:_FTS_MAX_TERMS]
70
+
71
+
72
+ def _build_fts_query(query: str, stopwords: bool = False) -> str:
73
+ terms = fts_terms(query, stopwords)
74
+ if not terms:
75
+ return "" # -> skip the trigram search
76
+ return " OR ".join('"' + t.replace('"', '""') + '"' for t in terms)
77
+
78
+
79
+ def bigram_text(text: str) -> str:
80
+ """Text for memories_fts_bi: punctuation removed, CJK runs split into overlapping 2-char terms."""
81
+ cleaned = strip_fts_punctuation(text or "")
82
+ out = []
83
+ for part in _CJK_RUN_RE.split(cleaned):
84
+ if not part:
85
+ continue
86
+ if _CJK_CHAR_RE.match(part[0]):
87
+ if len(part) == 1:
88
+ out.append(part)
89
+ else:
90
+ out.extend(part[i:i + 2] for i in range(len(part) - 1))
91
+ else:
92
+ out.extend(part.split())
93
+ return " ".join(out)
94
+
95
+
96
+ def bigram_terms(query: str, stopwords: bool = False) -> list:
97
+ """The bigram-index search terms of ``query`` (in order, de-duplicated, at most 40)."""
98
+ cleaned = _FTS_PUNCT_RE.sub(' ', _FTS_CTRL_RE.sub(' ', query or ''))
99
+ terms, seen = [], set()
100
+ for word in cleaned.split():
101
+ if _CJK_CHAR_RE.search(word):
102
+ cand = bigram_text(word).split()
103
+ else:
104
+ cand = [word]
105
+ for t in cand:
106
+ if not _CJK_CHAR_RE.search(t) and len(t) < 2:
107
+ continue # a lone non-CJK character
108
+ if t not in seen:
109
+ seen.add(t)
110
+ terms.append(t)
111
+ non_hira = [t for t in terms if not _HIRAGANA_ONLY_RE.match(t)]
112
+ if non_hira:
113
+ terms = non_hira
114
+ if stopwords:
115
+ terms = _drop_stopwords(terms)
116
+ return terms[:_FTS_MAX_TERMS]
117
+
118
+
119
+ def build_bigram_query(query: str, stopwords: bool = False) -> str:
120
+ terms = bigram_terms(query, stopwords)
121
+ if not terms:
122
+ return ""
123
+ return " OR ".join('"' + t.replace('"', '""') + '"' for t in terms)
124
+
125
+
126
+ def serialize_vector(vec) -> bytes:
127
+ return struct.pack(f"{len(vec)}f", *[float(x) for x in vec])
128
+
129
+
130
+ def deserialize_vector(blob) -> list:
131
+ return list(struct.unpack(f"{len(blob) // 4}f", bytes(blob)))
132
+
133
+
134
+ def _load_vec_extension(conn):
135
+ try:
136
+ conn.enable_load_extension(True)
137
+ import sqlite_vec
138
+ sqlite_vec.load(conn)
139
+ except Exception as e: # noqa: BLE001
140
+ msg = str(e).lower()
141
+ if "already" in msg or "duplicate" in msg:
142
+ return
143
+ raise RuntimeError(f"sqlite-vec could not be loaded ({e}). Recovery: pip install sqlite-vec") from e
144
+ finally:
145
+ try:
146
+ conn.enable_load_extension(False)
147
+ except Exception: # noqa: BLE001
148
+ pass
149
+
150
+
151
+ def get_connection(db_path=None):
152
+ path = db_path or DB_PATH
153
+ conn = sqlite3.connect(path, check_same_thread=False, timeout=BUSY_TIMEOUT_SECONDS)
154
+ try:
155
+ conn.row_factory = sqlite3.Row
156
+ conn.execute("PRAGMA synchronous = FULL")
157
+ conn.execute("PRAGMA journal_mode = WAL")
158
+ conn.execute("PRAGMA wal_autocheckpoint = 1000")
159
+ _load_vec_extension(conn)
160
+ except BaseException:
161
+ conn.close()
162
+ raise
163
+ return conn
164
+
165
+
166
+ def init_db(conn):
167
+ conn.execute(
168
+ """CREATE TABLE IF NOT EXISTS memories (
169
+ id TEXT PRIMARY KEY,
170
+ content TEXT NOT NULL,
171
+ timestamp TEXT NOT NULL,
172
+ owner_id TEXT NOT NULL,
173
+ local_id TEXT,
174
+ agent_name TEXT,
175
+ session_id TEXT,
176
+ turn_id TEXT
177
+ )"""
178
+ )
179
+ migrate_schema(conn)
180
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_turn_id ON memories(turn_id)")
181
+ conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(content, tokenize='trigram')")
182
+ conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts_bi USING fts5(content, tokenize='unicode61')")
183
+ conn.execute(f"CREATE VIRTUAL TABLE IF NOT EXISTS memories_vec USING vec0(embedding float[{EMBED_DIM}])")
184
+ conn.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
185
+ conn.commit()
186
+
187
+
188
+ def migrate_schema(conn):
189
+ """Idempotently add missing columns; rebuild a legacy porter FTS table as trigram."""
190
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(memories)").fetchall()}
191
+ for col in ("local_id", "agent_name", "session_id", "turn_id"):
192
+ if col not in cols:
193
+ conn.execute(f"ALTER TABLE memories ADD COLUMN {col} TEXT")
194
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_turn_id ON memories(turn_id)")
195
+ row = conn.execute("SELECT sql FROM sqlite_master WHERE name='memories_fts'").fetchone()
196
+ if row and row[0] and "trigram" not in row[0].lower():
197
+ conn.execute("DROP TABLE memories_fts")
198
+ conn.execute("CREATE VIRTUAL TABLE memories_fts USING fts5(content, tokenize='trigram')")
199
+ for r in conn.execute("SELECT rowid, content FROM memories"):
200
+ conn.execute("INSERT INTO memories_fts(rowid, content) VALUES (?, ?)",
201
+ (r[0], strip_fts_punctuation(fts_index_text(r[1]))))
202
+ conn.commit()
203
+
204
+
205
+ # ---- meta ---------------------------------------------------------------
206
+
207
+ def get_meta(conn, key, default=None):
208
+ row = conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
209
+ return row[0] if row else default
210
+
211
+
212
+ def set_meta(conn, key, value):
213
+ conn.execute("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", (key, str(value)))
214
+
215
+
216
+ def delete_meta(conn, key):
217
+ conn.execute("DELETE FROM meta WHERE key=?", (key,))
218
+
219
+
220
+ _VEC_DIM_RE = re.compile(r"float\[\s*(\d+)\s*\]", re.IGNORECASE)
221
+
222
+
223
+ def vec_dim(conn):
224
+ """Dimension of memories_vec, read from the table definition (the N of float[N]); None if unknown."""
225
+ row = conn.execute("SELECT sql FROM sqlite_master WHERE name='memories_vec'").fetchone()
226
+ m = _VEC_DIM_RE.search(row[0] or "") if row else None
227
+ return int(m.group(1)) if m else None
228
+
229
+
230
+ # ---- writes ---------------------------------------------------------------
231
+
232
+ def insert_memory(conn, id, content, timestamp, owner_id, local_id=None, agent_name=None,
233
+ session_id=None, *, turn_id=None, embedding=None):
234
+ """INSERT + COMMIT immediately (Immutable Memory). Returns the memories rowid."""
235
+ try:
236
+ cur = conn.execute(
237
+ "INSERT INTO memories(id, content, timestamp, owner_id, local_id, agent_name, session_id, turn_id) "
238
+ "VALUES (?,?,?,?,?,?,?,?)",
239
+ (id, content, timestamp, owner_id, local_id, agent_name, session_id, turn_id),
240
+ )
241
+ rowid = cur.lastrowid
242
+ conn.execute("INSERT INTO memories_fts(rowid, content) VALUES (?, ?)",
243
+ (rowid, strip_fts_punctuation(fts_index_text(content))))
244
+ conn.execute("INSERT INTO memories_fts_bi(rowid, content) VALUES (?, ?)",
245
+ (rowid, bigram_text(fts_index_text(content))))
246
+ if embedding is not None:
247
+ conn.execute("INSERT INTO memories_vec(rowid, embedding) VALUES (?, ?)",
248
+ (rowid, serialize_vector(embedding)))
249
+ conn.commit()
250
+ return rowid
251
+ except BaseException:
252
+ conn.rollback()
253
+ raise
254
+
255
+
256
+ def insert_memory_once(conn, id, content, timestamp, owner_id, local_id=None, agent_name=None,
257
+ session_id=None, *, turn_id=None, embedding=None):
258
+ """insert_memory, but re-check for an exact duplicate inside a write lock (R04). None if duplicate."""
259
+ if conn.in_transaction:
260
+ conn.commit()
261
+ conn.execute("BEGIN IMMEDIATE")
262
+ try:
263
+ if check_exact_duplicate(conn, content, turn_id=turn_id):
264
+ conn.rollback()
265
+ return None
266
+ except BaseException:
267
+ conn.rollback()
268
+ raise
269
+ return insert_memory(conn, id, content, timestamp, owner_id, local_id, agent_name, session_id,
270
+ turn_id=turn_id, embedding=embedding)
271
+
272
+
273
+ def delete_memory(conn, memory_id):
274
+ row = conn.execute("SELECT rowid FROM memories WHERE id=?", (memory_id,)).fetchone()
275
+ if not row:
276
+ return False
277
+ rowid = row[0]
278
+ _load_vec_extension(conn)
279
+ try:
280
+ conn.execute("DELETE FROM memories_fts WHERE rowid=?", (rowid,))
281
+ conn.execute("DELETE FROM memories_fts_bi WHERE rowid=?", (rowid,))
282
+ conn.execute("DELETE FROM memories_vec WHERE rowid=?", (rowid,))
283
+ conn.execute("DELETE FROM memories WHERE rowid=?", (rowid,))
284
+ conn.commit()
285
+ except BaseException:
286
+ conn.rollback()
287
+ raise
288
+ return True
289
+
290
+
291
+ # ---- reads ----------------------------------------------------------------
292
+
293
+ def check_exact_duplicate(conn, content, turn_id=None):
294
+ if turn_id:
295
+ row = conn.execute("SELECT 1 FROM memories WHERE content=? AND turn_id=? LIMIT 1",
296
+ (content, turn_id)).fetchone()
297
+ else:
298
+ row = conn.execute("SELECT 1 FROM memories WHERE content=? LIMIT 1", (content,)).fetchone()
299
+ return row is not None
300
+
301
+
302
+ def count_memories(conn):
303
+ return conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
304
+
305
+
306
+ def get_all_memories(conn, since=None, until=None):
307
+ sql, args = "SELECT rowid, * FROM memories", []
308
+ where = []
309
+ if since:
310
+ where.append("timestamp >= ?")
311
+ args.append(since)
312
+ if until:
313
+ where.append("timestamp <= ?")
314
+ args.append(until)
315
+ if where:
316
+ sql += " WHERE " + " AND ".join(where)
317
+ sql += " ORDER BY rowid"
318
+ return [dict(r) for r in conn.execute(sql, args).fetchall()]
319
+
320
+
321
+ def get_memories_by_turn_id(conn, turn_id):
322
+ rows = conn.execute("SELECT rowid, * FROM memories WHERE turn_id=? ORDER BY rowid", (turn_id,)).fetchall()
323
+ return [dict(r) for r in rows]
324
+
325
+
326
+ def find_unindexed_memories(conn, limit=200):
327
+ """Rows missing from any search index. OFFSET is always 0.
328
+
329
+ The same result as a double LEFT JOIN, written as NOT IN over each index's rowids: a LEFT JOIN
330
+ looks up memories_vec (vec0) once per memories row, about 0.5 ms each on a file DB, so the check
331
+ grew with the DB (about 0.5 s at 1,600 records, 10 s at 20,000) and ran before every prompt
332
+ (--hook-submit calls /repair). Each NOT IN subquery is read once."""
333
+ rows = conn.execute(
334
+ "SELECT rowid, id, content, no_vec, no_fts FROM ("
335
+ "SELECT m.rowid AS rowid, m.id AS id, m.content AS content, "
336
+ "(m.rowid NOT IN (SELECT rowid FROM memories_vec)) AS no_vec, "
337
+ "(m.rowid NOT IN (SELECT rowid FROM memories_fts)) AS no_fts "
338
+ "FROM memories m) WHERE no_vec OR no_fts OR rowid NOT IN (SELECT rowid FROM memories_fts_bi) ORDER BY rowid LIMIT ?",
339
+ (limit,),
340
+ ).fetchall()
341
+ return [dict(r) for r in rows]
342
+
343
+
344
+ def _time_clause(since, until, col="timestamp"):
345
+ where, args = [], []
346
+ if since:
347
+ where.append(f"{col} >= ?")
348
+ args.append(since)
349
+ if until:
350
+ where.append(f"{col} <= ?")
351
+ args.append(until)
352
+ return where, args
353
+
354
+
355
+ def _rows_by_rowid(conn, rowids):
356
+ if not rowids:
357
+ return {}
358
+ out = {}
359
+ ids = list(rowids)
360
+ for i in range(0, len(ids), 500):
361
+ part = ids[i:i + 500]
362
+ q = ",".join("?" * len(part))
363
+ for r in conn.execute(f"SELECT rowid AS rowid, * FROM memories WHERE rowid IN ({q})", part).fetchall():
364
+ out[r["rowid"]] = dict(r)
365
+ return out
366
+
367
+
368
+ def search_vector(conn, query_vec, k=60, since=None, until=None):
369
+ """KNN over memories_vec. Returns [(memory dict, L2 distance)]. With a time range, KNN runs only over
370
+ the filtered rowids (two steps); falls back to an exact scan if `rowid IN (subquery)` is unsupported."""
371
+ blob = serialize_vector(query_vec)
372
+ where, targs = _time_clause(since, until)
373
+ if where:
374
+ try:
375
+ sub = "SELECT rowid FROM memories WHERE " + " AND ".join(where)
376
+ rows = conn.execute(
377
+ "SELECT rowid, distance FROM memories_vec WHERE embedding MATCH ? AND k = ? "
378
+ f"AND rowid IN ({sub})", [blob, k] + targs).fetchall()
379
+ except sqlite3.OperationalError:
380
+ return _search_vector_exact(conn, query_vec, k, since, until)
381
+ else:
382
+ rows = conn.execute("SELECT rowid, distance FROM memories_vec WHERE embedding MATCH ? AND k = ?",
383
+ (blob, k)).fetchall()
384
+ mem = _rows_by_rowid(conn, [r[0] for r in rows])
385
+ return [(mem[r[0]], r[1]) for r in rows if r[0] in mem]
386
+
387
+
388
+ def _search_vector_exact(conn, query_vec, k=60, since=None, until=None):
389
+ blob = serialize_vector(query_vec)
390
+ where, targs = _time_clause(since, until, "m.timestamp")
391
+ sql = ("SELECT mv.rowid AS rid, vec_distance_l2(mv.embedding, ?) AS d FROM memories_vec mv "
392
+ "JOIN memories m ON m.rowid = mv.rowid")
393
+ if where:
394
+ sql += " WHERE " + " AND ".join(where)
395
+ sql += " ORDER BY d LIMIT ?"
396
+ rows = conn.execute(sql, [blob] + targs + [k]).fetchall()
397
+ mem = _rows_by_rowid(conn, [r[0] for r in rows])
398
+ return [(mem[r[0]], r[1]) for r in rows if r[0] in mem]
399
+
400
+
401
+ def _search_fts_table(conn, table, match, limit, since, until):
402
+ where, targs = _time_clause(since, until, "m.timestamp")
403
+ sql = (f"SELECT f.rowid AS rid, f.s AS s FROM (SELECT rowid, bm25({table}) AS s FROM {table} "
404
+ f"WHERE {table} MATCH ?) f JOIN memories m ON m.rowid = f.rowid")
405
+ if where:
406
+ sql += " WHERE " + " AND ".join(where)
407
+ sql += " ORDER BY f.s LIMIT ?"
408
+ rows = conn.execute(sql, [match] + targs + [limit]).fetchall()
409
+ mem = _rows_by_rowid(conn, [r[0] for r in rows])
410
+ return [(mem[r[0]], r[1]) for r in rows if r[0] in mem]
411
+
412
+
413
+ def search_fts(conn, query, limit=60, since=None, until=None, stopwords=False):
414
+ """Trigram keyword search. Returns [(memory dict, raw bm25 (negative = better))]."""
415
+ match = _build_fts_query(query, stopwords)
416
+ if not match:
417
+ return []
418
+ return _search_fts_table(conn, "memories_fts", match, limit, since, until)
419
+
420
+
421
+ def search_fts_bigram(conn, query, limit=60, since=None, until=None, stopwords=False):
422
+ match = build_bigram_query(query, stopwords)
423
+ if not match:
424
+ return []
425
+ return _search_fts_table(conn, "memories_fts_bi", match, limit, since, until)
426
+
427
+
428
+ def utc_now_iso():
429
+ return datetime.now(timezone.utc).isoformat()