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.
- n3memorycore_free_codex/__init__.py +3 -0
- n3memorycore_free_codex/codex_entry.py +203 -0
- n3memorycore_free_codex/codex_install.py +131 -0
- n3memorycore_free_codex/core/__init__.py +0 -0
- n3memorycore_free_codex/core/database.py +429 -0
- n3memorycore_free_codex/core/processor.py +613 -0
- n3memorycore_free_codex/n3memory.py +1977 -0
- n3memorycore_free_codex/paths.py +30 -0
- n3memorycore_free_codex/project.py +24 -0
- n3memorycore_free_codex-1.9.2.dist-info/METADATA +424 -0
- n3memorycore_free_codex-1.9.2.dist-info/RECORD +16 -0
- n3memorycore_free_codex-1.9.2.dist-info/WHEEL +5 -0
- n3memorycore_free_codex-1.9.2.dist-info/entry_points.txt +4 -0
- n3memorycore_free_codex-1.9.2.dist-info/licenses/LICENSE +190 -0
- n3memorycore_free_codex-1.9.2.dist-info/licenses/NOTICE +4 -0
- n3memorycore_free_codex-1.9.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1977 @@
|
|
|
1
|
+
"""N3MemoryCore (Free): CLI + resident FastAPI memory server.
|
|
2
|
+
|
|
3
|
+
Everything is saved by hooks (UserPromptSubmit + Stop). Saving is immediate and physical
|
|
4
|
+
(INSERT + COMMIT per record, PRAGMA synchronous=FULL): the "Immutable Memory" invariant.
|
|
5
|
+
"""
|
|
6
|
+
import os as _os
|
|
7
|
+
import sys as _sys
|
|
8
|
+
|
|
9
|
+
if __name__ == "__main__":
|
|
10
|
+
# Safe import path. Started as `python -m <package>.<module>`, Python has put the current folder
|
|
11
|
+
# first on sys.path, so a file there named like a module imported below would run inside this
|
|
12
|
+
# program. Drop that entry, unless this package itself lives in the current folder (a source
|
|
13
|
+
# checkout run in place). Nothing else may be imported before this block.
|
|
14
|
+
try:
|
|
15
|
+
_cwd = _os.path.normcase(_os.path.abspath(_os.getcwd()))
|
|
16
|
+
_pkg_parent = _os.path.normcase(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))))
|
|
17
|
+
if _sys.path and _os.path.normcase(_os.path.abspath(_sys.path[0])) == _cwd and _pkg_parent != _cwd:
|
|
18
|
+
del _sys.path[0]
|
|
19
|
+
except Exception: # noqa: BLE001
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import math
|
|
26
|
+
import re
|
|
27
|
+
import sqlite3
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
import tempfile
|
|
31
|
+
import threading
|
|
32
|
+
import time
|
|
33
|
+
import urllib.error
|
|
34
|
+
import urllib.request
|
|
35
|
+
import uuid
|
|
36
|
+
from contextlib import asynccontextmanager
|
|
37
|
+
from datetime import datetime, timedelta, timezone
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
from .paths import (
|
|
41
|
+
HOME_DIR, MEMORY_DIR, DB_PATH, PID_FILE, AUDIT_LOG, CONFIG_FILE, NOTICES_FILE,
|
|
42
|
+
SERVER_LOG, SERVER_START_FAILED_FILE, python_cmd,
|
|
43
|
+
)
|
|
44
|
+
from .core.database import (
|
|
45
|
+
get_connection, init_db, migrate_schema, insert_memory, insert_memory_once,
|
|
46
|
+
check_exact_duplicate, search_vector, find_unindexed_memories,
|
|
47
|
+
strip_fts_punctuation, fts_index_text, FTS_TEXT_RULES,
|
|
48
|
+
serialize_vector, bigram_text, get_meta, set_meta, delete_meta,
|
|
49
|
+
count_memories, get_memories_by_turn_id, vec_dim,
|
|
50
|
+
)
|
|
51
|
+
from .core.processor import (
|
|
52
|
+
embed_passage, embed_query, cosine_sim_from_l2, hybrid_search,
|
|
53
|
+
chunk_text, add_chunk_prefixes, purify_text, render_memory_context, sanitize_surrogates,
|
|
54
|
+
)
|
|
55
|
+
from .core import processor as _processor
|
|
56
|
+
from .core import database as _database
|
|
57
|
+
|
|
58
|
+
from uuid_extensions import uuid7
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _new_id():
|
|
62
|
+
return str(uuid7())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ============================================================ constants
|
|
66
|
+
|
|
67
|
+
DEFAULT_CONFIG = {
|
|
68
|
+
"owner_id": None,
|
|
69
|
+
"local_id": None,
|
|
70
|
+
"bind_host": "127.0.0.1",
|
|
71
|
+
"server_port": 18526,
|
|
72
|
+
"connect_server_port": None,
|
|
73
|
+
"connect_server_root": None,
|
|
74
|
+
"embed_model": "intfloat/multilingual-e5-base",
|
|
75
|
+
"half_life_days": 90,
|
|
76
|
+
"bm25_min_threshold": 0.1,
|
|
77
|
+
"search_result_limit": 20,
|
|
78
|
+
"min_score": 0.2,
|
|
79
|
+
"search_query_max_chars": 2000,
|
|
80
|
+
"vector_min_cos": 0.85,
|
|
81
|
+
"relative_min_score_ratio": 0.6,
|
|
82
|
+
"min_results": 3,
|
|
83
|
+
"pair_top_n": 3,
|
|
84
|
+
"pair_max_chars": 3000,
|
|
85
|
+
"version_order_enabled": True,
|
|
86
|
+
"version_sim_threshold": 0.98,
|
|
87
|
+
"version_min_chars": 100,
|
|
88
|
+
"reply_sim_rerank_enabled": False,
|
|
89
|
+
"reply_sim_alpha": 0.3,
|
|
90
|
+
"reply_sim_floor": 0.80,
|
|
91
|
+
"reply_sim_span": 0.15,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
_INT_RANGES = {
|
|
95
|
+
"server_port": (1, 65535), "search_result_limit": (1, 1365),
|
|
96
|
+
"pair_top_n": (1, None), "pair_max_chars": (1, None), "search_query_max_chars": (1, None),
|
|
97
|
+
"version_min_chars": (1, None), "min_results": (0, None),
|
|
98
|
+
}
|
|
99
|
+
_UNIT_KEYS = {"min_score", "vector_min_cos", "relative_min_score_ratio", "version_sim_threshold",
|
|
100
|
+
"reply_sim_alpha", "reply_sim_floor"}
|
|
101
|
+
|
|
102
|
+
AGENT_NAME = "codex"
|
|
103
|
+
NOTICE_INTERVAL_SECONDS = 86400
|
|
104
|
+
AUDIT_ROTATE_BYTES = 50 * 1024 * 1024
|
|
105
|
+
HTTP_TIMEOUT = 30
|
|
106
|
+
SERVER_WAIT_SECONDS = 60
|
|
107
|
+
|
|
108
|
+
_FOREIGN_SERVER_ROOT = None
|
|
109
|
+
_QUICK_CHECKED = False
|
|
110
|
+
_SERVER_PORT = None # the port this server process listens on (Host check)
|
|
111
|
+
_SERVER_STATE = {}
|
|
112
|
+
_CFG_CACHE = None
|
|
113
|
+
_CFG_SOURCE = None # config.json content _CFG_CACHE comes from (bytes; None: no readable file)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _norm(p):
|
|
117
|
+
return _os.path.normcase(_os.path.abspath(p))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _reconfigure_streams():
|
|
121
|
+
for name in ("stdin", "stdout", "stderr"):
|
|
122
|
+
s = getattr(sys, name, None)
|
|
123
|
+
if s is not None and hasattr(s, "reconfigure"):
|
|
124
|
+
try:
|
|
125
|
+
s.reconfigure(encoding="utf-8", newline="\n")
|
|
126
|
+
except Exception: # noqa: BLE001
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _ensure_dirs():
|
|
131
|
+
_os.makedirs(MEMORY_DIR, exist_ok=True)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _atomic_write_json(path, obj):
|
|
135
|
+
d = _os.path.dirname(path)
|
|
136
|
+
_os.makedirs(d, exist_ok=True)
|
|
137
|
+
fd, tmp = tempfile.mkstemp(dir=d, prefix="." + _os.path.basename(path) + ".")
|
|
138
|
+
try:
|
|
139
|
+
text = json.dumps(obj, indent=2, ensure_ascii=False) + "\n"
|
|
140
|
+
with _os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
141
|
+
f.write(text)
|
|
142
|
+
_os.replace(tmp, path)
|
|
143
|
+
return text
|
|
144
|
+
except BaseException:
|
|
145
|
+
try:
|
|
146
|
+
_os.unlink(tmp)
|
|
147
|
+
except OSError:
|
|
148
|
+
pass
|
|
149
|
+
raise
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ============================================================ audit + notices
|
|
153
|
+
|
|
154
|
+
def _audit_append(rec):
|
|
155
|
+
try:
|
|
156
|
+
_ensure_dirs()
|
|
157
|
+
with open(AUDIT_LOG, "a", encoding="utf-8", errors="replace") as f:
|
|
158
|
+
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
159
|
+
return True
|
|
160
|
+
except Exception as e: # noqa: BLE001
|
|
161
|
+
print(f"N3MC: could not write audit.log ({type(e).__name__}: {e})", file=sys.stderr)
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _notices_read():
|
|
167
|
+
try:
|
|
168
|
+
with open(NOTICES_FILE, "r", encoding="utf-8") as f:
|
|
169
|
+
d = json.load(f)
|
|
170
|
+
return d if isinstance(d, dict) else {}
|
|
171
|
+
except Exception: # noqa: BLE001
|
|
172
|
+
return {}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _notices_write(d):
|
|
176
|
+
try:
|
|
177
|
+
_atomic_write_json(NOTICES_FILE, d)
|
|
178
|
+
except Exception as e: # noqa: BLE001
|
|
179
|
+
print(f"N3MC: could not write notices.json ({e})", file=sys.stderr)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _notify(key, message):
|
|
183
|
+
print(f"N3MC: {message}", file=sys.stderr)
|
|
184
|
+
d = _notices_read()
|
|
185
|
+
ent = d.get(key)
|
|
186
|
+
if isinstance(ent, dict) and ent.get("message") == message:
|
|
187
|
+
return
|
|
188
|
+
d[key] = {"message": message, "last_shown": None}
|
|
189
|
+
_notices_write(d)
|
|
190
|
+
_audit_append({"ts": datetime.now(timezone.utc).isoformat(), "hook": "notice", "key": key, "message": message})
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _clear_notice(key):
|
|
194
|
+
d = _notices_read()
|
|
195
|
+
if key in d:
|
|
196
|
+
del d[key]
|
|
197
|
+
_notices_write(d)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _take_notices():
|
|
201
|
+
d = _notices_read()
|
|
202
|
+
now, out, changed = time.time(), [], False
|
|
203
|
+
for key, ent in d.items():
|
|
204
|
+
if not isinstance(ent, dict):
|
|
205
|
+
continue
|
|
206
|
+
last = ent.get("last_shown")
|
|
207
|
+
if type(last) not in (int, float) or not now - NOTICE_INTERVAL_SECONDS < last <= now:
|
|
208
|
+
out.append(ent.get("message", ""))
|
|
209
|
+
ent["last_shown"] = now
|
|
210
|
+
changed = True
|
|
211
|
+
if changed:
|
|
212
|
+
_notices_write(d)
|
|
213
|
+
return [m for m in out if m]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ============================================================ config
|
|
217
|
+
|
|
218
|
+
def _config_value_ok(key, value):
|
|
219
|
+
if key == "connect_server_port":
|
|
220
|
+
return value is None or (type(value) is int and 1 <= value <= 65535)
|
|
221
|
+
if key == "connect_server_root":
|
|
222
|
+
return value is None or (isinstance(value, str) and _os.path.isabs(value) and "\0" not in value)
|
|
223
|
+
if key not in DEFAULT_CONFIG or DEFAULT_CONFIG[key] is None:
|
|
224
|
+
return True
|
|
225
|
+
default = DEFAULT_CONFIG[key]
|
|
226
|
+
if isinstance(default, bool):
|
|
227
|
+
return isinstance(value, bool)
|
|
228
|
+
if isinstance(default, str):
|
|
229
|
+
return isinstance(value, str)
|
|
230
|
+
if isinstance(value, bool):
|
|
231
|
+
return False
|
|
232
|
+
if key in _INT_RANGES:
|
|
233
|
+
lo, hi = _INT_RANGES[key]
|
|
234
|
+
return isinstance(value, int) and value >= lo and (hi is None or value <= hi)
|
|
235
|
+
if not isinstance(value, (int, float)):
|
|
236
|
+
return False
|
|
237
|
+
if key in _UNIT_KEYS:
|
|
238
|
+
return 0 <= value <= 1
|
|
239
|
+
if key in ("half_life_days", "reply_sim_span"):
|
|
240
|
+
return value > 0
|
|
241
|
+
if key == "bm25_min_threshold":
|
|
242
|
+
return value >= 0
|
|
243
|
+
return True
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class _ConfigReadError(Exception):
|
|
247
|
+
"""config.json could not be parsed; `raw` holds the bytes read (None when the file could not be read)."""
|
|
248
|
+
|
|
249
|
+
def __init__(self, cause, raw):
|
|
250
|
+
super().__init__(str(cause))
|
|
251
|
+
self.raw = raw
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _read_config_file():
|
|
255
|
+
"""Read config.json -> (parsed JSON, bytes read). A file touched in the last 2 s is retried (it may
|
|
256
|
+
still be being written). On failure raises _ConfigReadError carrying the bytes of the last read."""
|
|
257
|
+
attempts = 1
|
|
258
|
+
try:
|
|
259
|
+
if time.time() - _os.path.getmtime(CONFIG_FILE) <= 2:
|
|
260
|
+
attempts = 20
|
|
261
|
+
except OSError:
|
|
262
|
+
pass
|
|
263
|
+
last, last_raw = None, None
|
|
264
|
+
for i in range(attempts):
|
|
265
|
+
raw = None
|
|
266
|
+
try:
|
|
267
|
+
with open(CONFIG_FILE, "rb") as f:
|
|
268
|
+
raw = f.read()
|
|
269
|
+
return json.loads(raw.decode("utf-8")), raw
|
|
270
|
+
except Exception as e: # noqa: BLE001
|
|
271
|
+
last, last_raw = e, raw
|
|
272
|
+
if i < attempts - 1:
|
|
273
|
+
time.sleep(0.05)
|
|
274
|
+
raise _ConfigReadError(last, last_raw)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
CONFIG_LOCK_WAIT_SECONDS = 10
|
|
278
|
+
CONFIG_LOCK_STALE_SECONDS = 10
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _config_lock_path():
|
|
282
|
+
return _os.path.join(MEMORY_DIR, "config.lock")
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _acquire_config_lock():
|
|
286
|
+
"""Take .memory/config.lock (exclusive create; retry every 0.05 s for up to 10 s; a lock older than
|
|
287
|
+
10 s is stale and removed). Returns True when the lock is held."""
|
|
288
|
+
path = _config_lock_path()
|
|
289
|
+
end = time.time() + CONFIG_LOCK_WAIT_SECONDS
|
|
290
|
+
while True:
|
|
291
|
+
try:
|
|
292
|
+
fd = _os.open(path, _os.O_CREAT | _os.O_EXCL | _os.O_WRONLY)
|
|
293
|
+
try:
|
|
294
|
+
_os.write(fd, str(_os.getpid()).encode("ascii"))
|
|
295
|
+
finally:
|
|
296
|
+
_os.close(fd)
|
|
297
|
+
return True
|
|
298
|
+
except FileExistsError:
|
|
299
|
+
try:
|
|
300
|
+
if time.time() - _os.path.getmtime(path) > CONFIG_LOCK_STALE_SECONDS:
|
|
301
|
+
_os.unlink(path)
|
|
302
|
+
continue
|
|
303
|
+
except OSError:
|
|
304
|
+
continue # removed meanwhile: try again at once
|
|
305
|
+
except OSError:
|
|
306
|
+
return False
|
|
307
|
+
if time.time() >= end:
|
|
308
|
+
return False
|
|
309
|
+
time.sleep(0.05)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _release_config_lock():
|
|
313
|
+
try:
|
|
314
|
+
_os.unlink(_config_lock_path())
|
|
315
|
+
except OSError:
|
|
316
|
+
pass
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _merge_config(raw):
|
|
320
|
+
"""Validated settings of a parsed config.json (defaults for missing keys) and the bad keys."""
|
|
321
|
+
bad, merged = [], {}
|
|
322
|
+
for k, v in raw.items():
|
|
323
|
+
if k in DEFAULT_CONFIG and not _config_value_ok(k, v):
|
|
324
|
+
bad.append(k)
|
|
325
|
+
else:
|
|
326
|
+
merged[k] = v
|
|
327
|
+
for k, v in DEFAULT_CONFIG.items():
|
|
328
|
+
if k not in merged:
|
|
329
|
+
merged[k] = v
|
|
330
|
+
return merged, bad
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _id_ok(v):
|
|
334
|
+
return isinstance(v, str) and bool(v)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _needs_fill(raw):
|
|
338
|
+
return any(k not in raw for k in DEFAULT_CONFIG) or not all(_id_ok(raw.get(k)) for k in ("owner_id", "local_id"))
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _recover_id(column):
|
|
342
|
+
try:
|
|
343
|
+
if not _os.path.exists(DB_PATH):
|
|
344
|
+
return None
|
|
345
|
+
conn = sqlite3.connect(DB_PATH, timeout=5)
|
|
346
|
+
try:
|
|
347
|
+
row = conn.execute(f"SELECT {column} FROM memories GROUP BY {column} "
|
|
348
|
+
"ORDER BY COUNT(*) DESC LIMIT 1").fetchone()
|
|
349
|
+
finally:
|
|
350
|
+
conn.close()
|
|
351
|
+
return row[0] if row and row[0] else None
|
|
352
|
+
except Exception: # noqa: BLE001
|
|
353
|
+
return None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _fill_ids_in_memory(merged):
|
|
357
|
+
for idk in ("owner_id", "local_id"):
|
|
358
|
+
if not _id_ok(merged.get(idk)):
|
|
359
|
+
merged[idk] = _recover_id(idk) or str(uuid.uuid4())
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _notify_bad(bad):
|
|
363
|
+
_notify("config_type", "These config.json items have the wrong type or are out of range and were "
|
|
364
|
+
f"ignored (defaults used): {', '.join(sorted(bad))}")
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _fill_config_locked(raw, src):
|
|
368
|
+
"""Add the missing keys / IDs of an existing, valid config.json under .memory/config.lock (review #2):
|
|
369
|
+
read the file again inside the lock and add only what is still missing, so every process ends with
|
|
370
|
+
the IDs on disk. Returns (settings, the config.json content they come from)."""
|
|
371
|
+
locked = _acquire_config_lock()
|
|
372
|
+
try:
|
|
373
|
+
try:
|
|
374
|
+
raw2, src2 = _read_config_file()
|
|
375
|
+
if isinstance(raw2, dict):
|
|
376
|
+
raw, src = raw2, src2
|
|
377
|
+
except Exception: # noqa: BLE001
|
|
378
|
+
pass # vanished or unreadable now: work from the first read, as before
|
|
379
|
+
merged, bad = _merge_config(raw)
|
|
380
|
+
if bad: # edited meanwhile with a bad value: leave the file alone
|
|
381
|
+
_fill_ids_in_memory(merged)
|
|
382
|
+
_notify_bad(bad)
|
|
383
|
+
return merged, src
|
|
384
|
+
if not _needs_fill(raw):
|
|
385
|
+
return merged, src
|
|
386
|
+
_fill_ids_in_memory(merged)
|
|
387
|
+
out = dict(raw)
|
|
388
|
+
for k, v in merged.items():
|
|
389
|
+
if k not in out or (k in ("owner_id", "local_id") and out.get(k) != v):
|
|
390
|
+
out[k] = v
|
|
391
|
+
try:
|
|
392
|
+
src = _atomic_write_json(CONFIG_FILE, out).encode("utf-8")
|
|
393
|
+
except Exception as e: # noqa: BLE001
|
|
394
|
+
print(f"N3MC: could not update config.json ({e})", file=sys.stderr)
|
|
395
|
+
return merged, src
|
|
396
|
+
finally:
|
|
397
|
+
if locked:
|
|
398
|
+
_release_config_lock()
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _load_config():
|
|
402
|
+
"""Load config.json. _CFG_SOURCE is set to the content the settings come from (the bytes read, or the
|
|
403
|
+
content written), so the server's code_version is computed from it, not from a second read (#9)."""
|
|
404
|
+
global _CFG_CACHE, _CFG_SOURCE
|
|
405
|
+
_ensure_dirs()
|
|
406
|
+
cfg = dict(DEFAULT_CONFIG)
|
|
407
|
+
if not _os.path.exists(CONFIG_FILE):
|
|
408
|
+
cfg["owner_id"] = _recover_id("owner_id") or str(uuid.uuid4())
|
|
409
|
+
cfg["local_id"] = _recover_id("local_id") or str(uuid.uuid4())
|
|
410
|
+
text = json.dumps(cfg, indent=2, ensure_ascii=False) + "\n"
|
|
411
|
+
try:
|
|
412
|
+
with open(CONFIG_FILE, "x", encoding="utf-8") as f:
|
|
413
|
+
f.write(text)
|
|
414
|
+
except FileExistsError:
|
|
415
|
+
return _load_config()
|
|
416
|
+
_clear_notice("config_unreadable")
|
|
417
|
+
_clear_notice("config_type")
|
|
418
|
+
_CFG_CACHE, _CFG_SOURCE = cfg, text.encode("utf-8")
|
|
419
|
+
return cfg
|
|
420
|
+
try:
|
|
421
|
+
raw, src = _read_config_file()
|
|
422
|
+
if not isinstance(raw, dict):
|
|
423
|
+
raise _ConfigReadError(ValueError("config.json is not a JSON object"), src)
|
|
424
|
+
except Exception as e: # noqa: BLE001
|
|
425
|
+
_notify("config_unreadable", f"{CONFIG_FILE} could not be read ({e}). It was left untouched; default "
|
|
426
|
+
"settings are in use. Fix the file to apply your settings.")
|
|
427
|
+
cfg["owner_id"] = _recover_id("owner_id") or str(uuid.uuid4())
|
|
428
|
+
cfg["local_id"] = _recover_id("local_id") or str(uuid.uuid4())
|
|
429
|
+
_CFG_CACHE, _CFG_SOURCE = cfg, getattr(e, "raw", None)
|
|
430
|
+
return cfg
|
|
431
|
+
_clear_notice("config_unreadable")
|
|
432
|
+
merged, bad = _merge_config(raw)
|
|
433
|
+
if bad:
|
|
434
|
+
_fill_ids_in_memory(merged)
|
|
435
|
+
_notify_bad(bad)
|
|
436
|
+
else:
|
|
437
|
+
_clear_notice("config_type")
|
|
438
|
+
if _needs_fill(raw): # fill in missing keys / ids and save (the file is valid)
|
|
439
|
+
merged, src = _fill_config_locked(raw, src)
|
|
440
|
+
_CFG_CACHE, _CFG_SOURCE = merged, src
|
|
441
|
+
return merged
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def get_config():
|
|
445
|
+
return _CFG_CACHE if _CFG_CACHE is not None else _load_config()
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
# ============================================================ time bounds
|
|
449
|
+
|
|
450
|
+
_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _parse_time_bound(value, upper=False):
|
|
454
|
+
"""Parse --since/--until into a UTC ISO string comparable with stored timestamps."""
|
|
455
|
+
v = (value or "").strip()
|
|
456
|
+
try:
|
|
457
|
+
if _DATE_ONLY_RE.match(v):
|
|
458
|
+
d = datetime.fromisoformat(v)
|
|
459
|
+
dt = d.replace(hour=23, minute=59, second=59, microsecond=999999) if upper else d
|
|
460
|
+
else:
|
|
461
|
+
if len(v) < 11 or v[10] not in ("T", "t", " "):
|
|
462
|
+
raise ValueError("missing date/time separator")
|
|
463
|
+
dt = datetime.fromisoformat(v[:-1] + "+00:00" if v.endswith(("Z", "z")) else v)
|
|
464
|
+
except ValueError:
|
|
465
|
+
raise ValueError(f"cannot read '{value}' (use 2026-11-13 or 2026-11-13T09:00)")
|
|
466
|
+
if dt.tzinfo is None:
|
|
467
|
+
try:
|
|
468
|
+
dt = dt.astimezone() # naive values are read as local time
|
|
469
|
+
except (ValueError, OverflowError, OSError):
|
|
470
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
471
|
+
try:
|
|
472
|
+
return dt.astimezone(timezone.utc).isoformat()
|
|
473
|
+
except OverflowError:
|
|
474
|
+
boundary = datetime.min if dt.utcoffset() > timedelta(0) else datetime.max
|
|
475
|
+
return boundary.replace(tzinfo=timezone.utc).isoformat()
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _time_bounds(since, until):
|
|
479
|
+
bounds = []
|
|
480
|
+
for flag, value, upper in (("--since", since, False), ("--until", until, True)):
|
|
481
|
+
try:
|
|
482
|
+
bounds.append(None if value is None else _parse_time_bound(value, upper))
|
|
483
|
+
except ValueError as exc:
|
|
484
|
+
raise ValueError(f"{flag}: {exc}") from None
|
|
485
|
+
lower, upper = bounds
|
|
486
|
+
if lower is not None and upper is not None and lower > upper:
|
|
487
|
+
raise ValueError("--since is later than --until")
|
|
488
|
+
return lower, upper
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
# ============================================================ DB open / corruption
|
|
492
|
+
|
|
493
|
+
class _DbCorrupt(Exception):
|
|
494
|
+
pass
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _is_corruption_error(e):
|
|
498
|
+
if not isinstance(e, sqlite3.DatabaseError) or isinstance(e, sqlite3.OperationalError):
|
|
499
|
+
return False
|
|
500
|
+
msg = str(e).lower()
|
|
501
|
+
return "file is not a database" in msg or "malformed" in msg
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _connect_checked(pragma=None):
|
|
505
|
+
conn = get_connection(DB_PATH)
|
|
506
|
+
if pragma:
|
|
507
|
+
try:
|
|
508
|
+
rows = conn.execute(f"PRAGMA {pragma}").fetchall()
|
|
509
|
+
except BaseException:
|
|
510
|
+
conn.close()
|
|
511
|
+
raise
|
|
512
|
+
if not (len(rows) == 1 and str(rows[0][0]).lower() == "ok"):
|
|
513
|
+
conn.close()
|
|
514
|
+
raise _DbCorrupt(f"PRAGMA {pragma} returned {[tuple(r) for r in rows][:3]}")
|
|
515
|
+
return conn
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _quarantine_db():
|
|
519
|
+
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
|
520
|
+
n, suffix = 1, ""
|
|
521
|
+
while _os.path.exists(f"{DB_PATH}.corrupt-{stamp}{suffix}.bak"):
|
|
522
|
+
n += 1
|
|
523
|
+
suffix = f"-{n}"
|
|
524
|
+
bak = f"{DB_PATH}.corrupt-{stamp}{suffix}.bak"
|
|
525
|
+
_os.replace(DB_PATH, bak)
|
|
526
|
+
for ext in ("-wal", "-shm"):
|
|
527
|
+
if _os.path.exists(DB_PATH + ext):
|
|
528
|
+
_os.replace(DB_PATH + ext, bak + ext)
|
|
529
|
+
msg = (f"The memory DB failed its integrity check and was set aside as {bak}. A new empty DB is in use. "
|
|
530
|
+
f"To recover records: sqlite3 {bak} .recover | sqlite3 recovered.db")
|
|
531
|
+
print("N3MC WARNING: " + msg, file=sys.stderr)
|
|
532
|
+
_notify("db_corrupt", msg)
|
|
533
|
+
return bak
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _open_db(pragma=None):
|
|
537
|
+
"""Open the DB (optionally integrity-checked), quarantining a corrupt file. Schema is initialised."""
|
|
538
|
+
_ensure_dirs()
|
|
539
|
+
try:
|
|
540
|
+
conn = _connect_checked(pragma)
|
|
541
|
+
except Exception as e: # noqa: BLE001
|
|
542
|
+
if isinstance(e, _DbCorrupt) or _is_corruption_error(e):
|
|
543
|
+
_quarantine_db()
|
|
544
|
+
conn = _connect_checked(None)
|
|
545
|
+
else:
|
|
546
|
+
raise
|
|
547
|
+
try:
|
|
548
|
+
init_db(conn)
|
|
549
|
+
except Exception as e: # noqa: BLE001
|
|
550
|
+
conn.close()
|
|
551
|
+
if _is_corruption_error(e):
|
|
552
|
+
_quarantine_db()
|
|
553
|
+
conn = _connect_checked(None)
|
|
554
|
+
init_db(conn)
|
|
555
|
+
else:
|
|
556
|
+
raise
|
|
557
|
+
return conn
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _open_db_direct():
|
|
561
|
+
"""DB for the direct (no server) paths: quick_check at most once per process."""
|
|
562
|
+
global _QUICK_CHECKED
|
|
563
|
+
pragma = None
|
|
564
|
+
if not _QUICK_CHECKED:
|
|
565
|
+
_QUICK_CHECKED = True
|
|
566
|
+
pragma = "quick_check"
|
|
567
|
+
return _open_db(pragma)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _read_db_if_exists():
|
|
571
|
+
if not _os.path.exists(DB_PATH):
|
|
572
|
+
return None
|
|
573
|
+
conn = sqlite3.connect(Path(DB_PATH).resolve().as_uri() + "?mode=ro", uri=True,
|
|
574
|
+
timeout=_database.BUSY_TIMEOUT_SECONDS)
|
|
575
|
+
conn.row_factory = sqlite3.Row
|
|
576
|
+
return conn
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
# ============================================================ code version
|
|
580
|
+
|
|
581
|
+
_FROM_DISK = object()
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def compute_code_version(config_source=_FROM_DISK):
|
|
585
|
+
"""config_source: the config.json content to hash (bytes, or None for no readable file). By default
|
|
586
|
+
the file is read (the client). The server passes the content _load_config used (review #9)."""
|
|
587
|
+
h = hashlib.sha256()
|
|
588
|
+
base = _os.path.dirname(_os.path.abspath(__file__))
|
|
589
|
+
package = Path(base)
|
|
590
|
+
sources = sorted((p for p in package.rglob("*.py") if "__pycache__" not in p.parts),
|
|
591
|
+
key=lambda p: p.relative_to(package).as_posix())
|
|
592
|
+
for source in sources:
|
|
593
|
+
h.update(source.relative_to(package).as_posix().encode("utf-8"))
|
|
594
|
+
try:
|
|
595
|
+
h.update(source.read_bytes())
|
|
596
|
+
except OSError:
|
|
597
|
+
h.update(b"?")
|
|
598
|
+
raw = config_source
|
|
599
|
+
if raw is _FROM_DISK:
|
|
600
|
+
try:
|
|
601
|
+
with open(CONFIG_FILE, "rb") as f:
|
|
602
|
+
raw = f.read()
|
|
603
|
+
except OSError:
|
|
604
|
+
raw = None
|
|
605
|
+
if raw is not None:
|
|
606
|
+
try:
|
|
607
|
+
h.update(json.dumps(json.loads(raw.decode("utf-8")), sort_keys=True).encode("utf-8"))
|
|
608
|
+
except Exception: # noqa: BLE001
|
|
609
|
+
h.update(raw)
|
|
610
|
+
return h.hexdigest()[:16]
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _server_code_version():
|
|
614
|
+
"""code_version of this server: from the config.json content its settings were loaded from (#9)."""
|
|
615
|
+
get_config()
|
|
616
|
+
return compute_code_version(_CFG_SOURCE)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
# ============================================================ storing
|
|
620
|
+
|
|
621
|
+
def _store_record(conn, cfg, content, agent_name=None, local_id=None, session_id=None, turn_id=None,
|
|
622
|
+
embed=True):
|
|
623
|
+
"""Save one record. Returns the response dict used by /buffer."""
|
|
624
|
+
content = purify_text(content or "")
|
|
625
|
+
if not content.strip():
|
|
626
|
+
return {"status": "skipped", "count": 0, "reason": "empty"}
|
|
627
|
+
if check_exact_duplicate(conn, content, turn_id=turn_id):
|
|
628
|
+
return {"status": "skipped", "count": 0, "reason": "exact_duplicate"}
|
|
629
|
+
vec = None
|
|
630
|
+
if embed:
|
|
631
|
+
try:
|
|
632
|
+
vec = embed_passage(content, cfg.get("embed_model"))
|
|
633
|
+
except Exception as e: # noqa: BLE001
|
|
634
|
+
print(f"N3MC: embedding unavailable ({type(e).__name__}); saved without a vector", file=sys.stderr)
|
|
635
|
+
before = count_memories(conn)
|
|
636
|
+
rid = insert_memory_once(conn, _new_id(), content, datetime.now(timezone.utc).isoformat(),
|
|
637
|
+
cfg["owner_id"], local_id or cfg["local_id"], agent_name, session_id,
|
|
638
|
+
turn_id=turn_id, embedding=vec)
|
|
639
|
+
if rid is None:
|
|
640
|
+
return {"status": "skipped", "count": 0, "reason": "exact_duplicate"}
|
|
641
|
+
if count_memories(conn) <= before:
|
|
642
|
+
return {"status": "error", "message": "record count did not change after INSERT"}
|
|
643
|
+
return {"status": "ok", "count": 1}
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
# ============================================================ repair
|
|
647
|
+
|
|
648
|
+
def _repair(conn, cfg, max_records=None):
|
|
649
|
+
"""Repair un-indexed records and run one-time migrations. Returns the number of records changed."""
|
|
650
|
+
changed = 0
|
|
651
|
+
budget = max_records
|
|
652
|
+
if budget is not None and budget <= 0:
|
|
653
|
+
return 0
|
|
654
|
+
# --- meta: model of the stored vectors
|
|
655
|
+
if get_meta(conn, "embed_model") is None:
|
|
656
|
+
model = cfg["embed_model"]
|
|
657
|
+
has_vec = conn.execute("SELECT 1 FROM memories_vec LIMIT 1").fetchone() is not None
|
|
658
|
+
if has_vec:
|
|
659
|
+
try:
|
|
660
|
+
with open(_os.path.join(MEMORY_DIR, "vec_model.txt"), "r", encoding="utf-8") as f:
|
|
661
|
+
model = f.read().strip() or model
|
|
662
|
+
except OSError:
|
|
663
|
+
pass
|
|
664
|
+
set_meta(conn, "embed_model", model)
|
|
665
|
+
dim = vec_dim(conn) # from the table itself, never EMBED_DIM (review #3)
|
|
666
|
+
if dim is not None:
|
|
667
|
+
set_meta(conn, "embed_dim", dim)
|
|
668
|
+
set_meta(conn, "embed_model_at", datetime.now(timezone.utc).isoformat())
|
|
669
|
+
conn.commit()
|
|
670
|
+
recorded = get_meta(conn, "embed_model")
|
|
671
|
+
if recorded != cfg["embed_model"]:
|
|
672
|
+
n = count_memories(conn)
|
|
673
|
+
_notify("embed_model_mismatch",
|
|
674
|
+
f"The stored vectors were made with {recorded}, but config.json sets embed_model to "
|
|
675
|
+
f"{cfg['embed_model']}. Search quality is degraded until they are re-made: run n3mc-free-codex --reembed "
|
|
676
|
+
f"(it re-embeds all {n} records with {cfg['embed_model']}), or set embed_model back to {recorded}.")
|
|
677
|
+
else:
|
|
678
|
+
_clear_notice("embed_model_mismatch")
|
|
679
|
+
processed = 0
|
|
680
|
+
# --- one-time FTS punctuation clean-up (keyset batches, resumable through meta.fts_punct_cursor)
|
|
681
|
+
if get_meta(conn, "fts_punct_cleaned") is None:
|
|
682
|
+
last = int(get_meta(conn, "fts_punct_cursor", 0))
|
|
683
|
+
finished = True
|
|
684
|
+
while True:
|
|
685
|
+
page_size = 200 if budget is None else min(200, budget - processed)
|
|
686
|
+
rows = conn.execute(
|
|
687
|
+
"SELECT m.rowid AS rid, m.content AS c, f.content AS fc FROM memories m "
|
|
688
|
+
"JOIN memories_fts f ON f.rowid = m.rowid WHERE m.rowid > ? ORDER BY m.rowid LIMIT ?",
|
|
689
|
+
(last, page_size)).fetchall()
|
|
690
|
+
if not rows:
|
|
691
|
+
break
|
|
692
|
+
for r in rows:
|
|
693
|
+
want = strip_fts_punctuation(fts_index_text(r["c"]))
|
|
694
|
+
if r["fc"] != want:
|
|
695
|
+
conn.execute("UPDATE memories_fts SET content=? WHERE rowid=?", (want, r["rid"]))
|
|
696
|
+
changed += 1
|
|
697
|
+
last = r["rid"]
|
|
698
|
+
processed += 1
|
|
699
|
+
set_meta(conn, "fts_punct_cursor", last) # same transaction as the rewrites of this batch
|
|
700
|
+
conn.commit()
|
|
701
|
+
if budget is not None and processed >= budget:
|
|
702
|
+
finished = False
|
|
703
|
+
break
|
|
704
|
+
if finished:
|
|
705
|
+
set_meta(conn, "fts_punct_cleaned", "1")
|
|
706
|
+
delete_meta(conn, "fts_punct_cursor")
|
|
707
|
+
conn.commit()
|
|
708
|
+
if budget is not None:
|
|
709
|
+
budget -= processed
|
|
710
|
+
# --- one-time bigram index fill
|
|
711
|
+
if get_meta(conn, "fts_bigram") is None:
|
|
712
|
+
while budget is None or budget > 0:
|
|
713
|
+
limit = 200 if budget is None else min(200, budget)
|
|
714
|
+
rows = conn.execute(
|
|
715
|
+
"SELECT m.rowid AS rid, m.content AS c FROM memories m LEFT JOIN memories_fts_bi b "
|
|
716
|
+
"ON b.rowid = m.rowid WHERE b.rowid IS NULL ORDER BY m.rowid LIMIT ?", (limit,)).fetchall()
|
|
717
|
+
if not rows:
|
|
718
|
+
set_meta(conn, "fts_bigram", "1")
|
|
719
|
+
conn.commit()
|
|
720
|
+
break
|
|
721
|
+
for r in rows:
|
|
722
|
+
conn.execute("INSERT OR REPLACE INTO memories_fts_bi(rowid, content) VALUES (?, ?)",
|
|
723
|
+
(r["rid"], bigram_text(fts_index_text(r["c"]))))
|
|
724
|
+
conn.commit()
|
|
725
|
+
if budget is not None:
|
|
726
|
+
budget -= len(rows)
|
|
727
|
+
# Rebuild indexes produced with older text rules. Each bounded transaction
|
|
728
|
+
# advances its cursor atomically with the two aligned FTS rows.
|
|
729
|
+
while budget is None or budget > 0:
|
|
730
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
731
|
+
try:
|
|
732
|
+
if get_meta(conn, "fts_text_rules") == FTS_TEXT_RULES:
|
|
733
|
+
conn.commit()
|
|
734
|
+
break
|
|
735
|
+
cursor = int(get_meta(conn, "fts_text_cursor", 0))
|
|
736
|
+
limit = 200 if budget is None else min(200, budget)
|
|
737
|
+
rows = conn.execute("SELECT rowid, content FROM memories WHERE rowid > ? ORDER BY rowid LIMIT ?",
|
|
738
|
+
(cursor, limit)).fetchall()
|
|
739
|
+
for row in rows:
|
|
740
|
+
rid = row["rowid"]
|
|
741
|
+
content = fts_index_text(row["content"])
|
|
742
|
+
conn.execute("DELETE FROM memories_fts WHERE rowid=?", (rid,))
|
|
743
|
+
conn.execute("DELETE FROM memories_fts_bi WHERE rowid=?", (rid,))
|
|
744
|
+
conn.execute("INSERT INTO memories_fts(rowid, content) VALUES (?, ?)",
|
|
745
|
+
(rid, strip_fts_punctuation(content)))
|
|
746
|
+
conn.execute("INSERT INTO memories_fts_bi(rowid, content) VALUES (?, ?)",
|
|
747
|
+
(rid, bigram_text(content)))
|
|
748
|
+
if len(rows) < limit:
|
|
749
|
+
set_meta(conn, "fts_text_rules", FTS_TEXT_RULES)
|
|
750
|
+
delete_meta(conn, "fts_text_cursor")
|
|
751
|
+
elif rows:
|
|
752
|
+
set_meta(conn, "fts_text_cursor", rows[-1]["rowid"])
|
|
753
|
+
conn.commit()
|
|
754
|
+
except BaseException:
|
|
755
|
+
conn.rollback()
|
|
756
|
+
raise
|
|
757
|
+
if budget is not None:
|
|
758
|
+
budget -= len(rows)
|
|
759
|
+
if len(rows) < limit:
|
|
760
|
+
break
|
|
761
|
+
|
|
762
|
+
# --- missing vectors / FTS rows
|
|
763
|
+
remaining = budget
|
|
764
|
+
while remaining is None or remaining > 0:
|
|
765
|
+
n_batch = 200 if remaining is None else min(200, remaining)
|
|
766
|
+
batch = find_unindexed_memories(conn, n_batch)
|
|
767
|
+
if not batch:
|
|
768
|
+
break
|
|
769
|
+
if conn.in_transaction:
|
|
770
|
+
conn.commit()
|
|
771
|
+
vecs = {}
|
|
772
|
+
for r in batch: # embeddings are computed outside any write transaction (F11)
|
|
773
|
+
if r["no_vec"]:
|
|
774
|
+
try:
|
|
775
|
+
vecs[r["rowid"]] = embed_passage(r["content"], cfg.get("embed_model"))
|
|
776
|
+
except Exception: # noqa: BLE001
|
|
777
|
+
vecs[r["rowid"]] = None
|
|
778
|
+
fixed = 0
|
|
779
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
780
|
+
try:
|
|
781
|
+
for r in batch:
|
|
782
|
+
rid, did = r["rowid"], False
|
|
783
|
+
cur = conn.execute("SELECT id, content FROM memories WHERE rowid=?", (rid,)).fetchone()
|
|
784
|
+
if cur is None or not (cur["id"] == r["id"] and cur["content"] == r["content"]):
|
|
785
|
+
continue # deleted, or the rowid now belongs to another record
|
|
786
|
+
if conn.execute("SELECT 1 FROM memories_fts WHERE rowid=?", (rid,)).fetchone() is None:
|
|
787
|
+
conn.execute("INSERT INTO memories_fts(rowid, content) VALUES (?, ?)",
|
|
788
|
+
(rid, strip_fts_punctuation(fts_index_text(r["content"]))))
|
|
789
|
+
did = True
|
|
790
|
+
if conn.execute("SELECT 1 FROM memories_fts_bi WHERE rowid=?", (rid,)).fetchone() is None:
|
|
791
|
+
conn.execute("INSERT INTO memories_fts_bi(rowid, content) VALUES (?, ?)",
|
|
792
|
+
(rid, bigram_text(fts_index_text(r["content"]))))
|
|
793
|
+
did = True
|
|
794
|
+
v = vecs.get(rid)
|
|
795
|
+
if v is not None and conn.execute("SELECT 1 FROM memories_vec WHERE rowid=?", (rid,)).fetchone() is None:
|
|
796
|
+
conn.execute("INSERT INTO memories_vec(rowid, embedding) VALUES (?, ?)",
|
|
797
|
+
(rid, serialize_vector(v)))
|
|
798
|
+
did = True
|
|
799
|
+
fixed += 1 if did else 0
|
|
800
|
+
conn.commit()
|
|
801
|
+
except BaseException:
|
|
802
|
+
conn.rollback()
|
|
803
|
+
raise
|
|
804
|
+
changed += fixed
|
|
805
|
+
if remaining is not None:
|
|
806
|
+
remaining -= len(batch)
|
|
807
|
+
if fixed == 0:
|
|
808
|
+
break
|
|
809
|
+
return changed
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
# ============================================================ FastAPI server
|
|
813
|
+
|
|
814
|
+
def create_app():
|
|
815
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
816
|
+
from fastapi.responses import JSONResponse
|
|
817
|
+
from pydantic import BaseModel
|
|
818
|
+
from typing import Optional
|
|
819
|
+
|
|
820
|
+
class BufferReq(BaseModel):
|
|
821
|
+
content: str = ""
|
|
822
|
+
agent_name: Optional[str] = None
|
|
823
|
+
local_id: Optional[str] = None
|
|
824
|
+
session_id: Optional[str] = None
|
|
825
|
+
turn_id: Optional[str] = None
|
|
826
|
+
|
|
827
|
+
class SearchReq(BaseModel):
|
|
828
|
+
query: str = ""
|
|
829
|
+
session_id: Optional[str] = None
|
|
830
|
+
since: Optional[str] = None
|
|
831
|
+
until: Optional[str] = None
|
|
832
|
+
|
|
833
|
+
class RepairReq(BaseModel):
|
|
834
|
+
max_records: Optional[int] = None
|
|
835
|
+
|
|
836
|
+
class ShutdownReq(BaseModel):
|
|
837
|
+
root: str = ""
|
|
838
|
+
|
|
839
|
+
@asynccontextmanager
|
|
840
|
+
async def lifespan(app: FastAPI):
|
|
841
|
+
if "cfg" not in _SERVER_STATE:
|
|
842
|
+
_SERVER_STATE["cfg"] = get_config()
|
|
843
|
+
_SERVER_STATE.setdefault("session_id", str(uuid.uuid4()))
|
|
844
|
+
yield
|
|
845
|
+
|
|
846
|
+
app = FastAPI(lifespan=lifespan)
|
|
847
|
+
|
|
848
|
+
@app.middleware("http")
|
|
849
|
+
async def guard(request: Request, call_next):
|
|
850
|
+
if "origin" in request.headers:
|
|
851
|
+
return JSONResponse({"detail": "forbidden (Origin header)"}, status_code=403)
|
|
852
|
+
port = _SERVER_PORT or get_config()["server_port"]
|
|
853
|
+
if request.headers.get("host", "") not in (f"127.0.0.1:{port}", f"localhost:{port}"):
|
|
854
|
+
return JSONResponse({"detail": "forbidden (Host header)"}, status_code=403)
|
|
855
|
+
return await call_next(request)
|
|
856
|
+
|
|
857
|
+
def cfg():
|
|
858
|
+
if "cfg" not in _SERVER_STATE:
|
|
859
|
+
_SERVER_STATE["cfg"] = get_config()
|
|
860
|
+
_SERVER_STATE.setdefault("session_id", str(uuid.uuid4()))
|
|
861
|
+
return _SERVER_STATE["cfg"]
|
|
862
|
+
|
|
863
|
+
@app.get("/health")
|
|
864
|
+
def health():
|
|
865
|
+
return {"status": "ok", "root": HOME_DIR,
|
|
866
|
+
"code_version": _SERVER_STATE.get("code_version") or _server_code_version(),
|
|
867
|
+
"pid": _os.getpid()}
|
|
868
|
+
|
|
869
|
+
@app.post("/buffer")
|
|
870
|
+
def buffer(req: BufferReq):
|
|
871
|
+
c = cfg()
|
|
872
|
+
conn = None
|
|
873
|
+
try:
|
|
874
|
+
conn = _open_db()
|
|
875
|
+
return _store_record(conn, c, req.content, req.agent_name, req.local_id,
|
|
876
|
+
req.session_id or _SERVER_STATE["session_id"], req.turn_id)
|
|
877
|
+
except Exception as e: # noqa: BLE001
|
|
878
|
+
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
|
|
879
|
+
finally:
|
|
880
|
+
if conn:
|
|
881
|
+
conn.close()
|
|
882
|
+
|
|
883
|
+
@app.post("/search")
|
|
884
|
+
def search(req: SearchReq):
|
|
885
|
+
c = cfg()
|
|
886
|
+
try:
|
|
887
|
+
since, until = _time_bounds(req.since, req.until)
|
|
888
|
+
except ValueError as e:
|
|
889
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
890
|
+
conn = _open_db()
|
|
891
|
+
try:
|
|
892
|
+
res = hybrid_search(conn, (req.query or "")[:c["search_query_max_chars"]], c,
|
|
893
|
+
session_id=req.session_id or _SERVER_STATE["session_id"],
|
|
894
|
+
since=since, until=until)
|
|
895
|
+
finally:
|
|
896
|
+
conn.close()
|
|
897
|
+
for r in res["results"]:
|
|
898
|
+
r.pop("rowid", None)
|
|
899
|
+
r.pop("_version_group", None)
|
|
900
|
+
return res
|
|
901
|
+
|
|
902
|
+
@app.post("/repair")
|
|
903
|
+
def repair(req: Optional[RepairReq] = None):
|
|
904
|
+
c = cfg()
|
|
905
|
+
conn = _open_db()
|
|
906
|
+
try:
|
|
907
|
+
n = _repair(conn, c, req.max_records if req else None)
|
|
908
|
+
finally:
|
|
909
|
+
conn.close()
|
|
910
|
+
return {"status": "ok", "count": n}
|
|
911
|
+
|
|
912
|
+
@app.get("/list")
|
|
913
|
+
def list_all():
|
|
914
|
+
conn = _open_db()
|
|
915
|
+
try:
|
|
916
|
+
rows = conn.execute("SELECT id, content, timestamp, agent_name FROM memories ORDER BY rowid").fetchall()
|
|
917
|
+
finally:
|
|
918
|
+
conn.close()
|
|
919
|
+
return {"records": [dict(r) for r in rows], "total": len(rows)}
|
|
920
|
+
|
|
921
|
+
@app.post("/shutdown")
|
|
922
|
+
def shutdown(req: ShutdownReq):
|
|
923
|
+
if _norm(req.root or "") != _norm(HOME_DIR):
|
|
924
|
+
raise HTTPException(status_code=403, detail="root mismatch")
|
|
925
|
+
threading.Timer(0.3, _exit_server).start()
|
|
926
|
+
return {"status": "ok"}
|
|
927
|
+
|
|
928
|
+
@app.delete("/delete/{memory_id}")
|
|
929
|
+
def delete(memory_id: str):
|
|
930
|
+
raise HTTPException(status_code=403, detail="Pro feature")
|
|
931
|
+
|
|
932
|
+
@app.post("/gc")
|
|
933
|
+
def gc(request: Request):
|
|
934
|
+
raise HTTPException(status_code=403, detail="Pro feature")
|
|
935
|
+
|
|
936
|
+
@app.post("/import")
|
|
937
|
+
def import_(request: Request):
|
|
938
|
+
raise HTTPException(status_code=403, detail="Pro feature")
|
|
939
|
+
|
|
940
|
+
return app
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _remove_own_pid_file():
|
|
944
|
+
"""Delete the PID file if it holds this process's PID. The file is closed before it is deleted
|
|
945
|
+
(Windows cannot delete a file that is still open)."""
|
|
946
|
+
try:
|
|
947
|
+
with open(PID_FILE, "r", encoding="utf-8") as f:
|
|
948
|
+
mine = f.read().strip() == str(_os.getpid())
|
|
949
|
+
if mine:
|
|
950
|
+
_os.unlink(PID_FILE)
|
|
951
|
+
except OSError:
|
|
952
|
+
pass
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def _exit_server():
|
|
956
|
+
_remove_own_pid_file()
|
|
957
|
+
_os._exit(0)
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def cmd_run_server():
|
|
961
|
+
global _SERVER_PORT
|
|
962
|
+
import uvicorn
|
|
963
|
+
cfg = get_config()
|
|
964
|
+
_SERVER_PORT = cfg["server_port"]
|
|
965
|
+
if _get_health(_SERVER_PORT) is not None:
|
|
966
|
+
print(f"N3MC: a memory server already listens on port {_SERVER_PORT}.", file=sys.stderr)
|
|
967
|
+
return 1
|
|
968
|
+
if cfg["bind_host"] != "127.0.0.1":
|
|
969
|
+
print(f"N3MC WARNING: bind_host is {cfg['bind_host']}; the API has no authentication and is reachable "
|
|
970
|
+
"from the network. Use 127.0.0.1.", file=sys.stderr)
|
|
971
|
+
_SERVER_STATE["cfg"] = cfg
|
|
972
|
+
_SERVER_STATE["session_id"] = str(uuid.uuid4())
|
|
973
|
+
_SERVER_STATE["code_version"] = compute_code_version(_CFG_SOURCE) # same content as cfg (#9)
|
|
974
|
+
conn = _open_db("integrity_check")
|
|
975
|
+
conn.close()
|
|
976
|
+
try:
|
|
977
|
+
_processor.get_model(cfg["embed_model"]) # preload before listening (first run may take minutes)
|
|
978
|
+
except Exception as e: # noqa: BLE001
|
|
979
|
+
print(f"N3MC: embedding model not loaded ({type(e).__name__}: {e}); continuing without vectors",
|
|
980
|
+
file=sys.stderr)
|
|
981
|
+
try:
|
|
982
|
+
with open(PID_FILE, "x", encoding="utf-8") as f:
|
|
983
|
+
f.write(str(_os.getpid()))
|
|
984
|
+
except FileExistsError:
|
|
985
|
+
try:
|
|
986
|
+
with open(PID_FILE, "w", encoding="utf-8") as f:
|
|
987
|
+
f.write(str(_os.getpid()))
|
|
988
|
+
except OSError:
|
|
989
|
+
pass
|
|
990
|
+
try:
|
|
991
|
+
uvicorn.run(create_app(), host=cfg["bind_host"], port=cfg["server_port"], log_level="error")
|
|
992
|
+
finally:
|
|
993
|
+
_remove_own_pid_file()
|
|
994
|
+
return 0
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
# ============================================================ HTTP client
|
|
998
|
+
|
|
999
|
+
def _port():
|
|
1000
|
+
return get_config()["server_port"]
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def _opener():
|
|
1004
|
+
# Never go through a proxy: the server is on 127.0.0.1 (F16).
|
|
1005
|
+
return urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _http(method, path, body=None, timeout=HTTP_TIMEOUT, port=None):
|
|
1009
|
+
url = f"http://127.0.0.1:{port or _port()}{path}"
|
|
1010
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
|
|
1011
|
+
req = urllib.request.Request(url, data=data, method=method,
|
|
1012
|
+
headers={"Content-Type": "application/json"} if data is not None else {})
|
|
1013
|
+
with _opener().open(req, timeout=timeout) as resp:
|
|
1014
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
def _post(path, body, timeout=HTTP_TIMEOUT, port=None):
|
|
1018
|
+
return _http("POST", path, body, timeout, port)
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def _get(path, timeout=HTTP_TIMEOUT, port=None):
|
|
1022
|
+
return _http("GET", path, None, timeout, port)
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
def _get_health(port=None):
|
|
1026
|
+
try:
|
|
1027
|
+
h = _get("/health", timeout=5, port=port)
|
|
1028
|
+
return h if isinstance(h, dict) and h.get("status") == "ok" else None
|
|
1029
|
+
except Exception: # noqa: BLE001
|
|
1030
|
+
return None
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def _health_decision(health):
|
|
1034
|
+
if not health:
|
|
1035
|
+
return "none"
|
|
1036
|
+
if not health.get("root"):
|
|
1037
|
+
return "legacy"
|
|
1038
|
+
if _norm(health["root"]) != _norm(HOME_DIR):
|
|
1039
|
+
return "foreign"
|
|
1040
|
+
if health.get("code_version") != compute_code_version():
|
|
1041
|
+
return "stale"
|
|
1042
|
+
return "ok"
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
def _request_shutdown(port=None):
|
|
1046
|
+
try:
|
|
1047
|
+
response = _post("/shutdown", {"root": HOME_DIR}, timeout=5, port=port)
|
|
1048
|
+
return isinstance(response, dict) and response.get("status") == "ok"
|
|
1049
|
+
except Exception: # noqa: BLE001
|
|
1050
|
+
return False
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def _wait_port_free(port=None, seconds=15):
|
|
1054
|
+
end = time.time() + seconds
|
|
1055
|
+
while time.time() < end:
|
|
1056
|
+
if _get_health(port) is None:
|
|
1057
|
+
return True
|
|
1058
|
+
time.sleep(0.3)
|
|
1059
|
+
return False
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def _read_pid():
|
|
1063
|
+
try:
|
|
1064
|
+
with open(PID_FILE, "r", encoding="utf-8") as f:
|
|
1065
|
+
return int(f.read().strip())
|
|
1066
|
+
except Exception: # noqa: BLE001
|
|
1067
|
+
return None
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
def _remove_pid_if(pid):
|
|
1071
|
+
if _read_pid() == pid:
|
|
1072
|
+
try:
|
|
1073
|
+
_os.unlink(PID_FILE)
|
|
1074
|
+
except OSError:
|
|
1075
|
+
pass
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def _home_of_env(env):
|
|
1079
|
+
h = env.get("N3MC_FREE_CODEX_HOME")
|
|
1080
|
+
return _os.path.abspath(_os.path.expanduser(h or _os.path.join("~", ".n3mc-free-codex")))
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
def _is_own_server_process(pid=None, health=None):
|
|
1084
|
+
"""True only if psutil confirms the process is this folder's `--run-server`."""
|
|
1085
|
+
try:
|
|
1086
|
+
import psutil
|
|
1087
|
+
if pid is None and health:
|
|
1088
|
+
pid = health.get("pid")
|
|
1089
|
+
if pid is None:
|
|
1090
|
+
port = _port()
|
|
1091
|
+
for c in psutil.net_connections(kind="inet"):
|
|
1092
|
+
if c.status == "LISTEN" and c.laddr and c.laddr.port == port and c.pid:
|
|
1093
|
+
pid = c.pid
|
|
1094
|
+
break
|
|
1095
|
+
if pid is None:
|
|
1096
|
+
return False
|
|
1097
|
+
p = psutil.Process(int(pid))
|
|
1098
|
+
cmd = p.cmdline()
|
|
1099
|
+
if "n3memorycore_free_codex.n3memory" not in " ".join(cmd) or "--run-server" not in cmd:
|
|
1100
|
+
return False
|
|
1101
|
+
return _norm(_home_of_env(p.environ())) == _norm(HOME_DIR)
|
|
1102
|
+
except Exception: # noqa: BLE001
|
|
1103
|
+
return False
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def _listen_ports(pid):
|
|
1107
|
+
try:
|
|
1108
|
+
import psutil
|
|
1109
|
+
p = psutil.Process(int(pid))
|
|
1110
|
+
conns = p.net_connections(kind="inet") if hasattr(p, "net_connections") else p.connections(kind="inet")
|
|
1111
|
+
return sorted({c.laddr.port for c in conns if c.status == "LISTEN" and c.laddr})
|
|
1112
|
+
except Exception: # noqa: BLE001
|
|
1113
|
+
return []
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def _terminate_process(pid):
|
|
1117
|
+
try:
|
|
1118
|
+
import psutil
|
|
1119
|
+
p = psutil.Process(int(pid))
|
|
1120
|
+
p.terminate()
|
|
1121
|
+
try:
|
|
1122
|
+
p.wait(5)
|
|
1123
|
+
except Exception: # noqa: BLE001
|
|
1124
|
+
p.kill()
|
|
1125
|
+
return True
|
|
1126
|
+
except Exception: # noqa: BLE001
|
|
1127
|
+
return False
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _stop_stale_server(health=None):
|
|
1131
|
+
"""Stop this folder's old server: /shutdown first; kill only after psutil confirms it is ours."""
|
|
1132
|
+
port = _port()
|
|
1133
|
+
if _request_shutdown():
|
|
1134
|
+
return _wait_port_free(port)
|
|
1135
|
+
if _is_own_server_process(health=health):
|
|
1136
|
+
pid = (health or {}).get("pid")
|
|
1137
|
+
if pid and _terminate_process(pid):
|
|
1138
|
+
_remove_pid_if(pid)
|
|
1139
|
+
return _wait_port_free(port)
|
|
1140
|
+
return False
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
_SERVER_STARTING = False
|
|
1144
|
+
_SERVER_OK = None
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
def _foreign(health, unknown=False):
|
|
1148
|
+
global _FOREIGN_SERVER_ROOT
|
|
1149
|
+
root = health.get("root") if health else None
|
|
1150
|
+
_FOREIGN_SERVER_ROOT = root or "(unknown: the server did not report its folder)"
|
|
1151
|
+
_notify("port_conflict", f"Another program or N3MC folder ({_FOREIGN_SERVER_ROOT}) is using port {_port()}. "
|
|
1152
|
+
f"Records are saved directly and memory search is off. Set a different server_port in {CONFIG_FILE}.")
|
|
1153
|
+
return False
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
def _clear_server_notices():
|
|
1157
|
+
for k in ("stale_server", "port_conflict", "server_start_failed"):
|
|
1158
|
+
_clear_notice(k)
|
|
1159
|
+
try:
|
|
1160
|
+
_os.unlink(SERVER_START_FAILED_FILE)
|
|
1161
|
+
except OSError:
|
|
1162
|
+
pass
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
PID_RESERVATION_SECONDS = 60
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def _reserve_pid_file():
|
|
1169
|
+
"""Create the PID file, empty, with exclusive creation (review #5). True: reserved by this call;
|
|
1170
|
+
False: it exists (another process starts or runs the server); None: it could not be created."""
|
|
1171
|
+
try:
|
|
1172
|
+
with open(PID_FILE, "x", encoding="utf-8"):
|
|
1173
|
+
pass
|
|
1174
|
+
return True
|
|
1175
|
+
except FileExistsError:
|
|
1176
|
+
return False
|
|
1177
|
+
except OSError:
|
|
1178
|
+
return None
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
def _drop_reservation():
|
|
1182
|
+
"""Delete our reservation (still empty: nobody else writes into it)."""
|
|
1183
|
+
try:
|
|
1184
|
+
if _os.path.getsize(PID_FILE) == 0:
|
|
1185
|
+
_os.unlink(PID_FILE)
|
|
1186
|
+
except OSError:
|
|
1187
|
+
pass
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def _write_reserved_pid(pid):
|
|
1191
|
+
"""Write the child's PID into our (still empty) reservation; never overwrite what is there."""
|
|
1192
|
+
try:
|
|
1193
|
+
with open(PID_FILE, "r+", encoding="utf-8") as f:
|
|
1194
|
+
if not f.read().strip():
|
|
1195
|
+
f.seek(0)
|
|
1196
|
+
f.write(str(pid))
|
|
1197
|
+
f.truncate()
|
|
1198
|
+
except OSError:
|
|
1199
|
+
pass
|
|
1200
|
+
|
|
1201
|
+
|
|
1202
|
+
def _wait_for_starting_server():
|
|
1203
|
+
"""Another process is starting this folder's server: poll /health for up to 60 s."""
|
|
1204
|
+
global _SERVER_STARTING
|
|
1205
|
+
end = time.time() + SERVER_WAIT_SECONDS
|
|
1206
|
+
while time.time() < end:
|
|
1207
|
+
h = _get_health()
|
|
1208
|
+
d = _health_decision(h)
|
|
1209
|
+
if d in ("ok", "stale"):
|
|
1210
|
+
return True
|
|
1211
|
+
if d in ("foreign", "legacy"):
|
|
1212
|
+
return _foreign(h)
|
|
1213
|
+
time.sleep(0.5)
|
|
1214
|
+
_SERVER_STARTING = True
|
|
1215
|
+
return False
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def _follow_pid_file():
|
|
1219
|
+
""""PID file handling" (no server answers). Returns True/False when the PID file decides the outcome,
|
|
1220
|
+
or None when there is no live PID file (it was dead and has been removed): start the server."""
|
|
1221
|
+
if not _os.path.exists(PID_FILE):
|
|
1222
|
+
return None
|
|
1223
|
+
pid = _read_pid()
|
|
1224
|
+
if pid is None:
|
|
1225
|
+
# Empty or unreadable: a start reserved by another process (review #5). Starting for 60 s after
|
|
1226
|
+
# the file's modification time, dead afterwards.
|
|
1227
|
+
try:
|
|
1228
|
+
age = time.time() - _os.path.getmtime(PID_FILE)
|
|
1229
|
+
except OSError:
|
|
1230
|
+
return None
|
|
1231
|
+
if age < PID_RESERVATION_SECONDS:
|
|
1232
|
+
return _wait_for_starting_server()
|
|
1233
|
+
try:
|
|
1234
|
+
if _read_pid() is None and time.time() - _os.path.getmtime(PID_FILE) >= PID_RESERVATION_SECONDS:
|
|
1235
|
+
_os.unlink(PID_FILE)
|
|
1236
|
+
except OSError:
|
|
1237
|
+
pass
|
|
1238
|
+
return None
|
|
1239
|
+
if _pid_is_own(pid):
|
|
1240
|
+
previous_port = _other_server_port(pid)
|
|
1241
|
+
if previous_port is not None and _shutdown_other_port(pid, previous_port):
|
|
1242
|
+
return _launch()
|
|
1243
|
+
return _wait_for_starting_server()
|
|
1244
|
+
_remove_pid_if(pid)
|
|
1245
|
+
return None
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
def _start_server():
|
|
1249
|
+
global _SERVER_STARTING, _FOREIGN_SERVER_ROOT
|
|
1250
|
+
_ensure_dirs()
|
|
1251
|
+
for _ in range(3):
|
|
1252
|
+
reserved = _reserve_pid_file()
|
|
1253
|
+
if reserved is not False:
|
|
1254
|
+
break
|
|
1255
|
+
r = _follow_pid_file() # another process starts or runs the server: do not launch
|
|
1256
|
+
if r is not None:
|
|
1257
|
+
return r
|
|
1258
|
+
else:
|
|
1259
|
+
return False
|
|
1260
|
+
try:
|
|
1261
|
+
if _os.path.exists(SERVER_LOG) and _os.path.getsize(SERVER_LOG) > 1024 * 1024:
|
|
1262
|
+
open(SERVER_LOG, "wb").close()
|
|
1263
|
+
kwargs = {}
|
|
1264
|
+
if _os.name == "nt":
|
|
1265
|
+
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
|
|
1266
|
+
else:
|
|
1267
|
+
kwargs["start_new_session"] = True
|
|
1268
|
+
with open(SERVER_LOG, "ab") as log:
|
|
1269
|
+
proc = subprocess.Popen(
|
|
1270
|
+
[*python_cmd(), "-m", "n3memorycore_free_codex.n3memory", "--run-server"],
|
|
1271
|
+
stderr=log, stdout=subprocess.DEVNULL, stdin=subprocess.DEVNULL, cwd=_server_cwd(), **kwargs,
|
|
1272
|
+
)
|
|
1273
|
+
except Exception as e: # noqa: BLE001
|
|
1274
|
+
print(f"N3MC: could not start the memory server ({type(e).__name__}: {e})", file=sys.stderr)
|
|
1275
|
+
if reserved:
|
|
1276
|
+
_drop_reservation()
|
|
1277
|
+
return False
|
|
1278
|
+
if reserved:
|
|
1279
|
+
_write_reserved_pid(proc.pid)
|
|
1280
|
+
end = time.time() + SERVER_WAIT_SECONDS
|
|
1281
|
+
while time.time() < end:
|
|
1282
|
+
h = _get_health()
|
|
1283
|
+
d = _health_decision(h)
|
|
1284
|
+
if d in ("ok", "stale"):
|
|
1285
|
+
_clear_server_notices()
|
|
1286
|
+
return True
|
|
1287
|
+
if d in ("foreign", "legacy"):
|
|
1288
|
+
_foreign(h)
|
|
1289
|
+
return False
|
|
1290
|
+
if proc.poll() is not None:
|
|
1291
|
+
_notify("server_start_failed", f"The N3MC memory server could not start (exit code {proc.returncode}). "
|
|
1292
|
+
f"See {SERVER_LOG} for the reason.")
|
|
1293
|
+
try:
|
|
1294
|
+
with open(SERVER_START_FAILED_FILE, "w", encoding="utf-8") as f:
|
|
1295
|
+
f.write(datetime.now(timezone.utc).isoformat())
|
|
1296
|
+
except OSError:
|
|
1297
|
+
pass
|
|
1298
|
+
_remove_pid_if(proc.pid)
|
|
1299
|
+
return False
|
|
1300
|
+
time.sleep(0.5)
|
|
1301
|
+
_SERVER_STARTING = True # still loading the model
|
|
1302
|
+
return False
|
|
1303
|
+
|
|
1304
|
+
|
|
1305
|
+
def _server_cwd():
|
|
1306
|
+
checkout = Path(__file__).resolve().parents[1]
|
|
1307
|
+
if not sys.flags.isolated and _norm(_os.getcwd()) == _norm(checkout):
|
|
1308
|
+
return str(checkout)
|
|
1309
|
+
return HOME_DIR
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
def _launch():
|
|
1313
|
+
try:
|
|
1314
|
+
if time.time() - _os.path.getmtime(SERVER_START_FAILED_FILE) < 300:
|
|
1315
|
+
return False
|
|
1316
|
+
except OSError:
|
|
1317
|
+
pass
|
|
1318
|
+
return _start_server()
|
|
1319
|
+
|
|
1320
|
+
|
|
1321
|
+
def _pid_is_own(pid):
|
|
1322
|
+
try:
|
|
1323
|
+
import psutil # noqa: F401
|
|
1324
|
+
except ImportError:
|
|
1325
|
+
try:
|
|
1326
|
+
return time.time() - _os.path.getmtime(PID_FILE) < 60
|
|
1327
|
+
except OSError:
|
|
1328
|
+
return False
|
|
1329
|
+
return _is_own_server_process(pid=pid)
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
def _other_server_port(pid):
|
|
1333
|
+
cur = _port()
|
|
1334
|
+
for p in _listen_ports(pid):
|
|
1335
|
+
if p == cur:
|
|
1336
|
+
continue
|
|
1337
|
+
h = _get_health(port=p)
|
|
1338
|
+
if h and h.get("root") and _norm(h["root"]) == _norm(HOME_DIR):
|
|
1339
|
+
return p
|
|
1340
|
+
return None
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def _shutdown_other_port(pid, port):
|
|
1344
|
+
if not _request_shutdown(port=port) or not _wait_port_free(port):
|
|
1345
|
+
return False
|
|
1346
|
+
_remove_pid_if(pid)
|
|
1347
|
+
return True
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
def ensure_server():
|
|
1351
|
+
"""True if this folder's up-to-date server answers; False -> work without a server."""
|
|
1352
|
+
global _FOREIGN_SERVER_ROOT, _SERVER_STARTING
|
|
1353
|
+
_FOREIGN_SERVER_ROOT = None
|
|
1354
|
+
_SERVER_STARTING = False
|
|
1355
|
+
h = _get_health()
|
|
1356
|
+
d = _health_decision(h)
|
|
1357
|
+
if d == "ok":
|
|
1358
|
+
_clear_server_notices()
|
|
1359
|
+
return True
|
|
1360
|
+
if d == "stale":
|
|
1361
|
+
if _stop_stale_server(h):
|
|
1362
|
+
return _launch()
|
|
1363
|
+
_notify("stale_server", "The old memory server could not be stopped. Check the server_port in each "
|
|
1364
|
+
"N3MC folder's config.json, then restart it by hand.")
|
|
1365
|
+
return True # same root, same DB: keep using it
|
|
1366
|
+
if d == "foreign":
|
|
1367
|
+
return _foreign(h)
|
|
1368
|
+
if d == "legacy":
|
|
1369
|
+
if _is_own_server_process(health=h) and _stop_stale_server(h):
|
|
1370
|
+
return _launch()
|
|
1371
|
+
return _foreign(h)
|
|
1372
|
+
# no server answers
|
|
1373
|
+
r = _follow_pid_file()
|
|
1374
|
+
if r is not None:
|
|
1375
|
+
return r
|
|
1376
|
+
return _launch()
|
|
1377
|
+
|
|
1378
|
+
|
|
1379
|
+
def _use_server():
|
|
1380
|
+
global _SERVER_OK
|
|
1381
|
+
if _SERVER_OK is None:
|
|
1382
|
+
try:
|
|
1383
|
+
_SERVER_OK = bool(ensure_server())
|
|
1384
|
+
except Exception as e: # noqa: BLE001
|
|
1385
|
+
print(f"N3MC: server check failed ({type(e).__name__}: {e})", file=sys.stderr)
|
|
1386
|
+
_SERVER_OK = False
|
|
1387
|
+
return _SERVER_OK
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
def _unavailable_reason():
|
|
1391
|
+
if _FOREIGN_SERVER_ROOT:
|
|
1392
|
+
return f"another N3MC folder's server is using port {_port()}"
|
|
1393
|
+
if _SERVER_STARTING:
|
|
1394
|
+
return "the memory server is still starting"
|
|
1395
|
+
return "the memory server is not running"
|
|
1396
|
+
|
|
1397
|
+
|
|
1398
|
+
# ============================================================ saving / searching
|
|
1399
|
+
|
|
1400
|
+
_PROCESS_SESSION_ID = str(uuid.uuid4())
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
def _env_session():
|
|
1404
|
+
return _os.environ.get("N3MC_FREE_CODEX_SESSION_ID") or None
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
def _buffer_direct(content, agent_name=None, session_id=None, turn_id=None, local_id=None):
|
|
1408
|
+
"""Save without the server (no embedding; a later --repair adds the vector). Never silent on failure."""
|
|
1409
|
+
try:
|
|
1410
|
+
conn = _open_db_direct()
|
|
1411
|
+
try:
|
|
1412
|
+
r = _store_record(conn, get_config(), content, agent_name, local_id,
|
|
1413
|
+
session_id or _env_session() or _PROCESS_SESSION_ID, turn_id, embed=False)
|
|
1414
|
+
finally:
|
|
1415
|
+
conn.close()
|
|
1416
|
+
if r.get("status") == "error":
|
|
1417
|
+
raise RuntimeError(r.get("message"))
|
|
1418
|
+
_clear_notice("save_failed")
|
|
1419
|
+
return r
|
|
1420
|
+
except Exception as e: # noqa: BLE001
|
|
1421
|
+
print("⚠️ Physical save failed. Current memories may be lost.", file=sys.stderr)
|
|
1422
|
+
_notify("save_failed", f"A record could not be saved ({type(e).__name__}: {e}). Current memories may be "
|
|
1423
|
+
"lost; if it happens again, check that no other program holds the memory database.")
|
|
1424
|
+
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
|
|
1425
|
+
|
|
1426
|
+
|
|
1427
|
+
def _connection_target(cfg=None):
|
|
1428
|
+
cfg = get_config() if cfg is None else cfg
|
|
1429
|
+
port = cfg.get("connect_server_port")
|
|
1430
|
+
root = cfg.get("connect_server_root")
|
|
1431
|
+
if bool(port) != bool(root):
|
|
1432
|
+
message = "Set both connect_server_port and connect_server_root; using standalone mode."
|
|
1433
|
+
notice = _notices_read().get("connection_incomplete")
|
|
1434
|
+
if not isinstance(notice, dict) or notice.get("message") != message:
|
|
1435
|
+
_notify("connection_incomplete", message)
|
|
1436
|
+
else:
|
|
1437
|
+
_clear_notice("connection_incomplete")
|
|
1438
|
+
return (port, root) if port and root else None
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def _verified_target(target):
|
|
1442
|
+
port, expected_root = target
|
|
1443
|
+
health = _get_health(port)
|
|
1444
|
+
root = health.get("root") if health else None
|
|
1445
|
+
return (isinstance(root, str) and _os.path.isabs(root)
|
|
1446
|
+
and _norm(root) == _norm(expected_root))
|
|
1447
|
+
|
|
1448
|
+
|
|
1449
|
+
def _save_record(content, agent_name=None, session_id=None, turn_id=None, local_id=None, project=None):
|
|
1450
|
+
cfg = get_config()
|
|
1451
|
+
target = _connection_target(cfg)
|
|
1452
|
+
if target:
|
|
1453
|
+
body = {"content": content, "agent_name": AGENT_NAME if agent_name is None else agent_name,
|
|
1454
|
+
"local_id": local_id or cfg["local_id"]}
|
|
1455
|
+
for key, value in (("session_id", session_id), ("turn_id", turn_id), ("project", project)):
|
|
1456
|
+
if value is not None:
|
|
1457
|
+
body[key] = value
|
|
1458
|
+
try:
|
|
1459
|
+
if not _verified_target(target):
|
|
1460
|
+
raise ValueError("configured server could not be verified")
|
|
1461
|
+
result = _post("/buffer", body, port=target[0])
|
|
1462
|
+
if not isinstance(result, dict) or result.get("status") not in ("ok", "skipped"):
|
|
1463
|
+
raise ValueError("server did not confirm save")
|
|
1464
|
+
return result
|
|
1465
|
+
except Exception as exc:
|
|
1466
|
+
return {"status": "error", "message": f"Connected save failed ({type(exc).__name__}); no local DB fallback."}
|
|
1467
|
+
if _use_server():
|
|
1468
|
+
body = {"content": content}
|
|
1469
|
+
for k, v in (("agent_name", agent_name), ("session_id", session_id), ("turn_id", turn_id),
|
|
1470
|
+
("local_id", local_id)):
|
|
1471
|
+
if v is not None:
|
|
1472
|
+
body[k] = v
|
|
1473
|
+
try:
|
|
1474
|
+
r = _post("/buffer", body)
|
|
1475
|
+
if isinstance(r, dict) and r.get("status") in ("ok", "skipped"):
|
|
1476
|
+
_clear_notice("save_failed") # any save that ends ok / skipped clears it (2026-11-22, F2)
|
|
1477
|
+
return r
|
|
1478
|
+
except Exception as e: # noqa: BLE001
|
|
1479
|
+
print(f"N3MC: server save failed ({type(e).__name__}); saving directly", file=sys.stderr)
|
|
1480
|
+
return _buffer_direct(content, agent_name, session_id, turn_id, local_id)
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
def _save_text(role, text, turn_id, session_id=None, project=None):
|
|
1484
|
+
"""Purify the whole message, chunk it, tag the chunks and save each. Returns (saved, failed)."""
|
|
1485
|
+
text = purify_text(text or "")
|
|
1486
|
+
if not text.strip():
|
|
1487
|
+
return 0, 0
|
|
1488
|
+
saved = failed = 0
|
|
1489
|
+
for rec in add_chunk_prefixes(role, chunk_text(text, 400, 40)):
|
|
1490
|
+
r = _save_record(rec, AGENT_NAME, session_id, turn_id, project=project)
|
|
1491
|
+
if r.get("status") == "ok":
|
|
1492
|
+
saved += 1
|
|
1493
|
+
elif r.get("status") == "error":
|
|
1494
|
+
failed += 1
|
|
1495
|
+
return saved, failed
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
def _placeholder(body_line, notices):
|
|
1499
|
+
out = ["# Recalled Memory Context", ""]
|
|
1500
|
+
for n in notices:
|
|
1501
|
+
out += [f"> ⚠️ N3MC notice: {n}", ""]
|
|
1502
|
+
out += [body_line, ""]
|
|
1503
|
+
return "\n".join(out)
|
|
1504
|
+
|
|
1505
|
+
|
|
1506
|
+
def _valid_search_hit(row):
|
|
1507
|
+
if not isinstance(row, dict) or not isinstance(row.get("content"), str):
|
|
1508
|
+
return False
|
|
1509
|
+
score = row.get("score")
|
|
1510
|
+
try:
|
|
1511
|
+
return (isinstance(row.get("timestamp"), str)
|
|
1512
|
+
and type(score) in (int, float) and math.isfinite(score))
|
|
1513
|
+
except OverflowError:
|
|
1514
|
+
return False
|
|
1515
|
+
|
|
1516
|
+
|
|
1517
|
+
def _search_exchanges(response, notices):
|
|
1518
|
+
raw_pairs = response.get("pairs")
|
|
1519
|
+
raw_omitted = response.get("pairs_omitted")
|
|
1520
|
+
malformed = False
|
|
1521
|
+
pairs, omitted = {}, {}
|
|
1522
|
+
if isinstance(raw_pairs, dict):
|
|
1523
|
+
for turn, chunks in raw_pairs.items():
|
|
1524
|
+
if not isinstance(chunks, list):
|
|
1525
|
+
malformed = True
|
|
1526
|
+
continue
|
|
1527
|
+
valid = [chunk for chunk in chunks if isinstance(chunk, dict)
|
|
1528
|
+
and isinstance(chunk.get("content"), str)]
|
|
1529
|
+
malformed |= len(valid) != len(chunks)
|
|
1530
|
+
if valid:
|
|
1531
|
+
pairs[turn] = valid
|
|
1532
|
+
elif raw_pairs is not None:
|
|
1533
|
+
malformed = True
|
|
1534
|
+
|
|
1535
|
+
if isinstance(raw_omitted, dict):
|
|
1536
|
+
for turn, count in raw_omitted.items():
|
|
1537
|
+
if type(count) is not int or count < 0:
|
|
1538
|
+
malformed = True
|
|
1539
|
+
elif count:
|
|
1540
|
+
omitted[turn] = count
|
|
1541
|
+
elif raw_omitted is not None:
|
|
1542
|
+
malformed = True
|
|
1543
|
+
|
|
1544
|
+
if malformed:
|
|
1545
|
+
notices.append("Supplementary exchanges could not be displayed in full.")
|
|
1546
|
+
return pairs, omitted
|
|
1547
|
+
|
|
1548
|
+
|
|
1549
|
+
def _search_text(query, session_id=None, since=None, until=None, *, cfg=None):
|
|
1550
|
+
cfg = get_config() if cfg is None else cfg
|
|
1551
|
+
query = sanitize_surrogates(query or "")[:cfg["search_query_max_chars"]]
|
|
1552
|
+
target = _connection_target(cfg)
|
|
1553
|
+
notices = _take_notices()
|
|
1554
|
+
if not query.strip():
|
|
1555
|
+
return _placeholder("_No relevant memories found._", notices)
|
|
1556
|
+
port = None
|
|
1557
|
+
if target:
|
|
1558
|
+
port = target[0]
|
|
1559
|
+
if not _verified_target(target):
|
|
1560
|
+
return _placeholder("_(memory search unavailable: the configured server could not be verified)_", notices)
|
|
1561
|
+
elif not _use_server():
|
|
1562
|
+
return _placeholder(f"_(memory search unavailable: {_unavailable_reason()})_", notices)
|
|
1563
|
+
body = {"query": query}
|
|
1564
|
+
if session_id:
|
|
1565
|
+
body["session_id"] = session_id
|
|
1566
|
+
if since:
|
|
1567
|
+
body["since"] = since
|
|
1568
|
+
if until:
|
|
1569
|
+
body["until"] = until
|
|
1570
|
+
try:
|
|
1571
|
+
r = _post("/search", body, port=port) if port else _post("/search", body)
|
|
1572
|
+
if not isinstance(r, dict) or not isinstance(r.get("results"), list):
|
|
1573
|
+
raise ValueError("invalid search response")
|
|
1574
|
+
results = [row for row in r["results"] if _valid_search_hit(row)]
|
|
1575
|
+
if len(results) != len(r["results"]):
|
|
1576
|
+
if not results:
|
|
1577
|
+
raise ValueError("no valid ranked search results")
|
|
1578
|
+
notices.append("Some ranked search results could not be displayed.")
|
|
1579
|
+
pairs, omitted = _search_exchanges(r, notices)
|
|
1580
|
+
context = render_memory_context(query, results, pairs, omitted, notices, connected=bool(target))
|
|
1581
|
+
return sanitize_surrogates(context)
|
|
1582
|
+
except Exception as e: # noqa: BLE001
|
|
1583
|
+
print(f"N3MC: search failed ({type(e).__name__}).", file=sys.stderr)
|
|
1584
|
+
return _placeholder(f"_(memory search unavailable: {type(e).__name__})_", notices)
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
# ============================================================ hook helpers
|
|
1588
|
+
|
|
1589
|
+
def _read_stdin_text():
|
|
1590
|
+
raw = getattr(sys.stdin, "buffer", None)
|
|
1591
|
+
return sys.stdin.read() if raw is None else raw.read().decode("utf-8")
|
|
1592
|
+
|
|
1593
|
+
|
|
1594
|
+
def _housekeeping():
|
|
1595
|
+
now = time.time()
|
|
1596
|
+
try:
|
|
1597
|
+
for name in _os.listdir(MEMORY_DIR):
|
|
1598
|
+
if re.fullmatch(r"skip_[0-9a-f]{64}", name):
|
|
1599
|
+
path = _os.path.join(MEMORY_DIR, name)
|
|
1600
|
+
try:
|
|
1601
|
+
if now - _os.path.getmtime(path) > 30 * 86400:
|
|
1602
|
+
_os.unlink(path)
|
|
1603
|
+
except FileNotFoundError:
|
|
1604
|
+
pass
|
|
1605
|
+
if _os.path.exists(AUDIT_LOG) and _os.path.getsize(AUDIT_LOG) > AUDIT_ROTATE_BYTES:
|
|
1606
|
+
_os.replace(AUDIT_LOG, AUDIT_LOG + ".1")
|
|
1607
|
+
except FileNotFoundError:
|
|
1608
|
+
pass
|
|
1609
|
+
except OSError as exc:
|
|
1610
|
+
print(f"N3MC: housekeeping failed ({exc})", file=sys.stderr)
|
|
1611
|
+
|
|
1612
|
+
|
|
1613
|
+
def cmd_stop():
|
|
1614
|
+
_housekeeping()
|
|
1615
|
+
return 0
|
|
1616
|
+
|
|
1617
|
+
|
|
1618
|
+
def cmd_init():
|
|
1619
|
+
from .codex_install import install
|
|
1620
|
+
|
|
1621
|
+
get_config()
|
|
1622
|
+
if not _connection_target():
|
|
1623
|
+
_open_db().close()
|
|
1624
|
+
return install()
|
|
1625
|
+
|
|
1626
|
+
|
|
1627
|
+
# ============================================================ read-only commands
|
|
1628
|
+
|
|
1629
|
+
def _fmt_line(r):
|
|
1630
|
+
agent = r.get("agent_name")
|
|
1631
|
+
fields = (r["id"], r["timestamp"], "-" if agent is None else agent, (r["content"] or "")[:80])
|
|
1632
|
+
return "\t".join(re.sub(r"[\r\n\t]", " ", field) for field in fields)
|
|
1633
|
+
|
|
1634
|
+
|
|
1635
|
+
def _bounds(since, until):
|
|
1636
|
+
try:
|
|
1637
|
+
return _time_bounds(since, until)
|
|
1638
|
+
except ValueError as exc:
|
|
1639
|
+
print(exc, file=sys.stderr)
|
|
1640
|
+
return None
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
def cmd_list(since=None, until=None, fmt="text"):
|
|
1644
|
+
b = _bounds(since, until)
|
|
1645
|
+
if b is None:
|
|
1646
|
+
return 2
|
|
1647
|
+
conn = _read_db_if_exists()
|
|
1648
|
+
if conn is None:
|
|
1649
|
+
print(f"No DB found at {DB_PATH}", file=sys.stderr)
|
|
1650
|
+
print("Total: 0 records", file=sys.stderr if fmt == "jsonl" else sys.stdout)
|
|
1651
|
+
return 0
|
|
1652
|
+
try:
|
|
1653
|
+
rows = _database.get_all_memories(conn, b[0], b[1])
|
|
1654
|
+
finally:
|
|
1655
|
+
conn.close()
|
|
1656
|
+
for r in rows:
|
|
1657
|
+
if fmt == "jsonl":
|
|
1658
|
+
print(json.dumps({k: r.get(k) for k in ("id", "timestamp", "agent_name", "content",
|
|
1659
|
+
"session_id", "turn_id", "owner_id", "local_id")},
|
|
1660
|
+
ensure_ascii=False))
|
|
1661
|
+
else:
|
|
1662
|
+
print(_fmt_line(r))
|
|
1663
|
+
print(f"Total: {len(rows)} records", file=sys.stderr if fmt == "jsonl" else sys.stdout)
|
|
1664
|
+
return 0
|
|
1665
|
+
|
|
1666
|
+
|
|
1667
|
+
def cmd_recall_thread(turn_id, before=2, after=2, fmt="text"):
|
|
1668
|
+
totals = sys.stderr if fmt == "jsonl" else sys.stdout
|
|
1669
|
+
conn = _read_db_if_exists()
|
|
1670
|
+
if conn is None:
|
|
1671
|
+
print(f"No DB found at {DB_PATH}", file=sys.stderr)
|
|
1672
|
+
print("Total: 0 records", file=totals)
|
|
1673
|
+
return 0
|
|
1674
|
+
try:
|
|
1675
|
+
columns = {r["name"] for r in conn.execute("PRAGMA table_info(memories)")}
|
|
1676
|
+
if "turn_id" not in columns:
|
|
1677
|
+
print("Total: 0 records", file=totals)
|
|
1678
|
+
return 0
|
|
1679
|
+
anchor = conn.execute(
|
|
1680
|
+
"SELECT MIN(rowid) AS lo, MAX(rowid) AS hi FROM memories WHERE turn_id=?", (turn_id,)
|
|
1681
|
+
).fetchone()
|
|
1682
|
+
if anchor["lo"] is None:
|
|
1683
|
+
print("Total: 0 records", file=totals)
|
|
1684
|
+
return 0
|
|
1685
|
+
session = conn.execute(
|
|
1686
|
+
"SELECT session_id FROM memories WHERE rowid=?", (anchor["lo"],)
|
|
1687
|
+
).fetchone()["session_id"] if "session_id" in columns else None
|
|
1688
|
+
if session:
|
|
1689
|
+
sql = """
|
|
1690
|
+
WITH turns AS (
|
|
1691
|
+
SELECT turn_id, MIN(rowid) AS lo, MAX(rowid) AS hi
|
|
1692
|
+
FROM memories WHERE turn_id IS NOT NULL AND turn_id != ?
|
|
1693
|
+
GROUP BY turn_id
|
|
1694
|
+
), same_session AS (
|
|
1695
|
+
SELECT turns.* FROM turns JOIN memories AS first ON first.rowid = turns.lo
|
|
1696
|
+
WHERE first.session_id = ?
|
|
1697
|
+
), previous AS (
|
|
1698
|
+
SELECT turn_id FROM same_session WHERE hi < ? ORDER BY hi DESC LIMIT ?
|
|
1699
|
+
), following AS (
|
|
1700
|
+
SELECT turn_id FROM same_session WHERE lo > ? ORDER BY lo LIMIT ?
|
|
1701
|
+
)
|
|
1702
|
+
SELECT * FROM memories WHERE turn_id IN (
|
|
1703
|
+
SELECT ? UNION ALL SELECT turn_id FROM previous UNION ALL SELECT turn_id FROM following
|
|
1704
|
+
) ORDER BY rowid
|
|
1705
|
+
"""
|
|
1706
|
+
# SQLite LIMIT parameters must fit a signed 64-bit integer.
|
|
1707
|
+
max_limit = (1 << 63) - 1
|
|
1708
|
+
args = (turn_id, session, anchor["lo"], min(max_limit, max(0, before)),
|
|
1709
|
+
anchor["hi"], min(max_limit, max(0, after)), turn_id)
|
|
1710
|
+
else:
|
|
1711
|
+
sql = "SELECT * FROM memories WHERE turn_id=? ORDER BY rowid"
|
|
1712
|
+
args = (turn_id,)
|
|
1713
|
+
rows = [dict(row) for row in conn.execute(sql, args)]
|
|
1714
|
+
finally:
|
|
1715
|
+
conn.close()
|
|
1716
|
+
for r in rows:
|
|
1717
|
+
if fmt == "jsonl":
|
|
1718
|
+
print(json.dumps({k: r.get(k) for k in ("id", "timestamp", "agent_name", "turn_id", "content")},
|
|
1719
|
+
ensure_ascii=False))
|
|
1720
|
+
else:
|
|
1721
|
+
print(_fmt_line(r))
|
|
1722
|
+
print(f"Total: {len(rows)} records", file=totals)
|
|
1723
|
+
return 0
|
|
1724
|
+
|
|
1725
|
+
|
|
1726
|
+
def cmd_show_turn(turn_id):
|
|
1727
|
+
conn = _read_db_if_exists()
|
|
1728
|
+
if conn is None:
|
|
1729
|
+
print(f"No DB found at {DB_PATH}", file=sys.stderr)
|
|
1730
|
+
rows = []
|
|
1731
|
+
else:
|
|
1732
|
+
try:
|
|
1733
|
+
columns = {r["name"] for r in conn.execute("PRAGMA table_info(memories)")}
|
|
1734
|
+
rows = get_memories_by_turn_id(conn, turn_id) if "turn_id" in columns else []
|
|
1735
|
+
finally:
|
|
1736
|
+
conn.close()
|
|
1737
|
+
rows.sort(key=lambda r: 0 if r["content"].startswith("[user") else 1)
|
|
1738
|
+
for r in rows:
|
|
1739
|
+
print(f"--- {r['id']} saved={_processor._fmt_saved(r['timestamp'])} ---")
|
|
1740
|
+
print(r["content"])
|
|
1741
|
+
print(f"Total: {len(rows)} records")
|
|
1742
|
+
return 0
|
|
1743
|
+
|
|
1744
|
+
|
|
1745
|
+
# ============================================================ --buffer / --search / --repair / --reembed
|
|
1746
|
+
|
|
1747
|
+
def cmd_buffer(text, agent_id=None):
|
|
1748
|
+
if text == "-":
|
|
1749
|
+
try:
|
|
1750
|
+
text = _read_stdin_text()
|
|
1751
|
+
except UnicodeDecodeError:
|
|
1752
|
+
print("N3MC: --buffer: stdin must be valid UTF-8.", file=sys.stderr)
|
|
1753
|
+
return 1
|
|
1754
|
+
text = sanitize_surrogates(text or "")
|
|
1755
|
+
if not text.strip():
|
|
1756
|
+
print("Skipped (empty).")
|
|
1757
|
+
return 0
|
|
1758
|
+
r = _save_record(text, agent_id, _env_session())
|
|
1759
|
+
if r.get("status") == "ok":
|
|
1760
|
+
print("Saved 1 record.")
|
|
1761
|
+
return 0
|
|
1762
|
+
if r.get("status") == "skipped":
|
|
1763
|
+
print(f"Skipped ({r.get('reason')}).")
|
|
1764
|
+
return 0
|
|
1765
|
+
print(r.get("message", "N3MC: record could not be saved."), file=sys.stderr)
|
|
1766
|
+
return 1
|
|
1767
|
+
|
|
1768
|
+
|
|
1769
|
+
def cmd_search(query, since=None, until=None):
|
|
1770
|
+
b = _bounds(since, until)
|
|
1771
|
+
if b is None:
|
|
1772
|
+
return 2
|
|
1773
|
+
out = _search_text(sanitize_surrogates(query or ""), _env_session(), b[0], b[1])
|
|
1774
|
+
sys.stdout.write(out if out.endswith("\n") else out + "\n")
|
|
1775
|
+
return 0
|
|
1776
|
+
|
|
1777
|
+
|
|
1778
|
+
def cmd_repair():
|
|
1779
|
+
if _connection_target():
|
|
1780
|
+
print("N3MC: --repair requires standalone mode.", file=sys.stderr)
|
|
1781
|
+
return 1
|
|
1782
|
+
if not _use_server():
|
|
1783
|
+
print(f"N3MC: --repair skipped ({_unavailable_reason()})", file=sys.stderr)
|
|
1784
|
+
return 0
|
|
1785
|
+
try:
|
|
1786
|
+
r = _post("/repair", {}, timeout=600)
|
|
1787
|
+
if not isinstance(r, dict) or r.get("status") != "ok":
|
|
1788
|
+
raise ValueError("server did not confirm repair")
|
|
1789
|
+
n = r.get("count")
|
|
1790
|
+
if type(n) is not int or n < 0:
|
|
1791
|
+
raise ValueError("invalid repair count")
|
|
1792
|
+
except Exception as e: # noqa: BLE001
|
|
1793
|
+
print(f"N3MC: repair failed ({type(e).__name__}: {e})", file=sys.stderr)
|
|
1794
|
+
return 1
|
|
1795
|
+
if n:
|
|
1796
|
+
print(f"Repaired {n} record(s).")
|
|
1797
|
+
return 0
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def cmd_reembed():
|
|
1801
|
+
cfg = get_config()
|
|
1802
|
+
if _connection_target(cfg):
|
|
1803
|
+
print("N3MC: --reembed requires standalone mode.", file=sys.stderr)
|
|
1804
|
+
return 1
|
|
1805
|
+
model = cfg["embed_model"]
|
|
1806
|
+
try:
|
|
1807
|
+
_processor.get_model(model)
|
|
1808
|
+
test = embed_passage("dimension probe", model)
|
|
1809
|
+
except Exception as e: # noqa: BLE001
|
|
1810
|
+
print(f"N3MC: --reembed: could not load {model} ({type(e).__name__}: {e})", file=sys.stderr)
|
|
1811
|
+
return 1
|
|
1812
|
+
current = _read_db_if_exists()
|
|
1813
|
+
dim = _database.EMBED_DIM # creation default, used only if there is no vector table yet
|
|
1814
|
+
if current is not None:
|
|
1815
|
+
try:
|
|
1816
|
+
if current.execute("SELECT 1 FROM sqlite_master WHERE name='memories_vec'").fetchone():
|
|
1817
|
+
dim = vec_dim(current)
|
|
1818
|
+
finally:
|
|
1819
|
+
current.close()
|
|
1820
|
+
if dim is None:
|
|
1821
|
+
print("N3MC: --reembed: could not read the dimension of memories_vec from its table definition.",
|
|
1822
|
+
file=sys.stderr)
|
|
1823
|
+
return 1
|
|
1824
|
+
if len(test) != dim:
|
|
1825
|
+
print(f"N3MC: --reembed: {model} makes {len(test)}-dimensional vectors but memories_vec has {dim}; "
|
|
1826
|
+
"a different dimension needs the manual procedure in §3 \"Embeddings\".", file=sys.stderr)
|
|
1827
|
+
return 1
|
|
1828
|
+
|
|
1829
|
+
h = _get_health()
|
|
1830
|
+
if h and h.get("root") and _norm(h["root"]) == _norm(HOME_DIR):
|
|
1831
|
+
stopped = _stop_stale_server(h)
|
|
1832
|
+
else:
|
|
1833
|
+
pid = _read_pid()
|
|
1834
|
+
previous_port = _other_server_port(pid) if pid is not None and _is_own_server_process(pid=pid) else None
|
|
1835
|
+
stopped = previous_port is None or _shutdown_other_port(pid, previous_port)
|
|
1836
|
+
if not stopped:
|
|
1837
|
+
print("N3MC: --reembed: could not stop the local memory server.", file=sys.stderr)
|
|
1838
|
+
return 1
|
|
1839
|
+
conn = _open_db()
|
|
1840
|
+
try:
|
|
1841
|
+
if vec_dim(conn) != dim:
|
|
1842
|
+
print("N3MC: --reembed: vector table changed during preflight.", file=sys.stderr)
|
|
1843
|
+
return 1
|
|
1844
|
+
total = count_memories(conn)
|
|
1845
|
+
cursor = 0
|
|
1846
|
+
if get_meta(conn, "reembed_model") == model:
|
|
1847
|
+
try:
|
|
1848
|
+
cursor = int(get_meta(conn, "reembed_cursor", 0))
|
|
1849
|
+
if not 0 <= cursor < 1 << 63:
|
|
1850
|
+
raise ValueError("cursor outside SQLite rowid range")
|
|
1851
|
+
except ValueError:
|
|
1852
|
+
print("N3MC: --reembed: invalid reembed_cursor in database metadata.", file=sys.stderr)
|
|
1853
|
+
return 1
|
|
1854
|
+
else:
|
|
1855
|
+
set_meta(conn, "reembed_model", model)
|
|
1856
|
+
set_meta(conn, "reembed_cursor", 0)
|
|
1857
|
+
conn.commit()
|
|
1858
|
+
done = conn.execute("SELECT COUNT(*) FROM memories WHERE rowid <= ?", (cursor,)).fetchone()[0]
|
|
1859
|
+
while True:
|
|
1860
|
+
rows = conn.execute("SELECT rowid AS rid, content FROM memories WHERE rowid > ? ORDER BY rowid LIMIT 200",
|
|
1861
|
+
(cursor,)).fetchall()
|
|
1862
|
+
if not rows:
|
|
1863
|
+
break
|
|
1864
|
+
try:
|
|
1865
|
+
vecs = [embed_passage(r["content"], model) for r in rows]
|
|
1866
|
+
except Exception as exc:
|
|
1867
|
+
print(f"N3MC: --reembed: embedding failed ({type(exc).__name__}: {exc}). "
|
|
1868
|
+
"Run --reembed again to resume.", file=sys.stderr)
|
|
1869
|
+
return 1
|
|
1870
|
+
if conn.in_transaction:
|
|
1871
|
+
conn.commit()
|
|
1872
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
1873
|
+
try:
|
|
1874
|
+
for r, v in zip(rows, vecs):
|
|
1875
|
+
conn.execute("DELETE FROM memories_vec WHERE rowid=?", (r["rid"],))
|
|
1876
|
+
conn.execute("INSERT INTO memories_vec(rowid, embedding) VALUES (?, ?)",
|
|
1877
|
+
(r["rid"], serialize_vector(v)))
|
|
1878
|
+
cursor = rows[-1]["rid"]
|
|
1879
|
+
set_meta(conn, "reembed_cursor", cursor)
|
|
1880
|
+
conn.commit()
|
|
1881
|
+
except BaseException:
|
|
1882
|
+
conn.rollback()
|
|
1883
|
+
raise
|
|
1884
|
+
done += len(rows)
|
|
1885
|
+
print(f"Re-embedded {done} / {total}", file=sys.stderr)
|
|
1886
|
+
set_meta(conn, "embed_model", model)
|
|
1887
|
+
set_meta(conn, "embed_dim", dim)
|
|
1888
|
+
set_meta(conn, "embed_model_at", datetime.now(timezone.utc).isoformat())
|
|
1889
|
+
delete_meta(conn, "reembed_model")
|
|
1890
|
+
delete_meta(conn, "reembed_cursor")
|
|
1891
|
+
conn.commit()
|
|
1892
|
+
finally:
|
|
1893
|
+
conn.close()
|
|
1894
|
+
_clear_notice("embed_model_mismatch")
|
|
1895
|
+
print(f"Re-embedded {total} record(s) with {model}.")
|
|
1896
|
+
return 0
|
|
1897
|
+
|
|
1898
|
+
|
|
1899
|
+
# ============================================================ main
|
|
1900
|
+
|
|
1901
|
+
def build_parser():
|
|
1902
|
+
p = argparse.ArgumentParser(prog="n3mc-free-codex", description="N3MemoryCore (Free): persistent memory for Codex")
|
|
1903
|
+
g = p.add_argument_group("commands").add_mutually_exclusive_group()
|
|
1904
|
+
g.add_argument("--init", action="store_true", help="create ~/.n3mc-free-codex and register the Codex hooks")
|
|
1905
|
+
g.add_argument("--buffer", metavar="TEXT", help="save text ('-' reads stdin)")
|
|
1906
|
+
g.add_argument("--search", metavar="QUERY", help="search memories")
|
|
1907
|
+
g.add_argument("--list", action="store_true", help="list records")
|
|
1908
|
+
g.add_argument("--recall-thread", metavar="TURN_ID", help="show the turns around a turn_id")
|
|
1909
|
+
g.add_argument("--show-turn", metavar="TURN_ID", help="show the full text of one exchange")
|
|
1910
|
+
g.add_argument("--repair", action="store_true", help="index records that lack vectors / FTS rows")
|
|
1911
|
+
g.add_argument("--reembed", action="store_true", help="re-embed all records with the configured model")
|
|
1912
|
+
g.add_argument("--stop", action="store_true", help="session-end clean-up (does not stop the server)")
|
|
1913
|
+
g.add_argument("--hook-submit", action="store_true", help=argparse.SUPPRESS)
|
|
1914
|
+
g.add_argument("--save-claude-turn", action="store_true", help=argparse.SUPPRESS)
|
|
1915
|
+
g.add_argument("--run-server", action="store_true", help=argparse.SUPPRESS)
|
|
1916
|
+
o = p.add_argument_group("options")
|
|
1917
|
+
o.add_argument("--agent-id", metavar="NAME", help="agent_name for --buffer")
|
|
1918
|
+
o.add_argument("--since", metavar="DATE")
|
|
1919
|
+
o.add_argument("--until", metavar="DATE")
|
|
1920
|
+
o.add_argument("--before", type=int)
|
|
1921
|
+
o.add_argument("--after", type=int)
|
|
1922
|
+
o.add_argument("--format", choices=("text", "jsonl"))
|
|
1923
|
+
return p
|
|
1924
|
+
|
|
1925
|
+
|
|
1926
|
+
def main(argv=None):
|
|
1927
|
+
_reconfigure_streams()
|
|
1928
|
+
parser = build_parser()
|
|
1929
|
+
args = parser.parse_args(argv)
|
|
1930
|
+
if (args.since is not None or args.until is not None) and args.search is None and not args.list:
|
|
1931
|
+
parser.error("--since and --until require --search or --list")
|
|
1932
|
+
if args.agent_id is not None and args.buffer is None:
|
|
1933
|
+
parser.error("--agent-id requires --buffer")
|
|
1934
|
+
if (args.before is not None or args.after is not None) and args.recall_thread is None:
|
|
1935
|
+
parser.error("--before and --after require --recall-thread")
|
|
1936
|
+
if args.format is not None and not args.list and args.recall_thread is None:
|
|
1937
|
+
parser.error("--format requires --list or --recall-thread")
|
|
1938
|
+
if args.show_turn == "" or args.recall_thread == "":
|
|
1939
|
+
parser.error("turn ID must not be empty")
|
|
1940
|
+
try:
|
|
1941
|
+
if args.run_server:
|
|
1942
|
+
return cmd_run_server()
|
|
1943
|
+
if args.hook_submit or args.save_claude_turn:
|
|
1944
|
+
from .codex_entry import prompt_main, stop_main
|
|
1945
|
+
|
|
1946
|
+
return prompt_main() if args.hook_submit else stop_main()
|
|
1947
|
+
if args.stop:
|
|
1948
|
+
return cmd_stop()
|
|
1949
|
+
if args.init:
|
|
1950
|
+
return cmd_init()
|
|
1951
|
+
if args.reembed:
|
|
1952
|
+
return cmd_reembed()
|
|
1953
|
+
if args.repair:
|
|
1954
|
+
return cmd_repair()
|
|
1955
|
+
if args.buffer is not None:
|
|
1956
|
+
return cmd_buffer(args.buffer, args.agent_id)
|
|
1957
|
+
if args.search is not None:
|
|
1958
|
+
return cmd_search(args.search, args.since, args.until)
|
|
1959
|
+
if args.list:
|
|
1960
|
+
return cmd_list(args.since, args.until, args.format or "text")
|
|
1961
|
+
if args.recall_thread:
|
|
1962
|
+
before = 2 if args.before is None else args.before
|
|
1963
|
+
after = 2 if args.after is None else args.after
|
|
1964
|
+
return cmd_recall_thread(args.recall_thread, before, after, args.format or "text")
|
|
1965
|
+
if args.show_turn:
|
|
1966
|
+
return cmd_show_turn(args.show_turn)
|
|
1967
|
+
except KeyboardInterrupt:
|
|
1968
|
+
return 130
|
|
1969
|
+
except (OSError, sqlite3.Error) as exc:
|
|
1970
|
+
print(f"N3MC: {exc}", file=sys.stderr)
|
|
1971
|
+
return 1
|
|
1972
|
+
parser.print_help()
|
|
1973
|
+
return 0
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
if __name__ == "__main__":
|
|
1977
|
+
sys.exit(main())
|