The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory/holographic): compact constants, release_all_under pop-in-place, hrr module docstring and blob error paths
Teknium011f22afdaac
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.pyindex 5aa79f4d936..8ff1d0ce9a8 100644--- a/plugins/memory/holographic/__init__.py+++ b/plugins/memory/holographic/__init__.py@@ -174,11 +174,10 @@ class HolographicMemoryProvider(MemoryProvider):return [FACT_STORE_SCHEMA, FACT_FEEDBACK_SCHEMA]def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:- handler = self._TOOL_HANDLERS.get(tool_name)- if handler is None:+ if tool_name not in self._TOOL_HANDLERS:return tool_error(f"Unknown tool: {tool_name}")try:- return handler(self, args)+ return self._TOOL_HANDLERS[tool_name](self, args)except KeyError as exc:return tool_error(f"Missing required argument: {exc}")except Exception as exc:diff --git a/plugins/memory/holographic/holographic.py b/plugins/memory/holographic/holographic.pyindex 17ce86c5373..05176df2ec3 100644--- a/plugins/memory/holographic/holographic.py+++ b/plugins/memory/holographic/holographic.py@@ -1,17 +1,13 @@-"""Holographic Reduced Representations (HRR) with phase encoding.--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.-"""+"""Holographic Reduced Representations (HRR) with phase encoding. 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."""import hashlibimport logging-import structimport math+import structtry:import numpy as np@@ -37,9 +33,8 @@ 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."""_require_numpy()- uint16_values: list[int] = []- for i in range(math.ceil(dim / 16)): # 32-byte digest = 16 uint16 values- uint16_values.extend(struct.unpack("<16H", hashlib.sha256(f"{word}:{i}".encode()).digest()))+ uint16_values = [v for i in range(math.ceil(dim / 16)) # 32-byte digest = 16 uint16 values+ for v in struct.unpack("<16H", hashlib.sha256(f"{word}:{i}".encode()).digest())]return np.array(uint16_values[:dim], dtype=np.float64) * (_TWO_PI / 65536.0)@@ -84,11 +79,8 @@ def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarrdef phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:- """Serialize as prefixed float32 (half the size of legacy float64 blobs).-- At dim=1 the prefixed float32 blob and a raw float64 blob are both 8 bytes,- so we write legacy float64 there to keep ``bytes_to_phases`` unambiguous.- """+ """Serialize as prefixed float32 (half the size of legacy float64 blobs). At dim=1 the prefixed float32 blob+ and a raw float64 blob are both 8 bytes, so write legacy float64 there to keep ``bytes_to_phases`` unambiguous."""_require_numpy()dim = int(phases.shape[0]) if dim is None else dimif len(_FLOAT32_BLOB_PREFIX) + dim * _F32 == dim * _F64:@@ -97,11 +89,9 @@ 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.- """+ """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."""_require_numpy()plen = len(_FLOAT32_BLOB_PREFIX)prefixed = data.startswith(_FLOAT32_BLOB_PREFIX)@@ -120,10 +110,9 @@ def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":return f64(data)if not prefixed:raise ValueError(f"HRR legacy vector blob has {len(data)} bytes; expected {float64_bytes} (float64) for dim={dim}")- expected = (f"{float64_bytes} (legacy float64)" if collides- else f"{float32_blob_bytes} (prefixed float32) or {float64_bytes} (legacy float64)")- raise ValueError(f"HRR vector blob has {len(data)} bytes ({len(data) - plen} payload bytes after "- f"the float32 prefix); expected {expected} for dim={dim}")+ expected = f"{float64_bytes} (legacy float64)" if collides else f"{float32_blob_bytes} (prefixed float32) or {float64_bytes} (legacy float64)"+ raise ValueError(f"HRR vector blob has {len(data)} bytes ({len(data) - plen} payload bytes after the float32 prefix); "+ f"expected {expected} 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 a926173d40d..8b8819b742a 100644--- a/plugins/memory/holographic/store.py+++ b/plugins/memory/holographic/store.py@@ -70,23 +70,16 @@ CREATE TABLE IF NOT EXISTS memory_banks ();"""-_HELPFUL_DELTA = 0.05-_UNHELPFUL_DELTA = -0.10--# Entity extraction patterns, applied in order: capitalized multi-word phrases-# ("John Doe"), double-quoted terms, single-quoted terms, then "X aka Y" (both sides).-_RE_SINGLE_ENTITY = (- re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b'),- re.compile(r'"([^"]+)"'),- re.compile(r"'([^']+)'"),-)+_HELPFUL_DELTA, _UNHELPFUL_DELTA = 0.05, -0.10++# Entity extraction patterns, applied in order: capitalized multi-word phrases ("John Doe"), double-quoted terms,+# single-quoted terms, then "X aka Y" (both sides).+_RE_SINGLE_ENTITY = (re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b'), re.compile(r'"([^"]+)"'), re.compile(r"'([^']+)'"))_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 '%,' || ? || ',%'",-)+_ENTITY_LOOKUPS = ("SELECT entity_id FROM entities WHERE name LIKE ?",+ "SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'")def _clamp_trust(value: float) -> float:@@ -126,9 +119,9 @@ class MemoryStore:entry["refs"] += 1self._entry, self._conn, self._lock = entry, entry["conn"], entry["lock"]with self._lock: # schema initialised once per shared connection- if not self._entry["ready"]:+ if not entry["ready"]:self._init_db()- self._entry["ready"] = True+ entry["ready"] = Truedef _init_db(self) -> None:"""Create schema, enable WAL via the shared fallback helper (NFS/SMB/FUSE degrade gracefully), add hrr_vector to pre-HRR DBs."""@@ -225,9 +218,8 @@ class MemoryStore:for m in _RE_AKA.finditer(text):raw += [m.group(1), m.group(2)]uniq: dict[str, str] = {} # lower-cased key -> first-seen spelling, insertion-ordered- for name in (n.strip() for n in raw):- if name:- uniq.setdefault(name.lower(), name)+ for name in filter(None, (n.strip() for n in raw)):+ uniq.setdefault(name.lower(), name)return list(uniq.values())def _link_entities(self, fact_id: int, content: str) -> None:@@ -263,13 +255,10 @@ class MemoryStore:returnbank_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._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._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)))@classmethoddef release_all_under(cls, directory: "str | Path") -> int:@@ -279,9 +268,8 @@ class MemoryStore:stale holder is expected to fail."""root = os.path.normcase(str(Path(directory).expanduser().resolve())) + os.sepwith cls._shared_guard:- doomed = [key for key in cls._shared if os.path.normcase(key).startswith(root)]- for key in doomed:- entry = cls._shared.pop(key)+ doomed = [cls._shared.pop(key) for key in list(cls._shared) if os.path.normcase(key).startswith(root)]+ for entry in doomed:try:with entry["lock"]:entry["conn"].close()