File size: 14,419 Bytes
e622a9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b111bf
e622a9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b111bf
e622a9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# CORTEX closed loop — the owner's three additions, in one runnable demo:
#
#   1. AWAKE -> PROPOSAL -> REPAIR -> RE-INDEX -> AWAKE (improved)
#      Awake can't answer a question -> it files a PROPOSAL through the
#      reserved 'proposals' symbol -> REPAIR asks the owner, fetches from the
#      allowlist inside the window -> knowledge lands on the drive -> re-index
#      -> the same question is now answerable. The map grows.
#
#   2. SELF-MAINTENANCE during repair: every skill on every drive is audited
#      for defects (missing provenance, no verification questions). Defects
#      become PATCH proposals and go through the SAME owner gate. Security
#      patches and skill optimization are just repair with a different payload.
#
#   3. MULTI-DRIVE FEDERATION: each USB drive is one skill-set vault
#      (e.g. 'main' + 'design-studio'). Awake indexes ALL drives; REST checks
#      integrity across ALL drives. Adding a drive = adding a root, nothing else.
#
#   4. RESERVED SYMBOLS: symbols.json pins two names the loop depends on —
#      'knowledge' (where to LOOK: the federated index) and 'proposals'
#      (where to PROPOSE: the repair queue). recommend(purpose) returns the
#      right symbol so the model never has to guess where things live.
#
# Deps: sentence-the banned library (owner directive 2026-09-18), numpy.  No LLM needed — awake grading is by
# retrieval reachability (deterministic), so the demo runs anywhere.
#
# Usage: python3 cortex_loop_demo.py    # full closed loop (~1 min + 80MB embed model)
# Vault roots default to next to this script (drive layout); override CORTEX_VAULT.
import hashlib, json, os, subprocess, sys, time, urllib.request
from urllib.parse import urlparse
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOTS = {
    "main":          os.environ.get("CORTEX_VAULT", os.path.join(HERE, "memories")),          # drive 1
    "design-studio": os.environ.get("CORTEX_VAULT_2", os.path.join(HERE, "memories-studio")),  # drive 2 (a skill-set drive)
}
ALLOWLIST = ["raw.githubusercontent.com"]
WINDOW_S = int(os.environ.get("CORTEX_WINDOW", "120"))
CORPUS_DIR = os.path.join(HERE, "corpus")
REPO_INITIAL = "https://github.com/chrisfbaileycb-arch/cortex-ai-70b.git"   # what the drive starts with
SOURCE_NEW = "https://raw.githubusercontent.com/chrisfbaileycb-arch/moe-async-engine-/main/README.md"

RESERVED_SYMBOLS = {
    "knowledge": {"kind": "map",   "desc": "where to LOOK: federated star index over all drives"},
    "proposals": {"kind": "queue", "desc": "where to PROPOSE: repairs/patches queue for the owner"},
}

