File size: 11,448 Bytes
8abad49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
"""SOFTWARE retrieval over the public second-brain projection.

575 in-repo chunks. BM25-like lexical rank. NEVER correctness.
Handles only — content stays in the controller.
The private 9464-node graph is not here and never enters gradients.
"""
from __future__ import annotations

import hashlib
import json
import math
import os
import re
import sys
from collections import Counter
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
CORPUS = ROOT / "data" / "brain-corpus.public.jsonl"
TOKEN = re.compile(r"[a-z0-9λ]+", re.I)
STOP = {
    "the", "is", "a", "an", "of", "and", "or", "to", "in", "for", "on", "at",
    "by", "as", "what", "which", "who", "how", "why", "does", "did", "are",
    "was", "be", "it", "this", "that", "with", "from", "into", "over", "not",
}
PUBLIC_CHUNK_COUNT = 575
PRIVATE_GRAPH_NODES = 9464
SCHEMA_RETRIEVE = "szl.second-brain.retrieve/v1"
SCHEMA_INDEX = "szl.second-brain.index/v1"
SCHEMA_NAV = "szl.brain.navigator-context/v1"


def tokenize(text: str) -> list[str]:
    return [
        t.lower()
        for t in TOKEN.findall(text or "")
        if len(t) > 1 and t.lower() not in STOP
    ]


def canonical_sha256(value: Any) -> str:
    return hashlib.sha256(
        json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    ).hexdigest()


def corpus_path(path: Path | None = None) -> Path:
    env = (os.environ.get("SECOND_BRAIN_CORPUS") or os.environ.get("AYLLU_BRAIN_CORPUS") or "").strip()
    if path is not None:
        return Path(path)
    if env:
        return Path(env)
    return CORPUS


