GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / tools

Build Layers and 3 more files

A Python command-line tool in the tools folder of Kuiper Belt that reads wafer meta, using SHA-256.

662 lines of Python from kuiper-belt, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1546 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Agent Start storage · kuiper-belt / tools/agent_start.py lines 1–89
  2. Build Layers storage · kuiper-belt / tools/build_layers.py lines 1–249
  3. Cadence storage · kuiper-belt / tools/cadence.py lines 1–147
  4. Check Proof storage · kuiper-belt / tools/check_proof.py lines 1–177

Agent Start

A Python command-line tool in the tools folder of Kuiper Belt that fetches SatNav contracts and kernel, using SHA-256 from GitHub API.

storagekuiper-belt / tools/agent_start.py · lines 1–89 of 89 · Entry point · pattern collect (shared by 23 files)

What it does
It fetches SatNav contracts and kernel. Defines api, collect, render, main. Uses libraries datetime, hashlib, html, json, os. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'agent'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: GitHub API; JSON file LATEST.json; JSON file satnav-source-contracts.json; JSON file STATE.json; JSON file kernel.json; JSON file graph_latest.json; JSON file START.json.
Downstream impact
Used directly by 2 files: Test Agent Start (kuiper-belt); Agent Start Workflow (kuiper-belt).
What it achieves
It is built from the API step (`api`), the collect step (`collect`) and the render step (`render`). Modular agent start: public source identity only, no estate recrawl.
Why it matters
Run by Agent Start Workflow. Checked by Test Agent Start.
Application
kuiper-belt · tools · Python CLI
Uses
Check Proof (import), datetime, hashlib, html, json, os, pathlib, re, urllib.request
Used by
imported by Test Agent Start (import), run by Agent Start Workflow (workflow run)
Produces
api, collect, render, main
Defines here
api, collect, render, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/agent_start.py:1-89 · blob 7c8d5b390d7c02f4220bf1e33b7efa84933e6539 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Modular agent start: public source identity only, no estate recrawl."""
import datetime as dt
import hashlib
import html
import json
import os
from pathlib import Path
import re
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
OWNER = "Ventusltd"
REPOS = {
    "gridatlas": ["tools/satnav/track/recorder.mjs", "tools/satnav/walk/gate/handoff.mjs"],
    "satnav": ["scope/index.html"],
    "spiders": ["AI_NEW_REPO_MEMORY_LOADER.md", "species/genome-spider/receipts/LATEST.json"],
    "vedic-": ["data/satnav-source-contracts.json", "docs/PAGED-COMMAND-REUSE.md"],
    "neural-link-between-agents": ["SESSIONS/2026-12-04-SATNAV-KUIPER-20/STATE.json"],
    "registry_of_all_content_in_repos_and_dependencies": ["registry/kernel.json", "registry/graph_latest.json"],
    "ventus-grid-engine": ["deeplink/contract.js"],
    "globalgrid2050": ["index.html"],
    "gemini": ["context/ACTIVE_TASKS.md"],
}
BASE = "https://ventusltd.github.io/kuiper-belt/agents/"
RAW = "https://raw.githubusercontent.com/Ventusltd/kuiper-belt/main/agents/"
SHA = re.compile(r"^[0-9a-f]{40}$")

def api(path):
    headers = {"Accept": "application/vnd.github+json", "User-Agent": "kuiper-agent-start"}
    if os.environ.get("GITHUB_TOKEN"):
        headers["Authorization"] = "Bearer " + os.environ["GITHUB_TOKEN"]
    req = urllib.request.Request("https://api.github.com/" + path, headers=headers)
    with urllib.request.urlopen(req, timeout=30) as response:
        return json.load(response)

def collect(get=api):
    rows = []
    for name, paths in sorted(REPOS.items()):
        repo = get("repos/"+OWNER+"/"+name)
        if repo.get("private") is not False or repo.get("visibility") != "public" or repo.get("full_name","").lower() != (OWNER+"/"+name).lower():
            raise ValueError("source is not verified public: "+name)
        branch = repo["default_branch"]
        from urllib.parse import quote
        commit = get("repos/"+OWNER+"/"+name+"/commits/"+quote(branch,safe=""))
        key = commit["sha"]
        tree = commit["commit"]["tree"]["sha"]
        stamp = commit["commit"]["committer"]["date"]
        if not SHA.fullmatch(key) or not SHA.fullmatch(tree) or dt.datetime.fromisoformat(stamp.replace("Z","+00:00")).tzinfo is None:
            raise ValueError("invalid key or timestamp")
        # Verify selected paths at the exact revision before publishing their links.
        files = []
        for path in paths:
            f = get("repos/"+OWNER+"/"+name+"/contents/"+quote(path,safe="/")+"?ref="+key)
            if f.get("type") != "file" or f.get("path") != path or not SHA.fullmatch(f.get("sha","")):
                raise ValueError("invalid source file: "+path)
            files.append({"path":path,"blob":f["sha"],"url":"https://github.com/"+OWNER+"/"+name+"/blob/"+key+"/"+path,"raw_url":"https://raw.githubusercontent.com/"+OWNER+"/"+name+"/"+key+"/"+path})
        rows.append({"repository":OWNER+"/"+name,"branch":branch,"commit":key,"tree":tree,"commit_time":stamp,"files":files})
    return rows

def render(rows):
    if not rows or len(rows)!=len(REPOS):
        raise ValueError("incomplete observation")
    manifest={"schema":"kuiper.agent-start.v1","scope":"public default branch source identities; not deployment or acceptance","sources":rows}
    data=(json.dumps(manifest,sort_keys=True,indent=2)+"\n").encode()
    digest=hashlib.sha256(data).hexdigest()
    lines=["# Kuiper — modular agent start","Evidence key before claim. Public default-branch identities, not candidate or production acceptance.","Resolve Kuiper > Vedic > Genome Spider > Spider > exact source. Read only the necessary file.","Canonical JSON SHA-256: "+digest]
    for r in rows:
        lines.append("## "+r["repository"]+" ("+r["branch"]+")\nCommit: "+r["commit"]+"\nTree: "+r["tree"]+"\nCommit time: "+r["commit_time"])
        for f in r["files"]:
            lines.append("- "+f["path"]+" | "+f["blob"]+" | "+f["url"]+" | raw: "+f["raw_url"])
    md="\n\n".join(lines)+"\n"
    h=html.escape
    body="".join("<section><h2>"+h(r["repository"])+"</h2><p>Branch: "+h(r["branch"])+" · Commit time: "+h(r["commit_time"])+"</p><p>Commit <code>"+h(r["commit"])+"</code><br>Tree <code>"+h(r["tree"])+"</code></p><ul>"+"".join('<li><a href="'+h(f["url"],quote=True)+'">'+h(f["path"])+'</a><br>Blob <code>'+h(f["blob"])+'</code><br><a href="'+h(f["raw_url"],quote=True)+'">Pinned raw source</a><br><co  … [line shortened here: 489 characters; full line on GitHub]
    page='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kuiper modular agent start</title><meta name="description" content="Canonical public engineering source keys for Gemini, Claude and ChatGPT"><link rel="canonical" href="https://ventusltd.github.io/kuiper-belt/agents/"><style>body{background:#000;color:#fff;  … [line shortened here: 1,105 characters; full line on GitHub]
    return {"START.json":data,"START.md":md.encode(),"START.html":page.encode(),"index.html":page.encode()}

def main():
    from check_proof import leaks
    outputs=render(collect())
    if any(leaks(x.decode()) for x in outputs.values()):
        raise ValueError("privacy guard refused publication")
    target=ROOT/"agents"
    target.mkdir(exist_ok=True)
    for name,data in outputs.items():
        (target/name).write_bytes(data)
    print("Agent start: "+str(len(REPOS))+" public repositories; SHA-256 "+hashlib.sha256(outputs["START.json"]).hexdigest())

if __name__=="__main__":
    main()

Build Layers

A Python command-line tool in the tools folder of Kuiper Belt that reads wafer meta, using SHA-256.

storagekuiper-belt / tools/build_layers.py · lines 1–249 of 249 · Entry point · pattern palette (shared by 3 files)

What it does
It loads wafer meta. Defines 9 functions or classes, including sha256, palette, space, module_requires, build_editions. Uses libraries argparse, glob, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file wafer-meta.json; JSON file editions.json; JSON file layers.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It builds editions (`build_editions`) and is built from the sha256 step (`sha256`) and the palette step (`palette`). What it writes (and nothing else): `editions/` `/data/editions.json` schema kuiper.editions.v1, one record per edition, built from `editions/README.md` (the "- **Kuiper Edition N** (`stamp`, published date)" lines), the edition's own `README.md` title and the pointer `editions/index.html` (location.replace target). source.bytes. It accepts `--edition` and `--check`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · tools · Python CLI
Uses
argparse, glob, hashlib, json, os, re, sys
Used by
none found
Produces
sha256, palette, space, module_requires, build_editions, features_of, measure, dump, main
Defines here
sha256, palette, space, module_requires, build_editions, features_of, measure, dump, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/build_layers.py:1-249 · blob fd24f225f44ec51943d42ef413debbe8b0796bb9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Build and check the Kuiper layer registry of one edition (NL-010 roadmap step 3, Opus team 3).

    python3 tools/build_layers.py --edition 202611012135          # write data/editions.json, then measure layers.json
    python3 tools/build_layers.py --edition 202611012135 --check  # change nothing; exit 1 on any difference or refusal

What it writes (and nothing else):
  editions/<stamp>/data/editions.json  schema kuiper.editions.v1, one record per edition, built from editions/README.md
                                       (the "- **Kuiper Edition N** (`stamp`, published date)" lines), the edition's own
                                       README.md title and the pointer editions/index.html (location.replace target).
  editions/<stamp>/data/layers.json    schema kuiper.layers.v1; for every record whose source names a file it writes
                                       source.bytes, source.features and source.sha256 measured from that file.

What it refuses (exit 1, the reason printed, nothing written), as galaxies-wafers' builder "refuses to write a key the
numbered database does not contain" (galaxies-wafers@fff6fc6 README.md:18):
  - a colour that is not one of PALETTE.md's hexes (kuiper-belt PALETTE.md:9-14, :19);
  - a key outside SPACE (cosmos/wafer-meta.json "address_space"), for a keys.json body placed on the wafer or for any
    geometry key of a code-feature-collection.v1 file;
  - a record whose `requires` is not within the `requires` of the module it names (team-2/STEPS.md 3.1);
  - a record whose key is not `layer:<id>`, an id twice, an `order` that does not name every record exactly once,
    an empty licence, a format the registry does not admit.

Licence: Apache-2.0 (kuiper-belt code). The files it writes are CC BY 4.0 (kuiper-belt data, README.md:156-157).
"""
import argparse
import glob
import hashlib
import json
import os
import re
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FORMATS = {"edition-keys.v1", "code-feature-collection.v1", "kuiper.editions.v1", "engine"}