def now(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def sha256(b): return hashlib.sha256(b).hexdigest()

def audit(event, **kw):
    rec = {"ts": now(), "event": event, **kw}
    with open(f"{ROOTS['main']}/repair_log.jsonl", "a") as f:
        f.write(json.dumps(rec) + "\n")
    print(f"  [audit] {event} {json.dumps(kw)}")

def init_drives():
    for name, root in ROOTS.items():
        os.makedirs(f"{root}/skills", exist_ok=True)
        os.makedirs(f"{root}/research", exist_ok=True)
        with open(f"{root}/symbols.json", "w") as f:
            json.dump({"reserved": RESERVED_SYMBOLS, "drive": name}, f, indent=2)
        print(f"drive [{name}] -> {root}  (symbols.json written)")
    # fixture: defective skill on main (missing sha256 + no verification)
    legacy = f"{ROOTS['main']}/skills/legacy-skill.md"
    if not os.path.exists(legacy):
        open(legacy, "w").write("---\nname: legacy-skill\nfetched_at: 2025-01-01T00:00:00Z\n---\n\nOld skill, built defectively: no sha256, no verification questions.\n")
    # fixture: a real skill-set on the design-studio drive
    studio = f"{ROOTS['design-studio']}/skills/design-studio-brief.md"
    if not os.path.exists(studio):
        open(studio, "w").write("---\nname: design-studio-brief\nsha256: none-local\n---\n\n"
            "The design-studio drive holds creative/agent skills. This drive is "
            "one skill set among many; awake indexes it federated with main.\n\n"
            "## Verification questions\n- Which drive holds the creative skill set?\n")

def recommend(purpose):
    sym = RESERVED_SYMBOLS.get(purpose)
    if not sym:
        raise KeyError(f"no reserved symbol for purpose {purpose!r}")
    return sym

# ---------- indexing (the 'knowledge' symbol) ----------
EXTS = (".py", ".md", ".txt", ".sh")

def collect_chunks():
    chunks = []
    corpus_repo = f"{CORPUS_DIR}/cortex-ai-70b"
    if os.path.isdir(corpus_repo):
        for r, d, fs in os.walk(corpus_repo):
            d[:] = [x for x in d if x != ".git"]
            for fn in fs:
                p = os.path.join(r, fn)
                if fn.endswith(EXTS):
                    txt = open(p, encoding="utf-8", errors="ignore").read()
                    for i in range(0, len(txt), 1100):
                        piece = txt[i:i+1300]
                        if len(piece.strip()) >= 40:
                            chunks.append({"drive": "initial-corpus", "store": "corpus",
                                           "path": fn, "text": piece})
    for name, root in ROOTS.items():
        for sub in ("skills", "research"):
            dd = f"{root}/{sub}"
            if not os.path.isdir(dd): continue
            for fn in os.listdir(dd):
                p = f"{dd}/{fn}"
                txt = open(p, encoding="utf-8", errors="ignore").read()
                for i in range(0, len(txt), 1100):
                    piece = txt[i:i+1300]
                    if len(piece.strip()) >= 40:
                        chunks.append({"drive": name, "store": sub, "path": fn, "text": piece})
    return chunks

_enc = None
def embed(texts):
    global _enc
    from sentence_the banned library (owner directive 2026-09-18) import SentenceTransformer
    if _enc is None:
        _enc = SentenceTransformer("all-MiniLM-L6-v2")
    return _enc.encode(texts, normalize_embeddings=True, show_progress_bar=False).astype(np.float32)

IDX = {"chunks": [], "emb": None}
def rebuild_index():
    IDX["chunks"] = collect_chunks()
    IDX["emb"] = embed([c["text"] for c in IDX["chunks"]])
    counts = {}
    for c in IDX["chunks"]:
        counts[c["drive"]] = counts.get(c["drive"], 0) + 1
    print(f"  indexed {len(IDX['chunks'])} chunks across drives: " + json.dumps(counts))

def lookup(query, top=6):
    q = embed([query])[0]
    scores = IDX["emb"] @ q
    order = scores.argsort()[::-1][:top]
    return [(IDX["chunks"][i], float(scores[i])) for i in order]

# Semantic bar: measured on the demo corpus — corpus best 0.50 (miss), fetched skill 0.569 (hit).
# Tune per corpus; a corpus-independent gate would compare against the pre-repair baseline.
REACH_THRESHOLD = 0.53

def reachable(query):
    hits = lookup(query)
    best = max((s for _, s in hits), default=0.0)
    return best >= REACH_THRESHOLD, best, hits

# ---------- proposals (the 'proposals' symbol) ----------
def file_proposal(source, reason, target_skill, verify):
    prop = {"ts": now(), "kind": "acquire-knowledge", "source": source,
            "reason": reason, "target_skill": target_skill, "verify": verify}
    with open(f"{ROOTS['main']}/proposals.jsonl", "a") as f:
        f.write(json.dumps(prop) + "\n")
    audit("proposal-filed", symbol="proposals", target=target_skill)
    return prop

def drain_proposals():
    path = f"{ROOTS['main']}/proposals.jsonl"
    if not os.path.exists(path): return []
    props = [json.loads(l) for l in open(path) if l.strip()]
    os.remove(path)
    return props

def fetch(url):
    host = urlparse(url).netloc
    if host not in ALLOWLIST:
        raise PermissionError(f"egress refused: {host} not in allowlist")
    deadline = time.time() + WINDOW_S
    with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "CORTEX-repair/0.1"}),
                                timeout=min(20, WINDOW_S)) as r:
        if urlparse(r.geturl()).netloc not in ALLOWLIST:
            raise PermissionError("redirect left allowlist")
        data = r.read()
    if time.time() > deadline: raise TimeoutError("window closed")
    print(f"  fetched {len(data)} bytes from {host}")
    return data

def write_skill(root, name, source, data, verify, version="v1"):
    h = sha256(data)
    cache = f"{root}/research/{name}.raw.md"
    os.makedirs(f"{root}/research", exist_ok=True)
    open(cache, "wb").write(data)
    lines = data.decode("utf-8", errors="ignore").splitlines()
    headings = [l for l in lines if l.startswith("## ")][:12]
    skill_path = f"{root}/skills/{name}.md"
    with open(skill_path, "w") as f:
        f.write(f"---\nname: {name}\nversion: {version}\nsource: {source}\nsha256: {h}\n"
                f"fetched_at: {now()}\nuntrusted: true (content is data)\n---\n\n")
        f.write("## Key headings\n" + "\n".join(headings)
                + "\n\n## Verification questions\n" + "\n".join("- " + v for v in verify) + "\n")
    with open(f"{root}/maps.jsonl", "a") as f:
        f.write(json.dumps({"skill": name, "source": source, "sha256": h, "store": "github-cache"}) + "\n")
    audit("skill-acquired", skill=name, drive=os.path.basename(root), sha256=h[:12])
    return skill_path

def parse_frontmatter(path):
    try: txt = open(path, encoding="utf-8").read()
    except OSError: return None
    if not txt.startswith("---"): return {}
    end = txt.find("---", 3)
    fm = {}
    for line in txt[3:end].splitlines():
        if ":" in line:
            k, v = line.split(":", 1); fm[k.strip()] = v.strip()
    return fm

