File size: 6,015 Bytes
aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 8e2dcb1 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 8e2dcb1 aa180cf 8e2dcb1 aa180cf 8e2dcb1 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 8e2dcb1 4c515c4 aa180cf 8e2dcb1 aa180cf 8e2dcb1 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 4c515c4 aa180cf 8e2dcb1 4c515c4 aa180cf 4c515c4 aa180cf 8e2dcb1 aa180cf 4c515c4 8e2dcb1 aa180cf 8e2dcb1 aa180cf 8e2dcb1 aa180cf 4c515c4 aa180cf | 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 | #!/usr/bin/env python3
# CORTEX knowledge graph builder — the model's map of its own knowledge.
#
# Reads the drive's actual artifacts (vaults, manifests, cores registry) and emits:
# - knowledge_graph.json {nodes: [...], edges: [...]}
# - knowledge_graph.mmd a mermaid rendering for humans
#
# Nodes: phases, reserved symbols, tiers/cores, models, drives, skills, stores, app.
# Edges: directional pointers only — every edge says WHERE, never what to think.
#
# Usage: python3 cortex_knowledge_graph.py [--root <DRIVE-ROOT>] [--out <path>]
# Deps: stdlib only. Run on the drive after any REPAIR to refresh the graph.
import json, os, re, sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(sys.argv[sys.argv.index("--root") + 1]) if "--root" in sys.argv else os.path.dirname(HERE)
OUT = sys.argv[sys.argv.index("--out") + 1] if "--out" in sys.argv else os.path.join(ROOT, "models", "knowledge_graph.json")
def load_json(path):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except (OSError, json.JSONDecodeError):
return None
def load_jsonl(path):
out = []
try:
with open(path, encoding="utf-8") as f:
for line in f:
if line.strip():
out.append(json.loads(line))
except OSError:
pass
return out
nodes, edges = [], []
_node_ids = set()
def node(nid, ntype, label, **props):
if nid in _node_ids: # dedupe (stores recur across maps.jsonl entries)
return
_node_ids.add(nid)
nodes.append({"id": nid, "type": ntype, "label": label, **props})
def edge(src, dst, rel):
edges.append({"src": src, "dst": dst, "rel": rel})
# ---- phases ----
for p in ["awake", "repair", "rest"]:
node(f"phase:{p}", "phase", p)
edges += [("phase:awake", "phase:repair", "files proposals via 'proposals' symbol"),
("phase:repair", "phase:rest", "hands over for integrity/consolidation"),
("phase:rest", "phase:awake", "re-indexed map")]
# ---- reserved symbols ----
for s, desc in [("knowledge", "where to LOOK: federated index"),
("proposals", "where to PROPOSE: owner-gated queue")]:
node(f"symbol:{s}", "symbol", s, desc=desc)
edges += [("phase:awake", "symbol:knowledge", "looks up via"),
("phase:awake", "symbol:proposals", "files into when it cannot answer"),
("phase:repair", "symbol:proposals", "consumes after owner gate")]
# ---- tiers (models/cores.json) ----
cores = load_json(os.path.join(ROOT, "models", "cores.json")) or {}
tier_ids = []
for tier, info in (cores.get("tiers") or {}).items():
node(f"tier:{tier}", "tier", tier, awake_core=info.get("awake_core", ""))
tier_ids.append(tier)
edges.append((f"tier:{tier}", "phase:awake", "runs the same three phases"))
# ---- models per tier (handles both manifest layouts) ----
MANIFESTS = [("models/models.json", "browser"), ("models/heavy.json", "heavy"), ("models/heavy70.json", "heavy70")]
for rel, tier in MANIFESTS:
m = load_json(os.path.join(ROOT, rel))
if not m:
continue
models = m.get("models") or m.get("heavy_models") or ([m["model"]] if m.get("model") else [])
for mod in models:
if not mod:
continue
mid = mod.get("gguf_repo") or mod.get("repo") or mod.get("id") or mod.get("name", "unknown")
props = {}
for k_src, k_out in (("gguf_file", "file"), ("file", "file"), ("size_on_disk_gb", "size_gb"),
("size_gb", "size_gb"), ("dtype", "dtype"), ("task", "task"),
("measured_gen_tok_s", "measured_gen_tok_s")):
if mod.get(k_src):
props[k_out] = mod[k_src]
node(f"model:{mid}", "model", mid, tier=tier, **props)
edges.append((f"tier:{tier}", f"model:{mid}", "awake core option"))
# ---- drives, skills, stores ----
for dname in ["memories", "memories-studio"]:
dpath = os.path.join(ROOT, dname)
if not os.path.isdir(dpath):
continue
node(f"drive:{dname}", "drive", dname)
edges.append(("symbol:knowledge", f"drive:{dname}", "federated index covers"))
skills_dir = os.path.join(dpath, "skills")
skill_files = os.listdir(skills_dir) if os.path.isdir(skills_dir) else []
for fn in skill_files:
if fn.endswith(".md"):
sid = f"skill:{fn[:-3]}"
node(sid, "skill", fn[:-3], drive=dname)
edges.append((f"drive:{dname}", sid, "holds"))
edges.append(("phase:repair", sid, "acquired/patched via owner gate"))
try:
with open(os.path.join(dpath, "maps.jsonl"), encoding="utf-8") as f:
map_entries = [json.loads(l) for l in f if l.strip()]
except OSError:
map_entries = []
for e in map_entries:
store = e.get("store", "github-cache")
node(f"store:{store}", "store", store)
edges.append((f"skill:{e['skill']}", f"store:{store}", f"points_to {str(e.get('source', '?'))[:60]}"))
# ---- app ----
node("app:runner", "app", "Portable AI Runner (index.html + serve.py)")
for t in tier_ids:
edges.append(("app:runner", f"tier:{t}", "serves"))
# ---- emit ----
edges = [e if isinstance(e, dict) else {"src": e[0], "dst": e[1], "rel": e[2]} for e in edges]
graph = {"generated_by": "scripts/cortex_knowledge_graph.py", "nodes": nodes, "edges": edges}
os.makedirs(os.path.dirname(os.path.abspath(OUT)), exist_ok=True)
with open(OUT, "w", encoding="utf-8") as f:
json.dump(graph, f, indent=2)
def mmd_id(nid):
return re.sub(r"[^A-Za-z0-9_]", "_", nid.replace(":", "_", 1).replace(".", "_"))
mmd = ["graph LR"]
seen = set()
for e in edges:
a, b = mmd_id(e["src"]), mmd_id(e["dst"])
if (a, b) not in seen:
mmd.append(f" {a}[{e['src']}] -->|{e['rel'][:40]}| {b}[{e['dst']}]")
seen.add((a, b))
open(OUT[:-5] + ".mmd", "w", encoding="utf-8").write("\n".join(mmd) + "\n")
print(f"knowledge graph: {len(nodes)} nodes, {len(edges)} edges -> {OUT}") |