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,613 @@
1
+ """Processing layer: embeddings, ranking, purify, chunking, hybrid search, rendering."""
2
+ import math
3
+ import re
4
+ import sqlite3
5
+ import sys
6
+ import threading
7
+ import time
8
+ from bisect import bisect_right
9
+ from collections import Counter
10
+ from datetime import datetime, timezone
11
+
12
+ from .database import (
13
+ get_connection, init_db, insert_memory, search_vector, search_fts, search_fts_bigram,
14
+ get_all_memories, delete_memory, count_memories, check_exact_duplicate,
15
+ find_unindexed_memories, serialize_vector, get_memories_by_turn_id, strip_fts_punctuation,
16
+ deserialize_vector, fts_terms, bigram_terms, bigram_text, fts_index_text,
17
+ )
18
+
19
+ DEFAULT_MODEL = "intfloat/multilingual-e5-base"
20
+ MODEL_RETRY_SECONDS = 60
21
+
22
+ _model = None
23
+ _model_name = None
24
+ _model_failures = {}
25
+ _model_lock = threading.Lock()
26
+ _warned_embed = False
27
+
28
+
29
+ # ---------------------------------------------------------------- embeddings
30
+
31
+ def _load_model(name):
32
+ from sentence_transformers import SentenceTransformer
33
+ try:
34
+ return SentenceTransformer(name, device="cpu")
35
+ except Exception as load_error:
36
+ # Hub metadata requests can fail even when the complete model is cached.
37
+ from huggingface_hub import snapshot_download
38
+ try:
39
+ cached_path = snapshot_download(name, local_files_only=True)
40
+ except Exception:
41
+ raise load_error from None
42
+ return SentenceTransformer(cached_path, device="cpu")
43
+
44
+
45
+ def get_model(name=None):
46
+ """Load the model lazily and apply the retry delay to that model only."""
47
+ global _model, _model_name
48
+ name = name or _current_model_name()
49
+ with _model_lock:
50
+ if _model is not None and _model_name == name:
51
+ return _model
52
+ failure = _model_failures.get(name)
53
+ if failure and time.monotonic() - failure[0] < MODEL_RETRY_SECONDS:
54
+ raise RuntimeError(f"embedding model unavailable ({failure[1]})")
55
+ try:
56
+ _model = _load_model(name)
57
+ _model_name = name
58
+ _model_failures.pop(name, None)
59
+ return _model
60
+ except Exception as e: # noqa: BLE001
61
+ error = f"{type(e).__name__}: {e}"
62
+ _model_failures[name] = time.monotonic(), error
63
+ print(f"N3MC: could not load embedding model {name}: {error}", file=sys.stderr)
64
+ raise
65
+
66
+
67
+ def _current_model_name():
68
+ try:
69
+ from .. import n3memory
70
+ return n3memory.get_config().get("embed_model", DEFAULT_MODEL)
71
+ except Exception: # noqa: BLE001
72
+ return DEFAULT_MODEL
73
+
74
+
75
+ def _encode(text, name=None):
76
+ vec = get_model(name).encode([text], normalize_embeddings=True)[0]
77
+ return [float(x) for x in vec]
78
+
79
+
80
+ def embed_passage(text, name=None):
81
+ return _encode("passage: " + text, name)
82
+
83
+
84
+ def embed_query(text, name=None):
85
+ return _encode("query: " + text, name)
86
+
87
+
88
+ def cosine_sim_from_l2(distance):
89
+ return max(0.0, 1.0 - (distance * distance) / 2.0)
90
+
91
+
92
+ # ------------------------------------------------------------------- ranking
93
+
94
+ def _parse_ts(ts):
95
+ dt = datetime.fromisoformat(ts)
96
+ if dt.tzinfo is None:
97
+ dt = dt.replace(tzinfo=timezone.utc)
98
+ return dt
99
+
100
+
101
+ def time_decay(timestamp, half_life_days=90, now=None):
102
+ try:
103
+ then = _parse_ts(timestamp)
104
+ except Exception: # noqa: BLE001
105
+ return 1.0
106
+ now = now or datetime.now(timezone.utc)
107
+ days = max(0.0, (now - then).total_seconds() / 86400.0)
108
+ return 2.0 ** (-days / float(half_life_days))
109
+
110
+
111
+ def keyword_relevances(raw_scores, bm25_min_threshold=0.1, small_db=False):
112
+ """raw_scores: {key: bm25 raw (negative)}. Returns {key: [0,1]} normalised by this table's max."""
113
+ if not raw_scores:
114
+ return {}
115
+ mx = max(-v for v in raw_scores.values())
116
+ out = {}
117
+ if small_db:
118
+ for k, v in raw_scores.items():
119
+ out[k] = (-v / mx) if mx > 0 else 0.0
120
+ return out
121
+ denom = max(1.0, mx)
122
+ for k, v in raw_scores.items():
123
+ out[k] = 0.0 if abs(v) < bm25_min_threshold else max(0.0, -v) / denom
124
+ return out
125
+
126
+
127
+ def b_session(record_session, current_session):
128
+ return 1.0 if (current_session and record_session and record_session == current_session) else 0.6
129
+
130
+
131
+ # ------------------------------------------------------------ text processing
132
+
133
+ _SURR_RE = re.compile('[\ud800-\udfff]')
134
+
135
+
136
+ def sanitize_surrogates(obj):
137
+ """Remove lone surrogate code points (recursively through dicts and lists)."""
138
+ if isinstance(obj, str):
139
+ return _SURR_RE.sub('', obj)
140
+ if isinstance(obj, dict):
141
+ return {sanitize_surrogates(k): sanitize_surrogates(v) for k, v in obj.items()}
142
+ if isinstance(obj, list):
143
+ return [sanitize_surrogates(v) for v in obj]
144
+ return obj
145
+
146
+
147
+ _CODE_BLOCK_RE = re.compile(r"```[^\n`]*\n.*?```", re.DOTALL)
148
+
149
+
150
+ def purify_text(text):
151
+ if text is None:
152
+ return ""
153
+ text = sanitize_surrogates(text)
154
+ return _CODE_BLOCK_RE.sub("[code omitted]", text)
155
+
156
+
157
+ _SENT_RE = re.compile(r'(?<=[.!?])\s+|(?<=[。!?])')
158
+ _PARAGRAPH_BREAK_RE = re.compile(r'\n\s*\n')
159
+
160
+
161
+ def chunk_text(text, max_chars=400, overlap=40):
162
+ """Take exact slices, preferring paragraph breaks, then sentence breaks."""
163
+ if not text or not text.strip():
164
+ return []
165
+ if max_chars < 1:
166
+ raise ValueError("max_chars must be positive")
167
+ if len(text) <= max_chars:
168
+ return [text]
169
+
170
+ boundaries = [[m.end() for m in pattern.finditer(text)]
171
+ for pattern in (_PARAGRAPH_BREAK_RE, _SENT_RE)]
172
+ overlap = max(0, min(overlap, max_chars - 1))
173
+ chunks = []
174
+ cursor = 0
175
+ while cursor < len(text):
176
+ start = max(0, cursor - overlap)
177
+ end = min(start + max_chars, len(text))
178
+ if end < len(text):
179
+ for positions in boundaries:
180
+ index = bisect_right(positions, end) - 1
181
+ if index >= 0 and positions[index] > cursor:
182
+ end = positions[index]
183
+ break
184
+ if text[start:end].strip():
185
+ chunks.append(text[start:end])
186
+ cursor = end
187
+ return chunks
188
+
189
+
190
+ def add_chunk_prefixes(role, chunks):
191
+ n = len(chunks)
192
+ if n == 1:
193
+ return [f"[{role}] {chunks[0]}"]
194
+ return [f"[{role} {i}/{n}] {c}" for i, c in enumerate(chunks, 1)]
195
+
196
+
197
+ # ------------------------------------------------------------------- searching
198
+
199
+ def _as_row(rec, cos, kw, session_id, cfg, now):
200
+ td = time_decay(rec["timestamp"], cfg["half_life_days"], now)
201
+ bs = b_session(rec.get("session_id"), session_id)
202
+ filt = cos * 0.7 + kw * 0.3
203
+ return {
204
+ "rowid": rec.get("rowid"), "id": rec["id"], "content": rec["content"], "timestamp": rec["timestamp"],
205
+ "turn_id": rec.get("turn_id"), "agent_name": rec.get("agent_name"), "session_id": rec.get("session_id"),
206
+ "cos_sim": cos, "keyword_relevance": kw, "filter_score": filt, "score": filt * td * bs, "weak": False,
207
+ }
208
+
209
+
210
+ def _matched_terms(content, terms):
211
+ """How many distinct query terms (trigram terms, bigram terms) occur in ``content``."""
212
+ tri, bi = terms
213
+ low = strip_fts_punctuation(content).lower()
214
+ toks = set(bigram_text(content).lower().split())
215
+ hit = {t.lower() for t in tri if t.lower() in low}
216
+ hit |= {t.lower() for t in bi if t.lower() in toks}
217
+ return len(hit)
218
+
219
+
220
+ _CJK_RE = re.compile(r'[぀-ヿ㐀-鿿가-힯]')
221
+ _PREFIX_RE = re.compile(r'^\[(?:user|claude)(?: \d+/\d+)?\] ')
222
+
223
+
224
+ def _is_cjk_text(text):
225
+ """True when the text (without its [user] / [claude i/N] tag) has CJK characters in a fifth or
226
+ more of its letters."""
227
+ body = _PREFIX_RE.sub('', text or '')
228
+ letters = [ch for ch in body if ch.isalpha()]
229
+ if not letters:
230
+ return False
231
+ return sum(1 for ch in letters if _CJK_RE.match(ch)) * 5 >= len(letters)
232
+
233
+
234
+ def _sort_key(r):
235
+ return (r["score"], r["timestamp"], r["id"])
236
+
237
+
238
+ def _dot(a, b):
239
+ return sum(x * y for x, y in zip(a, b))
240
+
241
+
242
+ def _stored_vector(conn, rowid):
243
+ row = conn.execute("SELECT embedding FROM memories_vec WHERE rowid=?", (rowid,)).fetchone()
244
+ return deserialize_vector(row[0]) if row and row[0] is not None else None
245
+
246
+
247
+ def _turn_representative(conn, turn_id, min_chars):
248
+ for r in conn.execute("SELECT rowid, content FROM memories WHERE turn_id=? AND content LIKE '[claude%' "
249
+ "ORDER BY rowid", (turn_id,)).fetchall():
250
+ if len(r["content"]) >= min_chars:
251
+ return _stored_vector(conn, r["rowid"])
252
+ return None
253
+
254
+
255
+ def _order_versions_newest_first(conn, results, cfg):
256
+ """Group results whose turns hold near-identical replies and put the newest version first."""
257
+ turns = []
258
+ for r in results:
259
+ if r.get("turn_id") and r["turn_id"] not in turns:
260
+ turns.append(r["turn_id"])
261
+ reps = {}
262
+ for t in turns:
263
+ v = _turn_representative(conn, t, cfg["version_min_chars"])
264
+ if v is not None:
265
+ reps[t] = v
266
+ ts = list(reps)
267
+ parent = {t: t for t in ts}
268
+
269
+ def find(x):
270
+ while parent[x] != x:
271
+ parent[x] = parent[parent[x]]
272
+ x = parent[x]
273
+ return x
274
+
275
+ for i in range(len(ts)):
276
+ for j in range(i + 1, len(ts)):
277
+ if _dot(reps[ts[i]], reps[ts[j]]) >= cfg["version_sim_threshold"]:
278
+ parent[find(ts[i])] = find(ts[j])
279
+ groups = {}
280
+ for t in ts:
281
+ groups.setdefault(find(t), []).append(t)
282
+ for members in groups.values():
283
+ if len(members) < 2:
284
+ continue
285
+ first_row = {}
286
+ for t in members:
287
+ r0 = conn.execute("SELECT timestamp, id FROM memories WHERE turn_id=? ORDER BY rowid LIMIT 1",
288
+ (t,)).fetchone()
289
+ first_row[t] = (r0["timestamp"], r0["id"]) if r0 else ("", "")
290
+ order = sorted(members, key=lambda t: first_row[t], reverse=True)
291
+ positions = [i for i, r in enumerate(results) if r.get("turn_id") in members]
292
+ new_rows = []
293
+ for t in order:
294
+ new_rows.extend(r for r in results if r.get("turn_id") == t)
295
+ old = [results[p] for p in positions]
296
+ for p, row, o in zip(positions, new_rows, old):
297
+ results[p] = {**row, "score": o["score"], "filter_score": o["filter_score"], "_version_group": True}
298
+ return results
299
+
300
+
301
+ def _collapse_identical_content(results):
302
+ first_pos, newest = {}, {}
303
+ for i, r in enumerate(results):
304
+ c = r["content"]
305
+ first_pos.setdefault(c, i)
306
+ if c not in newest or (r["timestamp"], r["id"]) > (newest[c]["timestamp"], newest[c]["id"]):
307
+ newest[c] = r
308
+ out = []
309
+ for i, r in enumerate(results):
310
+ if first_pos[r["content"]] != i:
311
+ continue
312
+ n = newest[r["content"]]
313
+ out.append({**r, "id": n["id"], "timestamp": n["timestamp"], "turn_id": n["turn_id"],
314
+ "rowid": n.get("rowid")})
315
+ return out
316
+
317
+
318
+ def _rerank_by_reply(conn, query_vec, results, cfg):
319
+ try:
320
+ if query_vec is None or not results:
321
+ return results
322
+ alpha, floor, span = cfg["reply_sim_alpha"], cfg["reply_sim_floor"], cfg["reply_sim_span"]
323
+ sims = {}
324
+ for t in {r["turn_id"] for r in results if r.get("turn_id")}:
325
+ vecs = []
326
+ for r in conn.execute("SELECT rowid FROM memories WHERE turn_id=? AND content LIKE '[claude%'",
327
+ (t,)).fetchall():
328
+ v = _stored_vector(conn, r["rowid"])
329
+ if v:
330
+ vecs.append(v)
331
+ if vecs:
332
+ mean = [sum(c) / len(vecs) for c in zip(*vecs)]
333
+ sims[t] = _dot(query_vec, mean)
334
+ top = max((r["score"] for r in results), default=0.0) or 1.0
335
+ out = []
336
+ for r in results:
337
+ s = sims.get(r.get("turn_id"))
338
+ bonus = max(0.0, (s - floor) / span) if s is not None else 0.0
339
+ out.append({**r, "score": (1 - alpha) * r["score"] / top + alpha * bonus})
340
+ out.sort(key=_sort_key, reverse=True)
341
+ return out
342
+ except Exception: # noqa: BLE001
343
+ return results
344
+
345
+
346
+ def _related_evidence_bonus(query, top_matches, pool):
347
+ """Score weak candidates using rare terms corroborated by distinct top turns."""
348
+ seeds = {}
349
+ for row in top_matches[:3]:
350
+ if row.get("turn_id"):
351
+ seeds.setdefault(row["turn_id"], row)
352
+ if len(seeds) < 2 or not pool:
353
+ return {}
354
+
355
+ def terms(row):
356
+ return set(bigram_terms(fts_index_text(row["content"]).casefold(), stopwords=True))
357
+
358
+ query_terms = set(bigram_terms(query.casefold()))
359
+ support = Counter(term for row in seeds.values() for term in terms(row) - query_terms)
360
+ corroborated = {term for term, count in support.items() if count >= 2}
361
+ if not corroborated:
362
+ return {}
363
+
364
+ candidates = {row["id"]: terms(row) & corroborated for row in [*top_matches, *pool]}
365
+ frequency = Counter(term for matched in candidates.values() for term in matched)
366
+ total = len(candidates)
367
+ weights = {
368
+ term: math.log1p((total - count + 0.5) / (count + 0.5))
369
+ for term, count in frequency.items() if count <= total / 4
370
+ }
371
+ return {
372
+ rid: 0.025 * sum(sorted((weights[t] for t in matched if t in weights), reverse=True)[:2])
373
+ for rid, matched in candidates.items() if matched
374
+ }
375
+
376
+
377
+ def hybrid_search(conn, query, cfg, session_id=None, since=None, until=None, embed_fn=None):
378
+ """Hybrid (vector + trigram FTS + bigram FTS) search with the v1.6 shaping pipeline."""
379
+ global _warned_embed
380
+ limit = cfg["search_result_limit"]
381
+ now = datetime.now(timezone.utc)
382
+ if not (query or "").strip():
383
+ return {"results": [], "pairs": {}, "pairs_omitted": {}}
384
+ embed_fn = embed_fn or embed_query
385
+
386
+ # --- vector candidates
387
+ qvec = None
388
+ vec_hits = [] # (rec, cos)
389
+ try:
390
+ qvec = embed_fn(query)
391
+ for rec, dist in search_vector(conn, qvec, k=3 * limit, since=since, until=until):
392
+ vec_hits.append((rec, cosine_sim_from_l2(dist)))
393
+ except Exception as e: # noqa: BLE001
394
+ qvec = None
395
+ if not _warned_embed:
396
+ _warned_embed = True
397
+ print(f"Warning: vector search degraded (embed_query failed: {e})", file=sys.stderr)
398
+
399
+ # --- keyword candidates (per table normalisation)
400
+ # fts_stopwords drops English function words from the keyword terms; kw_only_min_terms keeps a
401
+ # row that only the keywords found (cosine under vector_min_cos) out of Top matches unless it
402
+ # contains that many distinct query terms (it can still come back as a weak match).
403
+ stop = bool(cfg.get("fts_stopwords", False))
404
+ min_terms = int(cfg.get("kw_only_min_terms", 0) or 0)
405
+ q_terms = (fts_terms(query, stop), bigram_terms(query, stop)) if min_terms > 1 else None
406
+ small = count_memories(conn) <= 2
407
+ actual_cos = {rec["id"]: cosine for rec, cosine in vec_hits}
408
+ kw = {} # id -> relevance
409
+ recs = {}
410
+ for fn in (search_fts, search_fts_bigram):
411
+ try:
412
+ hits = fn(conn, query, limit=3 * limit, since=since, until=until, stopwords=stop)
413
+ except Exception as e: # noqa: BLE001
414
+ print(f"N3MC: keyword search failed ({type(e).__name__}: {e}); continuing without it", file=sys.stderr)
415
+ continue
416
+ raw = {rec["id"]: s for rec, s in hits}
417
+ for rec, _ in hits:
418
+ recs[rec["id"]] = rec
419
+ for k, v in keyword_relevances(raw, cfg["bm25_min_threshold"], small).items():
420
+ kw[k] = max(kw.get(k, 0.0), v)
421
+
422
+ for rec, _ in vec_hits:
423
+ recs[rec["id"]] = rec
424
+
425
+ floor = cfg["vector_min_cos"]
426
+ # cross_lang_min_cos (0 = off): the best vector hit written in the
427
+ # other script (CJK vs. not) counts as a vector match from this cosine on, below vector_min_cos.
428
+ # A query and a record in different languages score lower with e5 than a same-language pair.
429
+ cross_floor = float(cfg.get("cross_lang_min_cos", 0) or 0)
430
+ cross_best = None
431
+ if cross_floor and actual_cos:
432
+ q_cjk = _is_cjk_text(query)
433
+ other = [(c, rid) for rid, c in actual_cos.items()
434
+ if c < floor and _is_cjk_text(recs[rid]["content"]) != q_cjk]
435
+ if other:
436
+ c_top, rid_top = max(other)
437
+ if c_top >= cross_floor:
438
+ cross_best = rid_top
439
+ elif ("cross_lang_min_cos" not in cfg and cfg.get("embed_model") == DEFAULT_MODEL
440
+ and len(actual_cos) >= 2):
441
+ # E5 cosine scales are model-specific. A clear lead supplies additional
442
+ # evidence when the two scripts have no lexical overlap.
443
+ first, second = sorted(actual_cos, key=actual_cos.get, reverse=True)[:2]
444
+ if (actual_cos[first] >= 0.80 and actual_cos[first] - actual_cos[second] >= 0.05
445
+ and _is_cjk_text(query) != _is_cjk_text(recs[first]["content"])):
446
+ cross_best = first
447
+ main, pool = [], []
448
+ for rid, rec in recs.items():
449
+ c_act = actual_cos.get(rid, 0.0)
450
+ k = kw.get(rid, 0.0)
451
+ pool.append(_as_row(rec, c_act, k, session_id, cfg, now))
452
+ c_main = c_act if (c_act >= floor or rid == cross_best) else 0.0
453
+ in_vec = c_main > 0.0
454
+ if not in_vec and rid not in kw:
455
+ continue
456
+ if not in_vec and q_terms and _matched_terms(rec["content"], q_terms) < min_terms:
457
+ continue # keyword-only with too few query terms: stays a weak-match candidate
458
+ main.append(_as_row(rec, c_main, k, session_id, cfg, now))
459
+
460
+ # step 2: min_score on filter_score
461
+ results = [r for r in main if r["filter_score"] >= cfg["min_score"]]
462
+ results.sort(key=_sort_key, reverse=True)
463
+ if cfg.get("reply_sim_rerank_enabled"):
464
+ results = _rerank_by_reply(conn, qvec, results, cfg)
465
+ # step 3
466
+ if cfg.get("version_order_enabled", True):
467
+ try:
468
+ results = _order_versions_newest_first(conn, results, cfg)
469
+ except Exception as e: # noqa: BLE001
470
+ print(f"N3MC: version ordering skipped ({e})", file=sys.stderr)
471
+ # step 4
472
+ if results:
473
+ top = max(r["filter_score"] for r in results)
474
+ ratio = cfg["relative_min_score_ratio"]
475
+ if ratio > 0:
476
+ results = [r for r in results if r.get("_version_group") or r["filter_score"] >= ratio * top]
477
+ # step 5
478
+ results = _collapse_identical_content(results)
479
+ # step 6 (top_matches_max: a cap on Top matches only; 0 = none, the
480
+ # vector candidates and the weak matches still use search_result_limit)
481
+ strong_cap = min(limit, int(cfg.get("top_matches_max", 0) or 0) or limit)
482
+ capped, per_turn = [], {}
483
+ for r in results:
484
+ t = r.get("turn_id")
485
+ if t:
486
+ if per_turn.get(t, 0) >= 2:
487
+ continue
488
+ per_turn[t] = per_turn.get(t, 0) + 1
489
+ capped.append(r)
490
+ if len(capped) >= strong_cap:
491
+ break
492
+ results = capped
493
+ # step 7: weak fill
494
+ target = min(cfg["min_results"], limit)
495
+ if cfg["min_results"] > 0 and len(results) < target:
496
+ have_ids = {r["id"] for r in results}
497
+ have_content = {r["content"] for r in results}
498
+ pool = [p for p in pool if p["id"] not in have_ids and p["filter_score"] >= 1e-6]
499
+ bonus = _related_evidence_bonus(query, results, pool)
500
+ pool.sort(key=lambda p: (p["filter_score"] + bonus.get(p["id"], 0.0),
501
+ p["timestamp"], p["id"]), reverse=True)
502
+ for p in pool:
503
+ if len(results) >= target:
504
+ break
505
+ if p["content"] in have_content:
506
+ continue
507
+ t = p.get("turn_id")
508
+ if t and per_turn.get(t, 0) >= 2:
509
+ continue
510
+ if t:
511
+ per_turn[t] = per_turn.get(t, 0) + 1
512
+ have_content.add(p["content"])
513
+ results.append({**p, "weak": True})
514
+ pairs, omitted = _build_pairs(conn, results, cfg)
515
+ return {"results": results, "pairs": pairs, "pairs_omitted": omitted}
516
+
517
+
518
+ def _role_order(rec):
519
+ return 0 if rec["content"].startswith("[user") else 1
520
+
521
+
522
+ def _build_pairs(conn, results, cfg):
523
+ pairs, omitted = {}, {}
524
+ total, seen = 0, []
525
+ for r in results:
526
+ t = r.get("turn_id")
527
+ if r.get("weak") or not t or t in seen:
528
+ continue
529
+ seen.append(t)
530
+ if len(seen) > cfg["pair_top_n"]:
531
+ break
532
+ try:
533
+ sibs = sorted(get_memories_by_turn_id(conn, t), key=_role_order)
534
+ except sqlite3.Error as exc:
535
+ print(f"N3MC: supplementary exchange lookup failed ({type(exc).__name__}); "
536
+ "keeping search matches", file=sys.stderr)
537
+ continue
538
+ taken = []
539
+ for i, s in enumerate(sibs):
540
+ if total + len(s["content"]) > cfg["pair_max_chars"]:
541
+ omitted[t] = len(sibs) - i
542
+ break
543
+ total += len(s["content"])
544
+ taken.append({"id": s["id"], "content": s["content"], "timestamp": s["timestamp"]})
545
+ if taken:
546
+ pairs[t] = taken
547
+ if t in omitted:
548
+ break
549
+ return pairs, omitted
550
+
551
+
552
+ # -------------------------------------------------------------------- render
553
+
554
+ def _fmt_saved(ts):
555
+ try:
556
+ dt = _parse_ts(ts)
557
+ try:
558
+ dt = dt.astimezone()
559
+ except (OverflowError, OSError, ValueError):
560
+ dt = dt.astimezone(timezone.utc)
561
+ off = dt.strftime("%z") or "+0000"
562
+ return f"{dt.strftime('%Y-%m-%d %H:%M')} (UTC{off})"
563
+ except Exception: # noqa: BLE001
564
+ return str(ts)
565
+
566
+
567
+ def render_memory_context(query, results, pairs=None, pairs_omitted=None, notices=None, *, connected=False):
568
+ pairs, pairs_omitted = pairs or {}, pairs_omitted or {}
569
+ lines = ["# Recalled Memory Context", f"Search query: {query}", ""]
570
+ for n in notices or []:
571
+ lines += [f"> ⚠️ N3MC notice: {n}", ""]
572
+ normal = [r for r in results if not r.get("weak")]
573
+ weak = [r for r in results if r.get("weak")]
574
+ num = 0
575
+
576
+ def row(r):
577
+ nonlocal num
578
+ num += 1
579
+ turn = f" turn_id={r['turn_id']}" if r.get("turn_id") else ""
580
+ return [f"## [{num}] score={r['score']:.4f} saved={_fmt_saved(r['timestamp'])} "
581
+ f"{r.get('agent_name') or '-'}{turn}", r["content"], ""]
582
+
583
+ if normal:
584
+ lines += ["## Top matches (use these to answer the question)", "",
585
+ "_If several versions of the same content appear, the one with the newest `saved` "
586
+ "time is the current one._", ""]
587
+ for r in normal:
588
+ lines += row(r)
589
+ else:
590
+ lines += ["_No relevant memories found._", ""]
591
+ if weak:
592
+ lines += ["## Possibly related (weak matches — may be unrelated)", ""]
593
+ for r in weak:
594
+ lines += row(r)
595
+ if pairs or pairs_omitted:
596
+ lines += ["## Previous matching Q-A exchanges (supplementary context)", ""]
597
+ for t in list(pairs) + [t for t in pairs_omitted if t not in pairs]:
598
+ first = pairs.get(t, [{}])[0].get("timestamp")
599
+ head = f"### turn_id: {t}"
600
+ if first:
601
+ head += f" saved={_fmt_saved(first)}"
602
+ lines.append(head)
603
+ for s in pairs.get(t, []):
604
+ lines.append(s["content"])
605
+ if pairs_omitted.get(t):
606
+ full_text = (
607
+ f"Read full text with the connected product CLI: --show-turn {t} "
608
+ f"or --recall-thread {t}, using its configured data root." if connected else
609
+ f"Full text: `python -m n3memorycore_free_codex.n3memory --show-turn {t}`"
610
+ )
611
+ lines.append(f"_({pairs_omitted[t]} more chunk(s) of this exchange omitted. {full_text})_")
612
+ lines.append("")
613
+ return "\n".join(lines)