omp-memory 0.2.0__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.
omp_memory/db.py ADDED
@@ -0,0 +1,4638 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ omp-memory-db - SQLite-backed memory system with FTS5 full-text search.
4
+
5
+ Design constraints (verified by tests/test_memory_db.py):
6
+ - Opening a DB never deletes it. Corruption is reported, not silently repaired
7
+ by unlinking the file.
8
+ - Backups are consistent snapshots taken with VACUUM INTO, never a raw copy of
9
+ a live WAL database.
10
+ - FTS5 is maintained by triggers on the records table, so any write path keeps
11
+ the index in sync. Search input is tokenised and quoted before MATCH.
12
+ - Profile isolation lives in the profile_contexts table; no module-level
13
+ mutable state besides per-thread profile selection.
14
+ - Record ids are content-addressed: sha256 of type:content:source:project.
15
+ - Confidence is clamped to [0, 1]; reinforcement signals are validated.
16
+
17
+ Record types: FACT / ASSUMPTION / INFERENCE / DECISION / RULE / CORRECTION.
18
+ """
19
+ import difflib
20
+ import math
21
+ import sqlite3
22
+ import time
23
+ import subprocess
24
+ import re
25
+ import unicodedata
26
+ import json
27
+ import hashlib
28
+ import os
29
+ import glob
30
+ import threading
31
+ from datetime import datetime, timedelta, timezone
32
+ from pathlib import Path
33
+
34
+ def env_int(name: str, default: int, low: int = 0, high: int = 2 ** 31 - 1) -> int:
35
+ """Read an integer env var without ever raising.
36
+
37
+ These values are read at import time, so a typo like
38
+ OMP_MEMORY_BUSY_TIMEOUT_MS=30s used to abort the import of the whole
39
+ package -- the MCP server would not start at all, which reads to the
40
+ operator as "the tool is broken", not "one setting is wrong". A bad
41
+ value falls back to the default and is clamped to a sane range.
42
+ """
43
+ raw = os.environ.get(name)
44
+ if raw is None or raw == "":
45
+ return default
46
+ try:
47
+ value = int(str(raw).strip(), 10)
48
+ except (TypeError, ValueError):
49
+ return default
50
+ return max(low, min(high, value))
51
+
52
+
53
+ DB_PATH = os.environ.get("OMP_MEMORY_DB", str(Path.home() / ".omp/memory/memory.db"))
54
+ BACKUP_DIR = os.environ.get("OMP_MEMORY_BACKUP_DIR", str(Path.home() / ".omp/memory/backups"))
55
+ MAX_BACKUPS = env_int("OMP_MEMORY_MAX_BACKUPS", 10, 0, 1000)
56
+ BUSY_TIMEOUT_MS = env_int("OMP_MEMORY_BUSY_TIMEOUT_MS", 30000, 1, 600000)
57
+
58
+
59
+ def _restrict_to_owner(path: str) -> None:
60
+ """Best-effort 0600. POSIX honours it; Windows has no such mode bits and chmod only touches
61
+ the read-only flag, so a failure or a no-op there must not abort a backup or a repair."""
62
+ try:
63
+ os.chmod(path, 0o600)
64
+ except (OSError, NotImplementedError):
65
+ pass
66
+
67
+
68
+ VALID_TYPES = {"FACT", "ASSUMPTION", "INFERENCE", "DECISION", "RULE", "CORRECTION",
69
+ "INTENT", "WORKFLOW", "PROCEDURAL", "REFLECTIVE"}
70
+ VALID_SIGNALS = {"success", "failure", "correction", "reinforce", "decay"}
71
+ SIGNAL_DELTAS = {
72
+ "success": 0.1,
73
+ "failure": -0.1,
74
+ "correction": 0.15,
75
+ "reinforce": 0.05,
76
+ "decay": -0.05,
77
+ }
78
+
79
+ # Heat weights are fixed, not fitted. Fitting them to one corpus would bake that
80
+ # corpus's quirks into the ranking and make the numbers impossible to explain
81
+ # per record; fixed weights keep heat decomposable and comparable across
82
+ # sessions. They sum to 1.0 so heat stays inside [0, 1].
83
+ HEAT_WEIGHTS = {"confidence": 0.45, "recency": 0.25, "reinforcement": 0.30}
84
+ PROMOTE_HEAT = 0.80
85
+ PROMOTABLE_TYPES = ("INFERENCE", "ASSUMPTION")
86
+ DECAY_FLOOR = 0.15
87
+ # Power-law forgetting: retention = (1 + d/tau)**-beta, normalized so the
88
+ # 30-day point matches the old exponential half-life. Empirical forgetting
89
+ # curves follow a power law (Wixted & Ebbesen 1991; Murre & Dros 2015):
90
+ # fast early drop, long tail for genuinely important old records.
91
+ DECAY_POWER_TAU_DAYS = 10.0
92
+ DECAY_POWER_BETA = 0.5
93
+ # Schema-consistent prior (Tse et al. 2007): a new record that agrees with
94
+ # what high-confidence memory already holds starts closer to that memory's
95
+ # confidence; a contradictory one starts lower and must earn verification.
96
+ SCHEMA_PRIOR_WEIGHT = 0.2
97
+
98
+ # Heat recency rides the same power law as decay (see heat_parts).
99
+ HEAT_DECAY_POWER_TAU_DAYS = DECAY_POWER_TAU_DAYS
100
+ HEAT_DECAY_POWER_BETA = DECAY_POWER_BETA
101
+ # Spacing effect (Cepeda et al. 2006/2008): a repeat right after the last one
102
+ # is nearly worthless; the same repeat after a gap is what consolidates.
103
+ # The horizon is DECAY_POWER_TAU_DAYS: reinforcing on the scale of the
104
+ # retention curve is what keeps a record on it.
105
+ SPACING_MIN_GAP_HOURS = 1.0
106
+ SPACING_FULL_GAP_HOURS = 24.0
107
+ # Per-record memory strength (Duolingo HLR, Settles & Meeder 2016; MemoryBank
108
+ # 2305.10250): a successful recall at a spaced gap lengthens the record's own
109
+ # forgetting horizon; failure shortens it. decay_tau stores the personal tau
110
+ # in days (0 = global curve). Growth is multiplicative with a cap so one hot
111
+ # streak cannot make a record immortal; the floor keeps failure meaningful.
112
+ STRENGTH_GROWTH = 1.5
113
+ STRENGTH_SHRINK = 0.7
114
+ STRENGTH_TAU_MAX_DAYS = 365.0
115
+ STRENGTH_TAU_MIN_DAYS = 2.0
116
+ # Retrieval-induced forgetting (Anderson, Bjork & Bjork 1994; Murayama et
117
+ # al. 2014): retrieving some memories actively inhibits competing ones. A
118
+ # CORRECTION that supersedes an older record, or a retrieval that picks a
119
+ # winner out of a cluster of similar records, penalizes the loser by
120
+ # RIF_PENALTY. The penalty is ordinary confidence afterwards: inhibition
121
+ # wears off, and the record can still recover through reinforcement.
122
+ RIF_PENALTY = 0.15
123
+ RIF_MIN_CONFIDENCE = 0.7
124
+ # Retrieval practice (Roediger & Karpicke 2006): a successful retrieval is
125
+ # itself a learning event and beats restudying. Every recall that returns a
126
+ # record logs a zero-delta 'retrieval' signal; it moves nothing by itself
127
+ # but starts the spacing clock and feeds the consolidation pass. There,
128
+ # a record retrieved three or more times in the last week without a
129
+ # success signal earns CONSOLIDATE_GAIN: repeated retrieval without
130
+ # contradiction is evidence of stability.
131
+ RETRIEVAL_WINDOW_DAYS = 7
132
+ RETRIEVALS_FOR_CONSOLIDATION = 3
133
+ CONSOLIDATE_GAIN = 0.05
134
+ # Abstention (Chen & Liu 2018, "Recall Is Not What You Need"): if no candidate
135
+ # in the pool contains a single query term, nothing answers it and the caller
136
+ # gets abstained=True instead of a confident-looking list of near-misses. The
137
+ # rule is "at least one term matched", which does not depend on query length.
138
+ ABSTAIN_SCORE = 1
139
+ FORGET_FLOOR_SLACK = 0.01
140
+ FORGET_MIN_AGE_DAYS = 180
141
+ FORGET_WINDOW_DAYS = 365
142
+ # Offline consolidation (sleep-time compute, Lin et al. 2025): the pass runs
143
+ # decay, consolidation, pruning and eviction together, and evicts only when a
144
+ # project exceeds the budget. Budget is per project_id; unscoped records live
145
+ # under the empty-string project and are never evicted.
146
+ SLEEP_EVICT_BUDGET = 500
147
+ SLEEP_PRUNE_SIMILARITY = 0.80
148
+ # Conservative deletion (rate-distortion, A3): a merge is recoverable
149
+ # (the keeper still holds the fact) but a delete is not, so eviction
150
+ # requires stronger evidence of redundancy than a merge does.
151
+ # Hypercorrection (B2): correcting a high-confidence record produces a
152
+ # larger, more lasting update than correcting a doubtful one - the
153
+ # surprise gap drives the rewrite. Applied on reinforce(correction) when
154
+ # the record's confidence was already high, with a decay exemption so the
155
+ # correction is not immediately cooled back down.
156
+ HYPERCORRECTION_MIN_CONFIDENCE = 0.7
157
+ HYPERCORRECTION_FACTOR = 1.5
158
+ HYPERCORRECTION_DECAY_GRACE_DAYS = 30.0
159
+ # Event segmentation (B6): records written inside one event boundary share
160
+ # an event_id, so temporal joins and scoped replay can follow the event
161
+ # structure of a session instead of only its clock.
162
+ RECONSOLIDATION_WINDOW_MINUTES = 45.0
163
+ # Reconsolidation gate (Sevenster 2013; Lee et al. 2017): only a correction
164
+ # that contradicts what the record says opens the content-rewrite window.
165
+ # A success recall is read-only reinforcement, never a rewrite. The rewrite
166
+ # also demands trust: Metcalfe & Eich 2019 showed a wrong correction to a
167
+ # confidently-wrong record contaminates it deeper, so the caller must mark
168
+ # the correction as verified or the rewrite is refused.
169
+ REWRITE_MAX_CONTENT_LEN = 20000
170
+ # Hard ceiling on one stored record. Measured cause: five separate writers
171
+ # (reclaim, migrate, experience, agent writes, the .md ingest) each had their
172
+ # own idea of "one record", so entries of 2,000-2,400 characters sat beside
173
+ # 60-character facts. A record that long shares a term with almost any query
174
+ # and wins on matched-term fraction regardless of relevance -- measured: 30
175
+ # real prompts surfaced only 44 distinct records and one record appeared 10
176
+ # times. The ingest path splits at 700; this is the backstop for every other
177
+ # caller, so a new writer cannot reintroduce the problem.
178
+ MAX_RECORD_CHARS = 2000
179
+ # Superseded records keep their row (history is append-only) but are
180
+ # downranked in recall: the correction that replaced them is the current
181
+ # answer. A small penalty is enough because the replacement is usually
182
+ # the lexical match, not the loser; the replacement itself earns a small
183
+ # boost, so a correction outranks its stale twin rather than merely
184
+ # trailing it. Chain resolution lives on the write path: when a winner
185
+ # itself is superseded, every predecessor follows the new head, so a
186
+ # query always resolves a chain to its current answer.
187
+ SUPERSEDED_BOOST = 0.05
188
+ SUPERSEDED_PENALTY = 0.15
189
+ # Low-trust provenance. An auto-captured or scraped record competes with a
190
+ # human-verified one on equal footing unless something marks the difference.
191
+ # The penalty is deliberately small and only applies when the record is
192
+ # unverified AND its source is in the low-trust set: a big or unconditional
193
+ # penalty would downrank genuine auto-captured knowledge, which is most of a
194
+ # real corpus. Measured, not assumed: bench/provenance_ab.py.
195
+ PROVENANCE_PENALTY_ENABLED = True
196
+ PROVENANCE_PENALTY = 0.04
197
+ # A record whose anchor file changed (check_anchors sets stale=1) must not rank
198
+ # like a record whose evidence still holds. Measured before this constant
199
+ # existed: setting stale=1 moved the score by exactly 0.000000, so the whole
200
+ # checksum mechanism was written, tested, and completely inert at read time.
201
+ STALE_PENALTY = 0.20
202
+ LOW_TRUST_SOURCES = frozenset({
203
+ "auto-capture", "scrape", "scraped", "external", "web", "unknown",
204
+ })
205
+ # Cue-triggered recall for INTENT records (Rummel & Kvavilashvili 2023): a
206
+ # query carrying the intent's cue pulls the intent forward by this bonus,
207
+ # scaled by importance and faded by how long the intent has waited.
208
+ INTENT_CUE_BONUS = 0.10
209
+ # Intent decay tau (days): fulfillment probability fades like 1/(1+age/tau)
210
+ # (Rummel 2023 reports intentions lose ~.12 force per delay unit).
211
+ INTENT_DECAY_TAU_DAYS = 7.0
212
+
213
+ PRE_COMPRESS_CHECKPOINT_API_VERSION = 2
214
+
215
+ # Trust boundary. A record written through an agent surface (MCP, capture, the
216
+ # web editor) is a CLAIM about the world. Only an operator attestation makes it
217
+ # ATTESTED. Confidence on a claimed write is capped so an agent cannot promote
218
+ # its own opinion into high trust, and promotion to FACT requires ATTESTED:
219
+ # two success reports from one agent are one source, not corroboration.
220
+ TRUST_CLAIMED = "claimed"
221
+ TRUST_ATTESTED = "attested"
222
+ CLAIMED_CONFIDENCE_CAP = 0.65
223
+ # An attestation is a statement about a moment, not a permanent property. Past
224
+ # this age recall marks it and promotion treats the record as claimed again.
225
+ ATTESTED_MAX_AGE_DAYS = 90
226
+ # Credit assignment: records surfaced in a session before an objective outcome
227
+ # get a small signal, weighted by rank. Small on purpose: one run is noise.
228
+ CREDIT_ASSIGN_MAX_RANK = 10
229
+ CREDIT_ASSIGN_DELTA = 0.02
230
+ # Below this many labelled outcomes a calibration report is noise, so it says
231
+ # so instead of printing a number that looks authoritative.
232
+ CALIBRATION_MIN_SAMPLES = 30
233
+ # A stale attestation is not a lie, but it is no longer current: the file it
234
+ # named changed. Lower the confidence so a fresh unverified claim can outrank it.
235
+ EVIDENCE_STALE_PENALTY = 0.15
236
+ _SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
237
+ SCHEMA_VERSION = 20
238
+ # Recall reranking weights. Lexical is dominant (0.70) because recall is
239
+ # primarily an inquiry of relevance. Heat is moderate (0.25) so stale yet
240
+ # relevant records do not sink while breaking ties among equally relevant
241
+ # facts; confidence is already inside heat, so it gets no second term.
242
+ # Type prior is small (0.05) so trusted kinds (RULE, FACT) outrank INFERENCE
243
+ # without overriding topical relevance.
244
+ # Lexical dominates by design: on LoCoMo, recall() used to rank BELOW plain
245
+ # search() on hit@1 (0.274 vs 0.365) because a 0.25 heat weight could outvote a
246
+ # real lexical difference. Lifecycle is now a small tiebreaker over lexical,
247
+ # which is what the measurement asked for.
248
+ RECALL_WEIGHTS = {"lexical": 0.88, "heat": 0.07, "type_prior": 0.05}
249
+ TYPE_PRIOR = {
250
+ "RULE": 1.0,
251
+ "FACT": 1.0,
252
+ "CORRECTION": 0.85,
253
+ "DECISION": 0.60,
254
+ "WORKFLOW": 0.65,
255
+ "INTENT": 0.50,
256
+ "PROCEDURAL": 0.55,
257
+ "REFLECTIVE": 0.45,
258
+ "ASSUMPTION": 0.35,
259
+ "INFERENCE": 0.25,
260
+ }
261
+ RECALL_POOL_MIN = 20
262
+ # bm25 is type-blind: a tentative INFERENCE and a hard-won RULE matching the
263
+ # same words rank identically. Weight the bm25 rank by type so binding records
264
+ # surface above speculation on a lexical tie. Weight divides the (negative)
265
+ # rank, so a larger weight = smaller rank = earlier in the ORDER BY.
266
+ TYPE_BM25_WEIGHTS = {
267
+ "RULE": 1.4,
268
+ "CORRECTION": 1.4,
269
+ "WORKFLOW": 1.2,
270
+ "DECISION": 1.2,
271
+ "INTENT": 1.0,
272
+ "PROCEDURAL": 1.2,
273
+ "REFLECTIVE": 0.9,
274
+ "FACT": 1.0,
275
+ "INFERENCE": 0.8,
276
+ "ASSUMPTION": 0.7,
277
+ }
278
+ RECALL_POOL_FACTOR = 4
279
+ SNIPPET_CHARS = 120
280
+
281
+ _profile_context = threading.local()
282
+ _promotion_context = threading.local()
283
+
284
+
285
+ # --- helpers -----------------------------------------------------------------
286
+
287
+ def now_iso() -> str:
288
+ """Current UTC time as an ISO-8601 string (the store's timestamp format)."""
289
+ return datetime.now(timezone.utc).isoformat()
290
+
291
+
292
+ def sha(text: str) -> str:
293
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
294
+
295
+
296
+ def ensure_dirs():
297
+ """Create the database and backup directories if missing."""
298
+ Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
299
+ Path(BACKUP_DIR).mkdir(parents=True, exist_ok=True)
300
+
301
+
302
+ def get_profile() -> str:
303
+ """Profile name used for identity text and context lookups."""
304
+ return getattr(_profile_context, "profile", "default")
305
+
306
+
307
+ def set_profile(profile: str):
308
+ """Switch the process-wide profile name."""
309
+ _profile_context.profile = profile
310
+
311
+
312
+ def clear_profile():
313
+ """Reset the profile name to the default for this process."""
314
+ if hasattr(_profile_context, "profile"):
315
+ delattr(_profile_context, "profile")
316
+
317
+
318
+ def db_path_of(conn: sqlite3.Connection) -> str:
319
+ """Resolve the main database file of a live connection."""
320
+ row = conn.execute("PRAGMA database_list").fetchone()
321
+ if row is None:
322
+ return DB_PATH
323
+ try:
324
+ return row[2] or DB_PATH
325
+ except (IndexError, TypeError):
326
+ return DB_PATH
327
+
328
+
329
+ def record_id_for(rtype: str, content: str, source: str, project_id: str) -> str:
330
+ """Content-addressed id; identical inputs always yield the same id."""
331
+ return sha(f"{rtype}:{content}:{source or ''}:{project_id or ''}")
332
+
333
+
334
+ # --- identity ----------------------------------------------------------------
335
+
336
+ # Token pattern for lexical scoring: words, not punctuation, not underscores.
337
+ _TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)
338
+ _WS_RE = re.compile(r"\s+")
339
+
340
+
341
+ def normalize_content(content: str) -> str:
342
+ """Stored form: NFKC, runs of whitespace collapsed to one space, stripped.
343
+
344
+ Normalising on write means one fact has one spelling in the database, so a
345
+ tab, a trailing newline or fullwidth digits cannot create a second row.
346
+ """
347
+ text = unicodedata.normalize("NFKC", content or "")
348
+ # Zero-width and bidi control characters are invisible to a reader but not
349
+ # to a byte comparison: "run tests" with a ZWSP is a different row and a
350
+ # different FTS token. Drop the format category (Cf) and the zero-width
351
+ # space family, which NFKC does not fold.
352
+ # An invisible character inside a word is a homoglyph: drop it so
353
+ # "ref<ZWSP>unds" is the same fact as "refunds". Between two non-letters it
354
+ # is being used as a space, so keep the separation. Neither choice can be
355
+ # right for every case, but this closes the duplicate-row evasion without
356
+ # gluing two words together.
357
+ cleaned = []
358
+ for i, ch in enumerate(text):
359
+ if unicodedata.category(ch) == "Cf" or ch in "\u200b\u200c\u200d\u2060\ufeff":
360
+ prev = text[i - 1] if i else " "
361
+ nxt = text[i + 1] if i + 1 < len(text) else " "
362
+ if prev.isalnum() and nxt.isalnum():
363
+ continue
364
+ cleaned.append(" ")
365
+ else:
366
+ cleaned.append(ch)
367
+ text = "".join(cleaned)
368
+ return _WS_RE.sub(" ", text).strip()
369
+
370
+
371
+ def identity_text(content: str) -> str:
372
+ """Comparison form only; the stored text keeps its original casing."""
373
+ return normalize_content(content).casefold()
374
+
375
+
376
+ def normalize_cue(cue: str) -> str:
377
+ """Cue form: the normalized content, lowercased.
378
+
379
+ Cues are matched against query tokens, which the tokenizer already
380
+ lowercases, so a cased cue would need a second casefold on every read.
381
+ """
382
+ return normalize_content(cue).lower()
383
+
384
+
385
+ def content_id(content: str) -> str:
386
+ """Id is the normalised, case-folded content. Type and provenance excluded:
387
+ the same statement from another source or project is the same record.
388
+
389
+ A correction rewrite (reinforce, signal=correction) is the one operation
390
+ that deliberately breaks this binding: the row keeps its id while its
391
+ content moves to the corrected statement. Callers that need id-content
392
+ correspondence should read the row, not recompute content_id."""
393
+ return sha(identity_text(content))
394
+
395
+
396
+ def _uppercase_count(text: str) -> int:
397
+ return sum(1 for ch in text if ch.isupper())
398
+
399
+
400
+ def _richer_spelling(stored: str, incoming: str) -> str:
401
+ """Prefer the spelling with more capitalisation, ties keep what is stored.
402
+
403
+ Comparing by row means the result does not depend on write order for the
404
+ two-way case and never flaps between two writes of the same surface.
405
+ """
406
+ if _uppercase_count(incoming) > _uppercase_count(stored):
407
+ return incoming
408
+ return stored
409
+
410
+
411
+ def _merge_provenance(stored: str, incoming: str) -> str:
412
+ """Comma-joined, order-preserving, deduplicated.
413
+
414
+ Provenance accumulates, so merging two observations of one fact keeps both
415
+ names. Re-writing the same name is a no-op, which keeps the column stable
416
+ under repeated saves.
417
+ """
418
+ seen = [p for p in (stored or "").split(",") if p]
419
+ for p in (incoming or "").split(","):
420
+ if p and p not in seen:
421
+ seen.append(p)
422
+ return ",".join(seen)
423
+
424
+
425
+ # --- near-duplicate advisory -------------------------------------------------
426
+
427
+ # Similarity never merges on its own. Measured scores: real paraphrases of one
428
+ # fact land at 0.40-0.64, adversarial near-misses ("payment-service 1000" vs
429
+ # "shipping-service 1000") reach 0.82. No single threshold separates those two
430
+ # bands, so a high score is an advisory and the only automatic merge requires
431
+ # a number-identical candidate above UPSERT_THRESHOLD as well.
432
+ # SQLite's LIKE implementation has a pattern-complexity ceiling; tokens
433
+ # longer than this are truncated for the LIKE prefilter only.
434
+ MAX_LIKE_TOKEN = 64
435
+ SIMILAR_THRESHOLD = 0.50
436
+ UPSERT_THRESHOLD = 0.85
437
+
438
+
439
+ def _tokens(text: str) -> list:
440
+ return _TOKEN_RE.findall(identity_text(text))
441
+
442
+
443
+ _NUMERIC_RE = re.compile(
444
+ r"\d+(?:\.\d+)?\s*(?:"
445
+ r"seconds|secs|sec|minutes|mins|min|hours|hrs|hr|days|day|weeks|wk|months|years|yr"
446
+ r"|ms|tb|gb|mb|kb|px|rem|em|%|b|k|m|s|h|d|w|y"
447
+ r")?",
448
+ re.IGNORECASE)
449
+
450
+
451
+ def _numeric_tokens(text: str) -> frozenset:
452
+ """Numbers are compared exactly, including their unit.
453
+
454
+ "timeout 1000ms", "retention 30d", "$40k", "5GB" all reduce to nothing
455
+ under a bare isdigit() test, which silently disabled the number guard on
456
+ both the upsert path and the numeric-conflict branch. The unit is kept in
457
+ the token so "30 days" and "30 hours" cannot be treated as the same
458
+ quantity; whitespace between number and unit is normalised away.
459
+ """
460
+ out = set()
461
+ for m in _NUMERIC_RE.finditer(text):
462
+ t = re.sub(r"\s+", "", m.group(0).lower())
463
+ if not any(ch.isdigit() for ch in t):
464
+ continue
465
+ # Plural/long unit spellings normalise to one canonical form so
466
+ # "30 days" and "30d" are the same quantity, while "30d" and "30h"
467
+ # stay different.
468
+ t = re.sub(r"(seconds|secs|sec)$", "s", t)
469
+ t = re.sub(r"(minutes|mins|min)$", "min", t)
470
+ t = re.sub(r"(hours|hrs|hr)$", "h", t)
471
+ t = re.sub(r"(days|day)$", "d", t)
472
+ t = re.sub(r"(weeks|wk)$", "w", t)
473
+ t = re.sub(r"(months)$", "mo", t)
474
+ t = re.sub(r"(years|yr)$", "y", t)
475
+ out.add(t)
476
+ return frozenset(out)
477
+
478
+
479
+ def similarity(a: str, b: str) -> float:
480
+ """Jaccard over word tokens.
481
+
482
+ Jaccard, not the overlap coefficient: containment scoring returns 1.0 for
483
+ any text that is a subset of another, which made a short fragment look
484
+ identical to the whole record it came from.
485
+ """
486
+ ta, tb = set(_tokens(a)), set(_tokens(b))
487
+ if not ta or not tb:
488
+ return 0.0
489
+ return len(ta & tb) / len(ta | tb)
490
+
491
+
492
+ # --- backups -----------------------------------------------------------------
493
+
494
+ def rotate_backups():
495
+ """Keep the newest MAX_BACKUPS and delete the rest.
496
+
497
+ Sorted by (mtime, name): several backups can land in the same second,
498
+ and mtime alone then leaves the deletion order arbitrary -- an older
499
+ snapshot could survive while a newer one was deleted. The filename
500
+ carries the timestamp and a monotonic suffix, so it breaks the tie
501
+ correctly.
502
+ """
503
+ def _key(path):
504
+ return (os.path.getmtime(path), os.path.basename(path))
505
+
506
+ backups = sorted(glob.glob(os.path.join(BACKUP_DIR, "memory.db.bak.*")), key=_key)
507
+ while len(backups) > MAX_BACKUPS:
508
+ try:
509
+ os.remove(backups.pop(0))
510
+ except OSError:
511
+ pass
512
+
513
+
514
+ def backup_db(src: str) -> str:
515
+ """Consistent snapshot of src via VACUUM INTO. Returns the path, or "".
516
+
517
+ A raw file copy of a WAL database can capture a torn state: the main file
518
+ may not yet contain recently committed pages. VACUUM INTO writes a
519
+ compacted, self-consistent image.
520
+ """
521
+ if not os.path.exists(src):
522
+ return ""
523
+ ensure_dirs()
524
+ # Microseconds plus a collision loop: a seconds-resolution stamp made
525
+ # two backups in the same second overwrite each other, and rotation
526
+ # then kept an arbitrary subset instead of the newest N.
527
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%f")
528
+ for attempt in range(5):
529
+ dst = os.path.join(BACKUP_DIR,
530
+ f"memory.db.bak.{stamp}" + (f".{attempt}" if attempt else ""))
531
+ if os.path.exists(dst):
532
+ continue
533
+ try:
534
+ conn = sqlite3.connect(src, timeout=BUSY_TIMEOUT_MS / 1000.0)
535
+ try:
536
+ conn.execute("VACUUM INTO ?", (dst,))
537
+ finally:
538
+ conn.close()
539
+ _restrict_to_owner(dst)
540
+ rotate_backups()
541
+ return dst
542
+ except sqlite3.Error:
543
+ if os.path.exists(dst):
544
+ try:
545
+ os.remove(dst)
546
+ except OSError:
547
+ pass
548
+ continue
549
+ return ""
550
+
551
+
552
+ def repair_from_backup(db_path: str | None = None) -> bool:
553
+ """Restore db_path from the newest usable backup. Never deletes db_path.
554
+
555
+ VACUUM INTO reads a source database and writes a compacted image, so the
556
+ backup is the source and a temporary file is the destination. The target is
557
+ then replaced atomically, so a failure mid-repair cannot leave the database
558
+ missing.
559
+ """
560
+ db_path = db_path or os.environ.get("OMP_MEMORY_DB", DB_PATH)
561
+ backups = sorted(glob.glob(os.path.join(BACKUP_DIR, "memory.db.bak.*")),
562
+ key=os.path.getmtime, reverse=True)
563
+ for bak in backups:
564
+ if not os.path.exists(bak):
565
+ continue
566
+ tmp = f"{db_path}.repair-{os.getpid()}"
567
+ try:
568
+ src = sqlite3.connect(bak, timeout=BUSY_TIMEOUT_MS / 1000.0)
569
+ try:
570
+ row = src.execute("PRAGMA quick_check").fetchone()
571
+ usable = row is not None and str(row[0]) == "ok"
572
+ if usable:
573
+ src.execute("VACUUM INTO ?", (tmp,))
574
+ finally:
575
+ src.close()
576
+ if not usable:
577
+ continue
578
+ _restrict_to_owner(tmp)
579
+ os.replace(tmp, db_path)
580
+ for ext in ("-wal", "-shm"):
581
+ stale = db_path + ext
582
+ if os.path.exists(stale):
583
+ try:
584
+ os.remove(stale)
585
+ except OSError:
586
+ pass
587
+ return True
588
+ except (sqlite3.Error, OSError):
589
+ if os.path.exists(tmp):
590
+ try:
591
+ os.remove(tmp)
592
+ except OSError:
593
+ pass
594
+ continue
595
+ return False
596
+
597
+
598
+ # --- connections -------------------------------------------------------------
599
+
600
+ def connect(db_path: str | None = None) -> sqlite3.Connection:
601
+ """Open a connection. Raises on failure; the file is never removed."""
602
+ db_path = db_path or os.environ.get("OMP_MEMORY_DB", DB_PATH)
603
+ ensure_dirs()
604
+ conn = sqlite3.connect(db_path, timeout=BUSY_TIMEOUT_MS / 1000.0)
605
+ # The store holds everything the agent learned, including whatever a
606
+ # transcript leaked. Create it private; a world-readable memory file is one
607
+ # `cat` away for any other local user. Best-effort: a filesystem that does
608
+ # not support chmod must not stop the engine from opening.
609
+ try:
610
+ os.chmod(db_path, 0o600)
611
+ except OSError:
612
+ pass
613
+ conn.row_factory = sqlite3.Row
614
+ conn.execute("PRAGMA journal_mode=WAL")
615
+ conn.execute("PRAGMA synchronous=NORMAL")
616
+ conn.execute(f"PRAGMA busy_timeout={BUSY_TIMEOUT_MS}")
617
+ conn.execute("PRAGMA foreign_keys=ON")
618
+ # secure_delete: a forgotten or redacted row must not stay readable in
619
+ # free SQLite pages. Measured cost: ~10ms per 1000 deleted rows.
620
+ conn.execute("PRAGMA secure_delete=ON")
621
+ return conn
622
+
623
+
624
+ def store_version(conn: sqlite3.Connection) -> int:
625
+ """Change counter for cache invalidation across processes.
626
+
627
+ PRAGMA data_version increments when ANOTHER connection commits, so a
628
+ long-lived reader (web viewer, MCP server) can detect writes made by
629
+ the capture timer or a CLI call without polling row counts. Own writes
630
+ on this connection do not bump it; callers that also write through the
631
+ same connection should invalidate their caches at the write site.
632
+ """
633
+ return conn.execute("PRAGMA data_version").fetchone()[0]
634
+
635
+
636
+ def integrity_check(conn: sqlite3.Connection) -> bool:
637
+ """SQLite full integrity_check: slower than quick_check, catches more."""
638
+ return _run_check(conn, "integrity_check")
639
+
640
+
641
+ def _has_new_columns(conn: sqlite3.Connection) -> bool:
642
+ """Do the v11/v12 columns exist (migration may not have run yet)?"""
643
+ try:
644
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()}
645
+ except sqlite3.DatabaseError:
646
+ return False
647
+ return {"importance", "cue", "superseded_by"} <= cols
648
+
649
+
650
+ def _run_check(conn: sqlite3.Connection, pragma: str) -> bool:
651
+ """Run one integrity pragma; only real corruption counts as failure.
652
+
653
+ Two failure shapes here are contention, not a corrupt file:
654
+ - "database is locked"/"busy": a concurrent writer holds the lock.
655
+ - "malformed inverted index": an FTS5 shadow table is mid-write by
656
+ another connection. quick_check's scan is not snapshot-safe across a
657
+ concurrent FTS transaction even in WAL, so the verdict is transient.
658
+ It is retried, then arbitrated by fts5's own integrity-check command,
659
+ which is the canonical verdict for the index.
660
+ """
661
+ for attempt in range(8):
662
+ try:
663
+ row = conn.execute(f"PRAGMA {pragma}").fetchone()
664
+ value = str(row[0]) if row else "ok"
665
+ if value == "ok":
666
+ return True
667
+ if "malformed" in value:
668
+ if attempt < 7:
669
+ time.sleep(0.1)
670
+ continue
671
+ conn.execute(
672
+ "INSERT INTO records_fts(records_fts) VALUES('integrity-check')")
673
+ return True
674
+ return False
675
+ except sqlite3.OperationalError as exc:
676
+ if "locked" not in str(exc) and "busy" not in str(exc):
677
+ return False
678
+ time.sleep(0.02 * (attempt + 1))
679
+ except sqlite3.DatabaseError:
680
+ return False
681
+ return False
682
+
683
+
684
+ def quick_check(conn: sqlite3.Connection) -> bool:
685
+ """SQLite quick_check: True when the file is structurally sound."""
686
+ return _run_check(conn, "quick_check")
687
+
688
+
689
+ # --- schema ------------------------------------------------------------------
690
+
691
+ _RECORD_COLUMNS = (
692
+ "id", "type", "content", "evidence", "verified", "confidence", "source",
693
+ "tags", "created_at", "updated_at", "session_id", "project_id", "parent_id",
694
+ "project_ids", "last_decay_at", "about_peer", "event_id",
695
+ "decay_exempt_until", "superseded_by",
696
+ )
697
+ _RECORDS_DDL = """CREATE TABLE IF NOT EXISTS records (
698
+ id TEXT PRIMARY KEY,
699
+ type TEXT NOT NULL CHECK (type IN ('FACT','ASSUMPTION','INFERENCE','DECISION','RULE',
700
+ 'CORRECTION','INTENT','WORKFLOW','PROCEDURAL','REFLECTIVE')),
701
+ content TEXT NOT NULL,
702
+ evidence TEXT NOT NULL DEFAULT '',
703
+ verified INTEGER NOT NULL DEFAULT 0,
704
+ confidence REAL NOT NULL DEFAULT 0.5,
705
+ source TEXT NOT NULL DEFAULT '',
706
+ tags TEXT NOT NULL DEFAULT '',
707
+ created_at TEXT NOT NULL,
708
+ updated_at TEXT NOT NULL,
709
+ session_id TEXT NOT NULL DEFAULT '',
710
+ project_id TEXT NOT NULL DEFAULT '',
711
+ parent_id TEXT NOT NULL DEFAULT '',
712
+ project_ids TEXT NOT NULL DEFAULT '',
713
+ last_decay_at TEXT NOT NULL DEFAULT '',
714
+ about_peer TEXT NOT NULL DEFAULT '',
715
+ event_id TEXT NOT NULL DEFAULT '',
716
+ decay_exempt_until TEXT NOT NULL DEFAULT '',
717
+ superseded_by TEXT NOT NULL DEFAULT '',
718
+ importance REAL NOT NULL DEFAULT 0.5,
719
+ cue TEXT NOT NULL DEFAULT '',
720
+ decay_tau REAL NOT NULL DEFAULT 0,
721
+ valid_from TEXT NOT NULL DEFAULT '',
722
+ valid_until TEXT NOT NULL DEFAULT '',
723
+ anchor_path TEXT NOT NULL DEFAULT '',
724
+ anchor_sha TEXT NOT NULL DEFAULT '',
725
+ stale INTEGER NOT NULL DEFAULT 0,
726
+ consolidated_at TEXT NOT NULL DEFAULT '',
727
+ trust TEXT NOT NULL DEFAULT 'claimed',
728
+ attested_at TEXT NOT NULL DEFAULT ''
729
+ );"""
730
+
731
+
732
+ def _create_schema(conn: sqlite3.Connection):
733
+ conn.executescript(f"""
734
+ CREATE TABLE IF NOT EXISTS schema_version (
735
+ version INTEGER NOT NULL
736
+ );
737
+ {_RECORDS_DDL}
738
+ CREATE VIRTUAL TABLE IF NOT EXISTS records_fts USING fts5(
739
+ id, content, evidence, tags, tokenize="porter unicode61"
740
+ );
741
+ CREATE VIRTUAL TABLE IF NOT EXISTS records_fts_vocab
742
+ USING fts5vocab(records_fts, row);
743
+ CREATE TABLE IF NOT EXISTS sessions (
744
+ id TEXT PRIMARY KEY,
745
+ parent_id TEXT NOT NULL DEFAULT '',
746
+ started_at TEXT NOT NULL,
747
+ ended_at TEXT,
748
+ project_id TEXT NOT NULL DEFAULT '',
749
+ summary TEXT NOT NULL DEFAULT '',
750
+ capture_hash TEXT NOT NULL DEFAULT '',
751
+ profile TEXT NOT NULL DEFAULT ''
752
+ );
753
+ CREATE TABLE IF NOT EXISTS pre_compress_checkpoints (
754
+ id TEXT PRIMARY KEY,
755
+ session_id TEXT NOT NULL,
756
+ project_id TEXT NOT NULL DEFAULT '',
757
+ checkpoint_api_version INTEGER NOT NULL DEFAULT 2,
758
+ evidence_hash TEXT NOT NULL DEFAULT '',
759
+ record_count INTEGER NOT NULL DEFAULT 0,
760
+ payload TEXT NOT NULL DEFAULT '',
761
+ created_at TEXT NOT NULL,
762
+ restored_from TEXT NOT NULL DEFAULT ''
763
+ );
764
+ CREATE TABLE IF NOT EXISTS profile_contexts (
765
+ profile TEXT NOT NULL,
766
+ key TEXT NOT NULL,
767
+ value TEXT NOT NULL,
768
+ updated_at TEXT NOT NULL,
769
+ PRIMARY KEY (profile, key)
770
+ );
771
+ CREATE TABLE IF NOT EXISTS reinforcement (
772
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
773
+ record_id TEXT NOT NULL,
774
+ signal TEXT NOT NULL CHECK (signal IN ('success','failure','correction',
775
+ 'reinforce','decay','retrieval')),
776
+ delta REAL NOT NULL DEFAULT 0.1,
777
+ source TEXT NOT NULL DEFAULT '',
778
+ ts TEXT NOT NULL,
779
+ FOREIGN KEY (record_id) REFERENCES records(id)
780
+ );
781
+ CREATE INDEX IF NOT EXISTS idx_records_type ON records(type);
782
+ CREATE INDEX IF NOT EXISTS idx_records_project ON records(project_id);
783
+ CREATE INDEX IF NOT EXISTS idx_records_session ON records(session_id);
784
+ CREATE INDEX IF NOT EXISTS idx_records_parent ON records(parent_id);
785
+ CREATE INDEX IF NOT EXISTS idx_records_verified ON records(verified);
786
+ CREATE INDEX IF NOT EXISTS idx_records_confidence ON records(confidence);
787
+ CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_id);
788
+ CREATE INDEX IF NOT EXISTS idx_sessions_profile ON sessions(profile);
789
+ CREATE INDEX IF NOT EXISTS idx_checkpoints_session ON pre_compress_checkpoints(session_id);
790
+ CREATE INDEX IF NOT EXISTS idx_reinforcement_record ON reinforcement(record_id);
791
+ CREATE TABLE IF NOT EXISTS promotion_blocked (
792
+ record_id TEXT NOT NULL,
793
+ from_type TEXT NOT NULL,
794
+ reason TEXT NOT NULL,
795
+ heat REAL NOT NULL,
796
+ ts TEXT NOT NULL
797
+ );
798
+ CREATE TABLE IF NOT EXISTS promotion_log (
799
+ record_id TEXT NOT NULL,
800
+ from_type TEXT NOT NULL,
801
+ to_type TEXT NOT NULL,
802
+ heat REAL NOT NULL,
803
+ successes INTEGER NOT NULL DEFAULT 0,
804
+ sources TEXT NOT NULL DEFAULT '',
805
+ ts TEXT NOT NULL
806
+ );
807
+ CREATE TABLE IF NOT EXISTS forgotten_graveyard (
808
+ id TEXT PRIMARY KEY,
809
+ type TEXT NOT NULL,
810
+ content TEXT NOT NULL,
811
+ reason TEXT NOT NULL DEFAULT '',
812
+ ts TEXT NOT NULL
813
+ );
814
+ CREATE TABLE IF NOT EXISTS pending_writes (
815
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
816
+ rtype TEXT NOT NULL,
817
+ content TEXT NOT NULL,
818
+ evidence TEXT NOT NULL DEFAULT '',
819
+ confidence REAL NOT NULL DEFAULT 0.35,
820
+ source TEXT NOT NULL DEFAULT '',
821
+ tags TEXT NOT NULL DEFAULT '',
822
+ session_id TEXT NOT NULL DEFAULT '',
823
+ project_id TEXT NOT NULL DEFAULT '',
824
+ event_id TEXT NOT NULL DEFAULT '',
825
+ content_hash TEXT NOT NULL,
826
+ status TEXT NOT NULL DEFAULT 'pending',
827
+ created_at TEXT NOT NULL,
828
+ decided_at TEXT NOT NULL DEFAULT ''
829
+ );
830
+ CREATE TABLE IF NOT EXISTS not_conflict (
831
+ a TEXT NOT NULL,
832
+ b TEXT NOT NULL,
833
+ ts TEXT NOT NULL,
834
+ PRIMARY KEY (a, b)
835
+ );
836
+ CREATE INDEX IF NOT EXISTS idx_promotion_record ON promotion_log(record_id);
837
+ CREATE INDEX IF NOT EXISTS idx_graveyard_ts ON forgotten_graveyard(ts);
838
+ CREATE TABLE IF NOT EXISTS recall_events (
839
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
840
+ ts TEXT NOT NULL,
841
+ session_id TEXT NOT NULL DEFAULT '',
842
+ record_id TEXT NOT NULL,
843
+ query_hash TEXT NOT NULL DEFAULT '',
844
+ rank INTEGER NOT NULL DEFAULT 0,
845
+ channel TEXT NOT NULL DEFAULT 'recall',
846
+ confidence REAL NOT NULL DEFAULT 0
847
+ );
848
+ CREATE INDEX IF NOT EXISTS idx_recall_session ON recall_events(session_id);
849
+ CREATE INDEX IF NOT EXISTS idx_recall_record ON recall_events(record_id);
850
+ CREATE TABLE IF NOT EXISTS credit_assignments (
851
+ outcome_id INTEGER NOT NULL,
852
+ record_id TEXT NOT NULL,
853
+ PRIMARY KEY (outcome_id, record_id)
854
+ );
855
+ CREATE TABLE IF NOT EXISTS outcome_events (
856
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
857
+ ts TEXT NOT NULL,
858
+ session_id TEXT NOT NULL DEFAULT '',
859
+ kind TEXT NOT NULL,
860
+ evidence_ref TEXT NOT NULL DEFAULT ''
861
+ );
862
+ CREATE INDEX IF NOT EXISTS idx_outcome_session ON outcome_events(session_id);
863
+ CREATE TABLE IF NOT EXISTS evidence_checks (
864
+ record_id TEXT NOT NULL,
865
+ kind TEXT NOT NULL,
866
+ target TEXT NOT NULL DEFAULT '',
867
+ status TEXT NOT NULL,
868
+ detail TEXT NOT NULL DEFAULT '',
869
+ checked_at TEXT NOT NULL,
870
+ PRIMARY KEY (record_id, kind, target)
871
+ );
872
+ """)
873
+
874
+
875
+ _V20_TABLES = """
876
+ CREATE TABLE IF NOT EXISTS recall_events (
877
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
878
+ ts TEXT NOT NULL,
879
+ session_id TEXT NOT NULL DEFAULT '',
880
+ record_id TEXT NOT NULL,
881
+ query_hash TEXT NOT NULL DEFAULT '',
882
+ rank INTEGER NOT NULL DEFAULT 0,
883
+ channel TEXT NOT NULL DEFAULT 'recall',
884
+ confidence REAL NOT NULL DEFAULT 0
885
+ );
886
+ CREATE INDEX IF NOT EXISTS idx_recall_session ON recall_events(session_id);
887
+ CREATE INDEX IF NOT EXISTS idx_recall_record ON recall_events(record_id);
888
+ CREATE TABLE IF NOT EXISTS credit_assignments (
889
+ outcome_id INTEGER NOT NULL,
890
+ record_id TEXT NOT NULL,
891
+ PRIMARY KEY (outcome_id, record_id)
892
+ );
893
+ CREATE TABLE IF NOT EXISTS outcome_events (
894
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
895
+ ts TEXT NOT NULL,
896
+ session_id TEXT NOT NULL DEFAULT '',
897
+ kind TEXT NOT NULL,
898
+ evidence_ref TEXT NOT NULL DEFAULT ''
899
+ );
900
+ CREATE INDEX IF NOT EXISTS idx_outcome_session ON outcome_events(session_id);
901
+ CREATE TABLE IF NOT EXISTS evidence_checks (
902
+ record_id TEXT NOT NULL,
903
+ kind TEXT NOT NULL,
904
+ target TEXT NOT NULL DEFAULT '',
905
+ status TEXT NOT NULL,
906
+ detail TEXT NOT NULL DEFAULT '',
907
+ checked_at TEXT NOT NULL,
908
+ PRIMARY KEY (record_id, kind, target)
909
+ );
910
+ """
911
+
912
+
913
+ def _create_fts_triggers(conn: sqlite3.Connection):
914
+ """(Re)create the FTS sync triggers.
915
+
916
+ Called on every open by _reconcile_fts. When the three triggers already
917
+ exist the recreation is skipped: DROP+CREATE runs statement-by-statement
918
+ in autocommit, so a concurrent connection can observe the triggers
919
+ half-dropped (CREATE fails with "already exists" once another thread
920
+ re-adds them, "no such table" if a swap lands between the two halves).
921
+ The migration paths that legitimately replace the table drop them first.
922
+ """
923
+ # Existence is not enough: an older build keyed these triggers on the
924
+ # `id` column, and a DELETE ... WHERE id = ? makes FTS5 scan the whole
925
+ # content table (14k statements for one update at 14k rows, 264ms per
926
+ # write). The body is inspected so a database created by the old build
927
+ # gets the rowid-keyed triggers on its next open.
928
+ rows = conn.execute(
929
+ "SELECT sql FROM sqlite_master WHERE type='trigger'"
930
+ " AND name IN ('records_ai','records_ad','records_au')"
931
+ ).fetchall()
932
+ if len(rows) == 3 and all("rowid" in (r[0] or "") for r in rows):
933
+ return
934
+ conn.executescript("""
935
+ DROP TRIGGER IF EXISTS records_ai;
936
+ DROP TRIGGER IF EXISTS records_ad;
937
+ DROP TRIGGER IF EXISTS records_au;
938
+ CREATE TRIGGER records_ai AFTER INSERT ON records BEGIN
939
+ INSERT INTO records_fts(rowid, id, content, evidence, tags)
940
+ VALUES (new.rowid, new.id, new.content, new.evidence, new.tags);
941
+ END;
942
+ CREATE TRIGGER records_ad AFTER DELETE ON records BEGIN
943
+ DELETE FROM records_fts WHERE rowid = old.rowid;
944
+ END;
945
+ CREATE TRIGGER records_au AFTER UPDATE ON records BEGIN
946
+ DELETE FROM records_fts WHERE rowid = old.rowid;
947
+ INSERT INTO records_fts(rowid, id, content, evidence, tags)
948
+ VALUES (new.rowid, new.id, new.content, new.evidence, new.tags);
949
+ END;
950
+ """)
951
+
952
+
953
+
954
+ def _rebuild_records_check(conn: sqlite3.Connection) -> bool:
955
+ """Rebuild `records` when its CHECK constraint lacks a valid type.
956
+
957
+ SQLite cannot ALTER a CHECK, so adding a record type means rebuilding
958
+ the table. A new table is created, rows carry over, and the old table
959
+ is dropped. The rename would make FKs point at `records_old` and drop
960
+ the FTS triggers, so this is a new-table swap that keeps the name
961
+ `records`; `_reconcile_fts` recreates the trigger state afterwards.
962
+ The swap is one transaction: dying halfway would leave records
963
+ half-swapped and _migrate would never retry it. foreign_keys cannot
964
+ change inside a transaction, so the pragma calls bracket it.
965
+ """
966
+ check = conn.execute(
967
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='records'"
968
+ ).fetchone()[0]
969
+ stale = bool(check) and any(
970
+ f"'{t}'" not in check for t in sorted(VALID_TYPES)
971
+ )
972
+ if not stale:
973
+ return False
974
+ conn.execute("PRAGMA foreign_keys=off")
975
+ conn.execute("BEGIN")
976
+ try:
977
+ conn.execute(_RECORDS_DDL.replace(
978
+ "CREATE TABLE IF NOT EXISTS records", "CREATE TABLE records_new"))
979
+ carry = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
980
+ # rowid must travel with the row: the FTS index is keyed on it, so a
981
+ # rebuild that lets SQLite assign fresh rowids strands every FTS row
982
+ # on the old number. The stale rows then collide with new inserts
983
+ # ("constraint failed" on records_ai) and that write -- and every
984
+ # write after it -- fails. Reproduced on a live store: 26 orphans,
985
+ # next insert rowid 966 already taken by an orphan.
986
+ shared = "rowid," + ",".join(c for c in carry if c in _RECORD_COLUMNS)
987
+ conn.execute(f"INSERT INTO records_new ({shared})"
988
+ f" SELECT {shared} FROM records")
989
+ conn.execute("DROP TABLE records")
990
+ conn.execute("ALTER TABLE records_new RENAME TO records")
991
+ conn.execute("COMMIT")
992
+ except BaseException:
993
+ conn.execute("ROLLBACK")
994
+ raise
995
+ finally:
996
+ conn.execute("PRAGMA foreign_keys=on")
997
+ return True
998
+
999
+ def _current_schema_version(conn: sqlite3.Connection) -> int:
1000
+ try:
1001
+ row = conn.execute("SELECT version FROM schema_version").fetchone()
1002
+ return int(row[0]) if row else 0
1003
+ except sqlite3.Error:
1004
+ return 0
1005
+
1006
+
1007
+ def _reconcile_fts(conn: sqlite3.Connection):
1008
+ """Self-heal the FTS index and plain indexes on `records`.
1009
+
1010
+ Runs on every open, before the version gate: a database can reach
1011
+ SCHEMA_VERSION with a broken FTS index (a migration that crashed
1012
+ between the table swap and the refill, or the pre-hardened
1013
+ rename-based rebuild) and the version gate would never repair it.
1014
+ Trigger recreation and index creation are idempotent; the refill
1015
+ only fires when the index disagrees with the table, so a healthy
1016
+ database pays two counts and no writes.
1017
+ """
1018
+ _create_fts_triggers(conn)
1019
+ for name, col in (("idx_records_type", "type"),
1020
+ ("idx_records_project", "project_id"),
1021
+ ("idx_records_session", "session_id"),
1022
+ ("idx_records_parent", "parent_id"),
1023
+ ("idx_records_verified", "verified"),
1024
+ ("idx_records_confidence", "confidence")):
1025
+ conn.execute(f"CREATE INDEX IF NOT EXISTS {name} ON records({col})")
1026
+ fts_count = conn.execute("SELECT COUNT(*) FROM records_fts").fetchone()[0]
1027
+ rec_count = conn.execute("SELECT COUNT(*) FROM records").fetchone()[0]
1028
+ # Count equality is not health. A table rebuild that reassigned rowids
1029
+ # leaves the same NUMBER of FTS rows pointing at rowids the table no
1030
+ # longer has, so the counts still match while every future insert
1031
+ # collides with a stranded row. Compare identities instead.
1032
+ stale = conn.execute(
1033
+ "SELECT COUNT(*) FROM records_fts f LEFT JOIN records r"
1034
+ " ON r.rowid = f.rowid AND r.id = f.id WHERE r.rowid IS NULL"
1035
+ ).fetchone()[0]
1036
+ if fts_count != rec_count or stale:
1037
+ conn.execute("DELETE FROM records_fts")
1038
+ conn.execute(
1039
+ "INSERT INTO records_fts(rowid, id, content, evidence, tags)"
1040
+ " SELECT rowid, id, content, evidence, tags FROM records")
1041
+
1042
+
1043
+ def _migrate(conn: sqlite3.Connection):
1044
+ """Bring an older database up to SCHEMA_VERSION. Idempotent.
1045
+
1046
+ _reconcile_fts runs on BOTH paths. It used to run only on the
1047
+ already-current early return, so a legacy database that actually went
1048
+ through the migration blocks (v14 -> v18 and every other upgrade) ended
1049
+ up with an empty FTS index: quick_check passed, every row was present,
1050
+ and recall returned nothing. Reproduced with a synthetic v14 database:
1051
+ 30 rows, 0 FTS rows, recall 0 hits.
1052
+ """
1053
+ version = _current_schema_version(conn)
1054
+ if version >= SCHEMA_VERSION:
1055
+ _reconcile_fts(conn)
1056
+ return
1057
+
1058
+ if version < 1:
1059
+ # v1: FTS without the evidence column. Rebuild the index from records.
1060
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records_fts)").fetchall()]
1061
+ if cols and "evidence" not in cols:
1062
+ conn.execute("DROP TABLE records_fts")
1063
+ conn.execute(
1064
+ "CREATE VIRTUAL TABLE records_fts USING fts5(id, content, evidence, tags)"
1065
+ )
1066
+ conn.execute(
1067
+ "INSERT INTO records_fts(rowid, id, content, evidence, tags)"
1068
+ " SELECT rowid, id, content, evidence, tags FROM records"
1069
+ )
1070
+ _create_fts_triggers(conn)
1071
+ conn.execute("DELETE FROM schema_version")
1072
+ conn.execute("INSERT INTO schema_version(version) VALUES (1)")
1073
+ conn.commit()
1074
+
1075
+ if version < 2:
1076
+ # v2: checkpoints carry a restorable payload and a project id.
1077
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(pre_compress_checkpoints)").fetchall()]
1078
+ if cols and "payload" not in cols:
1079
+ conn.execute("ALTER TABLE pre_compress_checkpoints ADD COLUMN payload TEXT NOT NULL DEFAULT ''")
1080
+ if cols and "project_id" not in cols:
1081
+ conn.execute("ALTER TABLE pre_compress_checkpoints ADD COLUMN project_id TEXT NOT NULL DEFAULT ''")
1082
+ conn.execute("DELETE FROM schema_version")
1083
+ conn.execute("INSERT INTO schema_version(version) VALUES (2)")
1084
+ conn.commit()
1085
+
1086
+ if version < 3:
1087
+ # v3: provenance accumulates on a merge, so one row can name many
1088
+ # projects. Existing rows keep their ids; the column defaults to empty
1089
+ # and project_id stays the project that first wrote the record.
1090
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1091
+ if "project_ids" not in cols:
1092
+ conn.execute("ALTER TABLE records ADD COLUMN project_ids TEXT NOT NULL DEFAULT ''")
1093
+ conn.execute("DELETE FROM schema_version")
1094
+ conn.execute("INSERT INTO schema_version(version) VALUES (3)")
1095
+ conn.commit()
1096
+
1097
+ if version < 4:
1098
+ # v4 adds two append-only audit tables. Both are created by
1099
+ # _create_schema with IF NOT EXISTS, so this step only records that the
1100
+ # upgrade ran; an older database keeps every row it had.
1101
+ conn.execute("DELETE FROM schema_version")
1102
+ conn.execute("INSERT INTO schema_version(version) VALUES (4)")
1103
+ conn.commit()
1104
+
1105
+ if version < 5:
1106
+ # v5: decay needs its own anchor. Without it, applying decay twice
1107
+ # re-decays an already-decayed confidence for the same elapsed time,
1108
+ # which compounds instead of converging. last_decay_at records when the
1109
+ # value was last lowered; existing rows keep their data and begin
1110
+ # anchoring on updated_at until the first decay touches them.
1111
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1112
+ if "last_decay_at" not in cols:
1113
+ conn.execute("ALTER TABLE records ADD COLUMN last_decay_at TEXT NOT NULL DEFAULT ''")
1114
+ conn.execute("INSERT INTO schema_version(version) VALUES (5)")
1115
+ conn.commit()
1116
+
1117
+ if version < 6:
1118
+ # v6: the default FTS tokenizer indexes exact word forms only, so a
1119
+ # query for "deplo" or "deploying" misses a record that says "deploy".
1120
+ # porter unicode61 stems both sides and still supports prefix queries
1121
+ # ("deplo*"). The index is rebuilt from records, so existing rows keep
1122
+ # their ids and every recorded word stays searchable.
1123
+ conn.execute("DROP TABLE IF EXISTS records_fts_vocab")
1124
+ conn.execute("DROP TABLE records_fts")
1125
+ conn.execute(
1126
+ "CREATE VIRTUAL TABLE records_fts USING fts5("
1127
+ "id, content, evidence, tags, tokenize='porter unicode61')"
1128
+ )
1129
+ conn.execute(
1130
+ "INSERT INTO records_fts(rowid, id, content, evidence, tags)"
1131
+ " SELECT rowid, id, content, evidence, tags FROM records"
1132
+ )
1133
+ conn.execute(
1134
+ "CREATE VIRTUAL TABLE records_fts_vocab USING fts5vocab(records_fts, row)"
1135
+ )
1136
+ _create_fts_triggers(conn)
1137
+ conn.execute("DELETE FROM schema_version")
1138
+ if version < 7:
1139
+ # v7: typo tolerance. The vocabulary table mirrors the FTS index so a
1140
+ # query word the index has never seen can be repaired to its nearest
1141
+ # term instead of returning nothing. A read-only fts5vocab mirror
1142
+ # needs no maintenance; existing databases create it in place.
1143
+ has_vocab = conn.execute(
1144
+ "SELECT 1 FROM sqlite_master WHERE type='table' "
1145
+ "AND name='records_fts_vocab'").fetchone() is not None
1146
+ if not has_vocab:
1147
+ conn.execute(
1148
+ "CREATE VIRTUAL TABLE records_fts_vocab USING fts5vocab(records_fts, row)"
1149
+ )
1150
+ conn.execute("DELETE FROM schema_version")
1151
+ conn.execute("INSERT INTO schema_version(version) VALUES (7)")
1152
+ conn.commit()
1153
+
1154
+ if version < 8:
1155
+ # v8: retrieval practice (Roediger & Karpicke 2006). The signal CHECK
1156
+ # gains 'retrieval', logged by recall with delta 0. SQLite cannot
1157
+ # ALTER a CHECK, so the table is rebuilt and rows carried over.
1158
+ conn.execute("PRAGMA foreign_keys=off")
1159
+ conn.execute("BEGIN")
1160
+ conn.execute("ALTER TABLE reinforcement RENAME TO reinforcement_old")
1161
+ conn.execute(
1162
+ """CREATE TABLE reinforcement (
1163
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1164
+ record_id TEXT NOT NULL,
1165
+ signal TEXT NOT NULL CHECK (signal IN
1166
+ ('success','failure','correction','reinforce','decay','retrieval')),
1167
+ delta REAL NOT NULL DEFAULT 0.1,
1168
+ source TEXT NOT NULL DEFAULT '',
1169
+ ts TEXT NOT NULL,
1170
+ FOREIGN KEY (record_id) REFERENCES records(id)
1171
+ )""")
1172
+ conn.execute(
1173
+ "INSERT INTO reinforcement (id, record_id, signal, delta, source, ts)"
1174
+ " SELECT id, record_id, signal, delta, source, ts FROM reinforcement_old")
1175
+ conn.execute("DROP TABLE reinforcement_old")
1176
+ conn.execute("PRAGMA foreign_keys=on")
1177
+ conn.execute("COMMIT")
1178
+ conn.execute("DELETE FROM schema_version")
1179
+ conn.execute("INSERT INTO schema_version(version) VALUES (8)")
1180
+
1181
+ if version < 9:
1182
+ # v9: peer-scoped memory. `about_peer` marks whose facts a row is
1183
+ # about (nullable, default '' = operator's own). Filtering happens
1184
+ # in search, so a query can stay inside one peer's context.
1185
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1186
+ if cols and "about_peer" not in cols:
1187
+ conn.execute("ALTER TABLE records ADD COLUMN about_peer TEXT NOT NULL DEFAULT ''")
1188
+ conn.execute("DELETE FROM schema_version")
1189
+ conn.execute("INSERT INTO schema_version(version) VALUES (9)")
1190
+ conn.commit()
1191
+
1192
+ if version < 10:
1193
+ # v10: event segmentation (B6) and decay grace (B2). `event_id`
1194
+ # groups records written inside one event boundary so temporal
1195
+ # joins and scoped replay follow event structure, not just the
1196
+ # clock. `decay_exempt_until` shields a hypercorrected record
1197
+ # from decay for a grace period: the correction must be allowed
1198
+ # to settle before the forgetting curve applies again.
1199
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1200
+ if cols and "event_id" not in cols:
1201
+ conn.execute("ALTER TABLE records ADD COLUMN event_id TEXT NOT NULL DEFAULT ''")
1202
+ if cols and "decay_exempt_until" not in cols:
1203
+ conn.execute("ALTER TABLE records ADD COLUMN decay_exempt_until TEXT NOT NULL DEFAULT ''")
1204
+ _rebuild_records_check(conn)
1205
+ conn.execute("DELETE FROM schema_version")
1206
+ conn.execute("INSERT INTO schema_version(version) VALUES (10)")
1207
+ conn.commit()
1208
+ # The swap dropped the FTS triggers with the old records table;
1209
+ # recreate the index state before any write can land. On the
1210
+ # fresh-migration path the refill is a no-op (counts already
1211
+ # agree), so this only pays on the broken path.
1212
+ _reconcile_fts(conn)
1213
+
1214
+ if version < 11:
1215
+ # v11: supersede links. `superseded_by` points a superseded record at
1216
+ # the CORRECTION that replaced it, so recall can downrank it and a
1217
+ # caller can follow the chain instead of reading a stale fact as
1218
+ # current. Rewrites stay in the row history via the reinforcement log.
1219
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1220
+ if cols and "superseded_by" not in cols:
1221
+ conn.execute("ALTER TABLE records ADD COLUMN superseded_by TEXT NOT NULL DEFAULT ''")
1222
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_records_superseded ON records(superseded_by)")
1223
+ conn.execute("DELETE FROM schema_version")
1224
+ conn.execute("INSERT INTO schema_version(version) VALUES (11)")
1225
+ conn.commit()
1226
+
1227
+ if version < 12:
1228
+ # v12: intent fields. `cue` is the environment signal that should
1229
+ # trigger the intent (Rummel & Kvavilashvili 2023); `importance`
1230
+ # scales the recall bonus so an urgent intent outranks a casual
1231
+ # one when both cues appear in one query.
1232
+ # ALTER TABLE ADD COLUMN with a NOT NULL DEFAULT leaves the column
1233
+ # NULL on existing rows in this SQLite build: quick_check then
1234
+ # reports "NULL value in records.importance" even though a SELECT
1235
+ # shows the default. An explicit UPDATE backfills the real cells
1236
+ # and clears the report.
1237
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1238
+ if cols and "importance" not in cols:
1239
+ conn.execute("ALTER TABLE records ADD COLUMN importance REAL NOT NULL DEFAULT 0.5")
1240
+ if cols and "cue" not in cols:
1241
+ conn.execute("ALTER TABLE records ADD COLUMN cue TEXT NOT NULL DEFAULT ''")
1242
+ conn.execute("UPDATE records SET importance=0.5 WHERE importance IS NULL")
1243
+ conn.execute("UPDATE records SET cue='' WHERE cue IS NULL")
1244
+ conn.execute("DELETE FROM schema_version")
1245
+ conn.execute("INSERT INTO schema_version(version) VALUES (12)")
1246
+ conn.commit()
1247
+
1248
+ if version < 13:
1249
+ # v13: WORKFLOW record type (AMW 2409.07429, ExpeL 2308.10144).
1250
+ # Step-by-step procedures the operator confirmed working, distinct
1251
+ # from a DECISION (why) and a FACT (what): the workflow is the how.
1252
+ # Databases that already reached v12 skip the v10 block, so the
1253
+ # CHECK rebuild (SQLite cannot ALTER a CHECK) runs here too: the
1254
+ # guard checks the live CHECK, not the schema version.
1255
+ if _rebuild_records_check(conn):
1256
+ _reconcile_fts(conn)
1257
+ conn.execute("DELETE FROM schema_version")
1258
+ conn.execute("INSERT INTO schema_version(version) VALUES (13)")
1259
+ conn.commit()
1260
+
1261
+ if version < 13:
1262
+ # v13: WORKFLOW record type (AMW 2409.07429, ExpeL 2308.10144).
1263
+ # Step-by-step procedures the operator confirmed working, distinct
1264
+ # from a DECISION (why) and a FACT (what): the workflow is the how.
1265
+ # Databases that already reached v12 skip the v10 block, so the
1266
+ # CHECK rebuild (SQLite cannot ALTER a CHECK) runs here too: the
1267
+ # guard checks the live CHECK, not the schema version.
1268
+ if _rebuild_records_check(conn):
1269
+ _reconcile_fts(conn)
1270
+ conn.execute("DELETE FROM schema_version")
1271
+ conn.execute("INSERT INTO schema_version(version) VALUES (13)")
1272
+ conn.commit()
1273
+
1274
+ if version < 14:
1275
+ # v14: PROCEDURAL + REFLECTIVE types (MemBench 2506.21605).
1276
+ # PROCEDURAL is a repeatable how-to the operator executed (steps,
1277
+ # commands, worked sequence); REFLECTIVE is a distilled lesson
1278
+ # about process or judgment (what worked, what to do differently).
1279
+ # Same CHECK-rebuild pattern as v13: the guard checks the live
1280
+ # CHECK, so a v12 database replays v13 and v14 blocks in order.
1281
+ if _rebuild_records_check(conn):
1282
+ _reconcile_fts(conn)
1283
+ conn.execute("DELETE FROM schema_version")
1284
+ conn.execute("INSERT INTO schema_version(version) VALUES (14)")
1285
+ conn.commit()
1286
+
1287
+ if version < 15:
1288
+ # v15: per-record memory strength + temporal validity + code anchors.
1289
+ # decay_tau=0 means "use the global curve"; reinforce(success) grows
1290
+ # it (spacing effect, Cepeda 2006 / Duolingo HLR), failure shrinks it.
1291
+ # valid_from/until give bi-temporal as_of recall (Graphiti/Mnemosyne);
1292
+ # anchor_path/sha let a capture pass mark records stale when the file
1293
+ # they describe changes. All additive: existing rows keep behavior.
1294
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1295
+ for col, ddl in (
1296
+ ("decay_tau", "ALTER TABLE records ADD COLUMN decay_tau REAL NOT NULL DEFAULT 0"),
1297
+ ("valid_from", "ALTER TABLE records ADD COLUMN valid_from TEXT NOT NULL DEFAULT ''"),
1298
+ ("valid_until", "ALTER TABLE records ADD COLUMN valid_until TEXT NOT NULL DEFAULT ''"),
1299
+ ("anchor_path", "ALTER TABLE records ADD COLUMN anchor_path TEXT NOT NULL DEFAULT ''"),
1300
+ ("anchor_sha", "ALTER TABLE records ADD COLUMN anchor_sha TEXT NOT NULL DEFAULT ''"),
1301
+ ("stale", "ALTER TABLE records ADD COLUMN stale INTEGER NOT NULL DEFAULT 0"),
1302
+ ):
1303
+ if col not in cols:
1304
+ conn.execute(ddl)
1305
+ conn.execute("DELETE FROM schema_version")
1306
+ conn.execute("INSERT INTO schema_version(version) VALUES (15)")
1307
+ conn.commit()
1308
+
1309
+ if version < 16:
1310
+ # v16: write staging (hermes write_approval). Auto-capture candidates
1311
+ # below the trust threshold wait here for approve/reject instead of
1312
+ # landing in records directly. content_hash pins the candidate at
1313
+ # staging time: apply refuses if the payload changed since review.
1314
+ conn.execute("""
1315
+ CREATE TABLE IF NOT EXISTS pending_writes (
1316
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1317
+ rtype TEXT NOT NULL,
1318
+ content TEXT NOT NULL,
1319
+ evidence TEXT NOT NULL DEFAULT '',
1320
+ confidence REAL NOT NULL DEFAULT 0.35,
1321
+ source TEXT NOT NULL DEFAULT '',
1322
+ tags TEXT NOT NULL DEFAULT '',
1323
+ session_id TEXT NOT NULL DEFAULT '',
1324
+ project_id TEXT NOT NULL DEFAULT '',
1325
+ event_id TEXT NOT NULL DEFAULT '',
1326
+ content_hash TEXT NOT NULL,
1327
+ status TEXT NOT NULL DEFAULT 'pending',
1328
+ created_at TEXT NOT NULL,
1329
+ decided_at TEXT NOT NULL DEFAULT ''
1330
+ )""")
1331
+ conn.execute("DELETE FROM schema_version")
1332
+ conn.execute("INSERT INTO schema_version(version) VALUES (16)")
1333
+ conn.commit()
1334
+
1335
+ if version < 17:
1336
+ # v17: adjudicated non-conflicts (engram not_conflict pattern). A
1337
+ # pair the agent judged compatible never resurfaces in conflicts().
1338
+ conn.execute("""
1339
+ CREATE TABLE IF NOT EXISTS not_conflict (
1340
+ a TEXT NOT NULL,
1341
+ b TEXT NOT NULL,
1342
+ ts TEXT NOT NULL,
1343
+ PRIMARY KEY (a, b)
1344
+ )""")
1345
+ conn.execute("DELETE FROM schema_version")
1346
+ conn.execute("INSERT INTO schema_version(version) VALUES (17)")
1347
+ conn.commit()
1348
+
1349
+ if version < 18:
1350
+ # v18: consolidated_at closes the consolidation ratchet. Without it
1351
+ # the same three retrieval rows paid out CONSOLIDATE_GAIN on every
1352
+ # sleep pass, pinning any recalled record at confidence 1.0 within
1353
+ # hours and permanently defeating decay.
1354
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1355
+ if "consolidated_at" not in cols:
1356
+ conn.execute(
1357
+ "ALTER TABLE records ADD COLUMN consolidated_at TEXT NOT NULL DEFAULT ''")
1358
+ conn.execute("DELETE FROM schema_version")
1359
+ conn.execute("INSERT INTO schema_version(version) VALUES (18)")
1360
+ conn.commit()
1361
+
1362
+ if version < 19:
1363
+ # v19: trust separates what an agent claims from what an operator
1364
+ # attested. Verified-without-evidence is exactly the state the new
1365
+ # guard forbids, so those rows stay claimed. A verified row carrying
1366
+ # evidence is the best surviving signal of prior operator intent.
1367
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1368
+ if "trust" not in cols:
1369
+ conn.execute(
1370
+ "ALTER TABLE records ADD COLUMN trust TEXT NOT NULL DEFAULT 'claimed'")
1371
+ conn.execute(
1372
+ "UPDATE records SET trust='attested'"
1373
+ " WHERE verified=1 AND trim(evidence) <> ''")
1374
+ conn.execute("DELETE FROM schema_version")
1375
+ conn.execute("INSERT INTO schema_version(version) VALUES (19)")
1376
+ conn.commit()
1377
+
1378
+ if version < 20:
1379
+ # v20: attested_at gives attestation an age, and the recall/outcome
1380
+ # tables make credit assignment and calibration possible at all.
1381
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(records)").fetchall()]
1382
+ if "attested_at" not in cols:
1383
+ conn.execute(
1384
+ "ALTER TABLE records ADD COLUMN attested_at TEXT NOT NULL DEFAULT ''")
1385
+ # Seed the age from updated_at: an attested row needs some clock,
1386
+ # and updated_at is the closest honest one available.
1387
+ conn.execute(
1388
+ "UPDATE records SET attested_at=updated_at WHERE trust='attested'")
1389
+ conn.executescript(_V20_TABLES)
1390
+ conn.execute("DELETE FROM schema_version")
1391
+ conn.execute("INSERT INTO schema_version(version) VALUES (20)")
1392
+ conn.commit()
1393
+
1394
+ # Every migration path must leave the index consistent with the table.
1395
+ _reconcile_fts(conn)
1396
+
1397
+
1398
+ def init_db(conn: sqlite3.Connection, db_path: str = None, auto_repair: bool = True):
1399
+ """Create or migrate the schema on an open connection.
1400
+
1401
+ Raises sqlite3.DatabaseError when the database is unusable. The caller's
1402
+ connection is never closed and the file is never removed; a corrupt
1403
+ database is the operator's decision, made explicitly via repair_from_backup.
1404
+ """
1405
+ if not quick_check(conn) and _has_new_columns(conn):
1406
+ # quick_check flags NULL in a NOT NULL column added by ALTER TABLE,
1407
+ # where SQLite cannot backfill the default on existing rows.
1408
+ conn.execute("UPDATE records SET importance=0.5 WHERE importance IS NULL")
1409
+ conn.execute("UPDATE records SET cue='' WHERE cue IS NULL")
1410
+ conn.execute("UPDATE records SET superseded_by='' WHERE superseded_by IS NULL")
1411
+ conn.execute("UPDATE records SET decay_exempt_until='' WHERE decay_exempt_until IS NULL")
1412
+ conn.commit()
1413
+ if not quick_check(conn):
1414
+ if not integrity_check(conn):
1415
+ if auto_repair and db_path and repair_from_backup(db_path):
1416
+ # repair worked on the file; the caller must reconnect
1417
+ raise sqlite3.DatabaseError(
1418
+ f"database was corrupt and has been repaired from backup: {db_path}"
1419
+ )
1420
+ raise sqlite3.DatabaseError(f"database is corrupt: {db_path_of(conn)}")
1421
+ _create_schema(conn)
1422
+ _migrate(conn)
1423
+ conn.commit()
1424
+
1425
+
1426
+ OUTCOME_KINDS = ("test_pass", "test_fail", "build_pass", "build_fail",
1427
+ "revert", "user_correction")
1428
+ _PASS_KINDS = {"test_pass", "build_pass"}
1429
+
1430
+
1431
+ def effective_trust(row: dict, now=None) -> str:
1432
+ """Trust as it stands now. An attestation ages out; a claim never rises."""
1433
+ trust = (row.get("trust") or TRUST_CLAIMED)
1434
+ if trust != TRUST_ATTESTED:
1435
+ return TRUST_CLAIMED
1436
+ stamp = row.get("attested_at") or ""
1437
+ if not stamp:
1438
+ # Migrated rows predate the stamp; treat them as attested rather than
1439
+ # silently demoting everything the operator had already trusted.
1440
+ return TRUST_ATTESTED
1441
+ ts = _parse_ts(stamp)
1442
+ if not ts:
1443
+ return TRUST_ATTESTED
1444
+ now = now or datetime.now(timezone.utc)
1445
+ age = now - ts
1446
+ if age > timedelta(days=ATTESTED_MAX_AGE_DAYS):
1447
+ return TRUST_CLAIMED
1448
+ return TRUST_ATTESTED
1449
+
1450
+
1451
+ def trust_age_days(row: dict, now=None) -> float:
1452
+ stamp = _parse_ts(row.get("attested_at") or "")
1453
+ if not stamp:
1454
+ return 0.0
1455
+ now = now or datetime.now(timezone.utc)
1456
+ return max(0.0, (now - stamp).total_seconds() / 86400.0)
1457
+
1458
+
1459
+ # --- records -----------------------------------------------------------------
1460
+
1461
+ def upsert_record(conn: sqlite3.Connection, rtype: str, content: str, evidence: str = "",
1462
+ verified: int = 0, confidence: float = 0.5, source: str = "",
1463
+ tags: str = "", session_id: str = "", project_id: str = "",
1464
+ parent_id: str = "", event_id: str = "",
1465
+ happened_at: str = "") -> str:
1466
+ """Insert or merge one record by content identity; returns its id."""
1467
+ if rtype not in VALID_TYPES:
1468
+ raise ValueError(f"invalid type: {rtype}")
1469
+ if not content.strip():
1470
+ # Whitespace-only is not a fact: it stores a row that can never match
1471
+ # a query and inflates every count. save_memory() already strips-and-
1472
+ # rejects; this writer was the one place that let it through.
1473
+ raise ValueError("content must not be empty")
1474
+ if len(content) > MAX_RECORD_CHARS:
1475
+ # Refuse rather than silently truncate: a cut-off fact is worse than a
1476
+ # rejected write, because the caller believes the whole sentence is
1477
+ # stored. The message names the fix (split) instead of the symptom.
1478
+ raise ValueError(
1479
+ f"content is {len(content)} chars, over the {MAX_RECORD_CHARS} "
1480
+ "limit for one record; split it into self-contained entries")
1481
+ if verified and not (evidence or "").strip():
1482
+ # This is the merge primitive capture and md_ingest use. They pass the
1483
+ # flag loosely, so refuse the flag rather than the write: a verified
1484
+ # row with no evidence is what the trust boundary forbids.
1485
+ verified = 0
1486
+
1487
+ confidence = min(1.0, max(0.0, float(confidence)))
1488
+ # This primitive has no trust parameter; a verified write is the attested
1489
+ # case (it needed evidence above), so only an unverified write is a claim
1490
+ # and only a claim is capped.
1491
+ if not verified:
1492
+ confidence = min(confidence, CLAIMED_CONFIDENCE_CAP)
1493
+ project_key = project_id or ""
1494
+ session_key = session_id or ""
1495
+ # happened_at lets an import or a benchmark place a record at its real
1496
+ # time. It defaults to now, so every existing caller is unchanged, but
1497
+ # without it a temporal benchmark is inert: every row would look
1498
+ # one second old and the recency/decay machinery could never be tested.
1499
+ stamp = happened_at or now_iso()
1500
+ record_id = record_id_for(rtype, content, source, project_key)
1501
+
1502
+ existing = conn.execute(
1503
+ "SELECT id FROM records WHERE type=? AND content=? AND source=? AND project_id=?",
1504
+ (rtype, content, source, project_key)
1505
+ ).fetchone()
1506
+
1507
+ if existing:
1508
+ record_id = existing["id"]
1509
+ # event_id merges rather than overwrites: a re-capture of the same
1510
+ # lesson in a later event keeps the earlier grouping.
1511
+ if not event_id:
1512
+ row = conn.execute("SELECT event_id FROM records WHERE id=?",
1513
+ (record_id,)).fetchone()
1514
+ event_id = row["event_id"] if row else ""
1515
+ conn.execute(
1516
+ "UPDATE records SET updated_at=?, evidence=?, verified=?, confidence=?,"
1517
+ " tags=?, session_id=?, parent_id=?, event_id=? WHERE id=?",
1518
+ (stamp, evidence or "", 1 if verified else 0, confidence,
1519
+ tags or "", session_key, parent_id or "", event_id, record_id)
1520
+ )
1521
+ else:
1522
+ conn.execute("""
1523
+ INSERT INTO records
1524
+ (id,type,content,evidence,verified,confidence,source,tags,
1525
+ created_at,updated_at,session_id,project_id,parent_id,event_id)
1526
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1527
+ """, (record_id, rtype, content, evidence or "", 1 if verified else 0, confidence,
1528
+ source or "", tags or "", stamp, stamp, session_key, project_key,
1529
+ parent_id or "", event_id or ""))
1530
+
1531
+ conn.commit()
1532
+ return record_id
1533
+
1534
+
1535
+ def _insert_identity(conn: sqlite3.Connection, record_id: str, rtype: str, norm: str,
1536
+ evidence: str, verified: int, confidence: float, source: str,
1537
+ tags: str, session_id: str, project_id: str, parent_id: str,
1538
+ about_peer: str = "", event_id: str = "",
1539
+ importance: float = 0.5, cue: str = "",
1540
+ trust: str = TRUST_CLAIMED):
1541
+ stamp = now_iso()
1542
+ conn.execute("""
1543
+ INSERT INTO records
1544
+ (id,type,content,evidence,verified,confidence,source,tags,
1545
+ created_at,updated_at,session_id,project_id,parent_id,project_ids,
1546
+ about_peer,event_id,importance,cue,trust)
1547
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1548
+ """, (record_id, rtype, norm, evidence or "", 1 if verified else 0, confidence,
1549
+ source or "", tags or "", stamp, stamp, session_id or "", project_id or "",
1550
+ parent_id or "", project_id or "", about_peer or "", event_id or "",
1551
+ importance, cue, trust))
1552
+
1553
+
1554
+ def _candidates(conn: sqlite3.Connection, content: str, rtype: str, limit: int) -> list:
1555
+ """Lexical prefilter: FTS first, LIKE over rows as the fallback.
1556
+
1557
+ FTS only matches tokens that exist, so a reworded fact can score nothing
1558
+ there; the LIKE fallback on the longest tokens keeps such a record visible
1559
+ to the advisory stage. Both are bounded by a multiple of `limit`, so the
1560
+ cost is one query per remember call, not per record.
1561
+ """
1562
+ own = content_id(content)
1563
+ rows = []
1564
+ try:
1565
+ rows = search(conn, content, limit=limit * 8, rtype=rtype,
1566
+ allow_repair=False, rank=False)
1567
+ except sqlite3.Error:
1568
+ rows = []
1569
+ others = [r for r in rows if r["id"] != own]
1570
+ if others:
1571
+ return others
1572
+ # FTS matched nothing but the record itself, so nothing shares a token
1573
+ # suffix: widen to any row that contains one of the longest words.
1574
+ tokens = sorted(set(_tokens(content)), key=len, reverse=True)[:4]
1575
+ if not tokens:
1576
+ return []
1577
+ sql = "SELECT * FROM records WHERE 1=1"
1578
+ params = []
1579
+ if rtype:
1580
+ sql += " AND type=?"
1581
+ params.append(rtype)
1582
+ # SQLite caps LIKE pattern length (a 60k-character token raised
1583
+ # "LIKE or GLOB pattern too complex" and killed the whole write). The
1584
+ # first MAX_LIKE_TOKEN characters are enough to identify the row; a
1585
+ # truncated token can only make the prefilter broader, and Jaccard
1586
+ # scoring downstream still decides.
1587
+ tokens = [t[:MAX_LIKE_TOKEN] for t in tokens]
1588
+ sql += " AND (" + " OR ".join("content LIKE ?" for _ in tokens) + ")"
1589
+ params.extend(f"%{tok}%" for tok in tokens)
1590
+ # Newest-first so SQLite can stop early: a LIKE over content has no
1591
+ # index, and scanning the whole table cost 10ms per write at 12k
1592
+ # records (another linear term in the ingest curve). An advisory
1593
+ # near-duplicate check only needs recent candidates anyway.
1594
+ sql += " ORDER BY rowid DESC LIMIT ?"
1595
+ params.append(limit * 8)
1596
+ return [dict(r) for r in conn.execute(sql, params) if r["id"] != own]
1597
+
1598
+
1599
+ def find_similar(conn: sqlite3.Connection, content: str, limit: int = 5,
1600
+ threshold: float = SIMILAR_THRESHOLD, rtype: str = None) -> list:
1601
+ """Candidates for one fact, scored by Jaccard, best first.
1602
+
1603
+ Excludes the identical record: asking what a fact resembles does not
1604
+ include itself.
1605
+ """
1606
+ norm = normalize_content(content)
1607
+ hits = []
1608
+ for row in _candidates(conn, norm, rtype, limit):
1609
+ score = round(similarity(norm, row["content"]), 4)
1610
+ if score < threshold:
1611
+ continue
1612
+ hits.append({
1613
+ "id": row["id"],
1614
+ "type": row["type"],
1615
+ "content": row["content"],
1616
+ "confidence": row["confidence"],
1617
+ "score": score,
1618
+ "same_numbers": _numeric_tokens(row["content"]) == _numeric_tokens(norm),
1619
+ })
1620
+ hits.sort(key=lambda h: (-h["score"], h["id"]))
1621
+ return hits[:limit]
1622
+
1623
+
1624
+ IDF_VETO_DF_RATIO = 0.02 # a token in <=2% of the corpus is discriminating
1625
+ IDF_VETO_MIN_DF = 2 # never veto on a token that appears once
1626
+
1627
+
1628
+ def _idf_veto(conn: sqlite3.Connection, a: str, b: str) -> bool:
1629
+ """Fellegi-Sunter blocking-key veto on a *relative* rarity test.
1630
+
1631
+ The earlier absolute theta=2.0 was not a rarity test: log(1+N/(1+df))>2
1632
+ means df < 15.5% of the corpus at large N, is unsatisfiable for N<=6
1633
+ (so the shipped tests never exercised it), and for N>=7 fires on any
1634
+ token the other side merely lacks -- blocking legitimate paraphrase
1635
+ merges. Rarity is now stated directly as a document-frequency ratio
1636
+ with a floor, so a token present in one or two records is only treated
1637
+ as a blocking key once the corpus is large enough for that to mean
1638
+ something.
1639
+ """
1640
+ total = conn.execute("SELECT COUNT(*) FROM records").fetchone()[0] or 0
1641
+ if total < 8:
1642
+ return False
1643
+ limit = max(IDF_VETO_MIN_DF, int(total * IDF_VETO_DF_RATIO))
1644
+ sa = set(_tokens(a))
1645
+ sb = set(_tokens(b))
1646
+ for t in sa ^ sb:
1647
+ if len(t) > MAX_LIKE_TOKEN:
1648
+ continue
1649
+ df = conn.execute(
1650
+ "SELECT COUNT(*) FROM records WHERE content LIKE ?",
1651
+ (f"%{t}%",)).fetchone()[0]
1652
+ if 0 < df <= limit:
1653
+ return True
1654
+ return False
1655
+
1656
+
1657
+ def _upsertable(candidate: dict, norm: str, conn: sqlite3.Connection = None) -> bool:
1658
+ """Guards: high score, identical numbers, and no rare-token veto."""
1659
+ if float(candidate.get("score") or 0.0) < UPSERT_THRESHOLD:
1660
+ return False
1661
+ if _numeric_tokens(candidate.get("content") or "") != _numeric_tokens(norm):
1662
+ return False
1663
+ if conn is not None and _idf_veto(conn, candidate.get("content") or "", norm):
1664
+ return False
1665
+ return True
1666
+
1667
+
1668
+ def decide(conn: sqlite3.Connection, content: str, rtype: str = "FACT", limit: int = 5,
1669
+ threshold: float = SIMILAR_THRESHOLD, upsert: bool = False) -> dict:
1670
+ """Read-only: what remembering this content would do.
1671
+
1672
+ `reason` is one of three values and is the only thing that distinguishes a
1673
+ merge from a report, so it is contract, not a hint:
1674
+ identical the same content id is already stored; action update
1675
+ similar a candidate exists. With upsert and both guards met this is an
1676
+ explicit merge (action update, advisory says "merging into"),
1677
+ otherwise the write creates a new row and the candidate is
1678
+ only reported (action create, advisory says "similar to")
1679
+ novel nothing scored above the advisory threshold; action create
1680
+
1681
+ Returns action update|create|delete|noop, the id it would touch, the
1682
+ reason above, the similar candidates and the human-readable advisory.
1683
+ Never writes.
1684
+ """
1685
+ norm = normalize_content(content)
1686
+ own = content_id(norm)
1687
+ existing = get_record(conn, own)
1688
+ if existing:
1689
+ # Mem0-style taxonomy: not every write deserves a write. A restatement
1690
+ # of a discredited fact asks for deletion (the fact is wrong and the
1691
+ # duplicate adds nothing); a restatement of a fully-confirmed fact
1692
+ # asks for nothing at all.
1693
+ signals = _record_signals(conn, own)
1694
+ if signals and signals[-1].get("signal") == "failure" \
1695
+ and not existing["verified"]:
1696
+ return {"action": "delete", "id": own, "reason": "identical",
1697
+ "similar": [],
1698
+ "advisory": ("repeats a discredited fact; delete instead "
1699
+ "of re-storing it")}
1700
+ if existing["verified"] and float(existing["confidence"] or 0) >= 0.95:
1701
+ return {"action": "noop", "id": own, "reason": "identical",
1702
+ "similar": [],
1703
+ "advisory": "already confirmed; nothing to learn"}
1704
+ return {"action": "update", "id": own, "reason": "identical",
1705
+ "similar": [], "advisory": ""}
1706
+
1707
+ similar = find_similar(conn, norm, limit=limit, threshold=threshold, rtype=rtype)
1708
+ mergeable = [c for c in similar if upsert and _upsertable(c, norm, conn)]
1709
+ if mergeable:
1710
+ best = mergeable[0]
1711
+ return {"action": "update", "id": best["id"], "reason": "similar",
1712
+ "similar": similar,
1713
+ "advisory": f"merging into {best['id']} at similarity {best['score']}"}
1714
+ if similar:
1715
+ best = similar[0]
1716
+ return {"action": "create", "id": own, "reason": "similar",
1717
+ "similar": similar,
1718
+ "advisory": (f"similar to {best['id']} at {best['score']}; "
1719
+ "keep separate unless it is the same fact")}
1720
+ return {"action": "create", "id": own, "reason": "novel", "similar": [], "advisory": ""}
1721
+
1722
+
1723
+ def _schema_prior(confidence: float, similar: list) -> float:
1724
+ """Bias a new record's initial confidence by schema coherence.
1725
+
1726
+ Coherence is the best (score * existing confidence) among similar records
1727
+ that are themselves well-trusted (confidence >= 0.7). Agreement raises the
1728
+ prior, contradiction lowers it, never past the caller's own value by more
1729
+ than SCHEMA_PRIOR_WEIGHT: the caller's confidence is the base, the schema
1730
+ is the nudge (Tse et al. 2007 rapid consolidation; Bartlett 1932 guard:
1731
+ a prior never overrides an existing verified record, it only biases the
1732
+ new one).
1733
+ """
1734
+ coherence = 0.5
1735
+ for cand in similar:
1736
+ if cand.get("confidence", 0.0) < 0.7:
1737
+ continue
1738
+ coherence = max(coherence, cand["score"] * cand["confidence"])
1739
+ return min(1.0, max(0.0, confidence + SCHEMA_PRIOR_WEIGHT * (coherence - 0.5)))
1740
+
1741
+
1742
+ def _rif_supersede(conn, record_id: str, rtype: str, norm: str,
1743
+ similar: list) -> list:
1744
+ """Penalize records this write supersedes (Anderson et al. 1994).
1745
+
1746
+ Only a CORRECTION does it, and only when the loser is well-trusted:
1747
+ a low-confidence loser is already on its way out, and inhibiting it
1748
+ buys nothing. The loser keeps its decay curve and can recover through
1749
+ reinforcement, which is what makes RIF inhibition rather than
1750
+ deletion.
1751
+ """
1752
+ if rtype != "CORRECTION":
1753
+ return []
1754
+ # decide() scoped its similarity search to the incoming type, so a
1755
+ # CORRECTION never saw the FACT it supersedes. RIF must look across types.
1756
+ similar = find_similar(conn, norm, limit=5, threshold=SIMILAR_THRESHOLD)
1757
+ penalized = []
1758
+ for cand in similar:
1759
+ if cand["id"] == record_id:
1760
+ continue
1761
+ conf = float(cand.get("confidence") or 0.0)
1762
+ if conf < RIF_MIN_CONFIDENCE:
1763
+ continue
1764
+ new_conf = round(max(0.0, conf - RIF_PENALTY), 6)
1765
+ conn.execute("UPDATE records SET confidence=? WHERE id=?",
1766
+ (new_conf, cand["id"]))
1767
+ conn.execute(
1768
+ "INSERT INTO reinforcement (record_id, signal, delta, source, ts)"
1769
+ " VALUES (?, 'failure', ?, 'rif', ?)",
1770
+ (cand["id"], -RIF_PENALTY, now_iso()))
1771
+ penalized.append({"id": cand["id"], "from": conf, "to": new_conf})
1772
+ return penalized
1773
+
1774
+
1775
+ def _set_superseded(conn, record_id: str, source: str,
1776
+ prev_content: str = None) -> list:
1777
+ """Mark near-duplicates as superseded by a rewritten record.
1778
+
1779
+ A correction that replaced content left the old content in a
1780
+ near-duplicate somewhere. RIF already penalized them at write time;
1781
+ this links the loser to the winner so recall can downrank it and a
1782
+ caller can follow the chain. Similarity runs against the PRE-rewrite
1783
+ content when the rewrite is what linked this record: the losers are
1784
+ near-duplicates of what the record used to say. When the old content
1785
+ scores nothing above threshold, the new content is tried too: a
1786
+ correction can narrow the claim (prod-01 becomes prod-02) and the
1787
+ near-duplicate was only ever close to the narrower form.
1788
+ """
1789
+ rewritten = conn.execute(
1790
+ "SELECT content FROM records WHERE id=?", (record_id,)).fetchone()
1791
+ if rewritten is None:
1792
+ return []
1793
+ similar = find_similar(conn, prev_content, limit=5,
1794
+ threshold=SIMILAR_THRESHOLD) if prev_content else []
1795
+ if not similar:
1796
+ similar = find_similar(conn, rewritten[0], limit=5,
1797
+ threshold=SIMILAR_THRESHOLD)
1798
+ own_numbers = _numeric_tokens(rewritten[0])
1799
+ similar = [c for c in similar
1800
+ if _numeric_tokens(c["content"]) == own_numbers]
1801
+ # Close the loser's validity window at the winner's valid_from, the
1802
+ # Graphiti edge-invalidation rule: bi-temporal as_of must not return a
1803
+ # fact whose window should already be shut. The old code set only the
1804
+ # superseded_by pointer, so as_of queries kept serving the stale fact.
1805
+ winner_from = conn.execute(
1806
+ "SELECT valid_from, updated_at FROM records WHERE id=?",
1807
+ (record_id,)).fetchone()
1808
+ close_at = (winner_from[0] if winner_from and winner_from[0] else
1809
+ (winner_from[1] if winner_from else ""))
1810
+ linked = []
1811
+ for cand in similar:
1812
+ if cand["id"] == record_id:
1813
+ continue
1814
+ if close_at:
1815
+ conn.execute(
1816
+ "UPDATE records SET superseded_by=?,"
1817
+ " valid_until=CASE WHEN valid_until='' THEN ? ELSE valid_until END"
1818
+ " WHERE id=? AND superseded_by=''",
1819
+ (record_id, close_at, cand["id"]))
1820
+ else:
1821
+ conn.execute(
1822
+ "UPDATE records SET superseded_by=? WHERE id=?"
1823
+ " AND superseded_by=''",
1824
+ (record_id, cand["id"]))
1825
+ linked.append(cand["id"])
1826
+ # Chain resolution: rows superseded by the rewritten record may
1827
+ # themselves be the target of older markers (A -> B, B -> C). After
1828
+ # B is linked to C, A still points at a loser, so every row pointing
1829
+ # at B follows to C: the chain resolves to its head in one hop, and
1830
+ # no query walks A -> B -> C at read time.
1831
+ if linked:
1832
+ losers = [rid for rid in linked if not str(rid).startswith("chain:")]
1833
+ for loser in losers:
1834
+ conn.execute(
1835
+ "UPDATE records SET superseded_by=? WHERE superseded_by=?"
1836
+ " AND id != ?",
1837
+ (record_id, loser, record_id))
1838
+ linked.append(f"chain:{losers}->{record_id}" if losers
1839
+ else f"chain:none->{record_id}")
1840
+ return linked
1841
+
1842
+
1843
+ def log_retrieval(conn, record_ids: list, session_id: str = "",
1844
+ channel: str = "recall", query: str = "") -> int:
1845
+ """Log one zero-delta retrieval signal per record (Roediger & Karpicke 2006).
1846
+
1847
+ A retrieval is a learning event, not a confirmation: delta 0 moves no
1848
+ confidence, but it starts the spacing clock and counts toward
1849
+ consolidation. It also lands in recall_events, which is the only record of
1850
+ what was actually shown to the agent: credit assignment and calibration
1851
+ are impossible without it.
1852
+ """
1853
+ n = 0
1854
+ stamp = now_iso()
1855
+ qhash = hashlib.sha256(normalize_content(query).encode()).hexdigest()[:16] if query else ""
1856
+ for rank, rid in enumerate(record_ids):
1857
+ cur = conn.execute(
1858
+ "INSERT INTO reinforcement (record_id, signal, delta, source, ts)"
1859
+ " VALUES (?, 'retrieval', 0.0, 'recall', ?)", (rid, stamp))
1860
+ n += cur.rowcount
1861
+ row = conn.execute("SELECT confidence FROM records WHERE id=?", (rid,)).fetchone()
1862
+ conn.execute(
1863
+ "INSERT INTO recall_events (ts, session_id, record_id, query_hash,"
1864
+ " rank, channel, confidence) VALUES (?,?,?,?,?,?,?)",
1865
+ (stamp, session_id or "", rid, qhash, rank, channel,
1866
+ float(row[0]) if row else 0.0))
1867
+ conn.commit()
1868
+ return n
1869
+
1870
+
1871
+ def log_outcome(conn, kind: str, session_id: str = "", evidence_ref: str = "",
1872
+ assign: bool = True) -> dict:
1873
+ """Record an objective outcome, then credit the records that preceded it.
1874
+
1875
+ kind is one of OUTCOME_KINDS. Anything ambiguous must not reach here: a
1876
+ wrong label is worse than a missing one, because credit assignment is the
1877
+ only evidence the engine has about being right.
1878
+ """
1879
+ if kind not in OUTCOME_KINDS:
1880
+ raise ValueError(f"invalid outcome kind: {kind}")
1881
+ cur = conn.execute(
1882
+ "INSERT INTO outcome_events (ts, session_id, kind, evidence_ref)"
1883
+ " VALUES (?,?,?,?)", (now_iso(), session_id or "", kind, evidence_ref or ""))
1884
+ conn.commit()
1885
+ outcome_id = cur.lastrowid
1886
+ report = {"id": outcome_id, "kind": kind, "credited": 0}
1887
+ if assign:
1888
+ report["credited"] = assign_credit(conn, outcome_id, session_id, kind)
1889
+ return report
1890
+
1891
+
1892
+ def assign_credit(conn, outcome_id: int, session_id: str, kind: str) -> int:
1893
+ """Give the records surfaced in this session a small signal.
1894
+
1895
+ Weighted by rank (the first hit is the one most likely to have been used)
1896
+ and bounded: one outcome moves a record a little, not a lot. Each
1897
+ (outcome, record) pair is credited once.
1898
+ """
1899
+ if not session_id:
1900
+ return 0
1901
+ rows = conn.execute(
1902
+ "SELECT record_id, min(rank) AS rank FROM recall_events"
1903
+ " WHERE session_id=? GROUP BY record_id", (session_id,)).fetchall()
1904
+ applied = 0
1905
+ for row in rows:
1906
+ rid = row["record_id"]
1907
+ rank = int(row["rank"] or 0)
1908
+ if rank > CREDIT_ASSIGN_MAX_RANK:
1909
+ continue
1910
+ seen = conn.execute(
1911
+ "SELECT 1 FROM credit_assignments WHERE outcome_id=? AND record_id=?",
1912
+ (outcome_id, rid)).fetchone()
1913
+ if seen:
1914
+ continue
1915
+ delta = CREDIT_ASSIGN_DELTA / (1.0 + rank)
1916
+ if kind not in _PASS_KINDS:
1917
+ delta = -delta
1918
+ try:
1919
+ conn.execute(
1920
+ "INSERT INTO reinforcement (record_id, signal, delta, source, ts)"
1921
+ " VALUES (?,?,?,?,?)",
1922
+ (rid, "success" if kind in _PASS_KINDS else "failure", delta,
1923
+ f"credit:{outcome_id}", now_iso()))
1924
+ conn.execute(
1925
+ "UPDATE records SET confidence=min(1.0, max(0.0, confidence+?))"
1926
+ " WHERE id=?", (delta, rid))
1927
+ conn.execute(
1928
+ "INSERT INTO credit_assignments (outcome_id, record_id) VALUES (?,?)",
1929
+ (outcome_id, rid))
1930
+ applied += 1
1931
+ except sqlite3.Error:
1932
+ continue
1933
+ conn.commit()
1934
+ return applied
1935
+
1936
+
1937
+ def _check_evidence_payload(conn, spec: dict, repo_root: Path) -> list:
1938
+ """Return [(kind, target, status, detail)] for one structured evidence blob.
1939
+
1940
+ Never executes anything from the record. A file is read and hashed; a
1941
+ commit is asked about with `git cat-file -e` using an argument list (no
1942
+ shell) and a strict sha; a test_result only points at an outcome row.
1943
+ """
1944
+ out = []
1945
+ rel = spec.get("file")
1946
+ if rel:
1947
+ root = repo_root.resolve()
1948
+ target = (root / str(rel)).resolve()
1949
+ if not target.is_relative_to(root):
1950
+ out.append(("file", str(rel), "invalid", "path escapes the repo"))
1951
+ elif not target.is_file():
1952
+ out.append(("file", str(rel), "gone", "file no longer exists"))
1953
+ else:
1954
+ actual = hashlib.sha256(target.read_bytes()).hexdigest()
1955
+ expected = str(spec.get("sha256") or "").lower()
1956
+ if expected and actual != expected:
1957
+ out.append(("file", str(rel), "stale", "content hash changed"))
1958
+ else:
1959
+ out.append(("file", str(rel), "valid", ""))
1960
+ commit = spec.get("commit")
1961
+ if commit:
1962
+ sha = str(commit).strip().lower()
1963
+ if not _SHA_RE.match(sha):
1964
+ out.append(("commit", sha[:12], "invalid", "not a hex sha"))
1965
+ else:
1966
+ try:
1967
+ proc = subprocess.run(
1968
+ ["git", "cat-file", "-e", sha + "^{commit}"],
1969
+ cwd=str(repo_root), capture_output=True, timeout=10)
1970
+ ok = proc.returncode == 0
1971
+ except (OSError, subprocess.SubprocessError):
1972
+ ok = False
1973
+ out.append(("commit", sha[:12], "valid" if ok else "gone",
1974
+ "" if ok else "commit not in this repository"))
1975
+ test_ref = spec.get("test_result")
1976
+ if test_ref not in (None, ""):
1977
+ row = conn.execute("SELECT kind FROM outcome_events WHERE id=?",
1978
+ (test_ref,)).fetchone()
1979
+ if not row:
1980
+ out.append(("test_result", str(test_ref), "gone", "no such outcome"))
1981
+ elif row["kind"] not in _PASS_KINDS:
1982
+ out.append(("test_result", str(test_ref), "stale",
1983
+ f"outcome was {row['kind']}, not a pass"))
1984
+ else:
1985
+ out.append(("test_result", str(test_ref), "valid", row["kind"]))
1986
+ if not out:
1987
+ out.append(("unknown", "", "invalid", "no checkable field in evidence"))
1988
+ return out
1989
+
1990
+
1991
+ def verify_evidence(conn, repo_root=None, record_id=None, project_id=None,
1992
+ apply: bool = True) -> dict:
1993
+ """Re-check every structured evidence blob and act on what changed.
1994
+
1995
+ valid keeps attestation, stale lowers confidence and demotes the record to
1996
+ claimed, gone additionally flags it for supersede review. Free-text
1997
+ evidence has nothing to check, so it is counted and left alone.
1998
+ """
1999
+ root = Path(repo_root) if repo_root else _repo_root()
2000
+ sql = "SELECT * FROM records"
2001
+ params = []
2002
+ clauses = []
2003
+ if record_id:
2004
+ clauses.append("id=?")
2005
+ params.append(record_id)
2006
+ if project_id:
2007
+ clauses.append("(project_id=? OR project_ids LIKE ?)")
2008
+ params.extend([project_id, f"%{project_id}%"])
2009
+ if clauses:
2010
+ sql += " WHERE " + " AND ".join(clauses)
2011
+ summary = {"checked": 0, "valid": 0, "stale": 0, "gone": 0,
2012
+ "invalid": 0, "free_text": 0, "demoted": 0, "root": str(root)}
2013
+ for row in [dict(r) for r in conn.execute(sql, params)]:
2014
+ text = (row.get("evidence") or "").strip()
2015
+ if not text.startswith("{"):
2016
+ if text:
2017
+ summary["free_text"] += 1
2018
+ continue
2019
+ try:
2020
+ spec = json.loads(text)
2021
+ except json.JSONDecodeError:
2022
+ summary["invalid"] += 1
2023
+ continue
2024
+ if not isinstance(spec, dict):
2025
+ summary["invalid"] += 1
2026
+ continue
2027
+ summary["checked"] += 1
2028
+ checks = _check_evidence_payload(conn, spec, root)
2029
+ worst = "valid"
2030
+ for kind, target, status, detail in checks:
2031
+ summary[status] = summary.get(status, 0) + 1
2032
+ conn.execute(
2033
+ "INSERT OR REPLACE INTO evidence_checks"
2034
+ " (record_id, kind, target, status, detail, checked_at)"
2035
+ " VALUES (?,?,?,?,?,?)",
2036
+ (row["id"], kind, target, status, detail, now_iso()))
2037
+ if status in ("gone", "stale", "invalid"):
2038
+ worst = "gone" if status == "gone" else (
2039
+ "stale" if worst == "valid" else worst)
2040
+ if apply and worst != "valid":
2041
+ conn.execute(
2042
+ "UPDATE records SET trust=?, confidence=min(1.0, max(0.0,"
2043
+ " confidence-?)), stale=CASE WHEN ?='gone' THEN 1 ELSE stale END,"
2044
+ " updated_at=? WHERE id=?",
2045
+ (TRUST_CLAIMED, EVIDENCE_STALE_PENALTY, worst, now_iso(), row["id"]))
2046
+ summary["demoted"] += 1
2047
+ conn.commit()
2048
+ return summary
2049
+
2050
+
2051
+ def _repo_root() -> Path:
2052
+ try:
2053
+ proc = subprocess.run(["git", "rev-parse", "--show-toplevel"],
2054
+ capture_output=True, text=True, timeout=10)
2055
+ if proc.returncode == 0 and proc.stdout.strip():
2056
+ return Path(proc.stdout.strip())
2057
+ except (OSError, subprocess.SubprocessError):
2058
+ pass
2059
+ return Path.cwd()
2060
+
2061
+
2062
+ def calibrate(conn, min_samples: int = None) -> dict:
2063
+ """Confidence vs observed success after a retrieval.
2064
+
2065
+ Brier and ECE over bins of the confidence the engine claimed AT RECALL
2066
+ time. Below min_samples the honest answer is "not enough data", so it says
2067
+ that instead of printing a number that looks authoritative.
2068
+ """
2069
+ min_samples = CALIBRATION_MIN_SAMPLES if min_samples is None else min_samples
2070
+ rows = conn.execute("""
2071
+ SELECT r.confidence AS conf,
2072
+ CASE WHEN o.kind IN ('test_pass','build_pass') THEN 1 ELSE 0 END AS ok
2073
+ FROM recall_events r
2074
+ JOIN (SELECT o1.session_id, o1.kind FROM outcome_events o1
2075
+ JOIN (SELECT session_id, max(id) AS mid FROM outcome_events
2076
+ GROUP BY session_id) m ON m.mid = o1.id) o
2077
+ ON o.session_id = r.session_id
2078
+ WHERE r.session_id <> ''
2079
+ """).fetchall()
2080
+ n = len(rows)
2081
+ if n == 0:
2082
+ return {"samples": 0, "insufficient": True, "min_samples": min_samples,
2083
+ "message": "no recall events with a labelled outcome yet"}
2084
+ bins = {}
2085
+ for row in rows:
2086
+ conf = min(1.0, max(0.0, float(row["conf"])))
2087
+ idx = min(9, int(conf * 10))
2088
+ b = bins.setdefault(idx, {"lo": idx / 10, "hi": (idx + 1) / 10,
2089
+ "n": 0, "conf": 0.0, "ok": 0})
2090
+ b["n"] += 1
2091
+ b["conf"] += conf
2092
+ b["ok"] += int(row["ok"])
2093
+ table = []
2094
+ brier = 0.0
2095
+ ece = 0.0
2096
+ for idx in sorted(bins):
2097
+ b = bins[idx]
2098
+ mean_conf = b["conf"] / b["n"]
2099
+ acc = b["ok"] / b["n"]
2100
+ brier += sum((r["conf"] - r["ok"]) ** 2 for r in rows
2101
+ if min(9, int(max(0.0, float(r["conf"])) * 10)) == idx)
2102
+ ece += (b["n"] / n) * abs(acc - mean_conf)
2103
+ table.append({"lo": b["lo"], "hi": b["hi"], "n": b["n"],
2104
+ "mean_confidence": round(mean_conf, 4),
2105
+ "observed_success": round(acc, 4)})
2106
+ return {"samples": n, "insufficient": n < min_samples,
2107
+ "min_samples": min_samples,
2108
+ "brier": round(brier / n, 4), "ece": round(ece, 4), "bins": table}
2109
+
2110
+
2111
+ def consolidate(conn, now=None) -> list:
2112
+ """Reward repeated retrieval with a small confidence gain.
2113
+
2114
+ Roediger & Karpicke 2006: retrieval practice consolidates. A record
2115
+ pulled back RETRIEVALS_FOR_CONSOLIDATION times since its last
2116
+ consolidation with no success or failure attached is being used
2117
+ without contradiction; it earns CONSOLIDATE_GAIN once.
2118
+
2119
+ Two invariants keep this from becoming a ratchet:
2120
+ - Retrievals are counted only AFTER the record's last consolidation
2121
+ (`consolidated_at`), so the same three rows cannot pay out twice.
2122
+ - updated_at is NOT touched. It is the recency signal and one of
2123
+ apply_decay's anchors; resetting it on every pass made a frequently
2124
+ recalled record immortal (confidence pinned at 1.0 within hours and
2125
+ decay forever looking at a fresh timestamp).
2126
+ """
2127
+ now = now or datetime.now(timezone.utc)
2128
+ cutoff = (now - timedelta(days=RETRIEVAL_WINDOW_DAYS)).isoformat()
2129
+ rows = conn.execute(
2130
+ """
2131
+ SELECT r.id, r.confidence, r.consolidated_at,
2132
+ (SELECT count(*) FROM reinforcement x
2133
+ WHERE x.record_id = r.id AND x.signal = 'retrieval'
2134
+ AND x.ts >= ? AND x.ts > r.consolidated_at) AS retrievals,
2135
+ (SELECT count(*) FROM reinforcement x
2136
+ WHERE x.record_id = r.id AND x.signal = 'success'
2137
+ AND x.ts >= ? AND x.ts > r.consolidated_at) AS successes,
2138
+ (SELECT count(*) FROM reinforcement x
2139
+ WHERE x.record_id = r.id AND x.signal = 'failure'
2140
+ AND x.ts >= ? AND x.ts > r.consolidated_at) AS failures
2141
+ FROM records r
2142
+ WHERE r.verified = 0 AND r.superseded_by = ''
2143
+ """, (cutoff, cutoff, cutoff)).fetchall()
2144
+ consolidated = []
2145
+ for row in rows:
2146
+ if row["retrievals"] < RETRIEVALS_FOR_CONSOLIDATION:
2147
+ continue
2148
+ if row["successes"] or row["failures"]:
2149
+ continue
2150
+ conf = min(1.0, float(row["confidence"] or 0.0) + CONSOLIDATE_GAIN)
2151
+ conn.execute("UPDATE records SET confidence=?, consolidated_at=? WHERE id=?",
2152
+ (conf, now.isoformat(), row["id"]))
2153
+ consolidated.append({"id": row["id"], "from": row["confidence"],
2154
+ "to": conf})
2155
+ conn.commit()
2156
+ return consolidated
2157
+
2158
+
2159
+ def sleep_pass(conn, now=None, budget: int = SLEEP_EVICT_BUDGET,
2160
+ prune_similarity: float = SLEEP_PRUNE_SIMILARITY,
2161
+ apply: bool = True) -> dict:
2162
+ """One offline consolidation cycle over the whole store (wake/sleep split).
2163
+
2164
+ Lin et al. 2025: memory systems improve when maintenance happens between
2165
+ queries, not inside them. This pass is exactly that: decay ages
2166
+ confidence, consolidation rewards retrieved records, near-duplicate rows
2167
+ collapse into their keepers, and projects over budget evict their
2168
+ Unscoped records and verified/RULE/CORRECTION rows are never deleted.
2169
+
2170
+ Deletion is conservative (rate-distortion): the only deletes this pass
2171
+ performs are prune merges (recoverable, the keeper holds the fact). A
2172
+ project over budget does NOT lose its lowest-value rows: those are the
2173
+ last holders of their content and a delete is irreversible, so they stay
2174
+ and are reported in "kept" (reason "over budget, irreplaceable") for the
2175
+ operator to decide. The prune already collapsed every 0.80+ overlap, so
2176
+ the evict loop can only ever see rows below that band.
2177
+
2178
+ apply=False reports the same plan without writing: deleting memory is a
2179
+ decision, not a side effect.
2180
+ """
2181
+ now = now or datetime.now(timezone.utc)
2182
+ decayed = apply_decay(conn, now=now)
2183
+ consolidated = consolidate(conn, now=now)
2184
+ report = {"decayed": decayed, "consolidated": consolidated,
2185
+ "merged": [], "evicted": [], "kept": [], "apply": bool(apply)}
2186
+
2187
+ # Prune: near-duplicate unverified rows collapse into the older keeper.
2188
+ rows = [dict(r) for r in conn.execute(
2189
+ "SELECT id, content, created_at FROM records WHERE verified=0"
2190
+ " ORDER BY created_at")]
2191
+ for i, row in enumerate(rows):
2192
+ already_merged = {r["merged"] for r in report["merged"]}
2193
+ keepers = {r["keeper"] for r in report["merged"]}
2194
+ if row["id"] not in already_merged | keepers and \
2195
+ not _record_gone(conn, row["id"]):
2196
+ for other in rows[i + 1:]:
2197
+ if _record_gone(conn, other["id"]):
2198
+ continue
2199
+ # Prune guards. Jaccard strips punctuation and ignores
2200
+ # numbers, so two different facts can score 0.83+: measured on
2201
+ # the live store, all 18 pairs above the 0.80 threshold were
2202
+ # NOT byte-identical, and the write path already refuses to
2203
+ # merge such a pair (_upsertable requires identical numeric
2204
+ # tokens). The prune bypassed every one of those guards, so a
2205
+ # deletion here was strictly looser than a write. Apply the
2206
+ # same three tests before deleting anything.
2207
+ if (similarity(row["content"], other["content"]) >= prune_similarity
2208
+ and _numeric_tokens(row["content"])
2209
+ == _numeric_tokens(other["content"])
2210
+ and not _idf_veto(conn, row["content"], other["content"])):
2211
+ if apply:
2212
+ conn.execute(
2213
+ "INSERT OR REPLACE INTO forgotten_graveyard"
2214
+ " (id, type, content, reason, ts) VALUES (?,?,?,?,?)",
2215
+ (other["id"], "DUPLICATE",
2216
+ (other["content"] or "")[:200],
2217
+ f"sleep: near-duplicate of {row['id']}",
2218
+ now.isoformat()))
2219
+ conn.execute("DELETE FROM reinforcement WHERE record_id=?",
2220
+ (other["id"],))
2221
+ conn.execute("DELETE FROM records WHERE id=?", (other["id"],))
2222
+ report["merged"].append({"keeper": row["id"],
2223
+ "merged": other["id"]})
2224
+
2225
+ # Evict: per project, rows beyond budget leave lowest-value first.
2226
+ counts = conn.execute(
2227
+ "SELECT project_id, count(*) AS n FROM records"
2228
+ " WHERE verified=0 GROUP BY project_id").fetchall()
2229
+ for proj in counts:
2230
+ pid = proj["project_id"] or ""
2231
+ n = proj["n"]
2232
+ if n <= budget or pid == "":
2233
+ continue
2234
+ over = n - budget
2235
+ rows = [dict(r) for r in conn.execute(
2236
+ "SELECT id, content, confidence, updated_at FROM records"
2237
+ " WHERE project_id=? AND verified=0", (pid,))]
2238
+ for row in rows:
2239
+ age = 0.0
2240
+ ts = _parse_ts(row["updated_at"])
2241
+ if ts:
2242
+ age = max(0.0, (now - ts).total_seconds() / 86400.0)
2243
+ row["value"] = float(row["confidence"] or 0.0) * (
2244
+ (1.0 + age / DECAY_POWER_TAU_DAYS) ** -DECAY_POWER_BETA)
2245
+ rows.sort(key=lambda r: r["value"])
2246
+ for row in rows[:over]:
2247
+ # Report-only: the prune already collapsed every 0.80+ overlap,
2248
+ # so these are the last holders of their content. Deleting them
2249
+ # is irreversible, and the operator, not the sleep pass, owns
2250
+ # that decision.
2251
+ report["kept"].append({"id": row["id"], "project": pid,
2252
+ "reason": "over budget, irreplaceable",
2253
+ "value": round(row["value"], 6)})
2254
+ if apply and (report["merged"] or report["evicted"]):
2255
+ conn.commit()
2256
+ # Sleep is the natural backup moment: offline, consistent, and the
2257
+ # restore story is meaningless without a snapshot that actually runs.
2258
+ if apply:
2259
+ report["backup"] = backup_db(db_path_of(conn))
2260
+ return report
2261
+
2262
+
2263
+ def _record_gone(conn, record_id: str) -> bool:
2264
+ return conn.execute("SELECT 1 FROM records WHERE id=?",
2265
+ (record_id,)).fetchone() is None
2266
+
2267
+
2268
+ def remember(conn: sqlite3.Connection, rtype: str, content: str, evidence: str = "",
2269
+ verified: int = 0, confidence: float = 0.5, source: str = "",
2270
+ tags: str = "", session_id: str = "", project_id: str = "",
2271
+ parent_id: str = "", upsert: bool = False, limit: int = 5,
2272
+ about_peer: str = "", event_id: str = "",
2273
+ importance: float = 0.5, cue: str = "",
2274
+ valid_from: str = "", valid_until: str = "",
2275
+ trust: str = TRUST_CLAIMED) -> dict:
2276
+ """Write by content identity, not by provenance.
2277
+
2278
+ Two spellings of one fact (casing, whitespace) and two provenances of one
2279
+ fact (source, project) are the same row; `source` and `project_id` are
2280
+ provenance and accumulate, so a merge never loses where a fact was seen.
2281
+
2282
+ Near-duplicates follow `upsert`: off by default, in which case a similar
2283
+ record is reported and a new row is written; on, a candidate that clears
2284
+ both guards is merged in place. Either way the decision, the candidates and
2285
+ the advisory come back to the caller.
2286
+ """
2287
+ if rtype not in VALID_TYPES:
2288
+ raise ValueError(f"invalid type: {rtype}")
2289
+ if not (content or "").strip():
2290
+ raise ValueError("content must not be empty")
2291
+ if trust not in (TRUST_CLAIMED, TRUST_ATTESTED):
2292
+ raise ValueError(f"invalid trust: {trust}")
2293
+ if len(content) > MAX_RECORD_CHARS:
2294
+ raise ValueError(
2295
+ f"content is {len(content)} chars, over the {MAX_RECORD_CHARS} "
2296
+ "limit for one record; split it into self-contained entries")
2297
+ # Attested is not a flag a caller may just set: it is a statement that
2298
+ # something outside the writer checked. Without evidence it is the same
2299
+ # assertion the trust boundary exists to stop.
2300
+ if trust == TRUST_ATTESTED and not (evidence or "").strip():
2301
+ raise ValueError("trust=attested requires evidence")
2302
+ # Verified means a human or a machine checked it. Without evidence there
2303
+ # is nothing to check, so the flag would be an assertion by the writer.
2304
+ # And a verified record IS attested: the two are one fact, so a verified
2305
+ # write cannot stay claimed.
2306
+ if verified:
2307
+ if not (evidence or "").strip():
2308
+ raise ValueError("verified=True requires non-empty evidence")
2309
+ trust = TRUST_ATTESTED
2310
+ norm = normalize_content(content)
2311
+ confidence = min(1.0, max(0.0, float(confidence)))
2312
+ if trust == TRUST_CLAIMED:
2313
+ confidence = min(confidence, CLAIMED_CONFIDENCE_CAP)
2314
+
2315
+ decision = decide(conn, norm, rtype=rtype, limit=limit, upsert=upsert)
2316
+ record_id = decision["id"]
2317
+ # The merge re-reads the row inside BEGIN IMMEDIATE: decide() is read-only
2318
+ # and safe outside, but the merge itself is read-modify-write, and two
2319
+ # processes merging different provenance into one row lose the loser's
2320
+ # source when both read the same base.
2321
+ conn.execute("BEGIN IMMEDIATE")
2322
+ existing = get_record(conn, record_id)
2323
+
2324
+ if existing:
2325
+ conn.execute(
2326
+ "UPDATE records SET content=?, evidence=?, verified=?, confidence=?,"
2327
+ " tags=?, session_id=?, parent_id=?, source=?, project_id=?,"
2328
+ " project_ids=?, updated_at=?, about_peer=?, event_id=?, trust=?"
2329
+ " WHERE id=?",
2330
+ (_richer_spelling(existing["content"], norm),
2331
+ evidence or existing["evidence"],
2332
+ max(1 if verified else 0, existing["verified"]),
2333
+ max(confidence, existing["confidence"]),
2334
+ tags or existing["tags"],
2335
+ session_id or existing["session_id"],
2336
+ parent_id or existing["parent_id"],
2337
+ _merge_provenance(existing["source"], source),
2338
+ _merge_provenance(existing["project_id"], project_id),
2339
+ _merge_provenance(existing["project_ids"], project_id),
2340
+ now_iso(),
2341
+ about_peer or existing["about_peer"],
2342
+ event_id or existing["event_id"],
2343
+ TRUST_ATTESTED
2344
+ if TRUST_ATTESTED in (existing.get("trust"), trust)
2345
+ else TRUST_CLAIMED,
2346
+ record_id)
2347
+ )
2348
+ applied = "updated"
2349
+ else:
2350
+ prior = _schema_prior(confidence, decision["similar"])
2351
+ _insert_identity(conn, record_id, rtype, norm, evidence, verified, prior,
2352
+ source, tags, session_id, project_id, parent_id,
2353
+ about_peer, event_id, trust=trust,
2354
+ importance=min(1.0, max(0.0, float(importance))),
2355
+ cue=normalize_cue(cue))
2356
+ applied = "inserted"
2357
+
2358
+ if valid_from or valid_until:
2359
+ conn.execute("UPDATE records SET valid_from=?, valid_until=? WHERE id=?",
2360
+ (valid_from, valid_until, record_id))
2361
+ # One transaction: the record, its validity window and the predecessors it
2362
+ # supersedes. Committing between them left a record inserted with no
2363
+ # supersede history if the process died in between.
2364
+ rif_applied = _rif_supersede(conn, record_id, rtype, norm,
2365
+ decision["similar"])
2366
+ conn.commit()
2367
+ advisory = decision["advisory"]
2368
+ plan_note = _future_tense_note(content, valid_from)
2369
+ if plan_note:
2370
+ advisory = (advisory + " " + plan_note).strip() if advisory else plan_note
2371
+ return {"id": record_id, "type": rtype, "shape": norm, "applied": applied,
2372
+ "rif": rif_applied,
2373
+ "action": decision["action"], "reason": decision["reason"],
2374
+ "similar": decision["similar"], "advisory": advisory}
2375
+
2376
+
2377
+ def set_validity(conn: sqlite3.Connection, record_id: str,
2378
+ valid_from: str = "", valid_until: str = "") -> dict:
2379
+ """Set one record's bi-temporal window without touching its content.
2380
+
2381
+ The MCP remember path used to call remember() a second time to apply the
2382
+ window, which re-wrote evidence, verified and confidence to their defaults
2383
+ on the same row. This names the intent instead.
2384
+ """
2385
+ row = get_record(conn, record_id)
2386
+ if not row:
2387
+ raise NotFound(f"record {record_id} not found")
2388
+ conn.execute(
2389
+ "UPDATE records SET valid_from=?, valid_until=?, updated_at=? WHERE id=?",
2390
+ (valid_from or "", valid_until or "", now_iso(), record_id))
2391
+ conn.commit()
2392
+ return get_record(conn, record_id)
2393
+
2394
+
2395
+ # Future-tense markers (graphiti temporal_edge_utils.py pattern): a plan is
2396
+ # not a present fact. When wording says "will/akan" and the caller pinned a
2397
+ # validity window, remind them the window should start when the plan
2398
+ # executes, not when it was stated. Advisory only - never blocks a write.
2399
+ _FUTURE_RE = re.compile(
2400
+ r"\b(will|shall|going to|plans? to|planned|next (sprint|week|month|release)"
2401
+ r"|akan|nanti|rencana|mau di)\b", re.IGNORECASE)
2402
+
2403
+
2404
+ def _future_tense_note(content: str, valid_from: str) -> str:
2405
+ if valid_from and _FUTURE_RE.search(content or ""):
2406
+ return ("plan wording detected: valid_from should mark when the plan "
2407
+ "takes effect, not when it was stated")
2408
+ return ""
2409
+
2410
+
2411
+ def _fts_query(query: str) -> str:
2412
+ """Turn free text into a safe FTS5 MATCH expression.
2413
+
2414
+ A bare MATCH string is a query language: quotes, *, -, NEAR( and boolean
2415
+ keywords either raise or silently change meaning. Each word is re-derived
2416
+ from the tokenizer's own alphabet, so operator characters are dropped
2417
+ rather than escaped, and punctuation-only input collapses to no query.
2418
+ The last word carries a prefix marker: typing "deplo" should still find
2419
+ "deploy" mid-word, which is how an unfinished thought is typed.
2420
+ """
2421
+ words = _tokens(query)
2422
+ if not words:
2423
+ return ""
2424
+ quoted = ['"' + w + '"' for w in words[:-1]]
2425
+ quoted.append('"' + words[-1] + '"*')
2426
+ return " ".join(quoted)
2427
+
2428
+
2429
+ FUZZY_CUTOFF = 0.75
2430
+ MIN_REPAIR_LEN = 5
2431
+
2432
+ _VOCAB_CACHE: dict = {}
2433
+ _VOCAB_CACHE_LOCK = threading.Lock()
2434
+
2435
+
2436
+ def _vocab(conn: sqlite3.Connection) -> list:
2437
+ """Distinct stemmed terms in the index, for typo repair.
2438
+
2439
+ fts5vocab is a read-only mirror of the index, so it is always in sync
2440
+ and never needs maintenance. Missing table means an uninitialised or
2441
+ in-memory database; an empty vocabulary makes every repair a no-op.
2442
+
2443
+ Loading the full term list was the top cost of a rerank (0.35s of 1.4s
2444
+ over five queries) because it ran twice per query. The list is cached
2445
+ per (database file, sqlite data_version): any write by another
2446
+ connection bumps data_version and invalidates the entry, so the cache
2447
+ cannot go stale silently.
2448
+ """
2449
+ try:
2450
+ db_file = conn.execute("PRAGMA database_list").fetchone()[2]
2451
+ # data_version only bumps on commits from OTHER connections, so the
2452
+ # same-connection writer needs the record count too: any insert or
2453
+ # delete changes it, and an FTS term set cannot change without one.
2454
+ version = (conn.execute("PRAGMA data_version").fetchone()[0],
2455
+ conn.execute("SELECT COUNT(*) FROM records").fetchone()[0])
2456
+ except sqlite3.OperationalError:
2457
+ db_file, version = "", (-1, -1)
2458
+ key = (db_file, version)
2459
+ with _VOCAB_CACHE_LOCK:
2460
+ cached = _VOCAB_CACHE.get(key)
2461
+ if cached is not None:
2462
+ return cached
2463
+ try:
2464
+ vocab = [r[0] for r in conn.execute(
2465
+ "SELECT term FROM records_fts_vocab ORDER BY term")]
2466
+ except sqlite3.OperationalError:
2467
+ vocab = []
2468
+ with _VOCAB_CACHE_LOCK:
2469
+ _VOCAB_CACHE[key] = vocab
2470
+ if len(_VOCAB_CACHE) > 8:
2471
+ _VOCAB_CACHE.pop(next(iter(_VOCAB_CACHE)))
2472
+ return vocab
2473
+
2474
+
2475
+ def _repair_typos(conn: sqlite3.Connection, words: list, vocab: list) -> list:
2476
+ """Replace words the index has never seen with their nearest term.
2477
+
2478
+ A word is considered known when it, or anything it prefixes, occurs in
2479
+ the index. An unknown word gets the closest vocabulary term above
2480
+ FUZZY_CUTOFF, or stays as-is when nothing is close enough, so a
2481
+ genuinely novel query word is never rewritten into a wrong match.
2482
+ Repairs only run when the exact query returns nothing, which keeps a
2483
+ valid query's ranking untouched.
2484
+ """
2485
+ if not vocab:
2486
+ return words
2487
+ vocab_set = set(vocab)
2488
+ fixed = []
2489
+ for w in words:
2490
+ if w in vocab_set or any(t.startswith(w) for t in vocab_set):
2491
+ fixed.append(w)
2492
+ continue
2493
+ if len(w) < MIN_REPAIR_LEN or _WORD_TO_GROUP.get(w):
2494
+ # Short words clear the fuzzy cutoff too easily; known
2495
+ # synonyms are real words, not typos - the synonym tier
2496
+ # translates them, difflib must not mangle them first.
2497
+ fixed.append(w)
2498
+ continue
2499
+ close = difflib.get_close_matches(w, vocab, n=1, cutoff=FUZZY_CUTOFF)
2500
+ fixed.append(close[0] if close else w)
2501
+ return fixed
2502
+
2503
+
2504
+ def _search_after_repairs(conn: sqlite3.Connection, query: str,
2505
+ allow_repair: bool = True, rank: bool = True,
2506
+ **kwargs) -> list:
2507
+ """Search exact first; on an empty result, retry with repaired words.
2508
+
2509
+ allow_repair=False skips the fuzzy stage. The write path
2510
+ (decide -> find_similar -> _candidates) uses it: a near-duplicate
2511
+ lookup does not need typo correction, and difflib over the whole
2512
+ vocabulary (9.6k terms) cost ~46ms per write at 1.5k records -- the
2513
+ dominant term in a superlinear ingest curve (40ms at 500 rows to 81ms
2514
+ at 4k).
2515
+ """
2516
+ rows = _search_exact(conn, query, rank=rank, **kwargs)
2517
+ if rows or not allow_repair:
2518
+ return rows
2519
+ vocab = _vocab(conn)
2520
+ words = _repair_typos(conn, _tokens(query), vocab)
2521
+ if words != _tokens(query):
2522
+ rows = _search_exact(conn, " ".join(words), rank=rank, **kwargs)
2523
+ return rows
2524
+
2525
+
2526
+ def _stem(word: str) -> str:
2527
+ """Porter-ish suffix strip matching the FTS tokenizer's common cases."""
2528
+ # porter step 1b: *ied under a consonant just drops the d, so
2529
+ # "verified" rejoins "verify" before step 1c
2530
+ if word.endswith("ied") and len(word) >= 5:
2531
+ word = word[:-1]
2532
+ for suffix in ("ization", "ational", "iveness", "fulness", "ousness",
2533
+ "ation", "ement", "ances", "ences", "ingly", "edly",
2534
+ "ings", "ies", "ally", "es", "ed", "ing", "er",
2535
+ "est", "ly", "s"):
2536
+ if word.endswith(suffix) and len(word) - len(suffix) >= 3:
2537
+ word = word[: -len(suffix)]
2538
+ break
2539
+ # porter step 1c: trailing y after a consonant becomes i, so
2540
+ # "verify" and "verified" stem to "verifi"
2541
+ if word.endswith("y") and len(word) >= 3 and word[-2] not in "aeiou":
2542
+ word = word[:-1] + "i"
2543
+ elif word.endswith("ie") and len(word) >= 4:
2544
+ word = word[:-2] + "i"
2545
+ return word
2546
+
2547
+
2548
+ def _or_query(words: list) -> str:
2549
+ """Build an OR match: any word hitting is enough to surface a candidate."""
2550
+ return " OR ".join('"' + w + '"*' for w in words)
2551
+
2552
+
2553
+ # Concept groups for the synonym fallback tier (pattern adopted from
2554
+ # Mnemosyne core/synonyms.py, code-audited 2026-11-21). Curated, small,
2555
+ # lowercase; a word resolves to at most one group. Expansion runs only
2556
+ # when every earlier tier came back empty, so a working query's ranking
2557
+ # is never widened.
2558
+ SYNONYM_GROUPS = {
2559
+ "database": ["db", "datastore", "sqlite", "postgres"],
2560
+ "password": ["pass", "pwd", "passwd", "credential", "secret"],
2561
+ "config": ["configuration", "settings", "cfg"],
2562
+ "error": ["bug", "fault", "failure", "crash", "exception", "traceback"],
2563
+ "fix": ["repair", "resolve", "patch", "correct"],
2564
+ "deploy": ["deployment", "release", "rollout"],
2565
+ "server": ["host", "machine", "vps", "instance"],
2566
+ "api": ["endpoint", "interface"],
2567
+ "token": ["apikey", "bearer"],
2568
+ "user": ["account", "profile", "identity"],
2569
+ "model": ["llm", "provider"],
2570
+ "latency": ["slow", "lag", "timeout", "deadline"],
2571
+ "memory": ["recall", "remember", "retention"],
2572
+ "search": ["find", "lookup", "query", "retrieve"],
2573
+ "file": ["document", "doc", "path"],
2574
+ "delete": ["remove", "drop", "erase", "purge"],
2575
+ "create": ["add", "insert", "new"],
2576
+ "update": ["edit", "modify", "change", "upgrade"],
2577
+ "test": ["pytest", "spec", "assert"],
2578
+ "install": ["setup", "pip", "npm", "dependency"],
2579
+ "backup": ["snapshot", "dump", "restore"],
2580
+ "rotate": ["rotation", "refresh", "renew"],
2581
+ }
2582
+ _WORD_TO_GROUP = {}
2583
+ for _canonical, _group in SYNONYM_GROUPS.items():
2584
+ for _w in [_canonical] + _group:
2585
+ _WORD_TO_GROUP.setdefault(_w, _canonical)
2586
+
2587
+
2588
+ def _synonym_group(word: str):
2589
+ canonical = _WORD_TO_GROUP.get(word)
2590
+ if canonical is None:
2591
+ return None
2592
+ return [canonical] + SYNONYM_GROUPS[canonical]
2593
+
2594
+
2595
+ def _synonym_query(query: str) -> str:
2596
+ """OR-of-groups MATCH for the fallback tier; '' when nothing expands.
2597
+
2598
+ Each group becomes ("a" OR "b" ...) and groups AND together, so a
2599
+ two-word query still needs both concepts present, just spelled either
2600
+ way. Words without a group stay literal. Only fires on an otherwise
2601
+ empty result, so precision loss cannot touch a working query.
2602
+ """
2603
+ words = _tokens(query)
2604
+ if not words:
2605
+ return ""
2606
+ parts, expanded = [], False
2607
+ for w in words:
2608
+ group = _synonym_group(w)
2609
+ if group and len(group) > 1:
2610
+ alts = sorted(set(group) | {w})
2611
+ parts.append("(" + " OR ".join('"%s"' % a for a in alts) + ")")
2612
+ expanded = True
2613
+ else:
2614
+ parts.append('"%s"*' % w)
2615
+ if not expanded:
2616
+ return ""
2617
+ return ">>" + " AND ".join(parts)
2618
+
2619
+
2620
+ def _concept_overlap(query: str, row: dict) -> int:
2621
+ """Query words whose concept group the record satisfies (any spelling).
2622
+
2623
+ The AND-of-OR-groups MATCH already guarantees every concept is present;
2624
+ this counts them per record so the lexical fraction reflects concepts
2625
+ covered, not raw string overlap with words the operator never stored.
2626
+ """
2627
+ row_tokens = {_stem(w) for w in _tokens(" ".join(
2628
+ (row.get("content") or "", row.get("evidence") or "", row.get("tags") or "")))}
2629
+ n = 0
2630
+ for w in _tokens(query):
2631
+ group = _synonym_group(w) or [w]
2632
+ if any(_stem(g) in row_tokens for g in group):
2633
+ n += 1
2634
+ return max(1, n)
2635
+
2636
+
2637
+ def _query_known(conn: sqlite3.Connection, query: str) -> bool:
2638
+ """True when at least one query word (or a prefix of it) is indexed.
2639
+
2640
+ graphify vocabulary gate, stdlib: unknown vocabulary means the query is
2641
+ outside what this store can answer, so the honest reply is abstention,
2642
+ not a partial-token guess. Known synonyms count as known words.
2643
+
2644
+ Probed with three indexed lookups instead of materialising the whole
2645
+ vocabulary: _vocab() cost ~17ms per call at 4k records and the write
2646
+ path calls this once per write, which made ingest superlinear. An
2647
+ empty index still returns True so a fresh store does not abstain on
2648
+ everything.
2649
+ """
2650
+ # COUNT(*) over fts5vocab walks every term (17ms at 12k records); the
2651
+ # records count is O(1) and answers the same question (is the index
2652
+ # empty?). _query_known runs once per write, so the 17ms was a real
2653
+ # term in the ingest curve.
2654
+ total = conn.execute("SELECT COUNT(*) FROM records").fetchone()[0]
2655
+ if not total:
2656
+ return True
2657
+ for w in _tokens(query):
2658
+ s = _stem(w)
2659
+ row = conn.execute(
2660
+ "SELECT term FROM records_fts_vocab WHERE term >= ?"
2661
+ " ORDER BY term LIMIT 1", (s,)).fetchone()
2662
+ if row and (row[0] == s or row[0].startswith(s)):
2663
+ return True
2664
+ if _WORD_TO_GROUP.get(w):
2665
+ return True
2666
+ return False
2667
+
2668
+
2669
+ def _search_relaxed(conn: sqlite3.Connection, query: str,
2670
+ allow_repair: bool = True, rank: bool = True, **kwargs) -> list:
2671
+ """When no record contains every word, rank by best single-word match.
2672
+
2673
+ A four-word natural-language query ("ganti model pindah sesi") usually
2674
+ has no record containing all four, and an AND-only index answers zero
2675
+ even though several records cover the intent well. bm25 already ranks
2676
+ an OR pool by how strongly each record matches its best term, so the
2677
+ top rows are the ones sharing the most/strongest words with the query,
2678
+ not random one-word hits. Runs only after the exact AND and the
2679
+ typo-repaired retry both return nothing.
2680
+
2681
+ An INTENT whose cue carries a query term is pooled even when its body
2682
+ matches nothing: the cue is the environment signal that should pull the
2683
+ intent forward (Rummel & Kvavilashvili 2023). Cue hits ride at the end
2684
+ of the pool; the cue bonus in recall() does the ranking.
2685
+ """
2686
+ rows = _search_after_repairs(conn, query, allow_repair=allow_repair,
2687
+ **kwargs)
2688
+ if not rows:
2689
+ # Concept translation beats word soup: a record covering BOTH
2690
+ # concepts under different spellings is a better answer than one
2691
+ # sharing a single literal word, so the synonym tier runs before
2692
+ # the OR relaxation.
2693
+ syn_expr = _synonym_query(query)
2694
+ if syn_expr:
2695
+ rows = _search_exact(conn, syn_expr, rank=rank, **kwargs)
2696
+ for r in rows:
2697
+ # Provenance: matched via concept translation, not the
2698
+ # operator's literal words. recall() surfaces the flag.
2699
+ r["synonym_match"] = True
2700
+ r["matched_terms"] = _concept_overlap(query, r)
2701
+ r["query_terms"] = max(1, len(_tokens(query)))
2702
+ if not rows and not _query_known(conn, query):
2703
+ # Vocabulary gate (graphify _query_uses_known_words): a query whose
2704
+ # words exist nowhere in the index cannot be answered from one
2705
+ # incidental shared token; abstain instead of guessing. Cue hits
2706
+ # are exempt: an INTENT's cue is deliberately outside the FTS
2707
+ # index, so a cue-only match is still a real answer.
2708
+ cue_rows = _cue_pool(conn, query, **kwargs)
2709
+ return cue_rows
2710
+ if not rows:
2711
+ words = _tokens(query)
2712
+ if len(words) >= 2:
2713
+ or_expr = _or_query(words)
2714
+ if or_expr:
2715
+ rows = _search_exact(conn, ">" + or_expr, rank=rank, **kwargs)
2716
+ cue_rows = _cue_pool(conn, query, **kwargs)
2717
+ if cue_rows:
2718
+ seen = {r["id"] for r in rows}
2719
+ rows = rows + [r for r in cue_rows if r["id"] not in seen]
2720
+ return rows
2721
+
2722
+
2723
+ def _cue_pool(conn: sqlite3.Connection, query: str, limit: int = 20, rtype: str = None,
2724
+ project_id: str = None, session_id: str = None,
2725
+ verified_only: bool = False,
2726
+ min_confidence: float = 0.0, pool: int = None,
2727
+ about_peer: str = None, as_of: str = None) -> list:
2728
+ """INTENT records whose cue shares a token with the query.
2729
+
2730
+ Content search cannot see the cue (it is not in the FTS index), so this
2731
+ is a plain scan over the cue column. Kept small by the intent table's
2732
+ size; returns rows shaped like _search_exact's so recall()'s reranker
2733
+ can treat them uniformly.
2734
+ """
2735
+ qtokens = _tokens(query)
2736
+ if not qtokens:
2737
+ return []
2738
+ sql = """
2739
+ SELECT r.id, r.type, r.content, r.evidence, r.verified, r.confidence,
2740
+ r.source, r.tags, r.created_at, r.updated_at, r.session_id,
2741
+ r.project_id, r.parent_id, r.about_peer, r.superseded_by,
2742
+ r.importance, r.cue, r.decay_tau, r.stale, r.valid_from,
2743
+ r.valid_until, 0.0 AS rank
2744
+ FROM records r
2745
+ WHERE r.type = 'INTENT'
2746
+ """
2747
+ params = []
2748
+ if rtype:
2749
+ sql += " AND r.type = ?"
2750
+ params.append(rtype)
2751
+ if project_id:
2752
+ sql += " AND r.project_id = ?"
2753
+ params.append(project_id)
2754
+ if session_id:
2755
+ sql += " AND r.session_id = ?"
2756
+ params.append(session_id)
2757
+ if about_peer:
2758
+ sql += " AND r.about_peer = ?"
2759
+ params.append(about_peer)
2760
+ if verified_only:
2761
+ sql += " AND r.verified = 1"
2762
+ if min_confidence > 0:
2763
+ sql += " AND r.confidence >= ?"
2764
+ params.append(min_confidence)
2765
+ if as_of:
2766
+ sql += (" AND (r.valid_from='' OR r.valid_from<=?)"
2767
+ " AND (r.valid_until='' OR r.valid_until>?)")
2768
+ params.extend([as_of, as_of])
2769
+ rows = [dict(row) for row in conn.execute(sql, params)]
2770
+ picked = []
2771
+ for row in rows:
2772
+ cue_tokens = set(_tokens(row.get("cue") or ""))
2773
+ if cue_tokens & set(qtokens):
2774
+ row["matched_terms"] = 0
2775
+ row["query_terms"] = len(qtokens)
2776
+ picked.append(row)
2777
+ return picked[:pool if pool is not None else limit]
2778
+
2779
+
2780
+ def _search_exact(conn: sqlite3.Connection, query: str, limit: int = 20, rtype: str = None,
2781
+ project_id: str = None, session_id: str = None,
2782
+ verified_only: bool = False,
2783
+ min_confidence: float = 0.0, pool: int = None,
2784
+ about_peer: str = None, as_of: str = None,
2785
+ rank: bool = True):
2786
+ raw = query.startswith('>')
2787
+ match = query.lstrip('>') if raw else _fts_query(query)
2788
+ if not match:
2789
+ return []
2790
+ # bm25() in the SELECT list is evaluated per matching row: on a broad OR
2791
+ # query that matches the whole corpus it costs ~70ms because FTS5 scores
2792
+ # every candidate before LIMIT applies. The near-duplicate prefilter
2793
+ # only needs rows, so rank=False omits the scoring entirely.
2794
+ # rank=False drops the column entirely: a literal "0.0 AS rank" kept the
2795
+ # same three-column projection shape and measured *slower* than bm25,
2796
+ # because SQLite no longer used the bare MATCH plan.
2797
+ rank_expr = (""", bm25(records_fts, 0.0, 5.0, 1.0, 0.5) / CASE r.type
2798
+ WHEN 'RULE' THEN 1.4 WHEN 'CORRECTION' THEN 1.4
2799
+ WHEN 'DECISION' THEN 1.2 WHEN 'WORKFLOW' THEN 1.2
2800
+ WHEN 'PROCEDURAL' THEN 1.2 WHEN 'INTENT' THEN 1.0
2801
+ WHEN 'FACT' THEN 1.0 WHEN 'REFLECTIVE' THEN 0.9
2802
+ WHEN 'INFERENCE' THEN 0.8 WHEN 'ASSUMPTION' THEN 0.7
2803
+ ELSE 1.0 END AS rank""" if rank else "")
2804
+ sql = """
2805
+ SELECT r.id, r.type, r.content, r.evidence, r.verified, r.confidence, r.source, r.tags,
2806
+ r.created_at, r.updated_at, r.session_id, r.project_id, r.parent_id,
2807
+ r.about_peer, r.superseded_by, r.importance, r.cue, r.decay_tau,
2808
+ r.stale, r.valid_from, r.valid_until""" + rank_expr + """
2809
+ FROM records_fts
2810
+ JOIN records r ON r.id = records_fts.id
2811
+ WHERE records_fts MATCH ?
2812
+ """
2813
+ params = [match]
2814
+ if rtype:
2815
+ sql += " AND r.type = ?"
2816
+ params.append(rtype)
2817
+ if project_id:
2818
+ sql += " AND r.project_id = ?"
2819
+ params.append(project_id)
2820
+ if session_id:
2821
+ sql += " AND r.session_id = ?"
2822
+ params.append(session_id)
2823
+ if about_peer:
2824
+ sql += " AND r.about_peer = ?"
2825
+ params.append(about_peer)
2826
+ if verified_only:
2827
+ sql += " AND r.verified = 1"
2828
+ if min_confidence > 0:
2829
+ sql += " AND r.confidence >= ?"
2830
+ params.append(min_confidence)
2831
+ if as_of:
2832
+ sql += (" AND (r.valid_from='' OR r.valid_from<=?)"
2833
+ " AND (r.valid_until='' OR r.valid_until>?)")
2834
+ params.extend([as_of, as_of])
2835
+ # Ranking every candidate with bm25 costs ~12ms when a broad OR query
2836
+ # matches the whole corpus (12k rows); the near-duplicate prefilter only
2837
+ # needs *candidates*, so it passes rank=False and pays ~0.1ms instead.
2838
+ if rank:
2839
+ sql += (" ORDER BY rank, r.verified DESC, r.confidence DESC,"
2840
+ " r.updated_at DESC LIMIT ?")
2841
+ else:
2842
+ sql += " LIMIT ?"
2843
+ params.append(pool if pool is not None else limit)
2844
+ rows = [dict(row) for row in conn.execute(sql, params)]
2845
+ if not rows:
2846
+ return []
2847
+ if not rank:
2848
+ for row in rows:
2849
+ row.setdefault("rank", 0.0)
2850
+ # bm25 accumulates per matched term, so the lexical ceiling needs each
2851
+ # record's matched-term count: the query terms the record actually
2852
+ # matches. AND queries matched every term by construction; OR queries
2853
+ # may match a subset. The overlap runs over the same three fields the
2854
+ # FTS index covers (content, evidence, tags), and stems both sides
2855
+ # with the same suffix rules as the porter tokenizer so "verified"
2856
+ # matches "verify". ponytail: suffix-stemming is an approximation of
2857
+ # the porter algorithm; wrong stems are possible on irregular words,
2858
+ # ceiling: swap for the FTS index itself (one MATCH per term) when
2859
+ # lexical precision matters more than latency.
2860
+ query_tokens = set(_tokens(query if not raw else
2861
+ " ".join(re.findall(r'"([^"]+)"', match))))
2862
+ for r in rows:
2863
+ row_text = " ".join((r.get("content") or "", r.get("evidence") or "",
2864
+ r.get("tags") or ""))
2865
+ row_tokens = {_stem(w) for w in _tokens(row_text)}
2866
+ overlap = len({_stem(w) for w in query_tokens} & row_tokens)
2867
+ r["matched_terms"] = max(1, overlap)
2868
+ r["query_terms"] = max(1, len(query_tokens))
2869
+ ranks = [r["rank"] for r in rows]
2870
+ min_rank, max_rank = min(ranks), max(ranks)
2871
+ denom = max_rank - min_rank
2872
+ for r in rows:
2873
+ if denom == 0.0:
2874
+ r["lexical"] = 1.0
2875
+ else:
2876
+ r["lexical"] = 1.0 - (r["rank"] - min_rank) / denom
2877
+ return rows
2878
+
2879
+
2880
+ def search(conn: sqlite3.Connection, query: str, limit: int = 20, rtype: str = None,
2881
+ project_id: str = None, session_id: str = None,
2882
+ verified_only: bool = False,
2883
+ min_confidence: float = 0.0, pool: int = None,
2884
+ about_peer: str = None, as_of: str = None,
2885
+ allow_repair: bool = True, rank: bool = True):
2886
+ """Exact AND first, then typo-repaired, then best single-word match.
2887
+
2888
+ as_of (ISO timestamp) answers 'what was true then': records whose
2889
+ validity window excludes that moment are filtered out (Graphiti /
2890
+ Mnemosyne bi-temporal pattern). Empty windows mean always-valid.
2891
+ """
2892
+ return _search_relaxed(conn, query, limit=limit, rtype=rtype,
2893
+ project_id=project_id, session_id=session_id,
2894
+ allow_repair=allow_repair, rank=rank,
2895
+ verified_only=verified_only,
2896
+ min_confidence=min_confidence, pool=pool,
2897
+ about_peer=about_peer, as_of=as_of)
2898
+
2899
+ BM25_CEILING = 10.0
2900
+
2901
+
2902
+ def _stem_overlap(query: str, row: dict) -> int:
2903
+ """Query terms this row actually contains, stemmed on both sides.
2904
+
2905
+ Used for candidates whose lexical score arrived as 0 even though a lexical
2906
+ search returned them: on LongMemEval-S a gold ranked 6th by search() then
2907
+ got lexical 0.0 in the rerank, so the associative bonus could lift decoys
2908
+ above it. A row the search returned matched something; this recovers what.
2909
+ """
2910
+ q = {_stem(w) for w in _tokens(query)}
2911
+ row_tokens = {_stem(w) for w in _tokens(" ".join(
2912
+ (row.get("content") or "", row.get("evidence") or "",
2913
+ row.get("tags") or "")))}
2914
+ return len(q & row_tokens)
2915
+
2916
+
2917
+ def _absolute_lexical(candidates: list) -> dict:
2918
+ """Lexical strength on a fixed [0, 1] scale, keyed by record id.
2919
+
2920
+ bm25 saturates on long OR pools: a record matching 65 of 119 terms
2921
+ and one matching 14 can carry similar per-term scores, so bm25 rank
2922
+ alone cannot separate a join answer from an incidental hit. The
2923
+ primary signal is the matched-term fraction: query terms the record
2924
+ actually contains, over the query's term count. bm25 breaks ties
2925
+ within the same count, scaled by BM25_CEILING and normalised against
2926
+ the best rank in that count's group so it stays [0, 1]. Tiny corpora
2927
+ produce tiny bm25 magnitudes, so everything clamps near 1.0 there;
2928
+ that is the honest reading (all hits are near-perfect matches) and
2929
+ the spread reappears as the corpus grows.
2930
+ """
2931
+ qtokens = _pool_query_terms(candidates)
2932
+ groups = {}
2933
+ for c in candidates:
2934
+ groups.setdefault(c["matched_terms"] or 0, []).append(c)
2935
+ out = {}
2936
+ for n, group in groups.items():
2937
+ frac = n / qtokens if qtokens else 1.0
2938
+ # Within a matched-count bucket bm25 owns the full bucket step
2939
+ # (1/nterms): records matching the same term count order by
2940
+ # rank, and a stronger rank can beat a heat difference. The
2941
+ # spread stays inside the step so the fraction still dominates
2942
+ # across buckets, and the whole thing is normalised back to
2943
+ # [0, 1] so the documented scale holds.
2944
+ step = 1.0 / qtokens
2945
+ for c in group:
2946
+ tie = min(1.0, max(0.0, -c["rank"] / max(1.0, BM25_CEILING * n)))
2947
+ out[c["id"]] = round((frac + tie * step) / (1.0 + step), 6)
2948
+ return out
2949
+
2950
+
2951
+ def _pool_query_terms(candidates: list) -> int:
2952
+ """Query term count shared by the pool (all rows come from one query)."""
2953
+ n = candidates[0].get("query_terms") or 0
2954
+ return max(1, n)
2955
+
2956
+ def _ppr_expand(conn: sqlite3.Connection, seeds: list, all_rows: list,
2957
+ alpha: float = 0.15, iterations: int = 20) -> dict:
2958
+ """Personalized PageRank over the record association graph (HippoRAG,
2959
+ Gutierrez et al. 2024): seeds are the lexical hits, edges are shared
2960
+ rare terms + parent links. Power iteration spreads seed mass to
2961
+ associative neighbors that lexical search missed - the multi-hop join
2962
+ recall weakness, attacked without embeddings. Returns {id: ppr_mass}.
2963
+ """
2964
+ if not seeds or not all_rows:
2965
+ return {}
2966
+ ids = [r["id"] for r in all_rows]
2967
+ idx = {rid: i for i, rid in enumerate(ids)}
2968
+ n = len(ids)
2969
+ postings: dict = {}
2970
+ for i, r in enumerate(all_rows):
2971
+ for w in set(_tokens(r.get("content") or "")):
2972
+ postings.setdefault(w, []).append(i)
2973
+ adj: list = [dict() for _ in range(n)]
2974
+ for w, members in postings.items():
2975
+ if len(members) > 40: # hub terms link everything; no signal
2976
+ continue
2977
+ weight = 1.0 / len(members)
2978
+ for i in members:
2979
+ for j in members:
2980
+ if i != j:
2981
+ adj[i][j] = adj[i].get(j, 0.0) + weight
2982
+ # Hub penalty (graphify _path_hub_penalty, stdlib): a node that links to
2983
+ # a large share of the pool is a hub, and mass through it is association
2984
+ # by accident of degree, not meaning. Discount edges into such nodes.
2985
+ degree = [len(a) for a in adj]
2986
+ hub_cut = max(4, n // 8)
2987
+ for i in range(n):
2988
+ if degree[i] <= hub_cut:
2989
+ continue
2990
+ for j in list(adj[i]):
2991
+ adj[i][j] *= 0.5
2992
+ for i, r in enumerate(all_rows):
2993
+ other = r.get("parent_id")
2994
+ if other and other in idx:
2995
+ j = idx[other]
2996
+ adj[i][j] = adj[i].get(j, 0.0) + 1.0
2997
+ adj[j][i] = adj[j].get(i, 0.0) + 1.0
2998
+ for i in range(n):
2999
+ total = sum(adj[i].values())
3000
+ if total > 0:
3001
+ adj[i] = {j: w / total for j, w in adj[i].items()}
3002
+ seed_set = {idx[s["id"]] for s in seeds if s["id"] in idx}
3003
+ if not seed_set:
3004
+ return {}
3005
+ teleport = {i: 1.0 / len(seed_set) for i in seed_set}
3006
+ rank = dict(teleport)
3007
+ for _ in range(iterations):
3008
+ nxt: dict = {}
3009
+ for i, mass in rank.items():
3010
+ for j, w in adj[i].items():
3011
+ nxt[j] = nxt.get(j, 0.0) + (1.0 - alpha) * mass * w
3012
+ for i, t in teleport.items():
3013
+ nxt[i] = nxt.get(i, 0.0) + alpha * t
3014
+ rank = nxt
3015
+ # Dangling mass (nodes with no edges) redistributes uniformly so every
3016
+ # row has a score; isolated records get the floor, not a KeyError.
3017
+ floor = alpha / max(1, n) * 0.1
3018
+ return {ids[i]: rank.get(i, floor) for i in range(n)}
3019
+
3020
+
3021
+ PPR_WEIGHT = 0.10
3022
+ # Ablation switches. The roadmap asks for per-mechanism numbers, and a switch
3023
+ # is the only way to attribute a metric to a mechanism without editing code
3024
+ # between runs.
3025
+ PPR_ENABLED = os.environ.get("OMP_RECALL_PPR", "1").strip().lower() not in (
3026
+ "0", "false", "off", "no")
3027
+ MMR_ENABLED = os.environ.get("OMP_RECALL_MMR", "1").strip().lower() not in (
3028
+ "0", "false", "off", "no")
3029
+
3030
+
3031
+ def _ppr_bonus(conn: sqlite3.Connection, seeds: list, all_rows: list) -> dict:
3032
+ """Associative bonus per record, bounded by link strength (graphify
3033
+ weakest-hop): mass is scaled by the rarest shared term with a seed, so
3034
+ a hit joined only through a hub word earns little even when PPR mass is
3035
+ high. Returns {id: bonus in [0, PPR_WEIGHT]}.
3036
+ """
3037
+ ppr = _ppr_expand(conn, seeds, all_rows)
3038
+ if not ppr:
3039
+ return {}
3040
+ ppr_max = max(ppr.values())
3041
+ if ppr_max <= 0:
3042
+ return {}
3043
+ postings: dict = {}
3044
+ for i, r in enumerate(all_rows):
3045
+ for w in set(_tokens(r.get("content") or "")):
3046
+ postings.setdefault(w, []).append(r["id"])
3047
+ seed_terms = set()
3048
+ for s in seeds:
3049
+ seed_terms |= set(_tokens(s.get("content") or ""))
3050
+ n = max(1, len(all_rows))
3051
+ out = {}
3052
+ for r in all_rows:
3053
+ terms = set(_tokens(r.get("content") or "")) & seed_terms
3054
+ if not terms:
3055
+ continue
3056
+ # Rarest shared term decides the link strength: 1 member = 1.0,
3057
+ # a 40-member hub term = 0.025.
3058
+ strength = max(1.0 / len(postings[t]) for t in terms if t in postings)
3059
+ out[r["id"]] = PPR_WEIGHT * (ppr.get(r["id"], 0.0) / ppr_max) * min(1.0, strength * 4)
3060
+ return out
3061
+
3062
+
3063
+ MMR_LAMBDA = 0.7
3064
+
3065
+
3066
+ def _mmr_select(scored: list, limit: int) -> list:
3067
+ """Maximal Marginal Relevance over term overlap (graphiti pattern,
3068
+ stdlib): pick the best hit, then prefer candidates that add new terms
3069
+ over ones restating what is already selected. Relevance still leads
3070
+ (lambda 0.85); only near-duplicates get pushed down, so a window of
3071
+ k hits carries k distinct lessons instead of k spellings of one.
3072
+ """
3073
+ if len(scored) <= 1 or limit <= 1:
3074
+ return scored[:limit]
3075
+ pool = scored[:max(limit * 2, limit)]
3076
+ tokens = [set(_tokens(item[0].get("content") or "")) for item in pool]
3077
+ chosen: list = []
3078
+ chosen_tokens: set = set()
3079
+ remaining = list(range(len(pool)))
3080
+ while remaining and len(chosen) < limit:
3081
+ best_i, best_v = None, None
3082
+ for i in remaining:
3083
+ rel = pool[i][5]
3084
+ if chosen_tokens and tokens[i]:
3085
+ redundancy = len(tokens[i] & chosen_tokens) / len(tokens[i])
3086
+ else:
3087
+ redundancy = 0.0
3088
+ v = MMR_LAMBDA * rel - (1.0 - MMR_LAMBDA) * redundancy
3089
+ if best_v is None or v > best_v:
3090
+ best_i, best_v = i, v
3091
+ chosen.append(pool[best_i])
3092
+ chosen_tokens |= tokens[best_i]
3093
+ remaining.remove(best_i)
3094
+ # Selection order is deliberate: MMR's job is to decide WHICH items make
3095
+ # the window, and its ordering is the diversity ordering. Sorting by raw
3096
+ # score here would undo the diversification that
3097
+ # test_mmr_diversifies_near_duplicate_hits locks (a near-duplicate twin
3098
+ # would climb back above the distinct lesson). Measured on LoCoMo, the
3099
+ # sort changed hit@1 by 0.0000, so it bought nothing.
3100
+ #
3101
+ # The consequence is real and documented: recall() output is NOT
3102
+ # monotonic in `score`, so "top-1" means "first pick by the MMR formula".
3103
+ # Consumers that need strict score order must sort explicitly.
3104
+ return chosen
3105
+
3106
+
3107
+ def recall(conn: sqlite3.Connection, query: str, limit: int = 8, full: bool = False,
3108
+ pool: int = None, rtype: str = None, project_id: str = None,
3109
+ session_id: str = None, now=None,
3110
+ verified_only: bool = False, min_confidence: float = 0.0,
3111
+ about_peer: str = None, as_of: str = None,
3112
+ expand: int = 0, explain: bool = False,
3113
+ exclude: list = None) -> list:
3114
+ """Rerank candidate memories combining lexical match, heat and type prior.
3115
+
3116
+ Confidence enters once, through heat (which already weights it 0.45); a
3117
+ second direct term would count the same value twice and let a high
3118
+ confidence outrank a better lexical match. lexical comes back on an
3119
+ absolute [0, 1] scale (bm25 normalised by a fixed ceiling) so a score is
3120
+ comparable across queries instead of only within one result pool.
3121
+ """
3122
+ if not query or not query.strip():
3123
+ return []
3124
+ pool_size = max(pool or 0, limit * RECALL_POOL_FACTOR, RECALL_POOL_MIN)
3125
+ candidates = search(conn, query, limit=pool_size, pool=pool_size,
3126
+ rtype=rtype, project_id=project_id,
3127
+ session_id=session_id,
3128
+ verified_only=verified_only, min_confidence=min_confidence,
3129
+ about_peer=about_peer, as_of=as_of)
3130
+ if not candidates:
3131
+ return []
3132
+ for cand in candidates:
3133
+ if not cand.get("matched_terms"):
3134
+ # A pooled row with no recorded overlap still matched something,
3135
+ # or search() would not have returned it. Recover the real count
3136
+ # so the lexical term cannot be zero for a genuine hit.
3137
+ # query_terms is shared by the whole pool on purpose (see
3138
+ # _absolute_lexical); rewriting it per row would let one candidate
3139
+ # change every other row's fraction.
3140
+ cand["matched_terms"] = _stem_overlap(query, cand)
3141
+ lexicals = _absolute_lexical(candidates)
3142
+ # Associative expansion (HippoRAG): spread seed mass over the term graph
3143
+ # so a record that shares rare terms with several hits ranks above one
3144
+ # that matched a single common word. Bounded bonus, lexical still leads.
3145
+ ppr = _ppr_bonus(conn, candidates[:limit], candidates) if PPR_ENABLED else {}
3146
+
3147
+ # Cue triggering (Rummel & Kvavilashvili 2023): a query that carries an
3148
+ # INTENT's cue is the cue's appearance in the environment, so the intent
3149
+ # is pulled forward. The bonus scales with importance, and fades the
3150
+ # longer the intent has waited unfulfilled (Rummel 2023: intentions
3151
+ # lose ~.12 force per delay unit).
3152
+ qtokens = set(_tokens(query))
3153
+ cue_bonus = {}
3154
+ for cand in candidates:
3155
+ if cand.get("type") != "INTENT":
3156
+ continue
3157
+ cue = cand.get("cue") or ""
3158
+ if not cue or not (qtokens & set(_tokens(cue))):
3159
+ continue
3160
+ age_days = 0.0
3161
+ ts = _parse_ts(cand.get("updated_at"))
3162
+ if ts:
3163
+ ref = now or datetime.now(timezone.utc)
3164
+ age_days = max(0.0, (ref - ts).total_seconds() / 86400.0)
3165
+ fade = 1.0 / (1.0 + age_days / INTENT_DECAY_TAU_DAYS)
3166
+ cue_bonus[cand["id"]] = INTENT_CUE_BONUS * fade * float(
3167
+ cand.get("importance") or 0.5)
3168
+
3169
+ chain_heads = {c["superseded_by"] for c in candidates
3170
+ if c.get("superseded_by")}
3171
+ scored = []
3172
+ signal_map = _record_signals_bulk(conn, [c["id"] for c in candidates])
3173
+ for cand in candidates:
3174
+ signals = signal_map.get(cand["id"], [])
3175
+ parts = heat_parts(cand, signals, now=now)
3176
+ heat = parts["heat"]
3177
+ lexical = lexicals[cand["id"]]
3178
+ prior = TYPE_PRIOR.get(cand.get("type"), 0.0)
3179
+ superseded = bool(cand.get("superseded_by"))
3180
+ penalty = SUPERSEDED_PENALTY if superseded else 0.0
3181
+ if cand.get("stale"):
3182
+ penalty += STALE_PENALTY
3183
+ if (PROVENANCE_PENALTY_ENABLED and not cand.get("verified")
3184
+ and str(cand.get("source") or "").strip().casefold()
3185
+ in LOW_TRUST_SOURCES):
3186
+ penalty += PROVENANCE_PENALTY
3187
+ boost = SUPERSEDED_BOOST if cand["id"] in chain_heads else 0.0
3188
+ bonus = cue_bonus.get(cand["id"], 0.0)
3189
+ assoc = ppr.get(cand["id"], 0.0) * lexical
3190
+ base = (RECALL_WEIGHTS["lexical"] * lexical
3191
+ + RECALL_WEIGHTS["heat"] * heat
3192
+ + RECALL_WEIGHTS["type_prior"] * prior)
3193
+ score = round(max(0.0, base + bonus + boost - penalty + assoc), 6)
3194
+ # Explainability: every term above is already computed and then
3195
+ # discarded. Keeping the decomposition costs one tuple slot and makes
3196
+ # a score auditable instead of opaque -- the parts sum to `score`
3197
+ # exactly, so an explanation can never disagree with the ranking.
3198
+ parts_out = {
3199
+ "lexical": round(RECALL_WEIGHTS["lexical"] * lexical, 6),
3200
+ "heat": round(RECALL_WEIGHTS["heat"] * heat, 6),
3201
+ "type_prior": round(RECALL_WEIGHTS["type_prior"] * prior, 6),
3202
+ "ppr": round(assoc, 6),
3203
+ "cue": round(bonus, 6),
3204
+ "boost": round(boost, 6),
3205
+ "penalty": round(-penalty, 6),
3206
+ }
3207
+ scored.append((cand, parts, heat, lexical, prior, score, parts_out))
3208
+
3209
+ def _sort_key(item):
3210
+ c, parts, heat, lexical, prior, score, _parts = item
3211
+ ts = _parse_ts(c.get("updated_at"))
3212
+ epoch = ts.timestamp() if ts else 0.0
3213
+ return (
3214
+ -score,
3215
+ -int(bool(c.get("verified"))),
3216
+ -float(c.get("confidence") or 0.0),
3217
+ -epoch,
3218
+ str(c.get("id") or ""),
3219
+ )
3220
+
3221
+ scored.sort(key=_sort_key)
3222
+ top = _mmr_select(scored, limit) if MMR_ENABLED else scored[:limit]
3223
+ if exclude:
3224
+ # Cross-prompt diversity: a record already shown for the previous
3225
+ # prompt is usually the same generic lesson winning again (measured:
3226
+ # 30 prompts surfaced 44 distinct records, one of them 10 times). The
3227
+ # caller passes what it already injected; those drop out so the next
3228
+ # prompt reaches different memory instead of repeating the same three.
3229
+ skip = set(exclude)
3230
+ top = [item for item in top if item[0]["id"] not in skip] or top
3231
+ # Abstention asks whether anything matched the query, not whether the
3232
+ # first-ordered item scored well: reordering for diversity, or a weight
3233
+ # change, must not turn a good pool into a refusal.
3234
+ # Abstain when no candidate contains a single query term. A fraction floor
3235
+ # depended on how many words the caller typed (1 of 2 matched = 0.33, 1 of
3236
+ # 3 = 0.25), so the same evidence answered or refused by word count.
3237
+ abstained = (bool(scored)
3238
+ and max((item[0].get("matched_terms") or 0)
3239
+ for item in scored) < 1)
3240
+
3241
+ out = []
3242
+ if full:
3243
+ for c, parts, heat, lexical, prior, score, parts_out in top:
3244
+ item = {
3245
+ "id": c["id"],
3246
+ "type": c["type"],
3247
+ "confidence": c["confidence"],
3248
+ "verified": c["verified"],
3249
+ "score": score,
3250
+ "heat": heat,
3251
+ "abstained": abstained,
3252
+ "content": c.get("content", ""),
3253
+ "evidence": c.get("evidence", ""),
3254
+ "lexical": lexical,
3255
+ "matched_terms": c.get("matched_terms"),
3256
+ "type_prior": prior,
3257
+ "age_days": parts["age_days"],
3258
+ "successes": parts["successes"],
3259
+ "about_peer": c.get("about_peer", ""),
3260
+ "session_id": c.get("session_id", ""),
3261
+ "superseded_by": c.get("superseded_by", ""),
3262
+ "importance": c.get("importance", 0.5),
3263
+ "cue": c.get("cue", ""),
3264
+ "cue_triggered": c["id"] in cue_bonus,
3265
+ "stale": bool(c.get("stale")),
3266
+ "valid_from": c.get("valid_from", ""),
3267
+ "valid_until": c.get("valid_until", ""),
3268
+ }
3269
+ if c.get("synonym_match"):
3270
+ item["synonym_match"] = True
3271
+ if explain:
3272
+ item["explain"] = _explain_parts(parts_out, parts)
3273
+ out.append(item)
3274
+ else:
3275
+ for c, parts, heat, lexical, prior, score, parts_out in top:
3276
+ out.append({
3277
+ "id": c["id"],
3278
+ "type": c["type"],
3279
+ "confidence": c["confidence"],
3280
+ "verified": c["verified"],
3281
+ "score": score,
3282
+ "heat": heat,
3283
+ "abstained": abstained,
3284
+ "snippet": _snippet(c.get("content") or "", query),
3285
+ "session_id": c.get("session_id", ""),
3286
+ "about_peer": c.get("about_peer", ""),
3287
+ })
3288
+ if explain:
3289
+ out[-1]["explain"] = _explain_parts(parts_out, parts)
3290
+ if expand and out:
3291
+ out = _expand_context(conn, out, expand, full=full)
3292
+ return out
3293
+
3294
+
3295
+ def _explain_parts(weights: dict, heat_detail: dict) -> dict:
3296
+ """Score decomposition that sums to the score, plus the heat sub-parts.
3297
+
3298
+ `weights` holds the weighted terms; `heat_detail` is heat_parts(), which
3299
+ already decomposes heat into confidence/recency/reinforcement with their
3300
+ fixed 0.45/0.25/0.30 weights. Both are what the ranker actually used, so
3301
+ the explanation cannot drift from the ranking.
3302
+ """
3303
+ total = round(sum(weights.values()), 6)
3304
+ return {
3305
+ "terms": weights,
3306
+ "total": total,
3307
+ "heat_parts": {
3308
+ key: heat_detail.get(key)
3309
+ for key in ("confidence", "recency", "reinforcement",
3310
+ "successes", "age_days")
3311
+ },
3312
+ }
3313
+
3314
+
3315
+ def _expand_context(conn: sqlite3.Connection, hits: list, expand: int,
3316
+ full: bool = False) -> list:
3317
+ """Attach each hit's temporal neighbours from the same scope.
3318
+
3319
+ A single turn is often not self-contained: on LoCoMo the gold turn and the
3320
+ turn answering the previous question sit next to each other, so returning
3321
+ only the match hides half the answer. Measured: expanding a hit to its
3322
+ neighbours lifted hit@1 0.2266 -> 0.3799 and R@10 0.5190 -> 0.7714
3323
+ (window 5, 1,977 questions).
3324
+
3325
+ Ordering is by created_at because that is the only total order the store
3326
+ has; a corpus ingested with real timestamps (bench adapters now do) gets
3327
+ conversation order for free. `expand` is the total window size, so the
3328
+ neighbours come from (expand-1)//2 on each side.
3329
+ """
3330
+ half = max(0, (expand - 1) // 2)
3331
+ if half == 0:
3332
+ return hits
3333
+ for hit in hits:
3334
+ row = conn.execute(
3335
+ "SELECT created_at, project_id, session_id FROM records WHERE id=?",
3336
+ (hit["id"],)).fetchone()
3337
+ if not row:
3338
+ continue
3339
+ scope = ""
3340
+ scope_params = []
3341
+ if row["project_id"]:
3342
+ scope += " AND project_id = ?"
3343
+ scope_params.append(row["project_id"])
3344
+ if row["session_id"]:
3345
+ scope += " AND session_id = ?"
3346
+ scope_params.append(row["session_id"])
3347
+ # Symmetric window: `half` rows before the hit and `half` after, plus
3348
+ # the hit itself. Taking only following rows would bias the window
3349
+ # forward and miss the question that precedes its answer.
3350
+ before = [dict(r) for r in conn.execute(
3351
+ "SELECT id, content FROM records WHERE created_at <= ?" + scope +
3352
+ " ORDER BY created_at DESC, id DESC LIMIT ?",
3353
+ [row["created_at"], *scope_params, half + 1])]
3354
+ after = [dict(r) for r in conn.execute(
3355
+ "SELECT id, content FROM records WHERE created_at > ?" + scope +
3356
+ " ORDER BY created_at ASC, id ASC LIMIT ?",
3357
+ [row["created_at"], *scope_params, half])]
3358
+ neighbours = list(reversed(before)) + after
3359
+ if not neighbours:
3360
+ continue
3361
+ hit["window"] = [
3362
+ {"id": n["id"],
3363
+ "content": (n["content"] or "") if full else
3364
+ _snippet(n["content"] or "", "")}
3365
+ for n in neighbours
3366
+ ]
3367
+ return hits
3368
+
3369
+ def conflicts(conn: sqlite3.Connection, ids: list) -> list:
3370
+ """Surface candidate contradictions among recalled records (engram /
3371
+ remembrane pattern), never auto-merge. Two records conflict when they
3372
+ share most of their content terms but one supersedes the other, or a
3373
+ CORRECTION names the other's content. The agent judges; we only point.
3374
+ """
3375
+ rows = [dict(r) for r in conn.execute(
3376
+ "SELECT id, type, content, superseded_by FROM records WHERE id IN (%s)"
3377
+ % ",".join("?" * len(ids)), ids)] if ids else []
3378
+ token_sets = {r["id"]: set(_tokens(r["content"])) for r in rows}
3379
+ adjudicated = {tuple(sorted((r["a"], r["b"]))) for r in conn.execute(
3380
+ "SELECT a, b FROM not_conflict")}
3381
+ out = []
3382
+ seen = set(adjudicated)
3383
+ for a in rows:
3384
+ for b in rows:
3385
+ if a["id"] == b["id"]:
3386
+ continue
3387
+ key = tuple(sorted((a["id"], b["id"])))
3388
+ if key in seen:
3389
+ continue
3390
+ ta, tb = token_sets[a["id"]], token_sets[b["id"]]
3391
+ if not ta or not tb:
3392
+ continue
3393
+ overlap = len(ta & tb) / min(len(ta), len(tb))
3394
+ linked = a["superseded_by"] == b["id"] or b["superseded_by"] == a["id"]
3395
+ correction = (a["type"] == "CORRECTION" and overlap >= 0.5) or \
3396
+ (b["type"] == "CORRECTION" and overlap >= 0.5)
3397
+ numeric = (overlap >= 0.6 and _numeric_tokens(a["content"])
3398
+ and _numeric_tokens(b["content"])
3399
+ and _numeric_tokens(a["content"]) != _numeric_tokens(b["content"]))
3400
+ if overlap >= 0.6 and (linked or correction or numeric):
3401
+ seen.add(key)
3402
+ kind = "supersede" if linked else \
3403
+ "correction" if correction else "numeric"
3404
+ out.append({"a": a["id"], "b": b["id"],
3405
+ "overlap": round(overlap, 3), "kind": kind})
3406
+ return out
3407
+
3408
+
3409
+ def mark_not_conflict(conn: sqlite3.Connection, a: str, b: str) -> dict:
3410
+ """Record an adjudication: this pair is compatible, stop surfacing it.
3411
+
3412
+ engram's not_conflict verb: judgment belongs to the agent, and once
3413
+ made it persists so the same false positive never costs attention
3414
+ twice. Order-independent; idempotent.
3415
+ """
3416
+ lo, hi = sorted((a, b))
3417
+ conn.execute("INSERT OR IGNORE INTO not_conflict (a, b, ts) VALUES (?,?,?)",
3418
+ (lo, hi, now_iso()))
3419
+ conn.commit()
3420
+ return {"a": lo, "b": hi, "stored": True}
3421
+
3422
+
3423
+ def check_anchors(conn: sqlite3.Connection, apply: bool = False) -> dict:
3424
+ """Mark records stale when the file they describe has changed.
3425
+
3426
+ A record may carry anchor_path + anchor_sha (the file content it was
3427
+ learned from). When the current sha differs, the lesson may no longer
3428
+ hold: flag it for review instead of silently serving it. No competitor
3429
+ verified in the scan does checksum-triggered invalidation for coding
3430
+ memory; this is the 'memory that knows when it might be wrong' feature.
3431
+ """
3432
+ import hashlib
3433
+ rows = [dict(r) for r in conn.execute(
3434
+ "SELECT id, anchor_path, anchor_sha, stale FROM records"
3435
+ " WHERE anchor_path != '' AND anchor_sha != ''")]
3436
+ checked, flagged, cleared = 0, [], []
3437
+ for r in rows:
3438
+ checked += 1
3439
+ try:
3440
+ with open(r["anchor_path"], "rb") as f:
3441
+ current = hashlib.sha256(f.read()).hexdigest()
3442
+ except OSError:
3443
+ current = None # missing file: the anchor itself is gone
3444
+ changed = current != r["anchor_sha"]
3445
+ if changed and not r["stale"]:
3446
+ flagged.append(r["id"])
3447
+ if apply:
3448
+ conn.execute("UPDATE records SET stale=1 WHERE id=?", (r["id"],))
3449
+ elif not changed and r["stale"]:
3450
+ cleared.append(r["id"])
3451
+ if apply:
3452
+ conn.execute("UPDATE records SET stale=0 WHERE id=?", (r["id"],))
3453
+ if apply and (flagged or cleared):
3454
+ conn.commit()
3455
+ return {"checked": checked, "flagged": flagged, "cleared": cleared,
3456
+ "apply": bool(apply)}
3457
+
3458
+ def stage_write(conn: sqlite3.Connection, cand: dict) -> int:
3459
+ """Park a low-trust candidate for review (hermes write_approval).
3460
+ The content hash pins what was reviewed; decide refuses a changed payload.
3461
+ Duplicate pending content is not staged twice.
3462
+ """
3463
+ h = hashlib.sha256(normalize_content(cand["content"]).encode()).hexdigest()
3464
+ dup = conn.execute(
3465
+ "SELECT id FROM pending_writes WHERE content_hash=? AND status='pending'",
3466
+ (h,)).fetchone()
3467
+ if dup:
3468
+ return dup[0]
3469
+ cur = conn.execute(
3470
+ "INSERT INTO pending_writes (rtype, content, evidence, confidence, source,"
3471
+ " tags, session_id, project_id, event_id, content_hash, created_at)"
3472
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?)",
3473
+ (cand["rtype"], cand["content"], cand.get("evidence", ""),
3474
+ cand.get("confidence", 0.35), cand.get("source", ""),
3475
+ cand.get("tags", ""), cand.get("session_id", ""),
3476
+ cand.get("project_id", ""), cand.get("event_id", ""), h, now_iso()))
3477
+ conn.commit()
3478
+ return cur.lastrowid
3479
+
3480
+
3481
+ def list_pending(conn: sqlite3.Connection, status: str = "pending") -> list:
3482
+ return [dict(r) for r in conn.execute(
3483
+ "SELECT * FROM pending_writes WHERE status=? ORDER BY created_at", (status,))]
3484
+
3485
+
3486
+ class NotFound(LookupError):
3487
+ """A record or staged write the caller named does not exist.
3488
+
3489
+ Distinct from ValueError: the HTTP surface maps it to 404 and the CLI
3490
+ prints its message. A bare KeyError was used before, and str(KeyError)
3491
+ is just the id, so every surface printed "error: 3".
3492
+ """
3493
+
3494
+
3495
+ def decide_pending(conn: sqlite3.Connection, pending_id: int, approve: bool) -> dict:
3496
+ """Approve -> upsert into records; reject -> mark rejected. The hash is
3497
+ re-checked at decision time so an edited payload cannot ride an old approval.
3498
+ """
3499
+ row = conn.execute("SELECT * FROM pending_writes WHERE id=?",
3500
+ (pending_id,)).fetchone()
3501
+ if not row:
3502
+ # A bare KeyError prints as "error: 3" on the CLI, because str(exc) is
3503
+ # the key itself. Carry the meaning in the exception instead.
3504
+ raise NotFound(f"pending write {pending_id} not found")
3505
+ row = dict(row)
3506
+ if row["status"] != "pending":
3507
+ return {"id": pending_id, "status": row["status"], "noop": True}
3508
+ h = hashlib.sha256(normalize_content(row["content"]).encode()).hexdigest()
3509
+ if h != row["content_hash"]:
3510
+ raise ValueError("pending content changed since staging; re-review required")
3511
+ if approve:
3512
+ rid = upsert_record(
3513
+ conn, rtype=row["rtype"], content=row["content"],
3514
+ evidence=row["evidence"], verified=0, confidence=row["confidence"],
3515
+ source=row["source"], tags=row["tags"], session_id=row["session_id"],
3516
+ project_id=row["project_id"], event_id=row["event_id"])
3517
+ status = "approved"
3518
+ else:
3519
+ rid = ""
3520
+ status = "rejected"
3521
+ conn.execute("UPDATE pending_writes SET status=?, decided_at=? WHERE id=?",
3522
+ (status, now_iso(), pending_id))
3523
+ conn.commit()
3524
+ return {"id": pending_id, "status": status, "record_id": rid}
3525
+
3526
+ def _snippet(content: str, query: str, width: int = SNIPPET_CHARS) -> str:
3527
+ """A window onto the first query-term match, not the content's head.
3528
+
3529
+ FTS5's snippet() needs the original MATCH expression, which the rerank
3530
+ path no longer has; a local scan over the normalized query terms gives
3531
+ the same effect. No match, or content shorter than the window, falls
3532
+ back to the head.
3533
+ """
3534
+ norm = normalize_content(content)
3535
+ if len(norm) <= width:
3536
+ return norm
3537
+ terms = [w for w in normalize_content(query).split() if len(w) >= 4]
3538
+ low = norm.lower()
3539
+ pos = -1
3540
+ for term in terms:
3541
+ pos = low.find(term)
3542
+ if pos >= 0:
3543
+ break
3544
+ if pos < 0:
3545
+ return norm[: width - 3] + "..."
3546
+ start = max(0, pos - 30)
3547
+ end = min(len(norm), start + width - 6)
3548
+ prefix = "..." if start > 0 else ""
3549
+ suffix = "..." if end < len(norm) else ""
3550
+ return prefix + norm[start:end] + suffix
3551
+
3552
+
3553
+ def get_record(conn: sqlite3.Connection, record_id: str):
3554
+ """One record as a dict, or None when the id is absent."""
3555
+ row = conn.execute("SELECT * FROM records WHERE id=?", (record_id,)).fetchone()
3556
+ return dict(row) if row else None
3557
+
3558
+
3559
+ def find_record(conn: sqlite3.Connection, rtype: str, content: str,
3560
+ source: str = "", project_id: str = ""):
3561
+ """Look up a record by its content-addressed identity."""
3562
+ return get_record(conn, record_id_for(rtype, content, source, project_id))
3563
+
3564
+
3565
+ def digest(conn: sqlite3.Connection, budget: int = 2000,
3566
+ project_id: str = None, now=None) -> dict:
3567
+ """The always-in-context block: top verified/RULE/DECISION records rendered
3568
+ into a char-budgeted, deterministic text (hermes-agent frozen snapshot,
3569
+ but ranked instead of hand-curated). Stable ordering means host prefix
3570
+ caches survive; the budget header tells the agent how full it is.
3571
+
3572
+ L0 of progressive disclosure: one line per record (type, first sentence,
3573
+ confidence, id). Full content stays one recall/get away, so session start
3574
+ costs ~budget chars instead of the whole store.
3575
+ """
3576
+ now = now or datetime.now(timezone.utc)
3577
+ rows = [dict(r) for r in conn.execute(
3578
+ "SELECT * FROM records WHERE type IN ('RULE','DECISION','FACT','CORRECTION')"
3579
+ " AND (verified=1 OR confidence>=0.7) AND superseded_by=''"
3580
+ " AND (valid_until='' OR valid_until>?)",
3581
+ (now.isoformat(),))]
3582
+ if project_id:
3583
+ rows = [r for r in rows
3584
+ if project_id in (r.get("project_ids") or r.get("project_id") or "")]
3585
+ # The always-on block is injected without a human reading it. Instruction-
3586
+ # shaped content there is a command channel, whoever wrote it, so it is
3587
+ # excluded and named instead of obeyed.
3588
+ from . import capture as _capture
3589
+ quarantined = [r["id"] for r in rows
3590
+ if _capture.dangerous_instructions(r["content"])]
3591
+ if quarantined:
3592
+ rows = [r for r in rows if r["id"] not in quarantined]
3593
+ # Verified rules first, then by heat: the block should carry what the
3594
+ # agent must not violate before what merely worked once.
3595
+ def sort_key(r):
3596
+ signals = _record_signals(conn, r["id"])
3597
+ h = heat_parts(r, signals, now=now)["heat"]
3598
+ tier = 0 if r["type"] == "RULE" and r["verified"] else \
3599
+ 1 if r["verified"] else 2
3600
+ return (tier, -h, r["id"])
3601
+ rows.sort(key=sort_key)
3602
+ lines = []
3603
+ used = 0
3604
+ for r in rows:
3605
+ first = next((l for l in r["content"].splitlines() if l.strip()), "")
3606
+ line = (f"[{r['type']}] {first[:110]} "
3607
+ f"(conf {float(r['confidence']):.2f}"
3608
+ + (", verified" if r["verified"] else "") + f") id={r['id']}")
3609
+ if used + len(line) + 1 > budget:
3610
+ # Greedy refill (remembrane knapsack pattern, simplified): a
3611
+ # long line no longer fitting must not cut shorter records
3612
+ # behind it. Priority order is kept; only oversized lines skip.
3613
+ continue
3614
+ lines.append(line)
3615
+ used += len(line) + 1
3616
+ header = f"[memory digest {used}/{budget} chars, {len(lines)} records]"
3617
+ return {"text": header + "\n" + "\n".join(lines),
3618
+ "chars": used, "budget": budget, "records": len(lines),
3619
+ "total_eligible": len(rows)}
3620
+
3621
+
3622
+ def list_records(conn: sqlite3.Connection, rtype: str = None, project_id: str = None,
3623
+ limit: int = 100, offset: int = 0):
3624
+ """Records filtered by type and/or project, newest first."""
3625
+ sql = "SELECT * FROM records"
3626
+ params = []
3627
+ conds = []
3628
+ if rtype:
3629
+ conds.append("type=?")
3630
+ params.append(rtype)
3631
+ if project_id:
3632
+ conds.append("project_id=?")
3633
+ params.append(project_id)
3634
+ if conds:
3635
+ sql += " WHERE " + " AND ".join(conds)
3636
+ sql += " ORDER BY confidence DESC, updated_at DESC LIMIT ? OFFSET ?"
3637
+ params.extend([limit, offset])
3638
+ return [dict(row) for row in conn.execute(sql, params)]
3639
+
3640
+
3641
+ def _parse_ts(value: str):
3642
+ """Tolerant ISO parse; a malformed stamp ages to zero rather than crashing."""
3643
+ if not value:
3644
+ return None
3645
+ try:
3646
+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
3647
+ except ValueError:
3648
+ return None
3649
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
3650
+
3651
+
3652
+ def _record_signals(conn: sqlite3.Connection, record_id: str) -> list:
3653
+ rows = conn.execute(
3654
+ "SELECT signal, source, delta, ts FROM reinforcement WHERE record_id=? ORDER BY ts",
3655
+ (record_id,)).fetchall()
3656
+ return [dict(r) for r in rows]
3657
+
3658
+
3659
+ def _record_signals_bulk(conn: sqlite3.Connection, record_ids: list) -> dict:
3660
+ """Signals for many records in one query, keyed by record id.
3661
+
3662
+ recall() reranks a pool of candidates and needs each one's history for
3663
+ heat. One query per candidate is an N+1 that dominated rerank time on a
3664
+ large corpus (LoCoMo: ~5.9k turns). Chunked to stay under SQLite's
3665
+ variable limit.
3666
+ """
3667
+ out = {rid: [] for rid in record_ids}
3668
+ ids = list(dict.fromkeys(record_ids))
3669
+ for start in range(0, len(ids), 900):
3670
+ chunk = ids[start:start + 900]
3671
+ marks = ",".join("?" for _ in chunk)
3672
+ rows = conn.execute(
3673
+ "SELECT record_id, signal, source, delta, ts FROM reinforcement"
3674
+ f" WHERE record_id IN ({marks}) ORDER BY ts", chunk).fetchall()
3675
+ for row in rows:
3676
+ out[row["record_id"]].append(dict(row))
3677
+ return out
3678
+
3679
+
3680
+ def heat_parts(row: dict, signals: list, now=None) -> dict:
3681
+ """Decompose heat so every score can be explained and re-derived per record.
3682
+
3683
+ heat = 0.45*confidence + 0.25*recency + 0.30*reinforcement
3684
+
3685
+ recency is computed from `updated_at`, never from confidence. apply_decay
3686
+ already lowers confidence as time passes; ageing that value again here
3687
+ would count the same elapsed time twice and make an old record look older
3688
+ than its own timestamp says.
3689
+
3690
+ Weights are fixed rather than fitted: a fit would encode one corpus's
3691
+ behaviour, become unexplainable per record, and drift whenever the corpus
3692
+ changes. Fixed weights keep the components comparable across sessions.
3693
+ """
3694
+ now = now or datetime.now(timezone.utc)
3695
+ signals = signals or []
3696
+ updated = _parse_ts(row.get("updated_at"))
3697
+ age_days = max(0.0, (now - updated).total_seconds() / 86400.0) if updated else 0.0
3698
+ # ACT-R base-level activation (Anderson 1993): B = ln(sum (t - t_i)^-d)
3699
+ # approximated by the Park recency power law scaled by recency frequency.
3700
+ # Reinforcement count (n) lifts the base level: more accesses = higher
3701
+ # activation. This is the one remaining Park-term refinement (item 4
3702
+ # of the adopted queue) - kept conservative (0.15 weight on log-count).
3703
+ tau = float(row.get("decay_tau") or 0) or HEAT_DECAY_POWER_TAU_DAYS
3704
+ recency = (1.0 + age_days / tau) ** -HEAT_DECAY_POWER_BETA
3705
+
3706
+ successes = [s for s in signals if s.get("signal") == "success"]
3707
+ n_access = max(1, len(successes) + 1)
3708
+ sources = []
3709
+ for s in successes:
3710
+ name = normalize_content(s.get("source") or "").casefold()
3711
+ if name and name not in sources:
3712
+ sources.append(name)
3713
+ net_delta = sum(float(s.get("delta") or 0.0) for s in signals)
3714
+ # Smooth saturating maps instead of hard steps: each additional success
3715
+ # and each extra confidence delta still raises the term, but with
3716
+ # diminishing returns (Park et al. 2023 normalize each score to [0, 1]
3717
+ # before weighting; a step at n=2 or delta=0.2 makes the weight behave
3718
+ # as a threshold, not a weight).
3719
+ reinforcement = (0.5 * (1.0 - math.exp(-len(successes) / 1.25))
3720
+ + 0.5 * (1.0 - math.exp(-max(0.0, net_delta) / 0.1)))
3721
+
3722
+ confidence = min(1.0, max(0.0, float(row.get("confidence") or 0.0)))
3723
+ recency = min(1.0, recency + 0.15 * math.log(n_access) / math.log(10))
3724
+ heat = (HEAT_WEIGHTS["confidence"] * confidence
3725
+ + HEAT_WEIGHTS["recency"] * recency
3726
+ + HEAT_WEIGHTS["reinforcement"] * reinforcement)
3727
+ return {
3728
+ "heat": round(min(1.0, max(0.0, heat)), 6),
3729
+ "confidence": confidence,
3730
+ "age_days": round(age_days, 4),
3731
+ "recency": round(recency, 6),
3732
+ "reinforcement": round(reinforcement, 6),
3733
+ "successes": len(successes),
3734
+ "net_delta": round(net_delta, 6),
3735
+ "sources": sorted(sources),
3736
+ }
3737
+
3738
+
3739
+ def heat_of(conn: sqlite3.Connection, record_id: str, now=None) -> float:
3740
+ rec = get_record(conn, record_id)
3741
+ if not rec:
3742
+ raise ValueError(f"record not found: {record_id}")
3743
+ return heat_parts(rec, _record_signals(conn, record_id), now)["heat"]
3744
+
3745
+
3746
+ def last_promotion():
3747
+ """The promotion produced by the most recent reinforce() on this thread."""
3748
+ return getattr(_promotion_context, "last", None)
3749
+
3750
+
3751
+ def promote_hot(conn: sqlite3.Connection, record_id: str = None, now=None):
3752
+ """Turn a hot, twice-corroborated inference into a fact.
3753
+
3754
+ Every condition is required: a promotable type, heat at or above
3755
+ PROMOTE_HEAT, and successes reported from two distinct sources after
3756
+ normalising case and whitespace. `verified` is left alone: corroboration is
3757
+ evidence, not an operator's confirmation.
3758
+
3759
+ Returns the promotion dict, or None when nothing changed, in which case
3760
+ nothing is written. With no record_id, every promotable record is examined.
3761
+ """
3762
+ now = now or datetime.now(timezone.utc)
3763
+ if record_id:
3764
+ one = get_record(conn, record_id)
3765
+ rows = [one] if one else []
3766
+ else:
3767
+ marks = ",".join("?" for _ in PROMOTABLE_TYPES)
3768
+ rows = [dict(r) for r in conn.execute(
3769
+ f"SELECT * FROM records WHERE type IN ({marks})", PROMOTABLE_TYPES)]
3770
+
3771
+ promoted = None
3772
+ for row in rows:
3773
+ if row["type"] not in PROMOTABLE_TYPES:
3774
+ continue
3775
+ parts = heat_parts(row, _record_signals(conn, row["id"]), now)
3776
+ if parts["heat"] < PROMOTE_HEAT:
3777
+ continue
3778
+ if len(parts["sources"]) < 2:
3779
+ continue
3780
+ # Corroboration is not attestation: two success reports say the record
3781
+ # was useful, not that it is true. Promotion to FACT needs an operator
3782
+ # attestation; without it the move is refused and recorded, never
3783
+ # silently skipped.
3784
+ if effective_trust(row) != TRUST_ATTESTED:
3785
+ conn.execute(
3786
+ "INSERT INTO promotion_blocked (record_id, from_type, reason, heat, ts)"
3787
+ " VALUES (?,?,?,?,?)",
3788
+ (row["id"], row["type"],
3789
+ "no attestation (claimed by an agent surface)",
3790
+ parts["heat"], now.isoformat()))
3791
+ conn.commit()
3792
+ continue
3793
+ conn.execute("UPDATE records SET type=?, updated_at=? WHERE id=?",
3794
+ ("FACT", now.isoformat(), row["id"]))
3795
+ conn.execute("""
3796
+ INSERT INTO promotion_log
3797
+ (record_id, from_type, to_type, heat, successes, sources, ts)
3798
+ VALUES (?, ?, ?, ?, ?, ?, ?)
3799
+ """, (row["id"], row["type"], "FACT", parts["heat"], parts["successes"],
3800
+ ",".join(parts["sources"]), now.isoformat()))
3801
+ promoted = {"record_id": row["id"], "from_type": row["type"], "to_type": "FACT",
3802
+ "heat": parts["heat"], "successes": parts["successes"],
3803
+ "sources": parts["sources"], "promoted": True}
3804
+ if promoted:
3805
+ conn.commit()
3806
+ return promoted
3807
+
3808
+
3809
+ def purge_fts_free_pages(conn: sqlite3.Connection) -> None:
3810
+ """Rebuild the FTS index so deleted content leaves no readable bytes.
3811
+
3812
+ PRAGMA secure_delete scrubs ordinary pages; FTS5 keeps its own storage,
3813
+ so a merged index can still hold the text of a deleted row. `optimize`
3814
+ rewrites the index from live rows only. Cost is proportional to the
3815
+ index, so it is called on the delete paths (forget, forget_cold) rather
3816
+ than on every write.
3817
+ """
3818
+ try:
3819
+ conn.execute("INSERT INTO records_fts(records_fts) VALUES('optimize')")
3820
+ except sqlite3.Error:
3821
+ pass
3822
+
3823
+
3824
+ def forget_cold(conn: sqlite3.Connection, apply: bool = False, now=None,
3825
+ floor: float = DECAY_FLOOR, min_age_days: int = FORGET_MIN_AGE_DAYS,
3826
+ window_days: int = FORGET_WINDOW_DAYS) -> dict:
3827
+ """Find records nothing has touched, and optionally delete them.
3828
+
3829
+ All conditions must hold: unverified, not a RULE or CORRECTION, confidence
3830
+ at the decay floor, older than min_age_days since updated_at, and no
3831
+ reinforcement inside window_days. The window is bounded by default: any
3832
+ reinforcement ever recorded would otherwise protect a record forever, which
3833
+ makes forgetting impossible on a corpus that has ever been used. apply=False
3834
+ only reports, which is the default: deleting an operator's memory is a
3835
+ decision, not a side effect.
3836
+
3837
+ On apply the graveyard row is written before the delete, so a crash between
3838
+ the two leaves an audit trail rather than a silently missing record. Only a
3839
+ success signal inside the window protects a record: failure and decay lower
3840
+ confidence and must not keep a discredited record alive.
3841
+ """
3842
+ now = now or datetime.now(timezone.utc)
3843
+ cutoff = (now - timedelta(days=min_age_days)).isoformat()
3844
+ window_cutoff = ((now - timedelta(days=window_days)).isoformat()
3845
+ if window_days else None)
3846
+
3847
+ rows = [dict(r) for r in conn.execute(
3848
+ "SELECT * FROM records WHERE verified=0 AND type NOT IN ('RULE','CORRECTION')"
3849
+ " AND confidence <= ? AND updated_at < ?"
3850
+ " AND id NOT IN (SELECT superseded_by FROM records"
3851
+ " WHERE superseded_by != '')",
3852
+ (floor + FORGET_FLOOR_SLACK, cutoff))]
3853
+
3854
+ candidates = []
3855
+ for row in rows:
3856
+ sql = "SELECT COUNT(*) FROM reinforcement WHERE record_id=? AND signal='success'"
3857
+ params = [row["id"]]
3858
+ if window_cutoff:
3859
+ sql += " AND ts >= ?"
3860
+ params.append(window_cutoff)
3861
+ if conn.execute(sql, params).fetchone()[0]:
3862
+ continue
3863
+ candidates.append(row)
3864
+
3865
+ if apply:
3866
+ for row in candidates:
3867
+ conn.execute(
3868
+ "INSERT OR REPLACE INTO forgotten_graveyard (id, type, content, reason, ts)"
3869
+ " VALUES (?, ?, ?, ?, ?)",
3870
+ (row["id"], row["type"], (row["content"] or "")[:200],
3871
+ f"cold: confidence {row['confidence']} at floor, no reinforcement",
3872
+ now.isoformat()))
3873
+ conn.execute("DELETE FROM reinforcement WHERE record_id=?", (row["id"],))
3874
+ conn.execute("DELETE FROM records WHERE id=?", (row["id"],))
3875
+ if candidates:
3876
+ conn.commit()
3877
+ purge_fts_free_pages(conn)
3878
+ return {
3879
+ "forgotten": len(candidates) if apply else 0,
3880
+ "candidates": [r["id"] for r in candidates],
3881
+ "apply": bool(apply),
3882
+ }
3883
+
3884
+
3885
+ def apply_decay(conn: sqlite3.Connection, now=None, floor: float = DECAY_FLOOR) -> dict:
3886
+ """Age every unprotected record's confidence toward `floor`.
3887
+
3888
+ The decay anchor is the later of updated_at and last_decay_at. Anchoring on
3889
+ updated_at alone compounds: a second call would decay the already-decayed
3890
+ value over the same elapsed time again, so two calls at one instant would
3891
+ disagree. Recording the anchor makes the function idempotent for a given
3892
+ `now` and still linear across real time.
3893
+
3894
+ Verified records and the correction types are exempt: an operator's
3895
+ confirmation and a recorded correction do not become less true with time.
3896
+
3897
+ Returns {record_id: new_confidence} for the records that moved.
3898
+ """
3899
+ now = now or datetime.now(timezone.utc)
3900
+ moved = {}
3901
+ rows = [dict(r) for r in conn.execute(
3902
+ "SELECT id, confidence, updated_at, last_decay_at, verified, type,"
3903
+ " decay_exempt_until, decay_tau FROM records")]
3904
+ for row in rows:
3905
+ if row["verified"] or row["type"] in ("RULE", "CORRECTION"):
3906
+ continue
3907
+ exempt = _parse_ts(row["decay_exempt_until"])
3908
+ if exempt and now < exempt:
3909
+ continue
3910
+ anchors = [t for t in (_parse_ts(row["updated_at"]),
3911
+ _parse_ts(row["last_decay_at"])) if t]
3912
+ if not anchors:
3913
+ continue
3914
+ anchor = max(anchors)
3915
+ age_days = max(0.0, (now - anchor).total_seconds() / 86400.0)
3916
+ tau = float(row.get("decay_tau") or 0) or DECAY_POWER_TAU_DAYS
3917
+ factor = (1.0 + age_days / tau) ** -DECAY_POWER_BETA
3918
+ base = max(floor, float(row["confidence"]))
3919
+ target = floor + (base - floor) * factor
3920
+ if factor < 0.05:
3921
+ target = floor
3922
+ value = round(min(float(row["confidence"]), target), 6)
3923
+ if value < float(row["confidence"]):
3924
+ conn.execute("UPDATE records SET confidence=?, last_decay_at=? WHERE id=?",
3925
+ (value, now.isoformat(), row["id"]))
3926
+ moved[row["id"]] = value
3927
+ if moved:
3928
+ conn.commit()
3929
+ return moved
3930
+
3931
+
3932
+ def _spacing_factor(conn: sqlite3.Connection, record_id: str) -> float:
3933
+ """Scale a reinforcement by the gap since the last one (Cepeda 2006).
3934
+
3935
+ Inside SPACING_MIN_GAP_HOURS the repeat is massed and worth ~nothing;
3936
+ at SPACING_FULL_GAP_HOURS the gap is full strength; linear between.
3937
+ Explicit deltas bypass this: the caller has already decided the size.
3938
+ """
3939
+ row = conn.execute(
3940
+ "SELECT ts FROM reinforcement WHERE record_id=? AND signal IN"
3941
+ " ('success','reinforce') ORDER BY ts DESC LIMIT 1", (record_id,)).fetchone()
3942
+ if row is None:
3943
+ return 1.0
3944
+ try:
3945
+ last = _parse_ts(row[0])
3946
+ except Exception:
3947
+ return 1.0
3948
+ if last is None:
3949
+ return 1.0
3950
+ gap_h = (datetime.now(timezone.utc) - last).total_seconds() / 3600.0
3951
+ if gap_h <= SPACING_MIN_GAP_HOURS:
3952
+ return 0.1
3953
+ if gap_h >= SPACING_FULL_GAP_HOURS:
3954
+ return 1.0
3955
+ t = (gap_h - SPACING_MIN_GAP_HOURS) / (SPACING_FULL_GAP_HOURS - SPACING_MIN_GAP_HOURS)
3956
+ return round(0.1 + 0.9 * t, 4)
3957
+
3958
+
3959
+ def reinforce(conn: sqlite3.Connection, record_id: str, signal: str,
3960
+ delta: float = None, source: str = "",
3961
+ content: str = None, evidence: str = None,
3962
+ verified: int = 0) -> float:
3963
+ """Apply a reinforcement signal, then reconsider promotion on success.
3964
+
3965
+ An explicit delta overrides the canonical one. Promotion runs only for a
3966
+ success signal, and its outcome is reported through last_promotion() so the
3967
+ caller can say what happened without re-reading the row.
3968
+
3969
+ Negative signals (failure, decay) do not touch updated_at: a record a
3970
+ session just discredited must stay eligible for forgetting, not be
3971
+ refreshed by the very signal that lowered it.
3972
+
3973
+ Reconsolidation window: a correction with a positive rewrite also
3974
+ refreshes updated_at, which resets the decay anchor, so the rewritten
3975
+ memory coasts (RECONSOLIDATION_WINDOW_MINUTES documents the intent; the
3976
+ window IS the anchor reset, no separate timer). Hypercorrection adds
3977
+ decay_exempt_until on top for the grace period.
3978
+ """
3979
+ if signal not in VALID_SIGNALS:
3980
+ raise ValueError(f"invalid signal: {signal}")
3981
+ if verified and not (evidence or "").strip():
3982
+ raise ValueError("verified=True requires evidence")
3983
+
3984
+ row = conn.execute("SELECT confidence, trust FROM records WHERE id=?",
3985
+ (record_id,)).fetchone()
3986
+ if row is None:
3987
+ raise ValueError(f"record not found: {record_id}")
3988
+ pre_confidence = float(row[0])
3989
+ conf_ceiling = (CLAIMED_CONFIDENCE_CAP
3990
+ if (row["trust"] if "trust" in row.keys() else TRUST_CLAIMED)
3991
+ == TRUST_CLAIMED else 1.0)
3992
+
3993
+ # Reconsolidation gate (Sevenster 2013; Lee et al. 2017): a success
3994
+ # recall is read-only reinforcement. Only a correction that carries
3995
+ # replacement content opens the rewrite, and Metcalfe & Eich 2019
3996
+ # showed a wrong correction to a confidently-wrong record
3997
+ # contaminates it deeper, so the rewrite is refused unless the
3998
+ # caller marks it verified or supplies evidence.
3999
+ rewrite_applied = False
4000
+ if signal == "correction" and content is not None:
4001
+ if not (verified or (evidence or "").strip()):
4002
+ raise ValueError(
4003
+ "correction rewrite needs evidence or verified=True")
4004
+ if len(content) > REWRITE_MAX_CONTENT_LEN:
4005
+ raise ValueError(
4006
+ f"content exceeds {REWRITE_MAX_CONTENT_LEN} chars")
4007
+ if not content.strip():
4008
+ raise ValueError("correction content must not be empty")
4009
+ row_content = conn.execute(
4010
+ "SELECT content FROM records WHERE id=?", (record_id,)
4011
+ ).fetchone()[0]
4012
+ if content.strip() != row_content.strip():
4013
+ prev = conn.execute(
4014
+ "SELECT evidence, verified FROM records WHERE id=?",
4015
+ (record_id,)).fetchone()
4016
+ conn.execute(
4017
+ "UPDATE records SET content=?, evidence=?, verified=?,"
4018
+ " updated_at=?, superseded_by='' WHERE id=?",
4019
+ (content.strip(),
4020
+ evidence or prev[0] or "",
4021
+ max(1 if verified else 0, prev[1] or 0),
4022
+ now_iso(), record_id))
4023
+ rewrite_applied = True
4024
+
4025
+ actual_delta = float(delta) if delta is not None else SIGNAL_DELTAS[signal]
4026
+ if delta is None and signal in ("success", "reinforce"):
4027
+ actual_delta *= _spacing_factor(conn, record_id)
4028
+ # Hypercorrection (B2): the higher the confidence being corrected, the
4029
+ # bigger the surprise and the larger the rewrite. An explicit delta is
4030
+ # the caller's decision and is not second-guessed. The corrected record
4031
+ # also gets a decay grace window so the update settles before the
4032
+ # forgetting curve resumes (reconsolidation: a recalled-and-rewritten
4033
+ # memory is labile, not immediately re-consolidated).
4034
+ grace_iso = ""
4035
+ if signal == "correction" and delta is None \
4036
+ and pre_confidence >= HYPERCORRECTION_MIN_CONFIDENCE:
4037
+ actual_delta *= HYPERCORRECTION_FACTOR
4038
+ grace_iso = (datetime.now(timezone.utc)
4039
+ + timedelta(days=HYPERCORRECTION_DECAY_GRACE_DAYS)).isoformat()
4040
+ # Atomic clamp in SQL: concurrent reinforces each read the same base, so a
4041
+ # Python-side read-modify-write loses every signal but the last.
4042
+ if actual_delta >= 0:
4043
+ conn.execute(
4044
+ "UPDATE records SET confidence=CASE WHEN confidence > ? THEN confidence"
4045
+ " ELSE min(?, max(0.0, confidence+?)) END,"
4046
+ " updated_at=?, decay_exempt_until=? WHERE id=?",
4047
+ (conf_ceiling, conf_ceiling, actual_delta, now_iso(), grace_iso, record_id))
4048
+ else:
4049
+ conn.execute(
4050
+ "UPDATE records SET confidence=min(1.0, max(0.0, confidence+?)) WHERE id=?",
4051
+ (actual_delta, record_id))
4052
+ new_conf = conn.execute("SELECT confidence FROM records WHERE id=?",
4053
+ (record_id,)).fetchone()[0]
4054
+ # Memory strength (HLR): a spaced success lengthens this record's own
4055
+ # forgetting horizon, a failure shortens it. Massed repeats (spacing
4056
+ # factor ~0.1) do not grow strength: cramming is not consolidation.
4057
+ if signal in ("success", "reinforce") and actual_delta > 0:
4058
+ spaced = delta is not None or _spacing_factor(conn, record_id) >= 0.5
4059
+ if spaced:
4060
+ conn.execute(
4061
+ "UPDATE records SET decay_tau=min(?, max(?, "
4062
+ " (CASE WHEN decay_tau>0 THEN decay_tau ELSE ? END) * ?)) WHERE id=?",
4063
+ (STRENGTH_TAU_MAX_DAYS, STRENGTH_TAU_MIN_DAYS,
4064
+ DECAY_POWER_TAU_DAYS, STRENGTH_GROWTH, record_id))
4065
+ elif signal == "failure":
4066
+ conn.execute(
4067
+ "UPDATE records SET decay_tau=max(?, "
4068
+ " (CASE WHEN decay_tau>0 THEN decay_tau ELSE ? END) * ?) WHERE id=?",
4069
+ (STRENGTH_TAU_MIN_DAYS, DECAY_POWER_TAU_DAYS, STRENGTH_SHRINK, record_id))
4070
+ conn.execute("""
4071
+ INSERT INTO reinforcement (record_id, signal, delta, source, ts)
4072
+ VALUES (?, ?, ?, ?, ?)
4073
+ """, (record_id, signal, actual_delta, source, now_iso()))
4074
+ if rewrite_applied:
4075
+ _set_superseded(conn, record_id, source, prev_content=row_content)
4076
+ conn.commit()
4077
+
4078
+ _promotion_context.last = None
4079
+ if signal == "success":
4080
+ _promotion_context.last = promote_hot(conn, record_id)
4081
+ return new_conf
4082
+
4083
+
4084
+ def attest(conn: sqlite3.Connection, record_id: str, evidence: str = "") -> dict:
4085
+ """Mark one record operator-attested. The only path into ATTESTED trust.
4086
+
4087
+ Deliberately not reachable from any MCP tool: an agent that could attest
4088
+ would just be trusting itself, which is the defect this closes. Attestation
4089
+ needs evidence because the point is that something outside the writer
4090
+ verified it.
4091
+ """
4092
+ if not (evidence or "").strip():
4093
+ raise ValueError("attestation requires evidence naming what was checked")
4094
+ row = get_record(conn, record_id)
4095
+ if not row:
4096
+ raise NotFound(f"record {record_id} not found")
4097
+ conn.execute(
4098
+ "UPDATE records SET trust=?, verified=1, evidence=?, updated_at=?,"
4099
+ " attested_at=? WHERE id=?",
4100
+ (TRUST_ATTESTED, evidence.strip(), now_iso(), now_iso(), record_id))
4101
+ conn.commit()
4102
+ return get_record(conn, record_id)
4103
+
4104
+
4105
+ # --- sessions ----------------------------------------------------------------
4106
+
4107
+ def start_session(conn: sqlite3.Connection, session_id: str, project_id: str = "",
4108
+ parent_id: str = "", profile: str = "") -> str:
4109
+ """Record a session start so capture can attribute records to it."""
4110
+ conn.execute("""
4111
+ INSERT OR REPLACE INTO sessions (id, parent_id, started_at, project_id, summary, capture_hash, profile)
4112
+ VALUES (?, ?, ?, ?, '', '', ?)
4113
+ """, (session_id, parent_id, now_iso(), project_id, profile))
4114
+ conn.commit()
4115
+ return session_id
4116
+
4117
+
4118
+ def end_session(conn: sqlite3.Connection, session_id: str, summary: str = "", capture_hash: str = ""):
4119
+ """Close a session and store its summary and capture hash."""
4120
+ conn.execute("""
4121
+ UPDATE sessions SET ended_at=?, summary=?, capture_hash=? WHERE id=?
4122
+ """, (now_iso(), summary, capture_hash, session_id))
4123
+ conn.commit()
4124
+
4125
+
4126
+ def list_sessions(conn: sqlite3.Connection, project_id: str = None, limit: int = 100):
4127
+ """Recent sessions, optionally scoped to a project."""
4128
+ sql = "SELECT * FROM sessions"
4129
+ params = []
4130
+ if project_id:
4131
+ sql += " WHERE project_id=?"
4132
+ params.append(project_id)
4133
+ sql += " ORDER BY started_at DESC LIMIT ?"
4134
+ params.append(limit)
4135
+ return [dict(row) for row in conn.execute(sql, params)]
4136
+
4137
+
4138
+ # --- pre-compress checkpoints ------------------------------------------------
4139
+
4140
+ def create_pre_compress_checkpoint(conn: sqlite3.Connection, session_id: str,
4141
+ project_id: str = "", evidence_hash: str = "") -> dict:
4142
+ """Snapshot the evidence a compressed session needs to rebuild context.
4143
+
4144
+ The payload is the full record set for the session and its project, stored
4145
+ as JSON so restore does not depend on the live database.
4146
+ """
4147
+ rows = conn.execute(
4148
+ "SELECT * FROM records WHERE session_id=? OR project_id=? ORDER BY created_at",
4149
+ (session_id, project_id or "\x00none")
4150
+ ).fetchall()
4151
+ records = [dict(r) for r in rows]
4152
+
4153
+ checkpoint_id = sha(f"pre-compress:{session_id}:{now_iso()}")
4154
+ conn.execute("""
4155
+ INSERT INTO pre_compress_checkpoints
4156
+ (id, session_id, project_id, checkpoint_api_version, evidence_hash,
4157
+ record_count, payload, created_at, restored_from)
4158
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, '')
4159
+ """, (checkpoint_id, session_id, project_id or "", PRE_COMPRESS_CHECKPOINT_API_VERSION,
4160
+ evidence_hash, len(records), json.dumps(records, ensure_ascii=False), now_iso()))
4161
+ conn.commit()
4162
+
4163
+ return {
4164
+ "id": checkpoint_id,
4165
+ "session_id": session_id,
4166
+ "project_id": project_id or "",
4167
+ "api_version": PRE_COMPRESS_CHECKPOINT_API_VERSION,
4168
+ "record_count": len(records),
4169
+ "evidence_hash": evidence_hash,
4170
+ }
4171
+
4172
+
4173
+ def restore_from_checkpoint(conn: sqlite3.Connection, checkpoint_id: str) -> dict:
4174
+ """Write a checkpoint's records back into the database. Idempotent."""
4175
+ row = conn.execute("SELECT * FROM pre_compress_checkpoints WHERE id=?",
4176
+ (checkpoint_id,)).fetchone()
4177
+ if not row:
4178
+ raise ValueError(f"checkpoint not found: {checkpoint_id}")
4179
+ row = dict(row)
4180
+
4181
+ records = json.loads(row["payload"]) if row["payload"] else []
4182
+ restored = 0
4183
+ for rec in records:
4184
+ conn.execute("""
4185
+ INSERT OR REPLACE INTO records
4186
+ (id,type,content,evidence,verified,confidence,source,tags,
4187
+ created_at,updated_at,session_id,project_id,parent_id)
4188
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
4189
+ """, (rec["id"], rec["type"], rec["content"], rec.get("evidence", ""),
4190
+ rec.get("verified", 0), rec.get("confidence", 0.5), rec.get("source", ""),
4191
+ rec.get("tags", ""), rec.get("created_at", now_iso()), rec.get("updated_at", now_iso()),
4192
+ rec.get("session_id", ""), rec.get("project_id", ""), rec.get("parent_id", "")))
4193
+ restored += 1
4194
+
4195
+ conn.execute("UPDATE pre_compress_checkpoints SET restored_from=? WHERE id=?",
4196
+ (now_iso(), checkpoint_id))
4197
+ conn.commit()
4198
+
4199
+ return {
4200
+ "id": checkpoint_id,
4201
+ "session_id": row["session_id"],
4202
+ "restored_records": restored,
4203
+ "api_version": row["checkpoint_api_version"],
4204
+ }
4205
+
4206
+
4207
+ # --- stats / health ----------------------------------------------------------
4208
+
4209
+ def stats(conn: sqlite3.Connection) -> dict:
4210
+ """Record counts per type plus verified and total totals."""
4211
+ result = {}
4212
+ for t in sorted(VALID_TYPES):
4213
+ c = conn.execute("SELECT COUNT(*) AS n FROM records WHERE type=?", (t,)).fetchone()["n"]
4214
+ result[t] = c
4215
+ result["total"] = conn.execute("SELECT COUNT(*) AS n FROM records").fetchone()["n"]
4216
+ result["verified"] = conn.execute("SELECT COUNT(*) AS n FROM records WHERE verified=1").fetchone()["n"]
4217
+ result["sessions"] = conn.execute("SELECT COUNT(*) AS n FROM sessions").fetchone()["n"]
4218
+ result["checkpoints"] = conn.execute("SELECT COUNT(*) AS n FROM pre_compress_checkpoints").fetchone()["n"]
4219
+ result["reinforcements"] = conn.execute("SELECT COUNT(*) AS n FROM reinforcement").fetchone()["n"]
4220
+ result["promotions"] = conn.execute("SELECT COUNT(*) AS n FROM promotion_log").fetchone()["n"]
4221
+ result["forgotten"] = conn.execute("SELECT COUNT(*) AS n FROM forgotten_graveyard").fetchone()["n"]
4222
+ return result
4223
+
4224
+
4225
+ def health(conn: sqlite3.Connection) -> dict:
4226
+ """One-call status: record counts, backup count, and integrity result."""
4227
+ ok = quick_check(conn) or integrity_check(conn)
4228
+ backup_paths = glob.glob(os.path.join(BACKUP_DIR, "memory.db.bak.*"))
4229
+ backups = len(backup_paths)
4230
+ # A restore story needs a recent snapshot: none, or newest older than
4231
+ # 7 days, is a warning the operator can act on (run backup or sleep).
4232
+ newest = max((os.path.getmtime(p) for p in backup_paths), default=0)
4233
+ stale = backups == 0 or (time.time() - newest) > 7 * 86400
4234
+ try:
4235
+ total = stats(conn).get("total", 0)
4236
+ except sqlite3.DatabaseError:
4237
+ total = 0
4238
+ return {
4239
+ "status": "ok" if ok else "corrupt",
4240
+ "db_path": db_path_of(conn),
4241
+ "backup_count": backups,
4242
+ "backup_stale": stale,
4243
+ "total_records": total,
4244
+ "decay": decay_report(conn),
4245
+ }
4246
+
4247
+
4248
+ def decay_report(conn: sqlite3.Connection) -> dict:
4249
+ """What is actually rotting, measured rather than guessed.
4250
+
4251
+ Vendor thresholds (70% hit rate, 15% null rate) are useless here: this
4252
+ store sits at 88% never-retrieved, so a vendor number would fire
4253
+ permanently and train the operator to ignore it. These six numbers are
4254
+ computable from the tables that exist, and each has an action:
4255
+
4256
+ never_retrieved share of records with no retrieval row -- the store is
4257
+ larger than what recall actually reaches
4258
+ duplicate_groups exact-content duplicates (same normalized text)
4259
+ stale_anchors records whose anchor file changed (checksum mismatch)
4260
+ superseded records already replaced by a correction
4261
+ low_confidence unverified records at or near the decay floor
4262
+ unbacked_up_days age of the newest snapshot, in days
4263
+ """
4264
+ total = conn.execute("SELECT COUNT(*) FROM records").fetchone()[0] or 1
4265
+ never = conn.execute(
4266
+ "SELECT COUNT(*) FROM records r WHERE NOT EXISTS"
4267
+ " (SELECT 1 FROM reinforcement x WHERE x.record_id = r.id)").fetchone()[0]
4268
+ dupes = conn.execute(
4269
+ "SELECT COUNT(*) FROM (SELECT content FROM records"
4270
+ " GROUP BY content HAVING COUNT(*) > 1)").fetchone()[0]
4271
+ stale = conn.execute(
4272
+ "SELECT COUNT(*) FROM records WHERE stale = 1").fetchone()[0]
4273
+ superseded = conn.execute(
4274
+ "SELECT COUNT(*) FROM records WHERE superseded_by != ''").fetchone()[0]
4275
+ low = conn.execute(
4276
+ "SELECT COUNT(*) FROM records WHERE verified = 0 AND confidence <= ?",
4277
+ (DECAY_FLOOR + FORGET_FLOOR_SLACK,)).fetchone()[0]
4278
+ return {
4279
+ "never_retrieved": never,
4280
+ "never_retrieved_pct": round(100.0 * never / total, 1),
4281
+ "duplicate_groups": dupes,
4282
+ "stale_anchors": stale,
4283
+ "superseded": superseded,
4284
+ "low_confidence": low,
4285
+ "total_records": total,
4286
+ }
4287
+
4288
+
4289
+ # --- profile-scoped context --------------------------------------------------
4290
+
4291
+ def get_profile_context(conn: sqlite3.Connection, key: str, default=None):
4292
+ """JSON-encoded per-profile value. Returns `default` when absent."""
4293
+ profile = get_profile()
4294
+ row = conn.execute(
4295
+ "SELECT value FROM profile_contexts WHERE profile=? AND key=?",
4296
+ (profile, key)
4297
+ ).fetchone()
4298
+ if not row:
4299
+ return default
4300
+ try:
4301
+ return json.loads(row["value"])
4302
+ except (json.JSONDecodeError, TypeError):
4303
+ return row["value"]
4304
+
4305
+
4306
+ def set_profile_context(conn: sqlite3.Connection, key: str, value):
4307
+ """Persist one profile-scoped key/value pair used at session start."""
4308
+ profile = get_profile()
4309
+ conn.execute("""
4310
+ INSERT OR REPLACE INTO profile_contexts (profile, key, value, updated_at)
4311
+ VALUES (?, ?, ?, ?)
4312
+ """, (profile, key, json.dumps(value, ensure_ascii=False), now_iso()))
4313
+ conn.commit()
4314
+
4315
+
4316
+ # --- Markdown Mirror & Sync --------------------------------------------------
4317
+
4318
+ def _format_markdown_record(r: dict) -> str:
4319
+ parts = [f"## {r['id']}"]
4320
+ parts.append(f"- confidence: {r['confidence']}")
4321
+ parts.append(f"- verified: {r['verified']}")
4322
+ if r.get("source"):
4323
+ parts.append(f"- sources: {r['source']}")
4324
+ parts.append("")
4325
+ parts.append(r["content"])
4326
+ if r.get("evidence"):
4327
+ for ev_line in str(r["evidence"]).splitlines():
4328
+ parts.append(f"> {ev_line}")
4329
+ parts.append("")
4330
+ return "\n".join(parts) + "\n"
4331
+
4332
+
4333
+ def _git_run(args: list[str], cwd: Path) -> subprocess.CompletedProcess:
4334
+ try:
4335
+ return subprocess.run(
4336
+ args,
4337
+ cwd=cwd,
4338
+ check=True,
4339
+ capture_output=True,
4340
+ text=True,
4341
+ encoding="utf-8",
4342
+ errors="replace",
4343
+ )
4344
+ except subprocess.CalledProcessError as exc:
4345
+ err = exc.stderr.strip() if exc.stderr else exc.stdout.strip()
4346
+ raise RuntimeError(err) from exc
4347
+
4348
+
4349
+ def export_markdown(conn: sqlite3.Connection, out_dir, types=None) -> dict:
4350
+ """Export memory records to deterministic Markdown files with a manifest."""
4351
+ out_path = Path(out_dir)
4352
+ if not out_path.exists():
4353
+ raise FileNotFoundError(f"Output directory does not exist: {out_dir}")
4354
+ if not out_path.is_dir():
4355
+ raise NotADirectoryError(f"Output path is not a directory: {out_dir}")
4356
+ out_path = out_path.resolve()
4357
+
4358
+ for entry in out_path.iterdir():
4359
+ if entry.is_symlink():
4360
+ try:
4361
+ entry.resolve().relative_to(out_path)
4362
+ except ValueError:
4363
+ raise ValueError(f"Symlink escapes output directory: {entry}")
4364
+
4365
+ if types is not None:
4366
+ target_types = sorted(types)
4367
+ else:
4368
+ cur = conn.execute("SELECT DISTINCT type FROM records WHERE type IS NOT NULL")
4369
+ existing_types = {row[0] for row in cur.fetchall()}
4370
+ target_types = [t for t in sorted(VALID_TYPES) if t in existing_types]
4371
+
4372
+ new_files = {}
4373
+ index_entries = []
4374
+
4375
+ for rtype in target_types:
4376
+ cur = conn.execute(
4377
+ "SELECT id, type, content, confidence, verified, source, evidence "
4378
+ "FROM records WHERE type = ? ORDER BY id ASC",
4379
+ (rtype,),
4380
+ )
4381
+ rows = [dict(r) for r in cur.fetchall()]
4382
+ filename = f"{rtype.lower()}.md"
4383
+ body = f"# {rtype}\n\n" + "".join(_format_markdown_record(r) for r in rows)
4384
+ new_files[filename] = body
4385
+ index_entries.append(f"- [{rtype}]({filename}) - {len(rows)} record")
4386
+
4387
+ index_body = "# Memory Index\n\n"
4388
+ if index_entries:
4389
+ index_body += "\n".join(index_entries) + "\n"
4390
+ new_files["INDEX.md"] = index_body
4391
+
4392
+ for relpath in new_files:
4393
+ target_p = out_path / relpath
4394
+ if target_p.is_symlink():
4395
+ try:
4396
+ target_p.resolve().relative_to(out_path)
4397
+ except ValueError:
4398
+ raise ValueError(f"Symlink escapes output directory: {target_p}")
4399
+ try:
4400
+ target_p.resolve().relative_to(out_path)
4401
+ except ValueError:
4402
+ raise ValueError(f"Target path escapes output directory: {target_p}")
4403
+
4404
+ manifest_path = out_path / ".honcho-mirror.json"
4405
+ old_manifest_files = {}
4406
+ if manifest_path.is_file():
4407
+ try:
4408
+ old_data = json.loads(manifest_path.read_text(encoding="utf-8"))
4409
+ if isinstance(old_data, dict) and isinstance(old_data.get("files"), dict):
4410
+ old_manifest_files = old_data["files"]
4411
+ except Exception:
4412
+ old_manifest_files = {}
4413
+
4414
+ new_manifest_files = {
4415
+ relpath: hashlib.sha256(content.encode("utf-8")).hexdigest()
4416
+ for relpath, content in new_files.items()
4417
+ }
4418
+
4419
+ removed = []
4420
+ stale_relpaths = set(old_manifest_files.keys()) - set(new_manifest_files.keys())
4421
+ for rel in sorted(stale_relpaths):
4422
+ stale_path = out_path / rel
4423
+ try:
4424
+ stale_resolved = stale_path.resolve()
4425
+ stale_resolved.relative_to(out_path)
4426
+ except ValueError:
4427
+ continue
4428
+ if stale_path.is_file() or stale_path.is_symlink():
4429
+ stale_path.unlink()
4430
+ removed.append(rel)
4431
+
4432
+ written = []
4433
+ unchanged = []
4434
+ for relpath in sorted(new_files.keys()):
4435
+ content_bytes = new_files[relpath].encode("utf-8")
4436
+ target = out_path / relpath
4437
+ if target.is_file() and not target.is_symlink():
4438
+ if target.read_bytes() == content_bytes:
4439
+ unchanged.append(relpath)
4440
+ continue
4441
+ target.write_bytes(content_bytes)
4442
+ written.append(relpath)
4443
+
4444
+ new_manifest_data = {
4445
+ "version": 1,
4446
+ "files": dict(sorted(new_manifest_files.items())),
4447
+ }
4448
+ manifest_bytes = (json.dumps(new_manifest_data, indent=2, sort_keys=True) + "\n").encode("utf-8")
4449
+
4450
+ if not written and not removed and manifest_path.is_file():
4451
+ pass
4452
+ else:
4453
+ if not (manifest_path.is_file() and manifest_path.read_bytes() == manifest_bytes):
4454
+ manifest_path.write_bytes(manifest_bytes)
4455
+
4456
+ return {"written": written, "removed": removed, "unchanged": unchanged, "out_dir": str(out_path)}
4457
+
4458
+
4459
+ def sync_mirror(out_dir, message: str = None, init: bool = False) -> dict:
4460
+ """Sync markdown mirror directory to a dedicated git repository without pushing."""
4461
+ out_path = Path(out_dir)
4462
+ if not out_path.exists():
4463
+ raise FileNotFoundError(f"Output directory does not exist: {out_dir}")
4464
+ if not out_path.is_dir():
4465
+ raise NotADirectoryError(f"Output path is not a directory: {out_dir}")
4466
+ out_path = out_path.resolve()
4467
+
4468
+ module_dir = Path(__file__).resolve().parent
4469
+ if out_path == module_dir or module_dir.is_relative_to(out_path):
4470
+ raise ValueError(f"Module directory {module_dir} is inside output directory {out_path}")
4471
+
4472
+ proc_top = subprocess.run(
4473
+ ["git", "rev-parse", "--show-toplevel"],
4474
+ cwd=out_path,
4475
+ capture_output=True,
4476
+ text=True,
4477
+ encoding="utf-8",
4478
+ errors="replace",
4479
+ )
4480
+ if proc_top.returncode == 0:
4481
+ top_level = Path(proc_top.stdout.strip()).resolve()
4482
+ if top_level != out_path:
4483
+ raise ValueError(f"Git toplevel {top_level} differs from {out_path}")
4484
+ else:
4485
+ if not init:
4486
+ raise ValueError(f"Output directory is not a git repository: {out_dir}")
4487
+ _git_run(["git", "init"], cwd=out_path)
4488
+ proc_top = _git_run(["git", "rev-parse", "--show-toplevel"], cwd=out_path)
4489
+ top_level = Path(proc_top.stdout.strip()).resolve()
4490
+ if top_level != out_path:
4491
+ raise ValueError(f"Git toplevel {top_level} differs from {out_path}")
4492
+
4493
+ manifest_file = out_path / ".honcho-mirror.json"
4494
+ if not manifest_file.is_file():
4495
+ raise FileNotFoundError(f"Manifest not found in {out_path}")
4496
+ manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
4497
+ files_to_stage = sorted(manifest.get("files", {}).keys())
4498
+
4499
+ for rel in files_to_stage:
4500
+ target = (out_path / rel).resolve()
4501
+ try:
4502
+ target.relative_to(out_path)
4503
+ except ValueError:
4504
+ raise ValueError(f"Target file escapes output directory: {rel}")
4505
+
4506
+ if files_to_stage:
4507
+ _git_run(["git", "add", "--"] + files_to_stage, cwd=out_path)
4508
+
4509
+ diff_proc = subprocess.run(["git", "diff", "--cached", "--quiet"], cwd=out_path)
4510
+ if diff_proc.returncode == 0:
4511
+ return {"committed": False, "reason": "clean"}
4512
+ if diff_proc.returncode != 1:
4513
+ raise RuntimeError(f"git diff --cached failed with code {diff_proc.returncode}")
4514
+
4515
+ commit_msg = message or "chore(memory): sync markdown mirror"
4516
+ _git_run(["git", "commit", "-m", commit_msg], cwd=out_path)
4517
+ sha_proc = _git_run(["git", "rev-parse", "HEAD"], cwd=out_path)
4518
+ return {"committed": True, "sha": sha_proc.stdout.strip(), "files": files_to_stage}
4519
+
4520
+ def export_skill(conn: sqlite3.Connection, record_id: str, out_dir) -> dict:
4521
+ """Export a PROCEDURAL/WORKFLOW record (or a reflect cluster) as an
4522
+ agentskills.io SKILL.md folder: frontmatter + body + references/ for
4523
+ child episodes. Progressive disclosure: L0 name+description routes,
4524
+ L1 the body, L2 the evidence files. Description capped at 100 chars
4525
+ (hermes lesson: overlong descriptions never route).
4526
+ """
4527
+ r = get_record(conn, record_id)
4528
+ if not r:
4529
+ raise NotFound(f"record {record_id} not found")
4530
+ if r["type"] not in ("PROCEDURAL", "WORKFLOW", "REFLECTIVE", "RULE"):
4531
+ raise ValueError(f"skill export needs PROCEDURAL/WORKFLOW/REFLECTIVE/RULE, got {r['type']}")
4532
+ out_path = Path(out_dir).expanduser().resolve()
4533
+ slug = re.sub(r"[^a-z0-9]+", "-", normalize_content(r["content"])[:40].casefold()).strip("-")
4534
+ skill_dir = out_path / (slug or record_id)
4535
+ skill_dir.mkdir(parents=True, exist_ok=True)
4536
+ first = next((l for l in r["content"].splitlines() if l.strip()), "")
4537
+ desc = first[:100]
4538
+ body = ["---", f"name: {slug or record_id}", f"description: {desc}", "---", "",
4539
+ f"# {first[:80]}", "", r["content"], ""]
4540
+ if r["evidence"]:
4541
+ body += ["## Evidence", "", r["evidence"], ""]
4542
+ children = [dict(c) for c in conn.execute(
4543
+ "SELECT id, content, evidence FROM records WHERE parent_id=? ORDER BY created_at",
4544
+ (record_id,))]
4545
+ refs = []
4546
+ if children:
4547
+ ref_dir = skill_dir / "references"
4548
+ ref_dir.mkdir(exist_ok=True)
4549
+ body += ["## Episodes", ""]
4550
+ for i, ch in enumerate(children):
4551
+ fname = f"episode-{i + 1}.md"
4552
+ (ref_dir / fname).write_text(
4553
+ ch["content"] + ("\n\nEvidence: " + ch["evidence"] if ch["evidence"] else ""),
4554
+ encoding="utf-8")
4555
+ refs.append(f"references/{fname}")
4556
+ body.append(f"- [{fname}](references/{fname})")
4557
+ body.append("")
4558
+ (skill_dir / "SKILL.md").write_text("\n".join(body), encoding="utf-8")
4559
+ return {"dir": str(skill_dir), "name": slug or record_id,
4560
+ "references": refs, "record_id": record_id}
4561
+
4562
+
4563
+ def export_pack(conn: sqlite3.Connection, out_file) -> dict:
4564
+ """Git Sync one-file (engram pattern): a compressed, deterministic JSON
4565
+ pack of all records, committable to a team repo and importable on
4566
+ another machine. Content-addressed ids make the merge deterministic:
4567
+ the same lesson from two machines is the same row. No server needed.
4568
+ """
4569
+ import zlib
4570
+ rows = [dict(r) for r in conn.execute(
4571
+ "SELECT id, type, content, evidence, verified, confidence, source, tags,"
4572
+ " created_at, updated_at, project_id, project_ids, parent_id, event_id,"
4573
+ " importance, cue, decay_tau, valid_from, valid_until, anchor_path,"
4574
+ " anchor_sha FROM records ORDER BY id")]
4575
+ payload = json.dumps({"format": "honcho-pack-1", "records": rows},
4576
+ sort_keys=True, separators=(",", ":")).encode()
4577
+ packed = zlib.compress(payload, 9)
4578
+ out = Path(out_file).expanduser()
4579
+ out.parent.mkdir(parents=True, exist_ok=True)
4580
+ out.write_bytes(packed)
4581
+ return {"file": str(out), "records": len(rows), "bytes": len(packed),
4582
+ "sha256": hashlib.sha256(packed).hexdigest()}
4583
+
4584
+
4585
+ def import_pack(conn: sqlite3.Connection, in_file) -> dict:
4586
+ """Import a pack: upsert by content identity, so re-importing the same
4587
+ pack is a no-op and two machines' packs merge without conflicts on
4588
+ identical lessons. Confidence takes the max, verified ORs: a
4589
+ verification on one machine counts everywhere.
4590
+ """
4591
+ import zlib
4592
+ raw = Path(in_file).expanduser().read_bytes()
4593
+ data = json.loads(zlib.decompress(raw))
4594
+ if data.get("format") != "honcho-pack-1":
4595
+ raise ValueError("not a honcho-pack-1 file")
4596
+ imported, merged = 0, 0
4597
+ for r in data["records"]:
4598
+ existing = get_record(conn, r["id"])
4599
+ if not existing:
4600
+ # Insert with the pack's id, not a re-derived one: upsert_record
4601
+ # hashes raw content, but the pack id was derived from the
4602
+ # normalized form, so re-deriving would fork the identity.
4603
+ conn.execute(
4604
+ "INSERT INTO records (id, type, content, evidence, verified,"
4605
+ " confidence, source, tags, created_at, updated_at, project_id,"
4606
+ " project_ids, parent_id, event_id, importance, cue, decay_tau,"
4607
+ " valid_from, valid_until, anchor_path, anchor_sha)"
4608
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
4609
+ (r["id"], r["type"], r["content"], r.get("evidence", ""),
4610
+ r.get("verified", 0), r.get("confidence", 0.5),
4611
+ r.get("source", ""), r.get("tags", ""),
4612
+ r.get("created_at") or now_iso(), r.get("updated_at") or now_iso(),
4613
+ r.get("project_id", ""), r.get("project_ids", ""),
4614
+ r.get("parent_id", ""), r.get("event_id", ""),
4615
+ r.get("importance", 0.5), r.get("cue", ""),
4616
+ r.get("decay_tau", 0), r.get("valid_from", ""),
4617
+ r.get("valid_until", ""), r.get("anchor_path", ""),
4618
+ r.get("anchor_sha", "")))
4619
+ imported += 1
4620
+ else:
4621
+ conf = max(float(existing["confidence"]), float(r.get("confidence", 0)))
4622
+ verified = max(int(existing["verified"]), int(r.get("verified", 0)))
4623
+ conn.execute("UPDATE records SET confidence=?, verified=? WHERE id=?",
4624
+ (conf, verified, r["id"]))
4625
+ merged += 1
4626
+ conn.commit()
4627
+ return {"imported": imported, "merged": merged, "total": len(data["records"])}
4628
+
4629
+
4630
+
4631
+ if __name__ == "__main__":
4632
+ conn = connect()
4633
+ init_db(conn)
4634
+ print(json.dumps({
4635
+ "stats": stats(conn),
4636
+ "health": health(conn),
4637
+ }, indent=2))
4638
+ conn.close()