class SecondBrainIndex:
    def __init__(self, path: Path | None = None) -> None:
        self.rows: list[dict[str, Any]] = []
        self.df: Counter[str] = Counter()
        self.path = corpus_path(path)
        self.load_error: str | None = None
        self._load()
        self.n = len(self.rows)

    def _load(self) -> None:
        if not self.path.is_file():
            self.load_error = f"public corpus missing at {self.path}"
            return
        try:
            raw = self.path.read_text(encoding="utf-8")
        except OSError as exc:
            self.load_error = f"public corpus unreadable ({type(exc).__name__})"
            return
        for line in raw.splitlines():
            if not line.strip():
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError:
                continue
            if not isinstance(row, dict) or not row.get("id"):
                continue
            text = f"{row.get('title', '')} {row.get('text', '')}"
            toks = tokenize(text)
            digest = row.get("sha256")
            if not (isinstance(digest, str) and len(digest) == 64):
                digest = hashlib.sha256((row.get("text") or "").encode("utf-8")).hexdigest()
            self.rows.append({
                "id": str(row["id"]),
                "title": str(row.get("title") or ""),
                "source": str(row.get("source") or "unknown"),
                "sourceId": row.get("sourceId"),
                "sha256": digest,
                "_toks": toks,
                "_tf": Counter(toks),
            })
            self.df.update(set(toks))

    @property
    def built(self) -> bool:
        return self.load_error is None and self.n > 0

    def handle(self, row: dict[str, Any]) -> dict[str, Any]:
        """Controller handle. No node text. Never a private-graph row."""
        return {
            "nodeId": row["id"],
            "nodeKind": "INDEX",
            "label": "DECLARED",
            "note": (row.get("title") or "")[:160],
            "source": row.get("source"),
            "sha256": row.get("sha256"),
        }

    def model_handle(self, row: dict[str, Any]) -> dict[str, Any]:
        """Khipu candidate offered to the model. HANDLES_ONLY four-field shape."""
        return {
            "nodeId": row["id"],
            "nodeKind": "INDEX",
            "label": "DECLARED",
            "note": (row.get("title") or "")[:160],
        }

    def search(self, query: str, k: int = 6) -> dict[str, Any]:
        if not self.built:
            return {
                "schema": SCHEMA_RETRIEVE,
                "query": query,
                "handles": [],
                "ready": False,
                "kind": "SOFTWARE",
                "content_access": "HANDLES_ONLY",
                "corpus_n": 0,
                "honesty": (
                    f"Index UNAVAILABLE ({self.load_error or 'empty'}). "
                    "No LIVE retrieval fabricated. Private 9464-node graph is not here."
                ),
            }
        q = tokenize(query)
        if not q:
            return {
                "schema": SCHEMA_RETRIEVE,
                "query": query,
                "handles": [],
                "ready": False,
                "kind": "SOFTWARE",
                "content_access": "HANDLES_ONLY",
                "corpus_n": self.n,
                "honesty": "empty query — no ranking fabricated",
            }
        scored: list[tuple[float, dict[str, Any]]] = []
        qset = Counter(q)
        idf_n = max(1, self.n)
        for row in self.rows:
            score = 0.0
            for term, qf in qset.items():
                tf = row["_tf"].get(term, 0)
                if not tf:
                    continue
                idf = math.log((idf_n + 1) / (1 + self.df.get(term, 0))) + 1.0
                score += (tf / (tf + 1.2)) * idf * qf
            if score > 0:
                scored.append((score, row))
        scored.sort(key=lambda x: x[0], reverse=True)
        top = scored[: max(1, min(int(k), 12))]
        handles = [self.handle(r) for _, r in top]
        return {
            "schema": SCHEMA_RETRIEVE,
            "query": query,
            "k": len(handles),
            "handles": handles,
            "scores": [round(s, 4) for s, _ in top],
            "corpus_n": self.n,
            "ready": bool(handles),
            "kind": "SOFTWARE",
            "content_access": "HANDLES_ONLY",
            "index_is_model_weights": False,
            "raw_graph_nodes_admitted_to_gradients": 0,
            "honesty": (
                "Lexical rank over the PUBLIC in-repo projection (575 chunks). "
                "Score is overlap, never correctness. Content stays in the controller. "
                "Not LIVE retrieval. Private 9464-node graph is not here."
            ),
        }

    def stats(self) -> dict[str, Any]:
        by: dict[str, int] = {}
        for r in self.rows:
            src = str(r.get("source") or "unknown")
            by[src] = by.get(src, 0) + 1
        return {
            "schema": SCHEMA_INDEX,
            "chunk_count": self.n,
            "public_chunk_count_declared": PUBLIC_CHUNK_COUNT,
            "by_source": by,
            "path": str(self.path),
            "built": self.built,
            "load_error": self.load_error,
            "index_is_model_weights": False,
            "raw_graph_nodes_observed_private": PRIVATE_GRAPH_NODES,
            "raw_graph_nodes_admitted_to_gradients": 0,
            "kind": "SOFTWARE",
            "honesty": (
                "Public projection only. Private 9464-node graph is not here. "
                "Index is DATA, never weights."
            ),
        }

    def rag_status(self) -> dict[str, Any]:
        st = self.stats()
        return {
            "built": self.built,
            "state": "PUBLIC_PROJECTION_LOADED" if self.built else "UNAVAILABLE",
            "document_count": self.n,
            "files": self.n,
            "chunk_count": self.n,
            "chunks": self.n,
            "corpus_chunk_count": self.n,
            "brain_handle_count": self.n if self.built else 0,
            "brain_handle_plane": {
                "kind": "PUBLIC_JSONL_HANDLES",
                "count": self.n if self.built else 0,
                "private_graph_nodes": 0,
                "gradient_authority_rows": 0,
                "training_authority": "NONE",
            },
            "training_authority_rows": 0,
            "node_count": self.n if self.built else 0,
            "edge_count": 0,
            "mode": "SOFTWARE_BM25",
            "kind": "SOFTWARE",
            "integrity_state": "PUBLIC_PROJECTION_LOADED" if self.built else "UNAVAILABLE",
            "rehydration_state": "IN_PROCESS" if self.built else "UNAVAILABLE",
            "corpus": {
                "path": str(self.path),
                "public": True,
                "private_graph_nodes": 0,
                "declared_public_chunks": PUBLIC_CHUNK_COUNT,
            },
            "index_is_model_weights": False,
            "raw_graph_nodes_admitted_to_gradients": 0,
            "by_source": st["by_source"],
            "load_error": self.load_error,
            "honesty": st["honesty"],
        }

    def navigator_context(self, query: str, k: int = 6) -> dict[str, Any]:
        hit = self.search(query, k=k)
        handles = hit.get("handles") or []
        model_handles = [
            {key: h[key] for key in ("nodeId", "nodeKind", "label", "note") if key in h}
            for h in handles
            if isinstance(h, dict) and h.get("nodeId")
        ]
        evidence = [
            {
                "node_id": h.get("nodeId"),
                "sha256": h.get("sha256"),
                "source": h.get("source"),
            }
            for h in handles
            if isinstance(h, dict)
        ]
        ready = bool(hit.get("ready") and model_handles)
        handles_sha = canonical_sha256(model_handles)
        evidence_sha = canonical_sha256(evidence)
        return {
            "schema": SCHEMA_NAV,
            "state": "GROUNDED_HANDLES_READY" if ready else "ABSTAIN_NO_GROUNDED_HANDLES",
            "ready": ready,
            "content_access": "HANDLES_ONLY",
            "query": query,
            "query_sha256": hashlib.sha256((query or "").encode("utf-8")).hexdigest(),
            "handles": model_handles,
            "evidence": evidence,
            "evidence_set_sha256": evidence_sha,
            "handles_sha256": handles_sha,
            "handle_evidence_set_equivalent": len(model_handles) == len(evidence),
            "grounded_count": len(model_handles),
            "corpus_n": hit.get("corpus_n", self.n),
            "kind": "SOFTWARE",
            "index_is_model_weights": False,
            "raw_graph_nodes_admitted_to_gradients": 0,
            "honesty": hit.get("honesty"),
        }


_INDEX: SecondBrainIndex | None = None


def index() -> SecondBrainIndex:
    global _INDEX
    if _INDEX is None:
        _INDEX = SecondBrainIndex()
    return _INDEX


def reset_index() -> None:
    global _INDEX
    _INDEX = None


def retrieve(query: str, k: int = 6) -> dict[str, Any]:
    return index().search(query, k=k)


def rag_status() -> dict[str, Any]:
    return index().rag_status()


def navigator_context(query: str, k: int = 6) -> dict[str, Any]:
    return index().navigator_context(query, k=k)


def main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    q = " ".join(args).strip() or "Lambda uniqueness conjecture 1"
    hit = retrieve(q, k=6)
    print(json.dumps(hit, indent=2, ensure_ascii=False))
    return 0 if hit.get("ready") else 2


if __name__ == "__main__":
    raise SystemExit(main())