The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory/holographic): _tool_handler dispatch factory, retrieval _shift/_phases helpers, module-level FTS constants, drop redundant sync_turn no-op
Teknium002ace8602e7
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.pyindex 2a65d1105c3..927c6cc1a5e 100644--- a/plugins/memory/holographic/__init__.py+++ b/plugins/memory/holographic/__init__.py@@ -109,6 +109,15 @@ def _limit(args: dict) -> int:return int(args.get("limit", 10))+def _tool_handler(actions: dict):+ """Return a bound-style handler dispatching on args["action"] over ``actions`` (unknown -> tool_error)."""+ def handle(self, args: dict) -> str:+ action = args["action"]+ handler = actions.get(action)+ return handler(self, args) if handler is not None else tool_error(f"Unknown action: {action}")+ return handle++class HolographicMemoryProvider(MemoryProvider):"""Holographic memory with structured facts, entity resolution, and HRR retrieval."""@@ -153,18 +162,13 @@ class HolographicMemoryProvider(MemoryProvider):from hermes_constants import get_hermes_home_hermes_home = str(get_hermes_home())db_path = self._config.get("db_path", _hermes_home + "/memory_store.db")- # Expand $HERMES_HOME so configured paths resolve to the active profile's directory.- if isinstance(db_path, str):+ if isinstance(db_path, str): # expand $HERMES_HOME so paths resolve to the active profiledb_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,- )+ self._store = MemoryStore(db_path=db_path, default_trust=float(self._config.get("default_trust", 0.5)), hrr_dim=hrr_dim)self._retriever = FactRetriever(- store=self._store,- temporal_decay_half_life=int(self._config.get("temporal_decay_half_life", 0)),- hrr_weight=float(self._config.get("hrr_weight", 0.3)),- hrr_dim=hrr_dim,+ store=self._store, temporal_decay_half_life=int(self._config.get("temporal_decay_half_life", 0)),+ hrr_weight=float(self._config.get("hrr_weight", 0.3)), hrr_dim=hrr_dim,)self._session_id = session_id@@ -189,17 +193,12 @@ class HolographicMemoryProvider(MemoryProvider):return ""try:results = self._retriever.search(query, min_trust=self._min_trust, limit=5)- if not results:- return ""lines = [f"- [{r.get('trust_score', r.get('trust', 0)):.1f}] {r.get('content', '')}" for r in results]- return "## Holographic Memory\n" + "\n".join(lines)+ return "## Holographic Memory\n" + "\n".join(lines) if results else ""except Exception as e:logger.debug("Holographic prefetch failed: %s", e)return ""- def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:- 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]@@ -239,50 +238,42 @@ class HolographicMemoryProvider(MemoryProvider):self._store = Noneself._retriever = None- # Tool handlers. KeyError from args[...] / Exception -> tool_error in handle_tool_call.+ # -- 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.- def _handle_fact_store(self, args: dict) -> str:- action = args["action"]- handler = self._FACT_STORE_ACTIONS.get(action)- if handler is None:- return tool_error(f"Unknown action: {action}")- return handler(self, args)-- def _entity_query(self, method: str, args: dict) -> str:+ def _entity_query(self, method: str, a: dict) -> str:"""'probe' / 'related': single-entity retriever queries."""- return _results(getattr(self._retriever, method)(args["entity"], category=args.get("category"), limit=_limit(args)))+ return _results(getattr(self._retriever, method)(a["entity"], category=a.get("category"), limit=_limit(a)))- def _act_reason(self, args: dict) -> str:- entities = args.get("entities", [])+ 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=args.get("category"), limit=_limit(args)))+ return _results(self._retriever.reason(entities, category=a.get("category"), limit=_limit(a)))- def _act_update(self, args: dict) -> str:+ def _act_update(self, a: dict) -> str:updated = self._store.update_fact(- int(args["fact_id"]), content=args.get("content"),- trust_delta=float(args["trust_delta"]) if "trust_delta" in args else None,- tags=args.get("tags"), category=args.get("category"),+ 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})- _FACT_STORE_ACTIONS = {- "add": lambda self, a: json.dumps({"fact_id": self._store.add_fact(- a["content"], category=a.get("category", "general"), tags=a.get("tags", "")), "status": "added"}),- "search": lambda self, a: _results(self._retriever.search(- 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,- "contradict": lambda self, a: _results(self._retriever.contradict(category=a.get("category"), limit=_limit(a))),- "update": _act_update,- "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"),- }_TOOL_HANDLERS = {- "fact_store": _handle_fact_store,+ "fact_store": _tool_handler({+ "add": lambda self, a: json.dumps({"fact_id": self._store.add_fact(+ a["content"], category=a.get("category", "general"), tags=a.get("tags", "")), "status": "added"}),+ "search": lambda self, a: _results(self._retriever.search(+ 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,+ "contradict": lambda self, a: _results(self._retriever.contradict(category=a.get("category"), limit=_limit(a))),+ "update": _act_update,+ "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"),+ }),"fact_feedback": lambda self, a: json.dumps(self._store.record_feedback(int(a["fact_id"]), helpful=a["action"] == "helpful")),}@@ -329,6 +320,7 @@ class HolographicMemoryProvider(MemoryProvider):if extracted:logger.info("Auto-extracted %d facts from conversation", extracted)+def register(ctx) -> None:"""Register the holographic memory provider with the plugin system."""ctx.register_memory_provider(HolographicMemoryProvider(config=_load_plugin_config()))diff --git a/plugins/memory/holographic/retrieval.py b/plugins/memory/holographic/retrieval.pyindex 9f12a82e097..ecde0b094bd 100644--- a/plugins/memory/holographic/retrieval.py+++ b/plugins/memory/holographic/retrieval.py@@ -23,6 +23,22 @@ _FACT_COLUMNS = (_ROLE_ENTITY = "__hrr_role_entity__"_ROLE_CONTENT = "__hrr_role_content__"_PUNCT = ".,;:!?\"'()[]{}#@<>"+_FTS_OPERATORS = str.maketrans("", "", '"()*^:-+')+# Stopwords dropped before FTS5 OR-expansion: short English function words that+# carry no retrieval signal and force false-negative AND matches.+_FTS_STOPWORDS = frozenset("""+ a about above after again all am an and any are as at be because been before being between both but by+ can could did do does doing don down during each few for from further had has have having he her here hers+ herself him himself his how i if in into is it its itself just me more most my myself no nor not now of off+ on once only or other our ours ourselves out over own same she should so some such than that the their theirs+ them themselves then there these they this those through to too under until up very was we were what when+ where which while who whom why will with would you your yours yourself yourselves+""".split())+++def _shift(sim: float) -> float:+ """Cosine similarity [-1, 1] -> [0, 1]."""+ return (sim + 1.0) / 2.0class FactRetriever:@@ -45,36 +61,31 @@ class FactRetriever: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).+ def _phases(self, blob: bytes):+ return hrr.bytes_to_phases(blob, dim=self.hrr_dim)- Returns fact dicts with a 'score' field, sorted by score desc.- """+ 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). Returns fact dicts with 'score', sorted desc."""candidates = self._fts_candidates(query, category, min_trust, limit * 3)if not candidates:return []-query_tokens = self._tokenize(query)# 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 = Nonefor fact in candidates:- all_tokens = self._tokenize(fact["content"]) | self._tokenize(fact.get("tags", ""))- jaccard = self._jaccard_similarity(query_tokens, all_tokens)+ jaccard = self._jaccard_similarity(query_tokens, self._tokenize(fact["content"]) | self._tokenize(fact.get("tags", "")))hrr_sim = 0.5 # neutralif self.hrr_weight > 0 and fact.get("hrr_vector"):- fact_vec = hrr.bytes_to_phases(fact["hrr_vector"], dim=self.hrr_dim)+ fact_vec = self._phases(fact["hrr_vector"])if query_vec is None:query_vec = hrr.encode_text(query, self.hrr_dim)- hrr_sim = (hrr.similarity(query_vec, fact_vec) + 1.0) / 2.0 # shift to [0,1]- relevance = (self.fts_weight * fact.get("fts_rank", 0.0)- + self.jaccard_weight * jaccard- + self.hrr_weight * hrr_sim)+ hrr_sim = _shift(hrr.similarity(query_vec, fact_vec))+ relevance = self.fts_weight * fact.get("fts_rank", 0.0) + self.jaccard_weight * jaccard + self.hrr_weight * hrr_simfact["score"] = relevance * fact["trust_score"]if self.half_life > 0:fact["score"] *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))-candidates.sort(key=lambda x: x["score"], reverse=True)results = candidates[:limit]for fact in results:@@ -87,22 +98,13 @@ class FactRetriever:Not keyword search. Falls back to FTS5 without numpy."""if not hrr._HAS_NUMPY:return self.search(entity, category=category, limit=limit)-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:- bank_row = self.store._conn.execute(- "SELECT vector FROM memory_banks WHERE bank_name = ?",- (f"cat:{category}",),- ).fetchone()+ if category: # category bank first, then individual fact vectors+ bank_row = self.store._conn.execute("SELECT vector FROM memory_banks WHERE bank_name = ?", (f"cat:{category}",)).fetchone()if bank_row:- extracted = hrr.unbind(hrr.bytes_to_phases(bank_row["vector"], dim=self.hrr_dim), probe_key)- return self._rank_by_vector(- self._vector_rows(category), lambda _f, fact_vec: hrr.similarity(extracted, fact_vec), limit,- )-+ extracted = hrr.unbind(self._phases(bank_row["vector"]), probe_key)+ return self._rank_by_vector(self._vector_rows(category), lambda _f, fact_vec: hrr.similarity(extracted, fact_vec), limit)rows = self._vector_rows(category)if not rows:return self.search(entity, category=category, limit=limit)@@ -120,7 +122,6 @@ class FactRetriever:*about* it as in probe. Falls back to FTS5 without numpy."""if not hrr._HAS_NUMPY:return self.search(entity, category=category, limit=limit)-entity_vec = self._atom(entity.lower()) # bare atom, not role-bound: ANY structural matchrows = self._vector_rows(category)if not rows:@@ -139,7 +140,6 @@ class FactRetriever: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 = self._atom(_ROLE_ENTITY)probe_keys = [hrr.bind(self._atom(entity.lower()), role_entity) for entity in entities]rows = self._vector_rows(category)@@ -158,17 +158,11 @@ class FactRetriever:content-vector similarity (different claims). Empty without numpy."""if not hrr._HAS_NUMPY:return []-- rows = self._vector_rows(- category,- columns="fact_id, content, category, tags, trust_score, created_at, updated_at, hrr_vector",- )+ rows = self._vector_rows(category, columns="fact_id, content, category, tags, trust_score, created_at, updated_at, hrr_vector")if len(rows) < 2:return []- # O(n²) guard: above 500 facts only compare the most recently updated ones.- if len(rows) > 500:+ if len(rows) > 500: # O(n²) guard: only compare the most recently updated factsrows = sorted(rows, key=lambda r: r["updated_at"] or r["created_at"], reverse=True)[:500]-facts = [dict(r) for r in rows]for fact in facts:entity_rows = self.store._conn.execute(@@ -176,7 +170,7 @@ class FactRetriever:(fact["fact_id"],),).fetchall()fact["_entities"] = {r["name"].lower() for r in entity_rows}- fact["_vec"] = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)+ fact["_vec"] = self._phases(fact.pop("hrr_vector"))def _public(fact: dict) -> dict:return {k: v for k, v in fact.items() if k not in ("_entities", "_vec")}@@ -191,18 +185,15 @@ class FactRetriever:if entity_overlap < 0.3:continue # not enough shared subject to be contradictorycontent_sim = hrr.similarity(f1["_vec"], f2["_vec"])- # High entity overlap + low content similarity = contradiction- contradiction_score = entity_overlap * (1.0 - (content_sim + 1.0) / 2.0)+ contradiction_score = entity_overlap * (1.0 - _shift(content_sim)) # high overlap + low similarityif contradiction_score >= threshold:contradictions.append({- "fact_a": _public(f1),- "fact_b": _public(f2),+ "fact_a": _public(f1), "fact_b": _public(f2),"entity_overlap": round(entity_overlap, 3),"content_similarity": round(content_sim, 3),"contradiction_score": round(contradiction_score, 3),"shared_entities": sorted(ents1 & ents2),})-contradictions.sort(key=lambda x: x["contradiction_score"], reverse=True)return contradictions[:limit]@@ -210,21 +201,14 @@ class FactRetriever:def _vector_rows(self, category: str | None, columns: str = _FACT_COLUMNS + ", hrr_vector") -> list:"""All facts that carry an HRR vector, optionally filtered by category."""- where = "WHERE hrr_vector IS NOT NULL"- params: list = []- if category:- where += " AND category = ?"- params.append(category)- return self.store._conn.execute(f"SELECT {columns} FROM facts {where}", params).fetchall()+ where = "WHERE hrr_vector IS NOT NULL" + (" AND category = ?" if category else "")+ return self.store._conn.execute(f"SELECT {columns} FROM facts {where}", [category] if category else []).fetchall()def _rank_by_vector(self, rows: list, sim_fn: Callable[[dict, object], float], limit: int) -> list[dict]:"""Score each row as (sim + 1) / 2 * trust_score (sim shifted to [0, 1]), sorted desc."""- scored = []- for row in rows:- fact = dict(row)- fact_vec = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)- fact["score"] = (sim_fn(fact, fact_vec) + 1.0) / 2.0 * fact["trust_score"]- scored.append(fact)+ scored = [dict(row) for row in rows]+ for fact in scored:+ fact["score"] = _shift(sim_fn(fact, self._phases(fact.pop("hrr_vector")))) * fact["trust_score"]scored.sort(key=lambda x: x["score"], reverse=True)return scored[:limit]@@ -241,13 +225,11 @@ class FactRetriever:"ORDER BY facts_fts.rank LIMIT ?")try:- rows = self.store._conn.execute(sql, params).fetchall()+ 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 rows:+ if not results:return []-- results = [dict(row) for row in rows]# 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 zerofor fact in results:@@ -257,25 +239,10 @@ class FactRetriever:@staticmethoddef _tokenize(text: str) -> set[str]:"""Lowercase whitespace tokens with surrounding punctuation stripped (no stemming)."""- if not text:- return set()- 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.- _FTS_STOPWORDS = frozenset("""- a about above after again all am an and any are as at be because been before being- between both but by can could did do does doing don down during each few for from- further had has have having he her here hers herself him himself his how i if in- into is it its itself just me more most my myself no nor not now of off on once- only or other our ours ourselves out over own same she should so some such than that- the their theirs them themselves then there these they this those through to too under- until up very was we were what when where which while who whom why will with would- you your yours yourself yourselves- """.split())-- @classmethod- def _sanitize_fts_query(cls, query: str) -> str:+ return {c for c in (w.strip(_PUNCT) for w in text.lower().split()) if c} if text else set()++ @staticmethod+ def _sanitize_fts_query(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@@ -284,12 +251,8 @@ class FactRetriever:"""if not query:return ""- strip_special = str.maketrans("", "", '"()*^:-+')- tokens = [- f'"{cleaned}"'- 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- ]+ tokens = [f'"{c}"' for c in (raw.strip(_PUNCT).translate(_FTS_OPERATORS) for raw in query.lower().split())+ if len(c) >= 2 and c not in _FTS_STOPWORDS]return " OR ".join(tokens) if tokens else query@staticmethoddiff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.pyindex 7d6fdb49e8d..4c1cc01dca6 100644--- a/plugins/memory/holographic/store.py+++ b/plugins/memory/holographic/store.py@@ -85,6 +85,11 @@ _RE_SINGLE_ENTITY = ()_RE_AKA = re.compile(r'(\w+(?:\s+\w+)*)\s+(?:aka|also known as)\s+(\w+(?:\s+\w+)*)', re.IGNORECASE)_ENTITY_NAMES_SQL = "SELECT e.name FROM entities e JOIN fact_entities fe ON fe.entity_id = e.entity_id WHERE fe.fact_id = ?"+# Entity lookup order: exact name, then aliases (comma-separated; wrapped in commas for whole-alias matching).+_ENTITY_LOOKUPS = (+ "SELECT entity_id FROM entities WHERE name LIKE ?",+ "SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'",+)def _clamp_trust(value: float) -> float:@@ -113,9 +118,7 @@ class MemoryStore:self.default_trust = _clamp_trust(default_trust)self.hrr_dim = hrr_dimself._hrr_available = hrr._HAS_NUMPY-- # resolve() so symlinked/relative paths to the same file share ONE connection.- try:+ try: # resolve() so symlinked/relative paths to the same file share ONE connectionself._key = str(self.db_path.resolve())except OSError:self._key = str(self.db_path)@@ -140,13 +143,10 @@ class MemoryStore:from hermes_state import apply_wal_with_fallbackapply_wal_with_fallback(self._conn, db_label="memory_store.db (holographic)")self._conn.executescript(_SCHEMA)- columns = {row[1] for row in self._conn.execute("PRAGMA table_info(facts)").fetchall()}- if "hrr_vector" not in columns:+ if "hrr_vector" not in {row[1] for row in self._conn.execute("PRAGMA table_info(facts)").fetchall()}:self._conn.execute("ALTER TABLE facts ADD COLUMN hrr_vector BLOB")self._conn.commit()- # -- SQL helpers -----------------------------------------------------------def _one(self, sql: str, params=()):return self._conn.execute(sql, params).fetchone()@@ -220,9 +220,7 @@ class MemoryStore:def record_feedback(self, fact_id: int, helpful: bool) -> dict:"""Adjust trust asymmetrically: helpful -> +0.05 and helpful_count += 1; unhelpful -> -0.10.-- Returns {fact_id, old_trust, new_trust, helpful_count}. Raises KeyError if fact_id is unknown.- """+ Returns {fact_id, old_trust, new_trust, helpful_count}. Raises KeyError if fact_id is unknown."""with self._lock:row = self._one("SELECT fact_id, trust_score, helpful_count FROM facts WHERE fact_id = ?", (fact_id,))if row is None:@@ -256,9 +254,7 @@ class MemoryStore:def _resolve_entity(self, name: str) -> int:"""Return the entity_id for a case-insensitive name or alias match, creating the entity if absent."""- # Name first, then aliases (comma-separated; wrapped in commas for whole-alias matching).- for sql in ("SELECT entity_id FROM entities WHERE name LIKE ?",- "SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'"):+ for sql in _ENTITY_LOOKUPS:row = self._one(sql, (name,))if row is not None:return int(row["entity_id"])@@ -268,9 +264,9 @@ class MemoryStore:"""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._write("UPDATE facts SET hrr_vector = ? WHERE fact_id = ?", (hrr.phases_to_bytes(vector), fact_id))+ entities = [row["name"] for row in self._conn.execute(_ENTITY_NAMES_SQL, (fact_id,)).fetchall()]+ blob = hrr.phases_to_bytes(hrr.encode_fact(content, entities, self.hrr_dim))+ self._write("UPDATE facts SET hrr_vector = ? WHERE fact_id = ?", (blob, fact_id))def _rebuild_bank(self, category: str) -> None:"""Full rebuild of a category's memory bank from all its fact vectors."""