The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory/holographic): inline reason/update lambdas, flatten _harvestable_text, share ROLE atoms from holographic.py
Teknium12e291b0f3f6
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.pyindex 9fee7db3f61..736d48a84bf 100644--- a/plugins/memory/holographic/__init__.py+++ b/plugins/memory/holographic/__init__.py@@ -91,8 +91,7 @@ _EXTRACT_CATEGORIES = ((_PREF_PATTERNS, "user_pref"), (_DECISION_PATTERNS, "projdef _load_plugin_config() -> dict:try:- # Canonical loader: honors the managed-scope overlay + ${VAR} expansion.- from hermes_cli.config import load_config_readonly+ from hermes_cli.config import load_config_readonly # canonical: managed-scope overlay + ${VAR} expansionreturn cfg_get(load_config_readonly(), "plugins", "hermes-memory-store", default={}) or {}except Exception:return {}@@ -120,8 +119,7 @@ class HolographicMemoryProvider(MemoryProvider):def __init__(self, config: dict | None = None):self._config = config or _load_plugin_config()- self._store = None- self._retriever = None+ self._store = self._retriever = Noneself._min_trust = float(self._config.get("min_trust_threshold", 0.3))@property@@ -210,8 +208,7 @@ 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: auto_extract is a string enum ("false"/"true"); plain truthiness would treat "false" as on.if is_truthy_value(self._config.get("auto_extract", False)) and self._store and messages:self._auto_extract_facts(messages)@@ -224,8 +221,8 @@ class HolographicMemoryProvider(MemoryProvider):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.+ # Close on the caller's thread: leaving the shared connection (and its write lock) to GC keeps it+ # alive on a long-running gateway. close() is idempotent and refcount-guarded.if self._store is not None:try:self._store.close()@@ -234,27 +231,13 @@ class HolographicMemoryProvider(MemoryProvider):self._store = Noneself._retriever = None- # -- Tool handlers: KeyError from args[...] / Exception -> tool_error in handle_tool_call. ---- # Argument coercion order (and therefore which error surfaces first) mirrors the call order.+ # Tool handlers (self, args) -> str. KeyError from args[...] / Exception -> tool_error in handle_tool_call;+ # argument coercion order (and therefore which error surfaces first) mirrors the underlying call order.def _entity_query(self, method: str, a: dict) -> str:"""'probe' / 'related': single-entity retriever queries."""return _results(getattr(self._retriever, method)(a["entity"], category=a.get("category"), limit=_limit(a)))- def _act_reason(self, a: dict) -> str:- entities = a.get("entities", [])- if not entities:- return tool_error("reason requires 'entities' list")- return _results(self._retriever.reason(entities, category=a.get("category"), limit=_limit(a)))-- def _act_update(self, a: dict) -> str:- updated = self._store.update_fact(- int(a["fact_id"]), content=a.get("content"),- trust_delta=float(a["trust_delta"]) if "trust_delta" in a else None,- tags=a.get("tags"), category=a.get("category"),- )- return json.dumps({"updated": updated})-_TOOL_HANDLERS = {"fact_store": _tool_handler({"add": lambda self, a: json.dumps({"fact_id": self._store.add_fact(@@ -263,9 +246,12 @@ class HolographicMemoryProvider(MemoryProvider):a["query"], category=a.get("category"), min_trust=float(a.get("min_trust", self._min_trust)), limit=_limit(a))),"probe": lambda self, a: self._entity_query("probe", a),"related": lambda self, a: self._entity_query("related", a),- "reason": _act_reason,+ "reason": lambda self, a: _results(self._retriever.reason(a["entities"], category=a.get("category"), limit=_limit(a)))+ if a.get("entities") else tool_error("reason requires 'entities' list"),"contradict": lambda self, a: _results(self._retriever.contradict(category=a.get("category"), limit=_limit(a))),- "update": _act_update,+ "update": lambda self, a: json.dumps({"updated": self._store.update_fact(+ int(a["fact_id"]), content=a.get("content"), trust_delta=float(a["trust_delta"]) if "trust_delta" in a else None,+ tags=a.get("tags"), category=a.get("category"))}),"remove": lambda self, a: json.dumps({"removed": self._store.remove_fact(int(a["fact_id"]))}),"list": lambda self, a: _results(self._store.list_facts(category=a.get("category"), min_trust=float(a.get("min_trust", 0.0)), limit=_limit(a)), key="facts"),@@ -282,15 +268,11 @@ class HolographicMemoryProvider(MemoryProvider):# 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, is_compaction_summary_message- content = msg.get("content", "")+ content, pre = msg.get("content", ""), ""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):- pre = pre[len(_MERGED_PRIOR_CONTEXT_HEADER):]- if pre.strip():- content = pre.strip()- elif is_compaction_summary_message(msg):- return None+ pre = content.split(_MERGED_SUMMARY_DELIMITER, 1)[0].removeprefix(_MERGED_PRIOR_CONTEXT_HEADER).strip()+ if pre:+ content = preelif is_compaction_summary_message(msg):return Nonereturn content if isinstance(content, str) and len(content) >= 10 else Nonediff --git a/plugins/memory/holographic/holographic.py b/plugins/memory/holographic/holographic.pyindex f3736e4363f..17ce86c5373 100644--- a/plugins/memory/holographic/holographic.py+++ b/plugins/memory/holographic/holographic.py@@ -25,6 +25,7 @@ logger = logging.getLogger(__name__)_TWO_PI = 2.0 * math.pi_FLOAT32_BLOB_PREFIX = b"HRR1"_F32, _F64 = 4, 8 # itemsizes of np.float32 / np.float64+ROLE_CONTENT, ROLE_ENTITY = "__hrr_role_content__", "__hrr_role_entity__" # role atoms used by encode_factdef _require_numpy() -> None:@@ -77,7 +78,7 @@ def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarr"""bundle(bind(text, ROLE_CONTENT), bind(entity_i, ROLE_ENTITY)...), sounbind(fact, bind(entity, ROLE_ENTITY)) ≈ content_vector."""_require_numpy()- role_content, role_entity = encode_atom("__hrr_role_content__", dim), encode_atom("__hrr_role_entity__", dim)+ role_content, role_entity = encode_atom(ROLE_CONTENT, dim), encode_atom(ROLE_ENTITY, dim)return bundle(bind(encode_text(content, dim), role_content),*[bind(encode_atom(entity.lower(), dim), role_entity) for entity in entities])@@ -89,8 +90,7 @@ def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:so we write legacy float64 there to keep ``bytes_to_phases`` unambiguous."""_require_numpy()- if dim is None:- dim = int(phases.shape[0])+ dim = int(phases.shape[0]) if dim is None else dimif len(_FLOAT32_BLOB_PREFIX) + dim * _F32 == dim * _F64:return np.asarray(phases, dtype=np.float64).tobytes()return _FLOAT32_BLOB_PREFIX + np.asarray(phases, dtype=np.float32).tobytes()@@ -108,13 +108,10 @@ def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":f32 = lambda payload: np.frombuffer(payload, dtype=np.float32).astype(np.float64) # noqa: E731f64 = lambda payload: np.frombuffer(payload, dtype=np.float64).copy() # noqa: E731if dim is None:- if prefixed:- if (len(data) - plen) % _F32 != 0:- raise ValueError(f"HRR float32 vector blob has invalid payload byte length: {len(data) - plen}")- return f32(data[plen:])- if len(data) % _F64 != 0:- raise ValueError(f"HRR legacy vector blob has invalid byte length: {len(data)}")- return f64(data)+ payload, size, what = (data[plen:], _F32, "float32 vector blob has invalid payload") if prefixed else (data, _F64, "legacy vector blob has invalid")+ if len(payload) % size != 0:+ raise ValueError(f"HRR {what} byte length: {len(payload)}")+ return f32(payload) if prefixed else f64(payload)float32_blob_bytes, float64_bytes = plen + dim * _F32, dim * _F64collides = float32_blob_bytes == float64_bytesif not collides and prefixed and len(data) == float32_blob_bytes:diff --git a/plugins/memory/holographic/retrieval.py b/plugins/memory/holographic/retrieval.pyindex cc1673a194b..c65b28532b9 100644--- a/plugins/memory/holographic/retrieval.py+++ b/plugins/memory/holographic/retrieval.py@@ -20,8 +20,7 @@ _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__"+_ROLE_ENTITY, _ROLE_CONTENT = hrr.ROLE_ENTITY, hrr.ROLE_CONTENT_PUNCT = ".,;:!?\"'()[]{}#@<>"_FTS_OPERATORS = str.maketrans("", "", '"()*^:-+')# Stopwords dropped before FTS5 OR-expansion: short English function words that@@ -202,10 +201,8 @@ class FactRetriever:results = [dict(row) for row in self.store._conn.execute(sql, params).fetchall()]except Exception:return [] # FTS5 MATCH can fail on malformed queries- if not results:- return []- # FTS5 rank is negative (lower = better); normalize |rank| / max to [0, 1]- max_rank = max(max(abs(f["fts_rank_raw"]) for f in results), 1e-6) # avoid div by zero+ # FTS5 rank is negative (lower = better); normalize |rank| / max to [0, 1] (1e-6 floor avoids div by zero)+ max_rank = max([abs(f["fts_rank_raw"]) for f in results] + [1e-6])for fact in results:fact["fts_rank"] = abs(fact.pop("fts_rank_raw")) / max_rankreturn resultsdiff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.pyindex 6b52bfadc4e..b8ecbe30437 100644--- a/plugins/memory/holographic/store.py+++ b/plugins/memory/holographic/store.py@@ -182,9 +182,8 @@ class MemoryStore:assignments = ", ".join(["updated_at = CURRENT_TIMESTAMP"] + [f"{col} = ?" for col in changes])self._write(f"UPDATE facts SET {assignments} WHERE fact_id = ?", [*changes.values(), 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._write("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)self._rebuild_bank(category or self._one("SELECT category FROM facts WHERE fact_id = ?", (fact_id,))["category"])return True