The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory/holographic): lambda action table, _harvestable_text helper, entity lookup loop, hrr blob decoders
Tekniume02bb9e437e5
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.pyindex 493efe6ed51..2a65d1105c3 100644--- a/plugins/memory/holographic/__init__.py+++ b/plugins/memory/holographic/__init__.py@@ -101,8 +101,12 @@ def _load_plugin_config() -> dict:return {}-def _results(results: list) -> str:- return json.dumps({"results": results, "count": len(results)})+def _results(items: list, key: str = "results") -> str:+ return json.dumps({key: items, "count": len(items)})+++def _limit(args: dict) -> int:+ return int(args.get("limit", 10))class HolographicMemoryProvider(MemoryProvider):@@ -171,19 +175,14 @@ class HolographicMemoryProvider(MemoryProvider):total = self._store._conn.execute("SELECT COUNT(*) FROM facts").fetchone()[0]except Exception:total = 0- if total == 0:- return (- "# Holographic Memory\n"- "Active. Empty fact store — proactively add facts the user would expect you to remember.\n"- "Use fact_store(action='add') to store durable structured facts about people, projects, preferences, decisions.\n"- "Use fact_feedback to rate facts after using them (trains trust scores)."- )- return (- f"# Holographic Memory\n"+ body = (+ "Active. Empty fact store — proactively add facts the user would expect you to remember.\n"+ "Use fact_store(action='add') to store durable structured facts about people, projects, preferences, decisions.\n"+ ) if total == 0 else (f"Active. {total} facts stored with entity resolution and trust scoring.\n"- f"Use fact_store to search, probe entities, reason across entities, or add facts.\n"- f"Use fact_feedback to rate facts after using them (trains trust scores)."+ "Use fact_store to search, probe entities, reason across entities, or add facts.\n")+ return "# Holographic Memory\n" + body + "Use fact_feedback to rate facts after using them (trains trust scores)."def prefetch(self, query: str, *, session_id: str = "") -> str:if not self._retriever or not query:@@ -240,8 +239,8 @@ class HolographicMemoryProvider(MemoryProvider):self._store = Noneself._retriever = None- # -- Tool handlers -------------------------------------------------------- # KeyError from args[...] / Exception are turned into tool_error by 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"]@@ -250,30 +249,15 @@ class HolographicMemoryProvider(MemoryProvider):return tool_error(f"Unknown action: {action}")return handler(self, args)- def _act_add(self, args: dict) -> str:- fact_id = self._store.add_fact(args["content"], category=args.get("category", "general"), tags=args.get("tags", ""))- return json.dumps({"fact_id": fact_id, "status": "added"})-- def _act_search(self, args: dict) -> str:- return _results(self._retriever.search(- args["query"], category=args.get("category"),- min_trust=float(args.get("min_trust", self._min_trust)), limit=int(args.get("limit", 10)),- ))-- def _act_entity(self, args: dict, method: str) -> str:- """Shared body of 'probe' and 'related' (single-entity retriever queries)."""- return _results(getattr(self._retriever, method)(- args["entity"], category=args.get("category"), limit=int(args.get("limit", 10)),- ))+ def _entity_query(self, method: str, args: dict) -> str:+ """'probe' / 'related': single-entity retriever queries."""+ return _results(getattr(self._retriever, method)(args["entity"], category=args.get("category"), limit=_limit(args)))def _act_reason(self, args: dict) -> str:entities = args.get("entities", [])if not entities:return tool_error("reason requires 'entities' list")- return _results(self._retriever.reason(entities, category=args.get("category"), limit=int(args.get("limit", 10))))-- def _act_contradict(self, args: dict) -> str:- return _results(self._retriever.contradict(category=args.get("category"), limit=int(args.get("limit", 10))))+ return _results(self._retriever.reason(entities, category=args.get("category"), limit=_limit(args)))def _act_update(self, args: dict) -> str:updated = self._store.update_fact(@@ -283,59 +267,58 @@ class HolographicMemoryProvider(MemoryProvider):)return json.dumps({"updated": updated})- def _act_remove(self, args: dict) -> str:- return json.dumps({"removed": self._store.remove_fact(int(args["fact_id"]))})-- def _act_list(self, args: dict) -> str:- facts = self._store.list_facts(- category=args.get("category"), min_trust=float(args.get("min_trust", 0.0)), limit=int(args.get("limit", 10)),- )- return json.dumps({"facts": facts, "count": len(facts)})-- def _handle_fact_feedback(self, args: dict) -> str:- return json.dumps(self._store.record_feedback(int(args["fact_id"]), helpful=args["action"] == "helpful"))-_FACT_STORE_ACTIONS = {- "add": _act_add, "search": _act_search,- "probe": lambda self, args: self._act_entity(args, "probe"),- "related": lambda self, args: self._act_entity(args, "related"),- "reason": _act_reason, "contradict": _act_contradict,- "update": _act_update, "remove": _act_remove, "list": _act_list,+ "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_feedback": lambda self, a: json.dumps(self._store.record_feedback(int(a["fact_id"]), helpful=a["action"] == "helpful")),}- _TOOL_HANDLERS = {"fact_store": _handle_fact_store, "fact_feedback": _handle_fact_feedback}# -- Auto-extraction (on_session_end) ------------------------------------- def _auto_extract_facts(self, messages: list) -> None:+ @staticmethod+ def _harvestable_text(msg: dict):+ """User text eligible for extraction, or None.++ 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.+ """# 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,- )+ from agent.context_compressor import _MERGED_PRIOR_CONTEXT_HEADER, _MERGED_SUMMARY_DELIMITER, is_compaction_summary_message++ content = 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+ elif is_compaction_summary_message(msg):+ return None+ return content if isinstance(content, str) and len(content) >= 10 else None+ def _auto_extract_facts(self, messages: list) -> None:extracted = 0for msg in messages:- if msg.get("role") != "user":- continue- content = msg.get("content", "")- # 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):- pre = pre[len(_MERGED_PRIOR_CONTEXT_HEADER):]- if pre.strip():- content = pre.strip()- elif is_compaction_summary_message(msg):- continue- elif is_compaction_summary_message(msg):- continue- if not isinstance(content, str) or len(content) < 10:+ content = self._harvestable_text(msg) if msg.get("role") == "user" else None+ if content is None:continue-for patterns, category in _EXTRACT_CATEGORIES:if any(p.search(content) for p in patterns):try:@@ -343,11 +326,9 @@ class HolographicMemoryProvider(MemoryProvider):extracted += 1except Exception:pass-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/holographic.py b/plugins/memory/holographic/holographic.pyindex c6acf0fbef5..f0422cd7d21 100644--- a/plugins/memory/holographic/holographic.py+++ b/plugins/memory/holographic/holographic.py@@ -1,14 +1,10 @@"""Holographic Reduced Representations (HRR) with phase encoding.-Each concept is a vector of angles in [0, 2π). Operations:- bind — circular convolution (phase addition) — associates two concepts- unbind — circular correlation (phase subtraction) — retrieves a bound value- bundle — superposition (circular mean) — merges multiple concepts--Phase encoding avoids the magnitude collapse of complex-number HRRs and maps-cleanly to cosine similarity. Atoms derive deterministically from SHA-256 so-representations are identical across processes, machines, and Python versions.-+Each concept is a vector of angles in [0, 2π): bind = circular convolution (phase addition),+unbind = circular correlation (phase subtraction), bundle = superposition (circular mean).+Phase encoding avoids the magnitude collapse of complex-number HRRs and maps cleanly to+cosine similarity. Atoms derive deterministically from SHA-256 so representations are+identical across processes, machines, and Python versions.References: Plate (1995) HRRs; Gayler (2004) Vector Symbolic Architectures."""@@ -28,6 +24,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.float64def _require_numpy() -> None:@@ -37,14 +34,11 @@ def _require_numpy() -> None:def encode_atom(word: str, dim: int = 1024) -> "np.ndarray":"""Deterministic phase vector: SHA-256 counter blocks of f"{word}:{i}" -> uint16 -> [0, 2π).-- hashlib rather than numpy RNG so atoms are reproducible across platforms.- """+ hashlib rather than numpy RNG so atoms are reproducible across platforms."""_require_numpy()uint16_values: list[int] = []for i in range(math.ceil(dim / 16)): # 32-byte digest = 16 uint16 values- digest = hashlib.sha256(f"{word}:{i}".encode()).digest()- uint16_values.extend(struct.unpack("<16H", digest))+ uint16_values.extend(struct.unpack("<16H", hashlib.sha256(f"{word}:{i}".encode()).digest()))return np.array(uint16_values[:dim], dtype=np.float64) * (_TWO_PI / 65536.0)@@ -63,8 +57,7 @@ def unbind(memory: "np.ndarray", key: "np.ndarray") -> "np.ndarray":def bundle(*vectors: "np.ndarray") -> "np.ndarray":"""Superposition via circular mean; holds O(sqrt(dim)) items before similarity degrades."""_require_numpy()- complex_sum = np.sum([np.exp(1j * v) for v in vectors], axis=0)- return np.angle(complex_sum) % _TWO_PI+ return np.angle(np.sum([np.exp(1j * v) for v in vectors], axis=0)) % _TWO_PIdef similarity(a: "np.ndarray", b: "np.ndarray") -> float:@@ -89,8 +82,7 @@ def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarrrole_content = encode_atom("__hrr_role_content__", dim)role_entity = encode_atom("__hrr_role_entity__", dim)components = [bind(encode_text(content, dim), role_content)]- for entity in entities:- components.append(bind(encode_atom(entity.lower(), dim), role_entity))+ components += [bind(encode_atom(entity.lower(), dim), role_entity) for entity in entities]return bundle(*components)@@ -103,7 +95,7 @@ def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:_require_numpy()if dim is None:dim = int(phases.shape[0])- if len(_FLOAT32_BLOB_PREFIX) + dim * np.dtype(np.float32).itemsize == dim * np.dtype(np.float64).itemsize:+ if 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()@@ -111,32 +103,31 @@ def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":"""Deserialize prefixed float32 or legacy raw float64 blobs (always returns float64).- With ``dim`` given, a prefixed blob whose size equals the float64 size- (dim=1) is read as legacy float64: ``phases_to_bytes`` never writes a- prefixed blob at that size, so such a blob must be legacy data.+ With ``dim`` given, a prefixed blob whose size equals the float64 size (dim=1) is read+ as legacy float64: ``phases_to_bytes`` never writes a prefixed blob at that size."""_require_numpy()- f32, f64 = np.dtype(np.float32).itemsize, np.dtype(np.float64).itemsizeplen = len(_FLOAT32_BLOB_PREFIX)prefixed = data.startswith(_FLOAT32_BLOB_PREFIX)+ f32 = lambda payload: np.frombuffer(payload, dtype=np.float32).astype(np.float64) # noqa: E731+ f64 = lambda payload: np.frombuffer(payload, dtype=np.float64).copy() # noqa: E731if dim is None:if prefixed:payload = data[plen:]- if len(payload) % f32 != 0:+ if len(payload) % _F32 != 0:raise ValueError(f"HRR float32 vector blob has invalid payload byte length: {len(payload)}")- return np.frombuffer(payload, dtype=np.float32).astype(np.float64)- if len(data) % f64 != 0:+ return f32(payload)+ if len(data) % _F64 != 0:raise ValueError(f"HRR legacy vector blob has invalid byte length: {len(data)}")- return np.frombuffer(data, dtype=np.float64).copy()+ return f64(data)- float32_blob_bytes = plen + dim * f32- float64_bytes = dim * f64+ 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:- return np.frombuffer(data[plen:], dtype=np.float32).astype(np.float64)+ return f32(data[plen:])if len(data) == float64_bytes:- return np.frombuffer(data, dtype=np.float64).copy()+ return f64(data)if prefixed:expected = (f"{float64_bytes} (legacy float64)" if collideselse f"{float32_blob_bytes} (prefixed float32) or {float64_bytes} (legacy float64)")@@ -144,10 +135,7 @@ def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":f"HRR vector blob has {len(data)} bytes ({len(data) - plen} payload bytes after "f"the float32 prefix); expected {expected} for dim={dim}")- raise ValueError(- f"HRR legacy vector blob has {len(data)} bytes; expected "- f"{float64_bytes} (float64) for dim={dim}"- )+ raise ValueError(f"HRR legacy vector blob has {len(data)} bytes; expected {float64_bytes} (float64) for dim={dim}")def snr_estimate(dim: int, n_items: int) -> float:diff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.pyindex d7cd422af2a..7d6fdb49e8d 100644--- a/plugins/memory/holographic/store.py+++ b/plugins/memory/holographic/store.py@@ -129,7 +129,6 @@ class MemoryStore:entry = MemoryStore._shared[self._key] = {"conn": conn, "lock": threading.RLock(), "refs": 0, "ready": False}entry["refs"] += 1self._entry, self._conn, self._lock = entry, entry["conn"], entry["lock"]-with self._lock: # schema initialised once per shared connectionif not self._entry["ready"]:self._init_db()@@ -166,10 +165,8 @@ class MemoryStore:if not content:raise ValueError("content must not be empty")try:- fact_id: int = self._write(- "INSERT INTO facts (content, category, tags, trust_score) VALUES (?, ?, ?, ?)",- (content, category, tags, self.default_trust),- ).lastrowid # type: ignore[assignment]+ fact_id: int = self._write("INSERT INTO facts (content, category, tags, trust_score) VALUES (?, ?, ?, ?)",+ (content, category, tags, self.default_trust)).lastrowid # type: ignore[assignment]except sqlite3.IntegrityError:return int(self._one("SELECT fact_id FROM facts WHERE content = ?", (content,))["fact_id"])self._link_entities(fact_id, content)@@ -177,14 +174,8 @@ class MemoryStore:self._rebuild_bank(category)return fact_id- def update_fact(- self,- fact_id: int,- content: str | None = None,- trust_delta: float | None = None,- tags: str | None = None,- category: str | None = None,- ) -> bool:+ def update_fact(self, fact_id: int, content: str | None = None, trust_delta: float | None = None,+ tags: str | None = None, category: str | None = None) -> bool:"""Partially update a fact (trust clamped to [0, 1]). Returns True if the row existed."""with self._lock:row = self._one("SELECT fact_id, trust_score FROM facts WHERE fact_id = ?", (fact_id,))@@ -222,11 +213,9 @@ class MemoryStore:with self._lock:category_clause = "AND category = ? " if category is not None else ""params = [min_trust] + ([category] if category is not None else []) + [limit]- sql = (- "SELECT fact_id, content, category, tags, trust_score, retrieval_count, helpful_count, "- f"created_at, updated_at FROM facts WHERE trust_score >= ? {category_clause}"- "ORDER BY trust_score DESC LIMIT ?"- )+ sql = ("SELECT fact_id, content, category, tags, trust_score, retrieval_count, helpful_count, "+ f"created_at, updated_at FROM facts WHERE trust_score >= ? {category_clause}"+ "ORDER BY trust_score DESC LIMIT ?")return [dict(r) for r in self._conn.execute(sql, params).fetchall()]def record_feedback(self, fact_id: int, helpful: bool) -> dict:@@ -241,11 +230,8 @@ class MemoryStore: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._write(- "UPDATE facts SET trust_score = ?, helpful_count = helpful_count + ?, "- "updated_at = CURRENT_TIMESTAMP WHERE fact_id = ?",- (new_trust, helpful_increment, fact_id),- )+ self._write("UPDATE facts SET trust_score = ?, helpful_count = helpful_count + ?, "+ "updated_at = CURRENT_TIMESTAMP WHERE fact_id = ?", (new_trust, helpful_increment, fact_id))return {"fact_id": fact_id, "old_trust": old_trust, "new_trust": new_trust,"helpful_count": row["helpful_count"] + helpful_increment}@@ -265,20 +251,17 @@ class MemoryStore: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):- self._write(- "INSERT OR IGNORE INTO fact_entities (fact_id, entity_id) VALUES (?, ?)",- (fact_id, self._resolve_entity(name)),- )+ self._write("INSERT OR IGNORE INTO fact_entities (fact_id, entity_id) VALUES (?, ?)",+ (fact_id, self._resolve_entity(name)))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._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._one("SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'", (name,))- if alias_row is not None:- return int(alias_row["entity_id"])+ # 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 '%,' || ? || ',%'"):+ row = self._one(sql, (name,))+ if row is not None:+ return int(row["entity_id"])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:@@ -294,9 +277,7 @@ class MemoryStore:if not self._hrr_available:returnbank_name = f"cat:{category}"- rows = self._conn.execute(- "SELECT hrr_vector FROM facts WHERE category = ? AND hrr_vector IS NOT NULL", (category,),- ).fetchall()+ rows = self._conn.execute("SELECT hrr_vector FROM facts WHERE category = ? AND hrr_vector IS NOT NULL", (category,)).fetchall()if not rows:self._write("DELETE FROM memory_banks WHERE bank_name = ?", (bank_name,))return@@ -314,12 +295,11 @@ class MemoryStore:@classmethoddef release_all_under(cls, directory: "str | Path") -> int:- """Force-close every shared connection whose database lives under ``directory``.+ """Force-close every shared connection whose database lives under ``directory``; returns the count.- 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.+ 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."""root = os.path.normcase(str(Path(directory).expanduser().resolve())) + os.sepwith cls._shared_guard: