In this section
- Harvest ingest · kuiper-belt / tools/harvest.py lines 1–128
- Iterate storage · kuiper-belt / tools/iterate.py lines 1–195
- Publish Proof other · kuiper-belt / tools/publish_proof.py lines 1–104
- Swarm storage · kuiper-belt / tools/swarm.py lines 1–164
- Test Agent Start test · kuiper-belt / tools/test_agent_start.py lines 1–39
Harvest
A Python command-line tool in the tools folder of Kuiper Belt using data from GitHub API.
ingestkuiper-belt / tools/harvest.py · lines 1–128 of 128 · Entry point · pattern public_repos (shared by 3 files)
- What it does
- It fetches data. Defines public_repos, force_rm, on_err, measure, main. Uses libraries io, json, os, shutil, subprocess. 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: data source: GitHub API; command-line arguments.
- Downstream impact
- Used directly by 1 file: Engine Workflow (kuiper-belt).
- What it achieves
- It is built from the public repos helper (`public_repos`), the force rm helper (`force_rm`) and the on err helper (`on_err`). The engine that runs with nobody paying and nobody watching.
- Why it matters
- Run by Engine Workflow.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- Check Proof (import), io, json, os, shutil, subprocess, sys, tempfile, time
- Used by
- run by Engine Workflow (workflow run)
- Produces
- public_repos, force_rm, measure, main
- Defines here
- public_repos, force_rm, on_err, measure, 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/harvest.py:1-128 · blob a5fce3ef41ef7df1b7ef7938ec8822a1f1678c09 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
r"""tools/harvest.py - the engine that runs with nobody paying and nobody watching.
python tools/harvest.py [--limit N]
Run by .github/workflows/engine.yml on GitHub's own machine, on a timer. It needs no local clone,
no graphics card and no assistant. It asks GitHub which repositories of this account are PUBLIC,
takes the newest snapshot of each, counts the files and the lines standing in it now, and writes:
cosmos/standing.tsv one row per public repository: name, head, time of head, files, lines
cosmos/pulse.tsv one row added per run: time, repositories, files, lines
pulse.tsv is the record of the future arriving: every run adds one row and never rewrites an old
one, so the growth of the estate is measured from the day this was switched on.
SAFEGUARDS. It asks only for public repositories and skips anything marked private anyway. Before
writing, everything it is about to write is passed through the digest guard; one match and it
writes nothing and exits 2. A repository that cannot be cloned is recorded as missed, not guessed.
If more than a fifth are missed the run fails and writes nothing, so a bad night cannot look like
the estate shrinking.
"""
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.join(HERE, '..')
OWNER = 'Ventusltd'
sys.path.insert(0, HERE)
from check_proof import leaks
def public_repos():
out, page = [], 1
while True:
req = urllib.request.Request('https://api.github.com/users/%s/repos?type=owner&per_page=100&page=%d' % (OWNER, page),
headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'kuiper-harvest'})
tok = os.environ.get('GITHUB_TOKEN')
if tok:
req.add_header('Authorization', 'Bearer ' + tok)
rows = json.load(urllib.request.urlopen(req, timeout=60))
if not rows:
break
out += [r for r in rows if not r.get('private') and r.get('visibility', 'public') == 'public' and r.get('size', 0) > 0]
page += 1
return sorted(out, key=lambda r: r['name'].lower())
def force_rm(path):
def on_err(fn, p, _):
os.chmod(p, 0o700)
fn(p)
shutil.rmtree(path, onerror=on_err)
def measure(repo, tmp):
d = os.path.join(tmp, 'r')
if os.path.exists(d):
force_rm(d)
r = subprocess.run(['git', 'clone', '-q', '--depth', '1', repo['clone_url'], d], capture_output=True, text=True, timeout=900)
if r.returncode:
return None
g = lambda *a: subprocess.run(['git'] + list(a), cwd=d, capture_output=True, text=True).stdout.strip()
head, when = g('rev-parse', 'HEAD')[:12], int(g('log', '-1', '--format=%ct') or 0)
files = lines = 0
for f in subprocess.run(['git', 'ls-files', '-z'], cwd=d, capture_output=True).stdout.split(b'\0'):
p = os.path.join(d.encode(), f)
if not f or os.path.islink(p) or not os.path.isfile(p):
continue
body = open(p, 'rb').read()
if b'\0' in body[:8192]:
continue # not text: it has no lines
files += 1
lines += body.count(b'\n') + (1 if body and not body.endswith(b'\n') else 0)
force_rm(d)
return head, when, files, lines
def main():
a = sys.argv[1:]
limit = int(a[a.index('--limit') + 1]) if '--limit' in a else 0
repos = public_repos()
if limit:
repos = repos[:limit]
tmp = tempfile.mkdtemp(prefix='harvest-')
rows, missed = [], []
for r in repos:
try:
m = measure(r, tmp)
except Exception:
m = None
if m:
rows.append((r['name'],) + m)
else:
missed.append(r['name'])
force_rm(tmp)
print('%d public repositories, %d measured, %d missed' % (len(repos), len(rows), len(missed)))
if not rows or len(missed) * 5 > len(repos):
print('FAIL: too many missed to call this a measurement; nothing written')
return 1
now = int(time.time())
standing = '# repository\thead\thead_unix\tfiles\tlines\n' + ''.join('%s\t%s\t%d\t%d\t%d\n' % r for r in rows)
standing += ''.join('# missed\t%s\n' % n for n in missed)
pulse = '%d\t%d\t%d\t%d\t%d\n' % (now, len(rows), len(missed), sum(r[3] for r in rows), sum(r[4] for r in rows))
if leaks(standing):
print('REFUSED (L6): a name that is not public is in the result; nothing written')
return 2
if limit:
print(standing + pulse + 'dry run with --limit: nothing written')
return 0
io.open(os.path.join(ROOT, 'cosmos', 'standing.tsv'), 'w', encoding='utf-8', newline='\n').write(standing)
p = os.path.join(ROOT, 'cosmos', 'pulse.tsv')
if not os.path.exists(p):
io.open(p, 'w', encoding='utf-8', newline='\n').write('# unix\trepositories\tmissed\tfiles\tlines_standing\n')
io.open(p, 'a', encoding='utf-8', newline='\n').write(pulse)
print('lines standing now: %s in %s files' % (format(sum(r[4] for r in rows), ','), format(sum(r[3] for r in rows), ',')))
return 0
if __name__ == '__main__':
sys.exit(main())Iterate
A Python command-line tool in the tools folder of Kuiper Belt that reads verdict and wafer meta.
storagekuiper-belt / tools/iterate.py · lines 1–195 of 195 · Entry point · pattern folder (shared by 2 files)
- What it does
- It loads verdict and wafer meta. Defines 9 functions or classes, including Quiet, log_message, end_headers, folder, new. Uses libraries io, json, os, re, shutil. 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 verdict.json; JSON file wafer-meta.json; command-line arguments. Out: JSON file verdict.json.
- Downstream impact
- Used directly by 1 file: Swarm (kuiper-belt). Reached from 1 other entry point, including Cadence (kuiper-belt).
- What it achieves
- It is built from the quiet class (`Quiet`), the log message helper (`log_message`) and the end headers helper (`end_headers`). Run many iterations LOCALLY, test each one unattended, keep the best ten.
- Why it matters
- Imported by Swarm.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- Check Proof (import), io, json, os, re, shutil, subprocess, sys, threading
- Used by
- imported by Swarm (import)
- Produces
- Quiet, folder, new, headless, test, rank, main
- Defines here
- Quiet, log_message, end_headers, folder, new, headless, test, rank, 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/iterate.py:1-195 · blob 191a37bcbb562e07c2b6c69d95c86ba1dac3c886 · 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/iterate.py - run many iterations LOCALLY, test each one unattended, keep the best ten.
A hundred iterations overnight must not mean a hundred pushes. An iteration lives on the E: drive
and nowhere else until it has earned its place: it is served from its own folder, its self tests
are run in headless Chrome with nobody watching, the checks that need no browser are run on its
data, and it is given a score made only of things that passed or failed. The best ten are then
published by a person or a captain through tools/publish_proof.py, which has its own ten minute
rule and its own privacy guard. NOTHING IN E:\kuiper-iterations IS EVER COMMITTED.
python tools/iterate.py new "what this iteration tries" copy the current engine into a new numbered folder
python tools/iterate.py test <n> serve it, run its self tests headless, score it
python tools/iterate.py test-all every untested iteration
python tools/iterate.py rank the table, best first
An iteration folder holds: index.html (and any other page), cosmos/ (copied), NOTE.md (the
intent, one paragraph), selftests.txt (one query string per line, for example selftest=2026-07;
a line may end with " wait=6" for a test that animates in real time), and after testing
verdict.json. Edit index.html in the folder, then test. That is the whole loop.
THE SCORE CANNOT BE ARGUED WITH. One point for each self test whose page title ends PASS, one for
the data summing, one for no private digest anywhere in the folder, one for every script
parsing. A self test that does not finish scores nothing. There is no point for looking good:
eyes are for the ten that survive, not for the hundred.
"""
import io
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
KB = os.path.join(HERE, '..')
ROOT = r'E:\kuiper-iterations'
sys.path.insert(0, HERE)
from check_proof import leaks
CHROME = [p for p in (r'C:\Program Files\Google\Chrome\Application\chrome.exe',
r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe') if os.path.exists(p)]
# selftest=new does not yet finish headless (ORDERS block E); until it does it is not a default, or nothing could ever score full marks
DEFAULT_TESTS = ['selftest=2026-07', 'conductor.html:c=al400', 'conductor.html:c=cu6c5', 'conductor.html:c=cu6c6']
class Quiet(SimpleHTTPRequestHandler):
def log_message(self, *a):
pass
def end_headers(self):
self.send_header('Cache-Control', 'no-store')
super().end_headers()
def folder(n):
return os.path.join(ROOT, '%04d' % int(n))
def new(note):
os.makedirs(ROOT, exist_ok=True)
taken = [int(d) for d in os.listdir(ROOT) if re.match(r'^\d{4}$', d)]
n = (max(taken) + 1) if taken else 1
d = folder(n)
# START FROM THE NEWEST ITERATION THAT SCORED FULL MARKS, not from the repository. The repository is
# only promoted at a review, so starting from it would silently throw away every iteration since.
base = KB
for t in sorted(taken, reverse=True):
v = os.path.join(folder(t), 'verdict.json')
if os.path.exists(v):
j = json.load(io.open(v, encoding='utf-8'))
if j['score'] == j['out_of']:
base = folder(t)
break
os.makedirs(d)
for f in os.listdir(base):
if f.endswith('.html'):
shutil.copy(os.path.join(base, f), d)
shutil.copytree(os.path.join(base, 'cosmos'), os.path.join(d, 'cosmos'), ignore=shutil.ignore_patterns('commits', 'belt.tsv'))
print('started from %s' % base)
io.open(os.path.join(d, 'NOTE.md'), 'w', encoding='utf-8', newline='\n').write(note.strip() + '\n')
prior = os.path.join(base, 'selftests.txt') # tests are inherited too, so a new test is never lost
tests = io.open(prior, encoding='utf-8').read() if base != KB and os.path.exists(prior) else '\n'.join(DEFAULT_TESTS) + '\n'
io.open(os.path.join(d, 'selftests.txt'), 'w', encoding='utf-8', newline='\n').write(tests)
print('iteration %04d at %s' % (n, d))
return n
def headless(url, wait):
"""The page sets its own title to 'selftest PASS' or 'selftest FAIL'. A test that animates in
real time is given real seconds, because virtual time does not move requestAnimationFrame."""
prof = os.path.join(ROOT, '_profile')
args = [CHROME[0], '--headless=new', '--disable-gpu-sandbox', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist',
'--user-data-dir=' + prof, '--window-size=1280,900']
args += ['--timeout=%d' % (wait * 1000)] if wait else ['--virtual-time-budget=9000']
try:
out = subprocess.run(args + ['--dump-dom', url], capture_output=True, text=True, timeout=60 + wait,
encoding='utf-8', errors='replace').stdout
except subprocess.TimeoutExpired:
return 'TIMEOUT'
m = re.search(r'<title>([^<]*)</title>', out or '')
return m.group(1).strip() if m else 'NO TITLE'
def test(n):
d = folder(n)
if not CHROME:
print('REFUSED: no Chrome or Edge found, so no self test can run')
return 2
srv = ThreadingHTTPServer(('127.0.0.1', 0), partial(Quiet, directory=d))
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = 'http://127.0.0.1:%d/' % srv.server_address[1]
v = {'iteration': int(n), 'tested': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), 'selftests': {}, 'checks': {}}
lines = [l.strip() for l in io.open(os.path.join(d, 'selftests.txt'), encoding='utf-8') if l.strip()]
for line in lines:
m = re.match(r'^(\S+)(?:\s+wait=(\d+))?$', line)
q, wait = m.group(1), int(m.group(2) or 0)
page = 'index.html'
if ':' in q and q.split(':')[0].endswith('.html'):
page, q = q.split(':', 1)
t0 = time.time()
title = headless(base + page + '?' + q, wait)
v['selftests'][line] = {'title': title, 'pass': title.endswith('PASS'), 'seconds': round(time.time() - t0, 1)}
srv.shutdown()
# checks that need no browser
try:
rows = [l.split('\t') for l in io.open(os.path.join(d, 'cosmos', 'wafer.tsv'), encoding='utf-8') if l.strip() and l[0] != '#']
meta = json.load(io.open(os.path.join(d, 'cosmos', 'wafer-meta.json'), encoding='utf-8'))
v['checks']['data_sums'] = sum(int(r[1]) for r in rows) == meta['issued_keys'] and sum(int(r[4]) for r in rows) == meta['unissued_keys']
except Exception as e:
v['checks']['data_sums'] = False
v['data_error'] = repr(e)
hits = 0
parses = True
for root, _, files in os.walk(d):
if '_profile' in root:
continue
for f in files:
body = io.open(os.path.join(root, f), encoding='utf-8', errors='replace').read()
hits += leaks(body)
if f.endswith('.html'):
m = re.search(r'<script type="module">([\s\S]*)</script>', body)
if m:
js = os.path.join(d, '.check.mjs')
io.open(js, 'w', encoding='utf-8').write(m.group(1))
parses = parses and subprocess.run(['node', '--check', js], capture_output=True).returncode == 0
os.remove(js)
v['checks']['no_private_digest'] = hits == 0
v['checks']['scripts_parse'] = parses
v['score'] = sum(1 for t in v['selftests'].values() if t['pass']) + sum(1 for c in v['checks'].values() if c)
v['out_of'] = len(v['selftests']) + len(v['checks'])
json.dump(v, io.open(os.path.join(d, 'verdict.json'), 'w', encoding='utf-8', newline='\n'), indent=1)
print('%04d %d of %d %s' % (int(n), v['score'], v['out_of'],
' '.join('%s:%s' % (k.split()[0], 'PASS' if t['pass'] else t['title'][:18]) for k, t in v['selftests'].items())))
return 0
def rank():
table = []
for dname in sorted(os.listdir(ROOT)) if os.path.isdir(ROOT) else []:
p = os.path.join(ROOT, dname, 'verdict.json')
if os.path.exists(p):
v = json.load(io.open(p, encoding='utf-8'))
note = io.open(os.path.join(ROOT, dname, 'NOTE.md'), encoding='utf-8').read().strip().split('\n')[0][:70]
table.append((v['score'] / max(1, v['out_of']), v['score'], v['out_of'], dname, note))
for i, (_, s, o, dname, note) in enumerate(sorted(table, key=lambda t: (-t[0], -t[1], t[3]))):
print('%s %s %d/%d %s' % ('*' if i < 10 else ' ', dname, s, o, note))
print('%d tested. The starred ten are candidates for publishing; a person still looks at them first.' % len(table))
def main():
a = sys.argv[1:]
if a[:1] == ['new'] and len(a) == 2:
return 0 if new(a[1]) else 1
if a[:1] == ['test'] and len(a) == 2:
return test(a[1])
if a == ['test-all']:
for dname in sorted(os.listdir(ROOT)):
if re.match(r'^\d{4}$', dname) and not os.path.exists(os.path.join(ROOT, dname, 'verdict.json')):
test(dname)
return 0
if a == ['rank']:
rank()
return 0
print(__doc__)
return 1
if __name__ == '__main__':
sys.exit(main())Publish Proof
A Python command-line tool in the tools folder of Kuiper Belt that publishes one numbered proof to globalgrid2050.com, at most one per twenty minutes.
otherkuiper-belt / tools/publish_proof.py · lines 1–104 of 104 · Entry point
- What it does
- It lists and searches its content. Defines git, main. Uses libraries io, os, re, shutil, 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: command-line arguments.
- Downstream impact
- Used directly by 1 file: Cadence (kuiper-belt).
- What it achieves
- Its name says it publishes proof. Defines `git`.
- Why it matters
- Run by Cadence.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- Check Proof (import), io, os, re, shutil, subprocess, sys, datetime
- Used by
- run by Cadence (script call)
- Produces
- git, main
- Defines here
- git, 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/publish_proof.py:1-104 · blob b11ca796bda7fd9141ffba4bfd59eb4fd8733636 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""tools/publish_proof.py - publish one numbered proof to globalgrid2050.com, at most one per twenty minutes.
python tools/publish_proof.py <n> "<title>" "<one line for the homepage>" <proof.md> [<folder to publish from>]
With a fifth argument the pages and data are taken from that folder (a tested iteration on the E: drive)
instead of from this repository. The tools always come from this repository.
Copies the wafer page, its data and its tools into a stamped directory of the site worktree, adds
PROOF.md, links it from the homepage nest "Kuiper: proofs", commits and pushes to main.
SAFEGUARDS. Refuses if the last proof is less than twenty minutes old. Refuses if any name of a
repository known not to be public appears in what is about to be published. Refuses if the site
worktree is not at origin/main. Touches nothing on the homepage except its own nest.
"""
import io
import os
import re
import shutil
import subprocess
import sys
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
KB = os.path.join(HERE, '..')
SITE = os.path.join(KB, '..', '_wt-estate')
BASE = 'testcode/wafer-development-environment'
NEST = 'Kuiper: proofs'
sys.path.insert(0, HERE)
from check_proof import leaks # digests, not names: the guard must not spell what it guards
def git(*a):
return subprocess.run(['git'] + list(a), cwd=SITE, capture_output=True, text=True)
def main():
n, title, small, md = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
SRC = sys.argv[5] if len(sys.argv) > 5 else KB
now = datetime.now(timezone.utc)
stamps = sorted(d[:12] for d in os.listdir(os.path.join(SITE, BASE)) if re.match(r'^\d{12}-proof', d)
or d.endswith('-one-wafer'))
if stamps:
last = datetime.strptime(stamps[-1], '%Y%m%d%H%M').replace(tzinfo=timezone.utc)
if (now - last).total_seconds() < 1200:
print('REFUSED: the last proof is %d s old; one per twenty minutes' % (now - last).total_seconds())
return 2
git('fetch', '-q', 'origin')
if git('rev-list', '--count', 'HEAD..origin/main').stdout.strip() != '0':
print('REFUSED: the site worktree is behind origin/main')
return 2
stamp = now.strftime('%Y%m%d%H%M')
rel = '%s/%s-proof-%s' % (BASE, stamp, n)
dst = os.path.join(SITE, rel)
os.makedirs(os.path.join(dst, 'tools'))
for f in sorted(os.listdir(SRC)): # every page of the version, not a fixed list
if f.endswith('.html'):
shutil.copy(os.path.join(SRC, f), dst)
for extra in ('PALETTE.md', 'CHAINS.md', 'LAWS.md'):
if os.path.exists(os.path.join(KB, extra)):
shutil.copy(os.path.join(KB, extra), dst)
shutil.copytree(os.path.join(SRC, 'cosmos'), os.path.join(dst, 'cosmos'),
ignore=shutil.ignore_patterns('commits', 'belt.tsv'))
for t in ('key.py', 'wafer_keys.py', 'permanence.py'):
shutil.copy(os.path.join(HERE, t), os.path.join(dst, 'tools'))
shutil.copy(md, os.path.join(dst, 'PROOF.md'))
for root, _, files in os.walk(dst):
for f in files:
if f.endswith('.py'):
continue
body = io.open(os.path.join(root, f), encoding='utf-8', errors='replace').read()
if leaks(body):
shutil.rmtree(dst)
print('REFUSED (L6): a name that is not public appears in %s' % f)
return 2
p = os.path.join(SITE, 'index.html')
s = io.open(p, encoding='utf-8').read()
link = ('<a class="current" href="https://globalgrid2050.com/%s/">%s-proof-%s<small>%s</small></a>'
% (rel, stamp, n, small))
s = s.replace('<summary>Proofs</summary>', '<summary>%s</summary>' % NEST)
m = re.search(r'<summary>%s</summary><details class="area nest"><summary>[^<]*</summary>' % re.escape(NEST), s)
if not m:
shutil.rmtree(dst)
print('REFUSED: the homepage nest was not found')
return 2
s = s[:m.end()] + link + s[m.end():] # newest first
io.open(p, 'w', encoding='utf-8', newline='\n').write(s)
git('add', rel, 'index.html')
msg = ('PROOF %s: %s\n\n%s\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n'
'Claude-Session: https://claude.ai/code/session_01DGQ1FNfMmzNDkgnh5DycbN'
% (n, title, io.open(md, encoding='utf-8').read().strip()))
git('commit', '-q', '-m', msg)
r = git('push', 'origin', 'HEAD:main')
print((r.stderr or r.stdout).strip().split('\n')[-1])
print('https://globalgrid2050.com/%s/' % rel)
return 0
if __name__ == '__main__':
sys.exit(main())Swarm
A Python command-line tool in the tools folder of Kuiper Belt that fetches verdict and cables.
storagekuiper-belt / tools/swarm.py · lines 1–164 of 164 · Entry point · pattern neutral (shared by 2 files)
- What it does
- It fetches verdict and cables. Defines 9 functions or classes, including pages, text, phone, l1, l2. Uses libraries io, json, os, re, subprocess. 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). Domain terms in the code: cables.
- Inputs & outputs
- In: data source: 127.0.0.1:11434; JSON file verdict.json; command-line arguments. Out: JSON file swarm.json.
- Downstream impact
- Used directly by 1 file: Cadence (kuiper-belt).
- What it achieves
- It is built from the pages step (`pages`), the text step (`text`) and the phone step (`phone`). The checking load of one iteration, shared across three phases, with a neutral and an earth.
- Why it matters
- Run by Cadence.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- Check Proof (import), Iterate (import), io, json, os, re, subprocess, sys, threading, time
- Used by
- run by Cadence (script call)
- Produces
- pages, text, phone, l1, l2, l3, neutral, earth, main
- Defines here
- pages, text, phone, l1, l2, l3, neutral, earth, 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/swarm.py:1-164 · blob 9f8b425a86f9636cba39539333c39fa9e4598cc2 · 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/swarm.py - the checking load of one iteration, shared across three phases, with a neutral and an earth.
python tools/swarm.py NNNN
THREE PHASES, a third of the checks each, run side by side. All three must be healthy to release.
L1 SCOPE AND SAFETY nothing private, no banned word, the disclaimer on every page, and every conductor
page passes its own layout tests at PHONE width (390 x 844).
L2 TRUTH every keyed fact in E:\kuiper-iterations\FACTS.tsv that applies to a page is present in
that page exactly as keyed. L2 owns that file and adds a fact whenever it settles one.
L3 FUNCTION the builder's own verdict is full marks, was made after the last edit, and every
script parses.
NEUTRAL the local model on the graphics card reads the note and lists words a cable engineer would not know.
It carries the imbalance: bulk reading nobody else should pay for. It ADVISES. It never blocks.
EARTH GitHub Actions. It carries nothing in normal running. If the last run on the repository FAILED, that
is a fault to earth and the release trips, whatever the phases say.
Writes swarm.json in the iteration folder. tools/cadence.py releases only on three healthy phases, a sound
earth, and a written review by L1 or L2 (REVIEW.md, first line PASS or FAIL, with the reviewer's name).
The banned words and the facts live on the E: drive, not in this repository, so the guard never spells what it guards.
"""
import io
import json
import os
import re
import subprocess
import sys
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from functools import partial
from http.server import ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from check_proof import leaks
from iterate import CHROME, Quiet, folder, ROOT
DISCLAIMER = 'without warranty'
def pages(d):
return sorted(f for f in os.listdir(d) if f.endswith('.html'))
def text(p):
return io.open(p, encoding='utf-8', errors='replace').read()
def phone(d, base, page, query):
prof = os.path.join(ROOT, '_profile_phone')
out = subprocess.run([CHROME[0], '--headless=new', '--enable-unsafe-swiftshader', '--user-data-dir=' + prof, '--window-size=390,844',
'--virtual-time-budget=9000', '--dump-dom', base + page + '?' + query],
capture_output=True, text=True, timeout=90, encoding='utf-8', errors='replace').stdout or ''
m = re.search(r'<title>([^<]*)</title>', out)
return m.group(1).strip() if m else 'NO TITLE'
def l1(d):
r = {'checks': {}}
hits = sum(leaks(text(os.path.join(root, f))) for root, _, fs in os.walk(d) if '_profile' not in root for f in fs
if f.endswith(('.html', '.md', '.tsv', '.json', '.txt')))
r['checks']['nothing_private'] = hits == 0
bp = os.path.join(ROOT, 'BANNED.txt')
banned = [w.strip().lower() for w in text(bp).split('\n') if w.strip() and w[0] != '#'] if os.path.exists(bp) else []
found = sorted({w for f in pages(d) + ['NOTE.md'] for w in banned if w in text(os.path.join(d, f)).lower()})
r['checks']['no_banned_word'] = not found
r['banned_found'] = len(found) # a count, never the words
r['checks']['disclaimer_on_every_page'] = all(DISCLAIMER in text(os.path.join(d, f)).lower() for f in pages(d))
srv = ThreadingHTTPServer(('127.0.0.1', 0), partial(Quiet, directory=d))
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = 'http://127.0.0.1:%d/' % srv.server_address[1]
tests = [l.split()[0] for l in text(os.path.join(d, 'selftests.txt')).split('\n') if l.strip().startswith('conductor')]
titles = {t: phone(d, base, *t.split(':', 1)) for t in tests}
srv.shutdown()
r['phone'] = titles
r['checks']['passes_at_phone_width'] = bool(titles) and all(v.endswith('PASS') for v in titles.values())
return r
def l2(d):
r = {'checks': {}, 'facts': []}
fp = os.path.join(ROOT, 'FACTS.tsv')
rows = [l.rstrip('\n').split('\t') for l in text(fp).split('\n') if l.strip() and l[0] != '#'] if os.path.exists(fp) else []
for page, must, why in (x[:3] for x in rows if len(x) >= 3):
p = os.path.join(d, page)
if os.path.exists(p):
ok = must in text(p)
r['facts'].append({'page': page, 'fact': must, 'source': why, 'present': ok})
r['checks']['facts_file_has_facts'] = len(r['facts']) > 0
r['checks']['every_keyed_fact_is_present'] = all(f['present'] for f in r['facts'])
return r
def l3(d):
r = {'checks': {}}
v = os.path.join(d, 'verdict.json')
if not os.path.exists(v):
r['checks']['has_a_verdict'] = False
return r
j = json.load(io.open(v, encoding='utf-8'))
r['checks']['full_marks'] = j['score'] == j['out_of']
r['score'] = '%d/%d' % (j['score'], j['out_of'])
r['checks']['tested_after_last_edit'] = all(os.path.getmtime(os.path.join(d, f)) <= os.path.getmtime(v) for f in pages(d))
r['checks']['scripts_parse'] = bool(j.get('checks', {}).get('scripts_parse'))
r['checks']['data_sums'] = bool(j.get('checks', {}).get('data_sums'))
return r
def neutral(d):
note = text(os.path.join(d, 'NOTE.md'))[:1500]
try:
ps = json.load(urllib.request.urlopen('http://127.0.0.1:11434/api/ps', timeout=3)).get('models', [])
tags = json.load(urllib.request.urlopen('http://127.0.0.1:11434/api/tags', timeout=3)).get('models', [])
model = (ps or tags)[0]['name']
body = json.dumps({'model': model, 'stream': False, 'options': {'num_predict': 120, 'temperature': 0},
'prompt': 'A cable engineer who is not a programmer will read this note. List, as a short comma separated '
'list and nothing else, any words in it that such a reader would not understand. If none, reply NONE.\n\n' + note}).encode()
out = json.load(urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:11434/api/generate', body, {'Content-Type': 'application/json'}), timeout=120))
return {'advice': out.get('response', '').strip()[:400], 'model': model, 'blocks': False}
except Exception as e:
return {'advice': 'neutral not connected (%s)' % type(e).__name__, 'model': None, 'blocks': False}
def earth():
try:
j = json.loads(subprocess.run(['gh', 'run', 'list', '-R', 'Ventusltd/kuiper-belt', '-L', '1', '--json', 'conclusion,status,workflowName,createdAt'],
capture_output=True, text=True, timeout=30).stdout or '[]')
last = j[0] if j else {}
return {'sound': last.get('conclusion') != 'failure', 'last': last}
except Exception as e:
return {'sound': True, 'last': {'note': 'earth could not be read (%s); not treated as a fault' % type(e).__name__}}
def main():
n = sys.argv[1]
d = folder(n)
t0 = time.time()
with ThreadPoolExecutor(5) as ex:
f = {k: ex.submit(fn, *a) for k, fn, a in (('L1', l1, (d,)), ('L2', l2, (d,)), ('L3', l3, (d,)), ('N', neutral, (d,)), ('E', earth, ()))}
out = {}
for k, fut in f.items():
try:
out[k] = fut.result()
except Exception as e:
out[k] = {'checks': {'ran': False}, 'error': repr(e)[:200]}
for k in ('L1', 'L2', 'L3'):
out[k]['healthy'] = bool(out[k].get('checks')) and all(out[k]['checks'].values())
out['iteration'], out['checked'], out['seconds'] = n, datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), round(time.time() - t0, 1)
out['release_ready'] = all(out[k]['healthy'] for k in ('L1', 'L2', 'L3')) and out['E']['sound']
json.dump(out, io.open(os.path.join(d, 'swarm.json'), 'w', encoding='utf-8', newline='\n'), indent=1)
for k in ('L1', 'L2', 'L3'):
bad = [c for c, ok in out[k]['checks'].items() if not ok]
print('%s %s%s' % (k, 'HEALTHY' if out[k]['healthy'] else 'FAULT ', (' ' + ', '.join(bad)) if bad else ''))
print('N %s' % out['N']['advice'][:160].replace('\n', ' '))
print('E %s' % ('SOUND' if out['E']['sound'] else 'FAULT TO EARTH: the last Actions run failed'))
print('release ready: %s (%.0f s) a written review by L1 or L2 is still needed' % (out['release_ready'], out['seconds']))
return 0 if out['release_ready'] else 1
if __name__ == '__main__':
sys.exit(main())Test Agent Start
A test in the tools folder of Kuiper Belt that checks Agent Start. It is built from the agent start tests class (`AgentStartTests`) and the get step (`get`).
testkuiper-belt / tools/test_agent_start.py · lines 1–39 of 39 · Entry point · pattern test_deterministic (shared by 11 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including AgentStartTests, mock, test_deterministic, test_refuse_private, test_refuse_incomplete. Uses libraries unittest.
- 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).
- Downstream impact
- Used directly by 1 file: Agent Start Workflow (kuiper-belt).
- What it achieves
- Defines `AgentStartTests`, `mock`, `test_deterministic` and 5 more.
- Why it matters
- Run by Agent Start Workflow.
- Application
- kuiper-belt · tools · test
- Uses
- Agent Start (import), unittest
- Used by
- run by Agent Start Workflow (workflow run)
- Produces
- AgentStartTests
- Defines here
- AgentStartTests, mock, test_deterministic, test_refuse_private, test_refuse_incomplete, test_refuse_bad_file, get, test_static_complete
- 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/test_agent_start.py:1-39 · blob 5f051e2e7661e0340cd410eae5ace3a0611f5b63 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import unittest
import agent_start as a
class AgentStartTests(unittest.TestCase):
def mock(self, path):
if "/contents/" in path:
return {"type":"file","path":path.split("/contents/")[1].split("?")[0],"sha":"b"*40}
if "/commits/" in path:
return {"sha":"a"*40,"commit":{"tree":{"sha":"c"*40},"committer":{"date":"2026-12-04T12:00:00Z"}}}
return {"private":False,"visibility":"public","full_name":path.removeprefix("repos/"),"default_branch":"main"}
def test_deterministic(self):
rows=a.collect(self.mock)
self.assertEqual(len(rows),len(a.REPOS))
self.assertEqual(a.render(rows),a.render(rows))
self.assertIn(b"Default-branch observations",a.render(rows)["START.html"])
def test_refuse_private(self):
with self.assertRaises(ValueError):
a.collect(lambda _:{"private":True})
def test_refuse_incomplete(self):
with self.assertRaises(ValueError):
a.render([])
def test_refuse_bad_file(self):
def get(path):
return {"type":"dir"} if "/contents/" in path else self.mock(path)
with self.assertRaises(ValueError):
a.collect(get)
def test_static_complete(self):
rows=a.collect(self.mock)
out=a.render(rows)
self.assertEqual(out["START.html"],out["index.html"])
self.assertNotIn(b"<script",out["index.html"])
for row in rows:
for key in ("commit","tree","branch","commit_time"):
self.assertIn(row[key].encode(),out["index.html"])
for file in row["files"]:
for key in ("path","blob","raw_url"):
self.assertIn(file[key].encode(),out["index.html"])
self.assertIn(file["raw_url"].encode(),out["START.md"])