def sha256(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


def palette():
    text = open(os.path.join(ROOT, "PALETTE.md"), encoding="utf-8").read()
    hexes = set()
    for line in text.splitlines():
        if line.startswith("|") and "`#" in line and "near-black" not in line:
            hexes.update(h.lower() for h in re.findall(r"`(#[0-9a-fA-F]{6})`", line))
    return hexes


def space():
    meta = json.load(open(os.path.join(ROOT, "cosmos", "wafer-meta.json"), encoding="utf-8"))
    return int(meta["address_space"])


def module_requires(edition_dir, module):
    """The `requires` the module file itself declares (the list the loader checks, ROADMAP 4.4)."""
    if not module:
        return None, "no module named"
    path = os.path.join(edition_dir, "modules", module)
    if not module.endswith(".js"):
        cands = sorted(glob.glob(os.path.join(edition_dir, "modules", "*-" + module + ".js")))
        if not cands:
            return None, "module " + module + " not yet cut"
        path = cands[-1]
    if not os.path.exists(path):
        return None, "module file " + module + " not yet cut"
    src = open(path, encoding="utf-8").read()
    m = re.search(r"REQUIRES\s*=\s*\[([^\]]*)\]", src) or re.search(r"requires\s*:\s*\[([^\]]*)\]", src)
    if not m:
        return None, "module " + os.path.basename(path) + " declares no requires"
    return set(re.findall(r"['\"]([A-Za-z0-9_-]+)['\"]", m.group(1))), os.path.basename(path)


def build_editions(edition, edition_dir):
    readme = os.path.join(ROOT, "editions", "README.md")
    rows = []
    pat = re.compile(r"^- \*\*Kuiper Edition (\d+)\*\* \(`(\d{12})`, published (\d{4}-\d\d-\d\d)\)")
    for n, line in enumerate(open(readme, encoding="utf-8"), 1):
        m = pat.match(line)
        if m:
            rows.append({"number": int(m.group(1)), "stamp": m.group(2), "published": m.group(3),
                         "status": "published", "evidence": "editions/README.md:%d" % n})
    own = os.path.join(edition_dir, "README.md")
    first = open(own, encoding="utf-8").readline()
    m = re.match(r"^# Kuiper Edition (\d+) \((\d{12})\)", first)
    if m and m.group(2) == edition and not any(r["stamp"] == edition for r in rows):
        rows.append({"number": int(m.group(1)), "stamp": edition, "published": None,
                     "status": "under construction", "evidence": "editions/%s/README.md:1" % edition})
    ptr = open(os.path.join(ROOT, "editions", "index.html"), encoding="utf-8").read()
    pm = re.search(r"location\.replace\('(\d{12})/'", ptr)
    pointer = pm.group(1) if pm else None
    rows.sort(key=lambda r: r["number"])
    for r in rows:
        s = r["stamp"]
        r["key"] = "edition:" + s
        r["cut_utc"] = "%s-%s-%sT%s:%s:00Z" % (s[0:4], s[4:6], s[6:8], s[8:10], s[10:12])
        r["path"] = "../" + s + "/"
        r["pointer"] = s == pointer
    return {"schema": "kuiper.editions.v1", "edition": edition,
            "licence": "CC BY 4.0 (kuiper-belt data, README.md:156-157)",
            "built_by": "tools/build_layers.py",
            "sources": ["editions/README.md", "editions/%s/README.md:1" % edition, "editions/index.html (location.replace)"],
            "pointer": pointer, "editions": rows}


def features_of(fmt, data, path, SPACE, refuse):
    if fmt == "kuiper.editions.v1":
        return len(data["editions"])
    if fmt == "kuiper.elements.v1":
        return len(data.get("elements", []))
    if fmt == "edition-keys.v1":
        bodies = data.get("bodies", data) if isinstance(data, dict) else data
        for b in bodies:
            if b.get("on_wafer") and b.get("verified"):
                k = b.get("key")
                if not isinstance(k, int) or not (0 <= k < SPACE):
                    refuse("%s: key %r of %s outside SPACE %d" % (path, k, b.get("id"), SPACE))
        return len(bodies)
    if fmt == "code-feature-collection.v1":
        fs = data.get("features", [])
        for f in fs:
            g = f.get("geometry") or {}
            keys = [g["key"]] if "key" in g else list(g.get("keys", []))
            for k in keys:
                if not isinstance(k, int) or not (0 <= k < SPACE):
                    refuse("%s: geometry key %r outside SPACE %d" % (path, k, SPACE))
        return len(fs)
    return 0


def measure(f, r, edir, etext, editions, SPACE, refuse):
    """bytes, features and sha256 of one source file of record r (None when the record names no file)."""
    if not f:
        return None
    if f == "data/editions.json":
        raw, data = etext.encode("utf-8"), editions
    else:
        p = os.path.join(edir, f)
        if not os.path.exists(p):
            refuse("%s: source file %s does not exist" % (r["id"], f))
            return None
        raw = open(p, "rb").read()
        data = json.loads(raw.decode("utf-8"))
    return {"bytes": len(raw), "features": features_of(r["format"], data, f, SPACE, refuse),
            "sha256": hashlib.sha256(raw).hexdigest()}


def dump(obj):
    return json.dumps(obj, indent=1, ensure_ascii=False) + "\n"


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--edition", required=True)
    ap.add_argument("--check", action="store_true", help="write nothing; exit 1 if any file would change")
    a = ap.parse_args()
    edir = os.path.join(ROOT, "editions", a.edition)
    lpath = os.path.join(edir, "data", "layers.json")
    epath = os.path.join(edir, "data", "editions.json")
    reasons = []
    refuse = reasons.append
    PAL, SPACE = palette(), space()

    editions = build_editions(a.edition, edir)
    etext = dump(editions)
    L = json.load(open(lpath, encoding="utf-8"))
    if L.get("schema") != "kuiper.layers.v1":
        refuse("layers.json schema %r is not kuiper.layers.v1" % L.get("schema"))
    ids = [r["id"] for r in L["layers"]]
    if len(set(ids)) != len(ids):
        refuse("an id appears twice: %s" % ids)
    if sorted(L["order"]) != sorted(ids) or len(set(L["order"])) != len(L["order"]):
        refuse("order %s does not name every record exactly once %s" % (L["order"], ids))

    pending = {}
    for r in L["layers"]:
        rid = r["id"]
        if r.get("key") != "layer:" + rid:
            refuse("%s: key %r is not layer:%s" % (rid, r.get("key"), rid))
        if str(r.get("colour", "")).lower() not in PAL:
            refuse("%s: colour %s is not in PALETTE.md %s" % (rid, r.get("colour"), sorted(PAL)))
        if not r.get("licence"):
            refuse("%s: empty licence" % rid)
        if r.get("format") not in FORMATS:
            if str(r.get("licence", "")).upper().startswith("UNSETTLED"):
                print("note  %-11s format %s not admitted; the record is REFUSED at run time for its licence first" % (rid, r.get("format")))
            else:
                refuse("%s: format %r not admitted" % (rid, r.get("format")))
        for f in ("label", "group", "meaning", "draws", "source", "requires", "module"):
            if f not in r:
                refuse("%s: field %s missing" % (rid, f))
        mreq, mname = module_requires(edir, r.get("module"))
        if mreq is None:
            print("note  %-11s requires not checked: %s" % (rid, mname))
        else:
            extra = set(r.get("requires", [])) - mreq
            if extra:
                refuse("%s: requires %s not within module %s requires" % (rid, sorted(extra), mname))
        src = r.get("source", {})
        for key, part in (("", src), ("fallback", src.get("fallback") or {})):
            m = measure(part.get("file"), r, edir, etext, editions, SPACE, refuse)
            if m:
                pending[(rid, key)] = m

    if reasons:
        for x in reasons:
            print("REFUSED " + x)
        print("RESULT: REFUSED (%d)" % len(reasons))
        return 1
    changed = []
    for r in L["layers"]:
        for key in ("", "fallback"):
            if (r["id"], key) not in pending:
                continue
            tgt = r["source"] if not key else r["source"]["fallback"]
            for k, v in pending[(r["id"], key)].items():
                if tgt.get(k) != v:
                    changed.append("%s.source%s.%s %r -> %r" % (r["id"], "." + key if key else "", k, tgt.get(k), v))
                    tgt[k] = v
    ltext = dump(L)
    old_e = open(epath, encoding="utf-8").read() if os.path.exists(epath) else None
    old_l = open(lpath, encoding="utf-8").read()
    if old_e != etext:
        changed.append("data/editions.json")
    if old_l != ltext and not changed:
        changed.append("data/layers.json (format)")
    for r in L["layers"]:
        s = r["source"]
        print("layer %-11s %-26s %-8s %s" % (r["id"], s.get("file") or s.get("engine") or "-",
                                            s.get("features", ""), (s.get("sha256") or "")[:12]))
    if a.check:
        for c in changed:
            print("DIFF  " + c)
        print("RESULT: " + ("PASS" if not changed else "FAIL (%d differences)" % len(changed)))
        return 0 if not changed else 1
    os.makedirs(os.path.dirname(epath), exist_ok=True)
    with open(epath, "w", encoding="utf-8") as fh:
        fh.write(etext)
    with open(lpath, "w", encoding="utf-8") as fh:
        fh.write(ltext)
    for c in changed:
        print("wrote " + c)
    print("RESULT: PASS (written)")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Cadence

A Python command-line tool in the tools folder of Kuiper Belt that reads published, verdict, swarm and held.

storagekuiper-belt / tools/cadence.py · lines 1–147 of 147 · Entry point · pattern candidate (shared by 5 files)

What it does
It loads published, verdict, swarm and held. Defines say, state, candidate, look, main. Uses libraries io, json, os, re, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file published.json; JSON file verdict.json; JSON file swarm.json; command-line arguments. Out: JSON file held.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the say step (`say`), the state step (`state`) and the candidate step (`candidate`). Publish the next tested iteration every twenty minutes, with no assistant in the loop.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · tools · Python CLI
Uses
Swarm (script call), Publish Proof (script call), io, json, os, re, subprocess, sys, time, datetime
Used by
none found
Produces
say, state, candidate, look, main
Defines here
say, state, candidate, look, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/cadence.py:1-147 · blob b958f24599d16cb1ab4320e1dae37a1505f2efc2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
r"""tools/cadence.py - publish the next tested iteration every twenty minutes, with no assistant in the loop.

    python tools/cadence.py --until 2026-09-20T16:30        run until that local time
    python tools/cadence.py --once                          one look, then stop

Publishing must not cost an assistant a step. Assistants build iterations in E:\kuiper-iterations and
test them with tools/iterate.py. This script, plain Python on the desktop machine, looks once a minute.
When twenty minutes have passed since the last publication it takes the OLDEST iteration that

    has a verdict with full marks (every self test PASS, data sums, no private digest, scripts parse),
    was tested AFTER its pages were last edited (so a half edited folder is never published),
    and has not been published before,

and hands it to tools/publish_proof.py, which has its own twenty minute rule and its own privacy
guard. IF NOTHING QUALIFIES IT PUBLISHES NOTHING. An empty slot is a true record; a padded one is not.
Every decision is written to E:\kuiper-iterations\LOG.md, once per change, not once per minute.
"""
import io
import json
import os
import re
import subprocess
import sys
import time
from datetime import datetime

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = r'E:\kuiper-iterations'
SITE = os.path.join(HERE, '..', '..', '_wt-estate')
STATE = os.path.join(ROOT, 'published.json')
LOG = os.path.join(ROOT, 'LOG.md')
GAP = 1200
_last_said = [None]
HELD = {}                                                       # iteration -> why it is being held, shown on the HUD


def say(msg):
    if msg != _last_said[0]:
        _last_said[0] = msg
        line = '%s  %s\n' % (datetime.now().strftime('%Y-%m-%d %H:%M'), msg)
        io.open(LOG, 'a', encoding='utf-8', newline='\n').write(line)
        print(line, end='', flush=True)


def state():
    return json.load(io.open(STATE, encoding='utf-8')) if os.path.exists(STATE) else {'published': {}, 'last': 0}


def candidate(done):
    for d in sorted(x for x in os.listdir(ROOT) if re.match(r'^\d{4}$', x)):
        if d in done or d == '0001':                                # 0001 is the baseline, already public
            continue
        f = os.path.join(ROOT, d)
        if os.path.exists(os.path.join(f, 'SUPERSEDED.txt')):       # a later iteration carries this one's work: not waiting, not a fault
            HELD.pop(d, None)
            continue
        v = os.path.join(f, 'verdict.json')
        if not os.path.exists(v):
            continue
        verdict = json.load(io.open(v, encoding='utf-8'))
        if verdict['score'] != verdict['out_of']:
            continue
        pages = [os.path.join(f, p) for p in os.listdir(f) if p.endswith('.html')]
        if any(os.path.getmtime(p) > os.path.getmtime(v) for p in pages):
            continue                                                # edited after it was tested: test it again first
        newest = max(os.path.getmtime(p) for p in pages)
        # THE RELEASE GATE. Three healthy phases and a sound earth (tools/swarm.py), then a written review by L1 or L2.
        sw = os.path.join(f, 'swarm.json')
        if not os.path.exists(sw) or os.path.getmtime(sw) < newest:
            subprocess.run([sys.executable, os.path.join(HERE, 'swarm.py'), d], capture_output=True, text=True, timeout=600)
        if not os.path.exists(sw):
            HELD[d] = 'the swarm could not run'
            continue
        swarm = json.load(io.open(sw, encoding='utf-8'))
        if not swarm.get('release_ready'):
            bad = [k for k in ('L1', 'L2', 'L3') if not swarm.get(k, {}).get('healthy')] + ([] if swarm.get('E', {}).get('sound', True) else ['EARTH'])
            HELD[d] = 'fault on ' + ' '.join(bad)
            continue
        rv = os.path.join(f, 'REVIEW.md')
        first = io.open(rv, encoding='utf-8').read().strip().split('\n')[0].upper() if os.path.exists(rv) else ''
        if not os.path.exists(rv) or os.path.getmtime(rv) < newest:
            HELD[d] = 'waiting for a written review by L1 or L2'
            continue
        if not first.startswith('PASS'):
            HELD[d] = 'review says: ' + first[:80]
            continue
        HELD.pop(d, None)
        return d, verdict
    return None, None


def look():
    st = state()
    wait = GAP - (time.time() - st['last'])
    d, verdict = candidate(st['published'])                         # looked at every minute, so the swarm runs and the HUD knows why a thing is held
    if wait > 0:
        json.dump(HELD, io.open(os.path.join(ROOT, 'held.json'), 'w', encoding='utf-8', newline='\n'), indent=1)
        return
    json.dump(HELD, io.open(os.path.join(ROOT, 'held.json'), 'w', encoding='utf-8', newline='\n'), indent=1)
    if not d:
        say('slot open, nothing released: ' + ('; '.join('%s %s' % kv for kv in sorted(HELD.items())) or 'nothing tested and waiting'))
        return
    f = os.path.join(ROOT, d)
    note = io.open(os.path.join(f, 'NOTE.md'), encoding='utf-8').read().strip()
    first = note.split('\n')[0][:110]
    proof = os.path.join(f, 'PROOF.md')
    tests = '\n'.join('- `%s`: %s' % (k, t['title']) for k, t in verdict['selftests'].items())
    io.open(proof, 'w', encoding='utf-8', newline='\n').write(
        '# Iteration %s\n\n%s\n\n## Tested unattended before publishing\n\nScore %d of %d, %s.\n\n%s\n\n'
        'Built and tested locally, published by a Python timer with no assistant in the loop.\n'
        'Provided as is, without warranty of any kind; a chart, not a design.\n'
        % (d, note, verdict['score'], verdict['out_of'], verdict['tested'], tests))
    subprocess.run(['git', 'fetch', '-q', 'origin'], cwd=SITE)
    subprocess.run(['git', 'merge', '-q', '--ff-only', 'origin/main'], cwd=SITE, capture_output=True)
    r = subprocess.run([sys.executable, os.path.join(HERE, 'publish_proof.py'), 'k' + d, first, first, proof, f],
                       capture_output=True, text=True)
    out = (r.stdout + r.stderr).strip().split('\n')
    if r.returncode == 0:
        st['published'][d] = {'at': datetime.now().strftime('%Y-%m-%dT%H:%M'), 'url': out[-1]}
        st['last'] = time.time()
        json.dump(st, io.open(STATE, 'w', encoding='utf-8', newline='\n'), indent=1)
        say('PUBLISHED %s  %s' % (d, out[-1]))
    else:
        say('NOT published %s: %s' % (d, out[-1][:160]))


def main():
    a = sys.argv[1:]
    os.makedirs(ROOT, exist_ok=True)
    if '--once' in a:
        look()
        return 0
    until = datetime.fromisoformat(a[a.index('--until') + 1]) if '--until' in a else None
    say('cadence started, one publication per %d minutes at most%s' % (GAP // 60, ', until ' + until.isoformat() if until else ''))
    while not until or datetime.now() < until:
        try:
            look()
        except Exception as e:
            say('cadence error, carrying on: %r' % (e,))
        time.sleep(60)
    say('cadence stopped at its set time')
    return 0


if __name__ == '__main__':
    sys.exit(main())

Check Proof

A Python command-line tool in the tools folder of Kuiper Belt that fetches wafer meta, using SHA-256.

storagekuiper-belt / tools/check_proof.py · lines 1–177 of 177 · Entry point

What it does
It fetches wafer meta. Defines 7 functions or classes, including leaks, status, rows, check, write. Uses libraries hashlib, io, json, os, re. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file wafer-meta.json; JSON file CHECKS.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 9 files: Agent Start (kuiper-belt); CI Check (kuiper-belt); Element Keys (kuiper-belt); Explore Code (kuiper-belt); and 5 more. Reached from 16 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Modes (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html).
What it achieves
It is built from the leaks step (`leaks`), the status step (`status`) and the rows step (`rows`). THE CHECKING ENGINEER. Independent of whoever built the proof.
Why it matters
Imported by 9 files, including Agent Start, CI Check and Element Keys.
Application
kuiper-belt · tools · Python CLI
Uses
Testcode — Wafer Development Environment Page (estate URL), hashlib, io, json, os, re, subprocess, sys, time
Used by
imported by Agent Start (import), imported by CI Check (import), imported by Element Keys (import), imported by Explore Code (import), imported by Harvest (import), imported by Iterate (import), imported by Publish Proof (import), imported by Swarm (import), and 1 more
Produces
leaks, status, rows, check, write, proofs, main
Defines here
leaks, status, rows, check, write, proofs, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/check_proof.py:1-177 · blob 12994877c4585edf478f4f599d918fcf6677c8c6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
r"""tools/check_proof.py - THE CHECKING ENGINEER. Independent of whoever built the proof.

A proof is not checked by its author. Every proof published under "Kuiper: proofs" is examined
here by a separate process that did not write it, on the measuring machine, for nothing:

  C1  it is actually live: the page, its data and its PROOF.md answer 200 on globalgrid2050.com
  C2  the published data adds up: wafer.tsv re-summed equals wafer-meta.json, issued and silent
  C3  no name that is not public appears anywhere in what was published (grid law L6)
  C4  PROOF.md ends with the disclaimer and claims no number the data contradicts
  C5  three random keys from the PUBLISHED data resolve, by git alone, to a real line of text
  C6  a second opinion: a local model reads PROOF.md against the facts and hunts unsupported
      numbers. Its answer is a CANDIDATE. Only numbers it names that are genuinely absent from
      the facts are reported, and nothing it says can pass or fail a proof by itself.

    python tools/check_proof.py --watch-until 15:00      poll for new proofs until HH:MM UTC
    python tools/check_proof.py <proof directory name>   check one

Verdicts go to E:\particles-runs\checks\ as CHECK-<proof>.md and CHECKS.json. The checker never
edits a proof, never publishes and never commits: a checking engineer who can change the drawing
is not checking it.

THE GUARD DOES NOT SPELL WHAT IT GUARDS. An earlier guard listed the private repository names in
plain text inside a public repository, which is the leak it existed to prevent. Names are held
here as truncated SHA-256 digests, and text is checked by hashing every token in it.
"""
import hashlib
import io
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
SITE = os.path.join(HERE, '..', '..', '_wt-estate', 'testcode', 'wafer-development-environment')
LIVE = 'https://globalgrid2050.com/testcode/wafer-development-environment/'
OUT = r'E:\particles-runs\checks'
NOT_PUBLIC = {'49bef650dc462eb9628e123c', '485b71c91c9d26f6893e7b85', '9261ceef0b969e70ac20f151',
              'e10931bb0448851a45510bb9', '627a4b71075931067036fffe', '5a5926e194270c1482f3f813'}
DISCLAIMER = 'without warranty of any kind'


def leaks(text):
    """Every run of name characters is hashed, whole and with its leading path stripped, and
    compared with the digests. Returns how many tokens matched, never which."""
    n = 0
    for tok in set(re.findall(r'[A-Za-z0-9_][A-Za-z0-9_.-]*', text)):
        for t in {tok, tok.rstrip('.'), tok.split('/')[-1]}:
            if hashlib.sha256(t.lower().encode()).hexdigest()[:24] in NOT_PUBLIC:
                n += 1
    return n


def status(url):
    try:
        req = urllib.request.Request(url + '?t=%d' % time.time(), headers={'User-Agent': 'check'})
        with urllib.request.urlopen(req, timeout=25) as r:
            return r.status
    except Exception as e:
        return getattr(e, 'code', 0) or 0


def rows(path):
    return [l.rstrip('\n').split('\t') for l in io.open(path, encoding='utf-8')
            if l.strip() and not l.startswith('#')]


def check(name):
    d = os.path.join(SITE, name)
    res, notes = {}, []
    # C1 live
    codes = {f: status(LIVE + name + '/' + f) for f in ('', 'cosmos/wafer.tsv', 'PROOF.md')}
    res['C1_live'] = all(c == 200 for c in codes.values())
    notes.append('C1 live: ' + ', '.join('%s %s' % (k or 'index', v) for k, v in codes.items()))
    if not res['C1_live']:
        return None, notes                                   # not deployed yet: come back later
    # C2 sums
    w = rows(os.path.join(d, 'cosmos', 'wafer.tsv'))
    meta = json.load(io.open(os.path.join(d, 'cosmos', 'wafer-meta.json'), encoding='utf-8'))
    issued, silent = sum(int(r[1]) for r in w), sum(int(r[4]) for r in w)
    res['C2_sums'] = issued == meta['issued_keys'] and silent == meta['unissued_keys'] and len(w) == meta['commits']
    notes.append('C2 sums: issued %s vs %s, silent %s vs %s, commits %d vs %d'
                 % (format(issued, ','), format(meta['issued_keys'], ','), format(silent, ','),
                    format(meta['unissued_keys'], ','), len(w), meta['commits']))
    # C3 privacy, over every published file including the tools
    hits = 0
    for root, _, files in os.walk(d):
        for f in files:
            hits += leaks(io.open(os.path.join(root, f), encoding='utf-8', errors='replace').read())
    res['C3_no_private_names'] = hits == 0
    notes.append('C3 privacy: %d tokens matched a digest of a name that is not public' % hits)
    # C4 the proof text
    proof = io.open(os.path.join(d, 'PROOF.md'), encoding='utf-8').read()
    res['C4_disclaimer'] = DISCLAIMER in proof
    big = [int(x.replace(',', '')) for x in re.findall(r'\b\d{1,3}(?:,\d{3}){2,}\b', proof)]
    known = {issued, silent, issued + silent} | {int(r[1]) for r in w}
    notes.append('C4 text: disclaimer %s; %d large numbers quoted, %d of them are totals of the published data'
                 % ('present' if res['C4_disclaimer'] else 'MISSING', len(big), sum(1 for b in big if b in known)))
    # C5 keys from the PUBLISHED data, resolved by git on this machine
    sys.path.insert(0, HERE)
    import key as K
    K.COSMOS = os.path.join(d, 'cosmos')
    K.load_cache()
    commits, space, n = K.load()
    import random
    ok = 0
    for _ in range(3):
        msg, code = K.resolve(commits, space, K.key_of_line(commits, random.randrange(n)))
        ok += (code == 0)
    res['C5_keys_resolve'] = ok == 3
    notes.append('C5 keys: %d of 3 random keys from the published data resolved to text by git' % ok)
    # C6 a second opinion, advisory only
    try:
        facts = json.dumps(meta)
        body = json.dumps({'model': 'qwen2.5-coder:14b', 'stream': False, 'options': {'temperature': 0, 'num_predict': 200},
                           'prompt': 'FACTS (JSON):\n%s\n\nTEXT:\n%s\n\nList ONLY numbers in TEXT that contradict FACTS. '
                                     'One per line. If none, answer NONE.' % (facts, proof[:3000])}).encode()
        req = urllib.request.Request('http://127.0.0.1:11434/api/generate', data=body, headers={'Content-Type': 'application/json'})
        with urllib.request.urlopen(req, timeout=240) as r:
            ans = json.load(r).get('response', '').strip()
        notes.append('C6 local model (advisory, a candidate, never a verdict): ' + ans.replace('\n', ' | ')[:300])
    except Exception as e:
        notes.append('C6 local model did not answer: %s' % e)
    return res, notes


def write(name, res, notes):
    os.makedirs(OUT, exist_ok=True)
    verdict = 'PASS' if all(res.values()) else 'FAIL'
    now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
    io.open(os.path.join(OUT, 'CHECK-%s.md' % name), 'w', encoding='utf-8', newline='\n').write(
        '# Check of %s: %s\n\nChecked %s by tools/check_proof.py, which did not build it.\n\n%s\n\n%s\n'
        % (name, verdict, now, '\n'.join('- %s: %s' % (k, 'pass' if v else 'FAIL') for k, v in res.items()),
           '\n'.join('- ' + n for n in notes)))
    p = os.path.join(OUT, 'CHECKS.json')
    allc = json.load(io.open(p, encoding='utf-8')) if os.path.exists(p) else {}
    allc[name] = {'verdict': verdict, 'checked': now, 'checks': res}
    json.dump(allc, io.open(p, 'w', encoding='utf-8', newline='\n'), indent=1)
    print('%s %s %s' % (now, name, verdict), flush=True)


def proofs():
    return sorted(x for x in os.listdir(SITE) if re.match(r'^\d{12}-(proof-\d+|one-wafer)$', x))


def main():
    if len(sys.argv) == 3 and sys.argv[1] == '--watch-until':
        hh, mm = [int(x) for x in sys.argv[2].split(':')]
        done = set()
        while (datetime.now(timezone.utc).hour, datetime.now(timezone.utc).minute) < (hh, mm):
            for name in proofs():
                if name in done:
                    continue
                try:
                    res, notes = check(name)
                except Exception as e:
                    res, notes = {'checker_ran': False}, ['the checker itself failed: %r' % e]
                if res is None:
                    continue                                     # not live yet
                write(name, res, notes)
                done.add(name)
            time.sleep(90)
        return 0
    res, notes = check(sys.argv[1])
    if res is None:
        print('not live yet: ' + '; '.join(notes))
        return 3
    write(sys.argv[1], res, notes)
    return 0 if all(res.values()) else 1


if __name__ == '__main__':
    sys.exit(main())