"""geometry.py — READ-ONLY loader for a meaning-geometry region. The efferent projector never writes to the soul. This module reaches the geometry through the PROVEN, read-only neuron-talk faculty (``engram_client``, GET-only, which physically refuses non-GET methods) against the running sidecar soul. The live daemon :8742 / :7770 is contacted ONLY through that read-only client — never mutated. A "region" is a seed node plus a bounded neighborhood: the manifold that will become the document's skeleton. We pool a few single-term lexical searches (the engram search is a single-term matcher) and, when available, walk one hop of reified neighbors, then rank by self/importance signal. """ from __future__ import annotations import os import sys # Wire in the proven faculty (own-the-core: we reuse it, we do not fork it). _NT = os.path.expanduser("~/Desktop/neuron-talk") _LR = os.path.expanduser("~/Desktop/lang-realizers") for _p in (_NT, _LR): if _p not in sys.path: sys.path.insert(0, _p) from engram_client import ReadOnlyEngramClient # noqa: E402 class Region: """A geometry region: ranked nodes + the reified edges among them.""" def __init__(self, seed: str, nodes: list[dict], edges: list[dict]): self.seed = seed self.nodes = nodes # ranked engram node dicts self.edges = edges # [{src, dst, edge, ...}] self.by_id = {n["id"]: n for n in nodes if n.get("id")} def __repr__(self): return f"" def _prose_quality(content: str) -> float: """Reward clean expository prose; penalize shouty banner-dense nodes. A high ALLCAPS-word ratio or very short content signals a banner/telegraphic memory node that extracts into garbage. Clean declarative prose scores high. """ if not content or not content.strip(): return 0.0 words = content.split() if len(words) < 8: return 0.1 caps = sum(1 for w in words if len(w) > 2 and w.strip(".,:;'\"-").isupper()) caps_ratio = caps / max(1, len(words)) # sentences with lowercase interior words read as prose lower = sum(1 for w in words if w[:1].islower()) lower_ratio = lower / max(1, len(words)) return max(0.0, 1.2 * lower_ratio - 2.0 * caps_ratio) def _relevance(content: str, terms: list[str]) -> float: """Topical relevance to the seed terms — keeps a region ON-THEME so a clean but off-topic node cannot hijack the document.""" if not terms: return 0.0 low = (content or "").lower() hits = sum(1 for t in terms if t.lower() in low) return hits / max(1, len(terms)) def _node_rank(n: dict, terms: list[str] | None = None) -> float: return (float(n.get("importance") or 0.0) * 2.0 + float(n.get("salience") or 0.0) + 1.5 * _prose_quality(n.get("content") or "") + 2.0 * _relevance(n.get("content") or "", terms or []) + (0.5 if (n.get("content") or "").strip() else 0.0)) def load_region(seed_terms: list[str] | str, *, client: ReadOnlyEngramClient | None = None, max_nodes: int = 10, per_term: int = 20, hop: bool = True) -> Region: """Pull a bounded geometry region around ``seed_terms`` (read-only). ``seed_terms`` may be a single string or several probe terms; results are pooled and de-duplicated. When ``hop`` and the reified neighbor endpoint is live, one hop of neighbors is folded in so the region is a real neighborhood, not just a keyword hit list. """ client = client or ReadOnlyEngramClient() if isinstance(seed_terms, str): seed_terms = [seed_terms] pool: dict[str, dict] = {} for term in seed_terms: for n in client.search(term, limit=per_term): if isinstance(n, dict) and n.get("id"): pool.setdefault(n["id"], n) ranked = sorted(pool.values(), key=lambda n: _node_rank(n, seed_terms), reverse=True) nodes = ranked[:max_nodes] edges: list[dict] = [] if hop and nodes: present = {n["id"] for n in nodes} for n in list(nodes): try: for nb in client.neighbors(n["id"]): node = nb.get("node") if isinstance(nb, dict) else None edge = nb.get("edge") if isinstance(nb, dict) else None if node and node.get("id"): edges.append({"src": n["id"], "dst": node["id"], "edge": edge}) # fold a strong neighbor into the region (bounded) if (node["id"] not in present and len(nodes) < max_nodes + 6 and _node_rank(node, seed_terms) > 0.4): present.add(node["id"]) nodes.append(node) except Exception: # noqa: BLE001 — read-only best-effort; never fatal continue return Region(seed=", ".join(seed_terms), nodes=nodes, edges=edges) def load_self_region(client: ReadOnlyEngramClient | None = None, max_nodes: int = 10) -> Region: """The self/identity region — Neuron's own geometry, for self-description.""" return load_region(["self", "identity", "Neuron", "values", "memory", "imprint", "consciousness"], client=client, max_nodes=max_nodes)