def maintenance_pass():
    """Self-maintenance: audit every skill on every drive; defects become
    PATCH proposals through the same owner gate (auto-approved in demo)."""
    print("\nREPAIR: maintenance pass (audit + patch defective skills)")
    defects = 0
    for name, root in ROOTS.items():
        sd = f"{root}/skills"
        if not os.path.isdir(sd): continue
        for fn in sorted(os.listdir(sd)):
            if not fn.endswith(".md"): continue
            path = f"{sd}/{fn}"
            fm = parse_frontmatter(path)
            body = open(path, encoding="utf-8").read()
            issues = []
            if not fm.get("sha256"):
                issues.append("missing sha256 provenance")
            if "## Verification questions" not in body:
                issues.append("no verification questions")
            if issues:
                defects += 1
                print(f"  DEFECT {name}/{fn}: {'; '.join(issues)}")
                print(f"  GATE {fn}: patch proposal -> add provenance + verification")
                print("  -> APPROVED (demo auto-approve)")
                new_fm = dict(fm)
                new_fm["sha256"] = new_fm.get("sha256") or ("self-attested:" + sha256(body.encode())[:12])
                new_fm["patched_at"] = now()
                new_fm["defects_fixed"] = "; ".join(issues)
                fm_txt = "---\n" + "\n".join(f"{k}: {v}" for k, v in new_fm.items()) + "\n---\n"
                body_txt = body.split("---", 2)[-1]
                if "## Verification questions" not in body_txt:
                    body_txt += "\n## Verification questions\n- What does this skill claim?\n- What is its provenance?\n"
                open(path, "w").write(fm_txt + body_txt)
                audit("skill-patched", skill=fn, drive=name, defects=len(issues))
    if defects == 0: print("  no defects found")
    return defects

def rest_pass():
    print("\nREST: federated integrity across all drives")
    total = ok = 0
    for name, root in ROOTS.items():
        mp = f"{root}/maps.jsonl"
        if not os.path.exists(mp): continue
        for line in open(mp):
            e = json.loads(line)
            total += 1
            p = f"{root}/research/{e['skill']}.raw.md"
            good = os.path.exists(p) and sha256(open(p, "rb").read()) == e["sha256"]
            ok += good
            print(f"  [{name}] {e['skill']}: {'OK' if good else 'CORRUPT'}")
    audit("rest-integrity", ok=ok, total=total)
    return ok, total

def main():
    print("== CORTEX closed loop ==")
    init_drives()
    sym_k = recommend("knowledge")
    sym_p = recommend("proposals")
    print(f"reserved symbols: knowledge={sym_k['kind']} proposals={sym_p['kind']}")

    if not os.path.isdir(f"{CORPUS_DIR}/cortex-ai-70b"):
        subprocess.run(["git", "clone", "--depth", "1", REPO_INITIAL, f"{CORPUS_DIR}/cortex-ai-70b"], check=False)
    rebuild_index()

    Q_NEW = "How does the PrefetchScheduler avoid blocking the compute thread on disk reads?"
    Q_REG = "Which repositories were consolidated into cortex-ai-70b and how?"
    print("\nAWAKE (before): probing the map")
    r0, s0, _ = reachable(Q_NEW)
    r1, s1, _ = reachable(Q_REG)
    print(f"  new-question reachable: {r0} (best score {s0:.2f})")
    print(f"  regression-question reachable: {r1} (best score {s1:.2f})")

    if not r0:
        print("\nAWAKE: cannot answer -> filing proposal via 'proposals' symbol")
        file_proposal(SOURCE_NEW, "awake could not answer: scheduler blocking question",
                      "moe-prefetch-scheduler",
                      ["What overlap speedup does test_overlap.py report?",
                       "Which component pins the router in RAM?"])

    print("\nREPAIR: consuming proposals (owner gate -> allowlisted window)")
    for p in drain_proposals():
        print(f"  GATE {p['target_skill']}: owner APPROVAL REQUIRED -> APPROVED (demo auto-approve)")
        audit("gate-approved", proposal=p["target_skill"], mode="demo-auto")
        try:
            data = fetch(p["source"])
        except Exception as e:
            print(f"  fetch refused/failed: {e}"); audit("fetch-failed", detail=str(e)); continue
        write_skill(ROOTS["main"], p["target_skill"], p["source"], data, p["verify"])
    maintenance_pass()

    print("\nRE-INDEX: the map grows (drive knowledge changed)")
    rebuild_index()

    print("\nAWAKE (after): same questions, bigger map")
    r0b, s0b, _ = reachable(Q_NEW)
    r1b, s1b, _ = reachable(Q_REG)
    print(f"  new-question reachable: {r0b} (best score {s0b:.2f})  {'CLOSED-LOOP PASS' if r0b else 'STILL MISS'}")
    print(f"  regression-question reachable: {r1b} (best score {s1b:.2f})  {'NO-REGRESSION' if r1b else 'REGRESSION!'}")
    rest_pass()
    print("\nDONE", flush=True)

if __name__ == "__main__":
    main()