Skip to content

The agent that grows with you

refactor(memory/holographic): store _one/_write SQL helpers, retrieval atom helper, compact docstrings

Tekniumb0f7d0777308
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.py
index 08f799005fb..493efe6ed51 100644
--- a/plugins/memory/holographic/__init__.py
+++ b/plugins/memory/holographic/__init__.py
@@ -1,18 +1,10 @@
-"""hermes-memory-store — holographic memory plugin using MemoryProvider interface.
-
-Registers as a MemoryProvider plugin, giving the agent structured fact storage
+"""hermes-memory-store — holographic memory plugin (MemoryProvider): structured fact storage
with entity resolution, trust scoring, and HRR-based compositional retrieval.
-
Original plugin by dusterbloom (PR #2351), adapted to the MemoryProvider ABC.
-Config in $HERMES_HOME/config.yaml (profile-scoped):
- plugins:
- hermes-memory-store:
- db_path: $HERMES_HOME/memory_store.db # omit to use the default
- auto_extract: false
- default_trust: 0.5
- min_trust_threshold: 0.3
- temporal_decay_half_life: 0
+Config in $HERMES_HOME/config.yaml (profile-scoped) under plugins.hermes-memory-store:
+ db_path ($HERMES_HOME/memory_store.db), auto_extract (false), default_trust (0.5),
+ min_trust_threshold (0.3), temporal_decay_half_life (0), hrr_dim (1024), hrr_weight (0.3).
"""
from __future__ import annotations
@@ -97,14 +89,14 @@ _DECISION_PATTERNS = [
re.compile(r'\bwe\s+(?:decided|agreed|chose)\s+(?:to\s+)?(.+)', re.IGNORECASE),
re.compile(r'\bthe\s+project\s+(?:uses|needs|requires)\s+(.+)', re.IGNORECASE),
]
+_EXTRACT_CATEGORIES = ((_PREF_PATTERNS, "user_pref"), (_DECISION_PATTERNS, "project"))
def _load_plugin_config() -> dict:
try:
# Canonical loader: honors the managed-scope overlay + ${VAR} expansion.
from hermes_cli.config import load_config_readonly
- all_config = load_config_readonly()
- return cfg_get(all_config, "plugins", "hermes-memory-store", default={}) or {}
+ return cfg_get(load_config_readonly(), "plugins", "hermes-memory-store", default={}) or {}
except Exception:
return {}
@@ -134,8 +126,7 @@ class HolographicMemoryProvider(MemoryProvider):
config_path = Path(hermes_home) / "config.yaml"
try:
import yaml
- # Raw read for the write-back round-trip: merged defaults must not
- # be persisted into the user's file.
+ # Raw read for the write-back round-trip: merged defaults must not be persisted.
from hermes_cli.config import read_user_config_raw
existing = read_user_config_raw(config_path)
existing.setdefault("plugins", {})["hermes-memory-store"] = values
@@ -162,7 +153,6 @@ class HolographicMemoryProvider(MemoryProvider):
if isinstance(db_path, str):
db_path = db_path.replace("$HERMES_HOME", _hermes_home).replace("${HERMES_HOME}", _hermes_home)
hrr_dim = int(self._config.get("hrr_dim", 1024))
-
self._store = MemoryStore(
db_path=db_path, default_trust=float(self._config.get("default_trust", 0.5)), hrr_dim=hrr_dim,
)
@@ -209,8 +199,7 @@ class HolographicMemoryProvider(MemoryProvider):
return ""
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
- # Facts are stored explicitly via tools; on_session_end handles auto-extraction if configured.
- pass
+ pass # facts are stored explicitly via tools; on_session_end handles auto-extraction
def get_tool_schemas(self) -> List[Dict[str, Any]]:
return [FACT_STORE_SCHEMA, FACT_FEEDBACK_SCHEMA]
@@ -227,8 +216,8 @@ class HolographicMemoryProvider(MemoryProvider):
return tool_error(str(exc))
def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
- # is_truthy_value: the config schema declares auto_extract as a string
- # enum ("false"/"true"); plain truthiness would treat "false" as enabled.
+ # is_truthy_value: the config schema declares auto_extract as a string enum
+ # ("false"/"true"); plain truthiness would treat "false" as enabled.
if is_truthy_value(self._config.get("auto_extract", False)) and self._store and messages:
self._auto_extract_facts(messages)
@@ -236,15 +225,13 @@ class HolographicMemoryProvider(MemoryProvider):
"""Mirror built-in memory writes as facts."""
if action == "add" and self._store and content:
try:
- category = "user_pref" if target == "user" else "general"
- self._store.add_fact(content, category=category)
+ self._store.add_fact(content, category="user_pref" if target == "user" else "general")
except Exception as e:
logger.debug("Holographic memory_write mirror failed: %s", e)
def shutdown(self) -> None:
- # Release the shared SQLite connection on the caller's thread: leaving
- # it to GC keeps the connection (and its write lock) alive on a
- # long-running gateway. close() is idempotent and refcount-guarded.
+ # Release the shared SQLite connection on the caller's thread: leaving it to GC keeps
+ # the connection (and its write lock) alive on a long-running gateway. close() is idempotent.
if self._store is not None:
try:
self._store.close()
@@ -320,8 +307,7 @@ class HolographicMemoryProvider(MemoryProvider):
# -- Auto-extraction (on_session_end) ------------------------------------
def _auto_extract_facts(self, messages: list) -> None:
- # Local import: the compressor module is heavier than this plugin and
- # only needed when auto_extract is on.
+ # Local import: the compressor module is heavier than this plugin and only needed here.
from agent.context_compressor import (
_MERGED_PRIOR_CONTEXT_HEADER,
_MERGED_SUMMARY_DELIMITER,
@@ -333,12 +319,10 @@ class HolographicMemoryProvider(MemoryProvider):
if msg.get("role") != "user":
continue
content = msg.get("content", "")
- # Compaction handoff summaries arrive as role="user" and reliably
- # match the decision patterns; skip them so the compactor's own
- # output is never stored as a durable fact. A merge-into-tail row
- # holds genuine prior user text BEFORE _MERGED_SUMMARY_DELIMITER
- # (prefixed with the header) and the summary AFTER it — harvest
- # only the pre-delimiter segment.
+ # Compaction handoff summaries arrive as role="user" and reliably match the
+ # decision patterns; never store the compactor's own output as a durable fact.
+ # A merge-into-tail row holds genuine prior user text BEFORE _MERGED_SUMMARY_DELIMITER
+ # (prefixed with the header) and the summary AFTER it — harvest only the pre-delimiter segment.
if isinstance(content, str) and _MERGED_SUMMARY_DELIMITER in content:
pre = content.split(_MERGED_SUMMARY_DELIMITER, 1)[0]
if pre.startswith(_MERGED_PRIOR_CONTEXT_HEADER):
@@ -352,7 +336,7 @@ class HolographicMemoryProvider(MemoryProvider):
if not isinstance(content, str) or len(content) < 10:
continue
- for patterns, category in ((_PREF_PATTERNS, "user_pref"), (_DECISION_PATTERNS, "project")):
+ for patterns, category in _EXTRACT_CATEGORIES:
if any(p.search(content) for p in patterns):
try:
self._store.add_fact(content[:400], category=category)
diff --git a/plugins/memory/holographic/retrieval.py b/plugins/memory/holographic/retrieval.py
index a8a3fa86f12..9f12a82e097 100644
--- a/plugins/memory/holographic/retrieval.py
+++ b/plugins/memory/holographic/retrieval.py
@@ -1,8 +1,5 @@
-"""Hybrid keyword/BM25 retrieval for the memory store.
-
-Ported from KIK memory_agent.py — combines FTS5 full-text search with
-Jaccard similarity reranking and trust-weighted scoring.
-"""
+"""Hybrid keyword/BM25 retrieval for the memory store: FTS5 candidates reranked with
+Jaccard similarity and HRR vector similarity, trust-weighted (ported from KIK memory_agent.py)."""
from __future__ import annotations
@@ -23,6 +20,9 @@ _FACT_COLUMNS = (
"fact_id, content, category, tags, trust_score, "
"retrieval_count, helpful_count, created_at, updated_at"
)
+_ROLE_ENTITY = "__hrr_role_entity__"
+_ROLE_CONTENT = "__hrr_role_content__"
+_PUNCT = ".,;:!?\"'()[]{}#@<>"
class FactRetriever:
@@ -38,12 +38,13 @@ class FactRetriever:
self.store = store
self.half_life = temporal_decay_half_life
self.hrr_dim = hrr_dim
-
- # Auto-redistribute weights if numpy unavailable
- if hrr_weight > 0 and not hrr._HAS_NUMPY:
+ if hrr_weight > 0 and not hrr._HAS_NUMPY: # redistribute weights without numpy
fts_weight, jaccard_weight, hrr_weight = 0.6, 0.4, 0.0
self.fts_weight, self.jaccard_weight, self.hrr_weight = fts_weight, jaccard_weight, hrr_weight
+ def _atom(self, word: str):
+ return hrr.encode_atom(word, self.hrr_dim)
+
def search(self, query: str, category: str | None = None, min_trust: float = 0.3, limit: int = 10) -> list[dict]:
"""Hybrid search: FTS5 candidates (limit*3) → Jaccard + HRR rerank → trust
weighting → optional temporal decay 0.5^(age_days / half_life).
@@ -55,9 +56,8 @@ class FactRetriever:
return []
query_tokens = self._tokenize(query)
- # Query vector is loop-invariant; encode lazily on the first candidate
- # that carries an HRR vector so migrated stores whose hrr_vector was
- # never backfilled don't pay for an encode nothing uses.
+ # Query vector is loop-invariant; encode lazily on the first candidate that carries
+ # an HRR vector so stores whose hrr_vector was never backfilled don't pay for it.
query_vec = None
for fact in candidates:
all_tokens = self._tokenize(fact["content"]) | self._tokenize(fact.get("tags", ""))
@@ -82,16 +82,14 @@ class FactRetriever:
return results
def probe(self, entity: str, category: str | None = None, limit: int = 10) -> list[dict]:
- """Compositional entity query: unbind bind(entity, ROLE_ENTITY) from the
- category bank (or each fact vector) to find facts where the entity plays
- a structural role. Not keyword search. Falls back to FTS5 without numpy.
- """
+ """Compositional entity query: unbind bind(entity, ROLE_ENTITY) from the category bank
+ (or each fact vector) to find facts where the entity plays a structural role.
+ Not keyword search. Falls back to FTS5 without numpy."""
if not hrr._HAS_NUMPY:
return self.search(entity, category=category, limit=limit)
- role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
- entity_vec = hrr.encode_atom(entity.lower(), self.hrr_dim)
- probe_key = hrr.bind(entity_vec, role_entity)
+ role_entity = self._atom(_ROLE_ENTITY)
+ probe_key = hrr.bind(self._atom(entity.lower()), role_entity)
# Try the category-specific bank first, then individual fact vectors
if category:
@@ -108,75 +106,56 @@ class FactRetriever:
rows = self._vector_rows(category)
if not rows:
return self.search(entity, category=category, limit=limit)
-
- # role_content is loop-invariant — encode once, not per row.
- role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
+ role_content = self._atom(_ROLE_CONTENT) # loop-invariant — encode once
def _sim(fact: dict, fact_vec) -> float:
# Does unbinding the probe key leave the fact's content signal?
residual = hrr.unbind(fact_vec, probe_key)
- content_vec = hrr.bind(hrr.encode_text(fact["content"], self.hrr_dim), role_content)
- return hrr.similarity(residual, content_vec)
+ return hrr.similarity(residual, hrr.bind(hrr.encode_text(fact["content"], self.hrr_dim), role_content))
return self._rank_by_vector(rows, _sim, limit)
def related(self, entity: str, category: str | None = None, limit: int = 10) -> list[dict]:
- """Facts structurally connected to an entity (shared context), not just
- facts *about* it as in probe. Falls back to FTS5 without numpy.
- """
+ """Facts structurally connected to an entity (shared context), not just facts
+ *about* it as in probe. Falls back to FTS5 without numpy."""
if not hrr._HAS_NUMPY:
return self.search(entity, category=category, limit=limit)
- # Bare atom, not role-bound — we want ANY structural match
- entity_vec = hrr.encode_atom(entity.lower(), self.hrr_dim)
-
+ entity_vec = self._atom(entity.lower()) # bare atom, not role-bound: ANY structural match
rows = self._vector_rows(category)
if not rows:
return self.search(entity, category=category, limit=limit)
-
- # Both role atoms are loop-invariant — encode once, not per row.
- role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
- role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
+ role_entity, role_content = self._atom(_ROLE_ENTITY), self._atom(_ROLE_CONTENT) # encode once
def _sim(fact: dict, fact_vec) -> float:
- # A residual similar to ANY role vector means the entity plays a
- # structural role in the fact; take the max over both roles.
+ # A residual similar to ANY role vector means the entity plays a structural role.
residual = hrr.unbind(fact_vec, entity_vec)
return max(hrr.similarity(residual, role_entity), hrr.similarity(residual, role_content))
return self._rank_by_vector(rows, _sim, limit)
def reason(self, entities: list[str], category: str | None = None, limit: int = 10) -> list[dict]:
- """Multi-entity compositional query (vector-space JOIN): facts where ALL
- entities play structural roles. Falls back to FTS5 without numpy.
- """
+ """Multi-entity compositional query (vector-space JOIN): facts where ALL entities
+ play structural roles. Falls back to FTS5 without numpy."""
if not hrr._HAS_NUMPY or not entities:
return self.search(" ".join(entities), category=category, limit=limit)
- role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
- probe_keys = [
- hrr.bind(hrr.encode_atom(entity.lower(), self.hrr_dim), role_entity)
- for entity in entities
- ]
-
+ role_entity = self._atom(_ROLE_ENTITY)
+ probe_keys = [hrr.bind(self._atom(entity.lower()), role_entity) for entity in entities]
rows = self._vector_rows(category)
if not rows:
return self.search(" ".join(entities), category=category, limit=limit)
-
- role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
+ role_content = self._atom(_ROLE_CONTENT)
def _sim(fact: dict, fact_vec) -> float:
# AND semantics via min: high only if EVERY entity is structurally present.
- return min(
- hrr.similarity(hrr.unbind(fact_vec, key), role_content) for key in probe_keys
- )
+ return min(hrr.similarity(hrr.unbind(fact_vec, key), role_content) for key in probe_keys)
return self._rank_by_vector(rows, _sim, limit)
def contradict(self, category: str | None = None, threshold: float = 0.3, limit: int = 10) -> list[dict]:
- """Memory hygiene: pairs of facts that share entities (same subject) but
- have low content-vector similarity (different claims). Empty without numpy.
- """
+ """Memory hygiene: pairs of facts that share entities (same subject) but have low
+ content-vector similarity (different claims). Empty without numpy."""
if not hrr._HAS_NUMPY:
return []
@@ -186,8 +165,7 @@ class FactRetriever:
)
if len(rows) < 2:
return []
- # O(n²) guard: ~125K comparisons at 500 facts is acceptable; above that
- # only compare the most recently updated facts.
+ # O(n²) guard: above 500 facts only compare the most recently updated ones.
if len(rows) > 500:
rows = sorted(rows, key=lambda r: r["updated_at"] or r["created_at"], reverse=True)[:500]
@@ -281,7 +259,7 @@ class FactRetriever:
"""Lowercase whitespace tokens with surrounding punctuation stripped (no stemming)."""
if not text:
return set()
- return {c for c in (w.strip(".,;:!?\"'()[]{}#@<>") for w in text.lower().split()) if c}
+ return {c for c in (w.strip(_PUNCT) for w in text.lower().split()) if c}
# Stopwords dropped before FTS5 OR-expansion: short English function words
# that carry no retrieval signal and force false-negative AND matches.
@@ -300,17 +278,16 @@ class FactRetriever:
def _sanitize_fts_query(cls, query: str) -> str:
"""Natural-language query -> FTS5-safe OR expression of quoted tokens.
- FTS5 AND-joins a multi-word MATCH by default, which tanks recall on prose.
- Drops stopwords and <2-char tokens, strips FTS5 operator chars, and
- phrase-quotes each survivor. If nothing survives, returns the raw query
- (caller gets zero results rather than a SQL error).
+ FTS5 AND-joins a multi-word MATCH by default, which tanks recall on prose. Drops
+ stopwords and <2-char tokens, strips FTS5 operator chars, and phrase-quotes each
+ survivor. If nothing survives, returns the raw query (zero results, not a SQL error).
"""
if not query:
return ""
strip_special = str.maketrans("", "", '"()*^:-+')
tokens = [
f'"{cleaned}"'
- for cleaned in (raw.strip(".,;:!?\"'()[]{}#@<>").translate(strip_special) for raw in query.lower().split())
+ for cleaned in (raw.strip(_PUNCT).translate(strip_special) for raw in query.lower().split())
if len(cleaned) >= 2 and cleaned not in cls._FTS_STOPWORDS
]
return " OR ".join(tokens) if tokens else query
diff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.py
index 6e91c0791c6..d7cd422af2a 100644
--- a/plugins/memory/holographic/store.py
+++ b/plugins/memory/holographic/store.py
@@ -73,7 +73,6 @@ CREATE TABLE IF NOT EXISTS memory_banks (
);
"""
-# Trust adjustment constants
_HELPFUL_DELTA = 0.05
_UNHELPFUL_DELTA = -0.10
@@ -93,14 +92,15 @@ def _clamp_trust(value: float) -> float:
class MemoryStore:
- """SQLite-backed fact store with entity resolution and trust scoring."""
-
- # Process-wide shared connection registry. SQLite allows one writer at a
- # time, and several providers coexist per process (main agent + every
- # delegate_task subagent). All instances for the same database share ONE
- # connection and ONE re-entrant lock, so writes are fully serialized and
- # "database is locked" contention is impossible. Refcounted: closing one
- # instance never tears the connection out from under a live sibling.
+ """SQLite-backed fact store with entity resolution and trust scoring.
+
+ Process-wide shared connection registry: SQLite allows one writer at a time and
+ several providers coexist per process (main agent + every delegate_task subagent),
+ so all instances for the same database share ONE connection and ONE re-entrant
+ lock — writes are fully serialized and "database is locked" is impossible.
+ Refcounted: closing one instance never tears the connection out from under a sibling.
+ """
+
_shared: dict = {}
_shared_guard = threading.Lock()
@@ -114,8 +114,7 @@ class MemoryStore:
self.hrr_dim = hrr_dim
self._hrr_available = hrr._HAS_NUMPY
- # resolve() so symlinked/relative paths to the same file share ONE
- # connection instead of reintroducing multi-writer contention.
+ # resolve() so symlinked/relative paths to the same file share ONE connection.
try:
self._key = str(self.db_path.resolve())
except OSError:
@@ -123,26 +122,22 @@ class MemoryStore:
with MemoryStore._shared_guard:
entry = MemoryStore._shared.get(self._key)
if entry is None:
- # Autocommit: a write that raises mid-method can never leave a
- # dangling transaction (and its write lock) open. The explicit
- # commit() calls below are harmless no-ops.
+ # Autocommit: a write that raises mid-method can never leave a dangling
+ # transaction (and its write lock) open; explicit commit() calls are no-ops.
conn = sqlite3.connect(self._key, check_same_thread=False, timeout=10.0, isolation_level=None)
conn.row_factory = sqlite3.Row
- entry = MemoryStore._shared[self._key] = {
- "conn": conn, "lock": threading.RLock(), "refs": 0, "ready": False,
- }
+ entry = MemoryStore._shared[self._key] = {"conn": conn, "lock": threading.RLock(), "refs": 0, "ready": False}
entry["refs"] += 1
self._entry, self._conn, self._lock = entry, entry["conn"], entry["lock"]
- # Initialise the schema once per shared connection.
- with self._lock:
+ with self._lock: # schema initialised once per shared connection
if not self._entry["ready"]:
self._init_db()
self._entry["ready"] = True
def _init_db(self) -> None:
- """Create tables/indexes/triggers, enable WAL (via the shared fallback helper so
- NFS/SMB/FUSE HERMES_HOME degrades gracefully), and add hrr_vector to pre-HRR databases."""
+ """Create schema, enable WAL via the shared fallback helper (NFS/SMB/FUSE HERMES_HOME
+ degrades gracefully), and add hrr_vector to pre-HRR databases."""
from hermes_state import apply_wal_with_fallback
apply_wal_with_fallback(self._conn, db_label="memory_store.db (holographic)")
self._conn.executescript(_SCHEMA)
@@ -151,28 +146,32 @@ class MemoryStore:
self._conn.execute("ALTER TABLE facts ADD COLUMN hrr_vector BLOB")
self._conn.commit()
- def add_fact(self, content: str, category: str = "general", tags: str = "") -> int:
- """Insert a fact and return its fact_id.
+ # -- SQL helpers ----------------------------------------------------------
- Deduplicates by content (UNIQUE constraint): on duplicate, returns the
- existing fact_id without modifying the row. Links extracted entities.
- """
+ def _one(self, sql: str, params=()):
+ return self._conn.execute(sql, params).fetchone()
+
+ def _write(self, sql: str, params=()) -> sqlite3.Cursor:
+ cur = self._conn.execute(sql, params)
+ self._conn.commit()
+ return cur
+
+ # -- Public API -----------------------------------------------------------
+
+ def add_fact(self, content: str, category: str = "general", tags: str = "") -> int:
+ """Insert a fact and return its fact_id; on duplicate content (UNIQUE) return the
+ existing fact_id untouched. Links extracted entities and rebuilds the category bank."""
with self._lock:
content = content.strip()
if not content:
raise ValueError("content must not be empty")
-
try:
- cur = self._conn.execute(
+ fact_id: int = self._write(
"INSERT INTO facts (content, category, tags, trust_score) VALUES (?, ?, ?, ?)",
(content, category, tags, self.default_trust),
- )
- self._conn.commit()
- fact_id: int = cur.lastrowid # type: ignore[assignment]
+ ).lastrowid # type: ignore[assignment]
except sqlite3.IntegrityError:
- row = self._conn.execute("SELECT fact_id FROM facts WHERE content = ?", (content,)).fetchone()
- return int(row["fact_id"])
-
+ return int(self._one("SELECT fact_id FROM facts WHERE content = ?", (content,))["fact_id"])
self._link_entities(fact_id, content)
self._compute_hrr_vector(fact_id, content)
self._rebuild_bank(category)
@@ -188,12 +187,9 @@ class MemoryStore:
) -> bool:
"""Partially update a fact (trust clamped to [0, 1]). Returns True if the row existed."""
with self._lock:
- row = self._conn.execute(
- "SELECT fact_id, trust_score FROM facts WHERE fact_id = ?", (fact_id,)
- ).fetchone()
+ row = self._one("SELECT fact_id, trust_score FROM facts WHERE fact_id = ?", (fact_id,))
if row is None:
return False
-
changes = [(col, val) for col, val in (
("content", content.strip() if content is not None else None),
("tags", tags),
@@ -201,34 +197,23 @@ class MemoryStore:
("trust_score", _clamp_trust(row["trust_score"] + trust_delta) if trust_delta is not None else None),
) if val is not None]
assignments = ", ".join(["updated_at = CURRENT_TIMESTAMP"] + [f"{col} = ?" for col, _ in changes])
- self._conn.execute(f"UPDATE facts SET {assignments} WHERE fact_id = ?", [val for _, val in changes] + [fact_id])
- self._conn.commit()
-
- if content is not None:
- # Content changed: re-extract entities and recompute the HRR vector.
+ self._write(f"UPDATE facts SET {assignments} WHERE fact_id = ?", [val for _, val in changes] + [fact_id])
+ if content is not None: # re-extract entities and recompute the HRR vector
self._conn.execute("DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,))
self._link_entities(fact_id, content)
self._conn.commit()
self._compute_hrr_vector(fact_id, content)
- cat = category or self._conn.execute(
- "SELECT category FROM facts WHERE fact_id = ?", (fact_id,)
- ).fetchone()["category"]
- self._rebuild_bank(cat)
-
+ self._rebuild_bank(category or self._one("SELECT category FROM facts WHERE fact_id = ?", (fact_id,))["category"])
return True
def remove_fact(self, fact_id: int) -> bool:
"""Delete a fact and its entity links. Returns True if the row existed."""
with self._lock:
- row = self._conn.execute(
- "SELECT fact_id, category FROM facts WHERE fact_id = ?", (fact_id,)
- ).fetchone()
+ row = self._one("SELECT fact_id, category FROM facts WHERE fact_id = ?", (fact_id,))
if row is None:
return False
-
self._conn.execute("DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,))
- self._conn.execute("DELETE FROM facts WHERE fact_id = ?", (fact_id,))
- self._conn.commit()
+ self._write("DELETE FROM facts WHERE fact_id = ?", (fact_id,))
self._rebuild_bank(row["category"])
return True
@@ -250,22 +235,17 @@ class MemoryStore:
Returns {fact_id, old_trust, new_trust, helpful_count}. Raises KeyError if fact_id is unknown.
"""
with self._lock:
- row = self._conn.execute(
- "SELECT fact_id, trust_score, helpful_count FROM facts WHERE fact_id = ?",
- (fact_id,),
- ).fetchone()
+ row = self._one("SELECT fact_id, trust_score, helpful_count FROM facts WHERE fact_id = ?", (fact_id,))
if row is None:
raise KeyError(f"fact_id {fact_id} not found")
-
old_trust: float = row["trust_score"]
new_trust = _clamp_trust(old_trust + (_HELPFUL_DELTA if helpful else _UNHELPFUL_DELTA))
helpful_increment = 1 if helpful else 0
- self._conn.execute(
+ self._write(
"UPDATE facts SET trust_score = ?, helpful_count = helpful_count + ?, "
"updated_at = CURRENT_TIMESTAMP WHERE fact_id = ?",
(new_trust, helpful_increment, fact_id),
)
- self._conn.commit()
return {"fact_id": fact_id, "old_trust": old_trust, "new_trust": new_trust,
"helpful_count": row["helpful_count"] + helpful_increment}
@@ -276,75 +256,59 @@ class MemoryStore:
raw = [m.group(1) for pattern in _RE_SINGLE_ENTITY for m in pattern.finditer(text)]
for m in _RE_AKA.finditer(text):
raw += [m.group(1), m.group(2)]
- seen: set[str] = set()
- candidates: list[str] = []
+ uniq: dict[str, str] = {} # lower-cased key -> first-seen spelling, insertion-ordered
for name in (n.strip() for n in raw):
- if name and name.lower() not in seen:
- seen.add(name.lower())
- candidates.append(name)
- return candidates
+ if name:
+ uniq.setdefault(name.lower(), name)
+ return list(uniq.values())
def _link_entities(self, fact_id: int, content: str) -> None:
"""Extract entities from content, resolve/create them, and link each to the fact."""
for name in self._extract_entities(content):
- entity_id = self._resolve_entity(name)
- self._conn.execute(
+ self._write(
"INSERT OR IGNORE INTO fact_entities (fact_id, entity_id) VALUES (?, ?)",
- (fact_id, entity_id),
+ (fact_id, self._resolve_entity(name)),
)
- self._conn.commit()
def _resolve_entity(self, name: str) -> int:
"""Return the entity_id for a case-insensitive name or alias match, creating the entity if absent."""
- row = self._conn.execute("SELECT entity_id FROM entities WHERE name LIKE ?", (name,)).fetchone()
+ row = self._one("SELECT entity_id FROM entities WHERE name LIKE ?", (name,))
if row is not None:
return int(row["entity_id"])
-
# Aliases are comma-separated; wrap both sides in commas for whole-alias matching.
- alias_row = self._conn.execute(
- "SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'", (name,)
- ).fetchone()
+ alias_row = self._one("SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'", (name,))
if alias_row is not None:
return int(alias_row["entity_id"])
-
- cur = self._conn.execute("INSERT INTO entities (name) VALUES (?)", (name,))
- self._conn.commit()
- return int(cur.lastrowid) # type: ignore[return-value]
+ return int(self._write("INSERT INTO entities (name) VALUES (?)", (name,)).lastrowid) # type: ignore[arg-type]
def _compute_hrr_vector(self, fact_id: int, content: str) -> None:
"""Compute and store the HRR vector for a fact (linked entities as roles). No-op without numpy."""
if not self._hrr_available:
return
-
rows = self._conn.execute(_ENTITY_NAMES_SQL, (fact_id,)).fetchall()
vector = hrr.encode_fact(content, [row["name"] for row in rows], self.hrr_dim)
- self._conn.execute("UPDATE facts SET hrr_vector = ? WHERE fact_id = ?", (hrr.phases_to_bytes(vector), fact_id))
- self._conn.commit()
+ self._write("UPDATE facts SET hrr_vector = ? WHERE fact_id = ?", (hrr.phases_to_bytes(vector), fact_id))
def _rebuild_bank(self, category: str) -> None:
"""Full rebuild of a category's memory bank from all its fact vectors."""
if not self._hrr_available:
return
-
bank_name = f"cat:{category}"
rows = self._conn.execute(
"SELECT hrr_vector FROM facts WHERE category = ? AND hrr_vector IS NOT NULL", (category,),
).fetchall()
if not rows:
- self._conn.execute("DELETE FROM memory_banks WHERE bank_name = ?", (bank_name,))
- self._conn.commit()
+ self._write("DELETE FROM memory_banks WHERE bank_name = ?", (bank_name,))
return
-
bank_vector = hrr.bundle(*[hrr.bytes_to_phases(row["hrr_vector"], dim=self.hrr_dim) for row in rows])
hrr.snr_estimate(self.hrr_dim, len(rows)) # warns when near capacity
- self._conn.execute(
+ self._write(
"INSERT INTO memory_banks (bank_name, vector, dim, fact_count, updated_at) "
"VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) ON CONFLICT(bank_name) DO UPDATE SET "
"vector = excluded.vector, dim = excluded.dim, fact_count = excluded.fact_count, "
"updated_at = excluded.updated_at",
(bank_name, hrr.phases_to_bytes(bank_vector), self.hrr_dim, len(rows)),
)
- self._conn.commit()
# -- Lifecycle ------------------------------------------------------------
@@ -352,10 +316,10 @@ class MemoryStore:
def release_all_under(cls, directory: "str | Path") -> int:
"""Force-close every shared connection whose database lives under ``directory``.
- close() is refcount-driven, so a live holder (e.g. an agent's provider) keeps
- a profile's SQLite handle open; on Windows that makes rmtree of the profile
- fail while any handle is open. The directory is going away, so later use by a
- stale holder is expected to fail. Returns how many connections were closed.
+ close() is refcount-driven, so a live holder (e.g. an agent's provider) keeps a
+ profile's SQLite handle open, which on Windows makes rmtree of the profile fail.
+ The directory is going away, so later use by a stale holder is expected to fail.
+ Returns how many connections were closed.
"""
root = os.path.normcase(str(Path(directory).expanduser().resolve())) + os.sep
with cls._shared_guard:
@@ -380,9 +344,8 @@ class MemoryStore:
try:
entry["conn"].close()
finally:
- # Pop only OUR entry: after release_all_under() a same-path
- # store may have registered a FRESH entry under this key,
- # and a stale holder's late close() must not evict it.
+ # Pop only OUR entry: after release_all_under() a same-path store may have
+ # registered a FRESH entry under this key; a stale late close() must not evict it.
if MemoryStore._shared.get(self._key) is entry:
MemoryStore._shared.pop(self._key, None)
self._entry = None