File size: 7,092 Bytes
8fa9876 1b5a84b 8fa9876 1b5a84b 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 1b5a84b 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 179c32c 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 1b5a84b 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 1b5a84b 8fa9876 1b5a84b 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 8e6d561 8fa9876 | 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 | #!/usr/bin/env python3
"""CORTEX knowledge-vault builder v3 — owner directive execution:
clone approved skill repos -> /modules/, AST-extract -> /symbols/schemas/,
sha256 manifests, merge real entries into symbol_evolution_index.json, upload tree.
"""
import ast, hashlib, json, os, subprocess, time
REPO = "Johnny5b/portable-ai-runner"
BASE = "/work"
MODULES = os.path.join(BASE, "modules")
SCHEMAS = os.path.join(BASE, "schemas_out")
SKILLS = [
("EVO_TREE:TINYVERSE", "TinyverseGP", "https://github.com/GPBench/TinyverseGP.git"),
("EVO_OPT:DEAP", "deap", "https://github.com/deap/deap.git"),
("EVO_NEURO:EVOTORCH", "evotorch", "https://github.com/nnaisense/evotorch.git"),
("AGENT:EVA", "eva-evolutional-agent","https://github.com/arturkorb3/eva-evolutional-agent.git"),
("RHETORIC:RST", "isanlp_rst", "https://github.com/tchewik/isanlp_rst.git"),
("RHETORIC:ARG_MINER", "e2e-microtexts", "https://github.com/tchewik/e2e-microtexts.git"),
]
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
MAX_PARSE_BYTES = 300 * 1024
def sh(cmd, cwd=None):
"""cmd: list -> no shell; str -> shell. Never mix."""
if isinstance(cmd, list):
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=900)
else:
r = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True, timeout=900)
return r.returncode, (r.stdout or "") + (r.stderr or "")
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def clone(url, dest):
if os.path.exists(dest):
return sh("git rev-parse HEAD", cwd=dest)[1].strip()
code, out = sh(["git", "clone", "--depth", "1", url, dest])
if code != 0:
raise RuntimeError(f"clone failed {url}: {out[-300:]}")
return sh("git rev-parse HEAD", cwd=dest)[1].strip()
def walk_files(root):
for dirpath, _, files in os.walk(root):
if ".git" in dirpath:
continue
for fn in files:
yield os.path.join(dirpath, fn)
def parse_module(name, root):
fns, classes, nfiles = [], [], 0
for p in walk_files(root):
if not p.endswith(".py") or os.path.getsize(p) > MAX_PARSE_BYTES:
continue
nfiles += 1
try:
src = open(p, encoding="utf-8", errors="ignore").read()
tree = ast.parse(src)
except SyntaxError:
continue
rel = os.path.relpath(p, root)
for node in tree.body:
if isinstance(node, ast.FunctionDef):
fns.append({"file": rel, "name": node.name,
"args": [a.arg for a in node.args.args],
"doc": (ast.get_docstring(node) or "")[:160]})
elif isinstance(node, ast.ClassDef):
ms = [m.name for m in node.body if isinstance(m, ast.FunctionDef)]
classes.append({"file": rel, "name": node.name, "methods": ms,
"doc": (ast.get_docstring(node) or "")[:160]})
return {"module": name, "files_parsed": nfiles, "functions": fns, "classes": classes}, fns, classes
def templates_md(name, fns, classes, commit):
L = [f"# {name} — execution schema",
f"upstream commit: `{commit}` | extractor: stdlib `ast` (no the banned library (owner directive 2026-09-18))",
f"{len(fns)} functions, {len(classes)} classes parsed", "",
"## Function signatures"]
for f in fns[:80]:
sig = ", ".join(f["args"]) or "()"
L.append(f"- `{f['name']}({sig})` — {f['file']}" + (f" · {f['doc']}" if f["doc"] else ""))
if len(fns) > 80:
L.append(f"- … and {len(fns) - 80} more (see {name}.json)")
L += ["", "## Classes"]
for c in classes[:60]:
L.append(f"- `{c['name']}` ({len(c['methods'])} methods) — {c['file']}")
return "\n".join(L) + "\n"
def file_manifest(root):
out = {}
for p in walk_files(root):
if os.path.getsize(p) <= MAX_UPLOAD_BYTES:
out[os.path.relpath(p, root)] = sha256(p)
return out
def main():
from huggingface_hub import HfApi, hf_hub_download
token = os.environ["HF_TOKEN"]
api = HfApi(token=token)
os.makedirs(MODULES, exist_ok=True)
os.makedirs(SCHEMAS, exist_ok=True)
entries = {}
for sym, name, url in SKILLS:
t0 = time.time()
dest = os.path.join(MODULES, name)
commit = sh("git rev-parse HEAD", cwd=dest)[1].strip() if os.path.exists(dest) else clone(url, dest)
parsed, fns, classes = parse_module(name, dest)
json.dump(parsed, open(os.path.join(SCHEMAS, f"{name}.json"), "w"), indent=1)
open(os.path.join(SCHEMAS, f"{name}.md"), "w").write(templates_md(name, fns, classes, commit))
man = file_manifest(dest)
json.dump({"module": name, "commit": commit, "files": len(man), "sha256": man},
open(os.path.join(SCHEMAS, f"{name}.manifest.json"), "w"))
print(f"[OK] {name} symbol:{sym} commit={commit[:12]} files={len(man)} "
f"parsed={len(fns)}f/{len(classes)}c in {time.time() - t0:.0f}s", flush=True)
entries[name] = {"symbol": f"symbol:{sym}", "type": "skill_module",
"path": f"modules/{name}", "upstream": url, "commit": commit,
"schema_md": f"symbols/schemas/{name}.md",
"schema_json": f"symbols/schemas/{name}.json",
"manifest": f"symbols/schemas/{name}.manifest.json",
"status": "active-mirror"}
idx_path = hf_hub_download(REPO, "symbols/symbol_evolution_index.json",
repo_type="dataset", token=token)
idx = json.load(open(idx_path))
idx.setdefault("symbols", {})
for k, v in entries.items():
idx["symbols"][f"symbol:MODULE:{k}"] = v
idx["last_build"] = {"ts": time.time(), "builder": "scripts/build_knowledge_vault.py v3",
"modules": sorted(entries)}
json.dump(idx, open(idx_path, "w"), indent=2)
for name in entries:
api.upload_folder(repo_id=REPO, repo_type="dataset",
folder_path=os.path.join(MODULES, name),
path_in_repo=f"modules/{name}",
commit_message=f"CORTEX vault: module {name} (active-mirror)")
print(f"[UP] modules/{name}", flush=True)
api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=SCHEMAS,
path_in_repo="symbols/schemas",
commit_message="CORTEX vault: AST-extracted schemas")
api.upload_file(repo_id=REPO, repo_type="dataset", path_or_fileobj=idx_path,
path_in_repo="symbols/symbol_evolution_index.json",
commit_message="CORTEX vault: symbol index with sha256 manifests")
print(f"BUILD DONE modules={len(entries)}", flush=True)
if __name__ == "__main__":
main() |