GLOBALGRID2050 / EXPLORE CODE

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

Count Lines and 1 more file

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

383 lines of Python from kuiper-belt, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1547 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. CI Check automation · kuiper-belt / tools/ci_check.py lines 1–102
  2. Count Lines storage · kuiper-belt / tools/count_lines.py lines 1–281

CI Check

A Python command-line tool in the tools folder of Kuiper Belt that reads wafer meta. It is built from the tracked step (`tracked`).

automationkuiper-belt / tools/ci_check.py · lines 1–102 of 102 · Entry point · pattern tracked (shared by 2 files)

What it does
It loads wafer meta. Defines tracked, main. Uses libraries ast, io, json, os, re. Side effects: changes the web page (DOM); 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.
Downstream impact
Used directly by 4 files: Test (kuiper-belt); Test (kuiper-belt); Check Workflow (kuiper-belt); Engine Workflow (kuiper-belt).
What it achieves
What GitHub checks on every push, on its own machine, knowing nothing local.
Why it matters
Run by Check Workflow and Engine Workflow. Checked by 2 tests, including Test.
Application
kuiper-belt · tools · Python CLI
Uses
Check Proof (import), ast, io, json, os, re, subprocess, sys
Used by
run by Test (script call), run by Test (script call), run by Check Workflow (workflow run), run by Engine Workflow (workflow run)
Produces
tracked, main
Defines here
tracked, 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/ci_check.py:1-102 · blob ff5ebcf7bd4b0c133731cf5a8d4ff4b51fda1659 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
r"""tools/ci_check.py - what GitHub checks on every push, on its own machine, knowing nothing local.

The checking engineer on the measuring machine (check_proof.py) can follow a key to its text,
because it has the clones. A hosted runner has only this repository, so it checks what can be
checked from the repository alone, and it fails closed:

  K1  no tracked file contains a token whose digest matches a repository name that is not public
  K2  cosmos/wafer.tsv re-summed equals cosmos/wafer-meta.json, and equals cosmos/repos.tsv
  K3  every tool is valid python, and the script inside every page parses as JavaScript
  K4  keys are in time order and no commit overlaps the one before it

Exit 0 only if all pass. Nothing here can be satisfied by editing a number in a document.
"""
import ast
import io
import json
import os
import re
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.join(HERE, '..')
sys.path.insert(0, HERE)
from check_proof import leaks


def tracked():
    out = subprocess.run(['git', 'ls-files'], cwd=ROOT, capture_output=True, text=True).stdout
    return [f for f in out.split('\n') if f]


def main():
    fails = []

    bad = []
    for f in tracked():
        p = os.path.join(ROOT, f)
        if os.path.isfile(p) and os.path.getsize(p) <= 3_000_000:
            try:
                if leaks(io.open(p, encoding='utf-8', errors='replace').read()):
                    bad.append(f)
            except Exception:
                pass
    print('K1 privacy: %d tracked files scanned, %d match a private digest' % (len(tracked()), len(bad)))
    if bad:
        fails.append('K1: ' + ', '.join(bad[:8]))

    rows = lambda n: [l.rstrip('\n').split('\t') for l in io.open(os.path.join(ROOT, 'cosmos', n), encoding='utf-8')
                      if l.strip() and not l.startswith('#')]
    w, meta = rows('wafer.tsv'), json.load(io.open(os.path.join(ROOT, '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)
    repo_sum = sum(int(r[2]) for r in rows('repos.tsv'))
    ok2 = issued == meta['issued_keys'] == repo_sum and silent == meta['unissued_keys'] and len(w) == meta['commits']
    print('K2 sums: issued %s, meta %s, repositories %s, silent %s, commits %d: %s'
          % (format(issued, ','), format(meta['issued_keys'], ','), format(repo_sum, ','),
             format(silent, ','), len(w), 'agree' if ok2 else 'DISAGREE'))
    if not ok2:
        fails.append('K2: the published data does not add up')

    for f in sorted(os.listdir(HERE)):
        if f.endswith('.py'):
            try:
                ast.parse(io.open(os.path.join(HERE, f), encoding='utf-8').read())
            except SyntaxError as e:
                fails.append('K3: %s does not parse: %s' % (f, e))
    pages = [f for f in os.listdir(ROOT) if f.endswith('.html')]
    for f in pages:
        s = io.open(os.path.join(ROOT, f), encoding='utf-8').read()
        m = re.search(r'<script type="module">([\s\S]*)</script>', s)
        if not m:
            continue
        js = os.path.join(ROOT, '.ci-%s.mjs' % f)
        io.open(js, 'w', encoding='utf-8').write(m.group(1))
        r = subprocess.run(['node', '--check', js], capture_output=True, text=True)
        os.remove(js)
        if r.returncode:
            fails.append('K3: the script in %s does not parse: %s' % (f, r.stderr.strip().split('\n')[-1][:160]))
    print('K3 syntax: %d tools, %d pages' % (len([f for f in os.listdir(HERE) if f.endswith('.py')]), len(pages)))

    k, prev_unix, disorder = 0, -1, 0
    for r in w:
        unix, n, gap = int(r[0]), int(r[1]), int(r[4])
        if unix < prev_unix or gap < 0 or n <= 0:
            disorder += 1
        prev_unix = unix
        k += gap + n
    ok4 = disorder == 0 and k == meta['address_space']
    print('K4 order: %d commits out of order or overlapping; address space %s vs %s'
          % (disorder, format(k, ','), format(meta['address_space'], ',')))
    if not ok4:
        fails.append('K4: keys are not in time order, or the address space does not close')

    for f in fails:
        print('FAIL ' + f)
    print('RESULT: ' + ('PASS' if not fails else 'FAIL'))
    return 1 if fails else 0


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

Count Lines

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

storagekuiper-belt / tools/count_lines.py · lines 1–281 of 281 · Entry point · pattern find_repos (shared by 2 files)

What it does
It loads counts. Defines 10 functions or classes, including find_repos, git, lines_of, batch_count, do_head. Uses libraries argparse, hashlib, json, os, 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 counts.json; JSON file -counts.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: What Is Kuiper (kuiper-belt, https://ventusltd.github.io/kuiper-belt/what-is-kuiper.html). Reached from 7 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 writes tsv (`write_tsv`) and is built from the batch count helper (`batch_count`) and the do head helper (`do_head`). Defines `find_repos`, `git`, `lines_of` and 6 more. It accepts `--roots`, `--depth` and `--out`.
Why it matters
Loaded by the What Is Kuiper page at https://ventusltd.github.io/kuiper-belt/what-is-kuiper.html.
Application
kuiper-belt · tools · Python CLI
Uses
argparse, hashlib, json, os, subprocess, sys, datetime
Used by
linked from What Is Kuiper (link)
Produces
find_repos, git, lines_of, batch_count, do_head, do_history, do_authored, do_entries, write_tsv, main
Defines here
find_repos, git, lines_of, batch_count, do_head, do_history, do_authored, do_entries, write_tsv, 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/count_lines.py:1-281 · blob 206e0e147b295f8fd0a9e3315eceaa5cf0b07bcd · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
MINE = lambda sha: True
SUF = ''
#!/usr/bin/env python3
"""tools/count_lines.py - count every line in the estate, at HEAD and across all history.

    python tools/count_lines.py --roots <dir> [--depth head|history|authored|all] [--out data]

Three different numbers, never conflated:

  head      lines of text in distinct blobs at HEAD          measured 2026-09-19: 25,335,587
  history   lines of text in EVERY blob ever stored          8.75 GB of content, never counted
  authored  lines added by commits, from git log --numstat   the one change detection keys on

A blob with a NUL byte in its first 8,000 is binary: counted as a blob, excluded from line totals.
Distinct blobs only, so identical content in many places counts once, exactly as the Kuiper belt
counts bodies.

GitLab adds nothing to any of these. The mirror holds the same objects with the same SHAs, which is
what HONOURED means. Counting it would be double counting.

Writes, for the renderer and for change detection, with no further work needed:

  data/blob-lines.tsv           sha<TAB>lines             one row per text blob at HEAD
  data/blob-lines-history.tsv   sha<TAB>lines             one row per text blob ever stored
  data/authored.tsv             repo<TAB>added<TAB>deleted<TAB>commits
  data/counts.json              every total, with the command and the time that produced it
  proof/<run>-counts.json       the sha256 of each file above

The scaffolding is the point. Re-run it, diff counts.json against the last one, and you have change
detection with a key behind every number.
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
from datetime import datetime, timezone


def find_repos(roots):
    out = []
    for root in roots:
        if not os.path.isdir(root):
            continue
        for name in sorted(os.listdir(root)):
            d = os.path.join(root, name)
            if os.path.isdir(os.path.join(d, '.git')):
                out.append((name, d))
    return out


def git(d, args):
    r = subprocess.run(['git'] + args, cwd=d, capture_output=True,
                       text=True, encoding='utf-8', errors='replace')
    return r.stdout


def lines_of(body, size):
    """-1 means binary. Otherwise newlines, plus one if the file does not end in a newline."""
    if b'\x00' in body[:8000]:
        return -1
    return body.count(b'\n') + (1 if size and not body.endswith(b'\n') else 0)


def batch_count(d, shas):
    """One git cat-file --batch pass. Returns {sha: lines, or -1 for binary}."""
    if not shas:
        return {}
    p = subprocess.run(['git', 'cat-file', '--batch'], cwd=d,
                       input=('\n'.join(shas) + '\n').encode(), capture_output=True)
    out, i, res = p.stdout, 0, {}
    for sha in shas:
        nl = out.find(b'\n', i)
        if nl < 0:
            break
        hdr = out[i:nl].split()
        if len(hdr) < 3:
            break
        size = int(hdr[2])
        res[sha] = lines_of(out[nl + 1:nl + 1 + size], size)
        i = nl + 1 + size + 1
    return res


def do_head(rs, seen):
    global MINE
    paths = 0
    for name, d in rs:
        new = []
        for line in git(d, ['ls-tree', '-r', '-l', 'HEAD']).splitlines():
            p = line.split(None, 4)
            if len(p) < 5 or p[1] != 'blob':
                continue
            paths += 1
            if p[2] not in seen and MINE(p[2]):
                seen[p[2]] = None
                new.append(p[2])
        seen.update(batch_count(d, new))
        print('  head %-34s %10s paths so far' % (name, format(paths, ',')), file=sys.stderr)
    return paths


def do_history(rs, seen):
    global MINE
    for name, d in rs:
        new = []
        for line in git(d, ['cat-file', '--batch-all-objects',
                            '--batch-check=%(objectname) %(objecttype)']).splitlines():
            p = line.split()
            if len(p) == 2 and p[1] == 'blob' and p[0] not in seen and MINE(p[0]):
                seen[p[0]] = None
                new.append(p[0])
        seen.update(batch_count(d, new))
        print('  history %-31s %10s blobs so far' % (name, format(len(seen), ',')), file=sys.stderr)


def do_authored(rs):
    rows = []
    for name, d in rs:
        added = deleted = commits = 0
        for line in git(d, ['log', '--all', '--numstat', '--format=%H']).splitlines():
            if not line.strip():
                continue
            p = line.split('\t')
            if len(p) == 3:
                if p[0] != '-':
                    added += int(p[0])
                if p[1] != '-':
                    deleted += int(p[1])
            elif len(line.strip()) == 40:
                commits += 1
        rows.append((name, added, deleted, commits))
        print('  authored %-30s +%s' % (name, format(added, ',')), file=sys.stderr)
    return rows



def do_entries(rs, shard, of):
    """EVERY ENTRY EVER ENTERED: every path in every commit's tree, duplicates included.

    A file unchanged across 500 commits counts 500 times. This is the only count that does not
    deduplicate, and it is far larger than the distinct-blob figure by design. Sharded by COMMIT
    SHA so the slices are disjoint and sum to the whole.
    """
    entries = 0
    lines = 0
    commits_done = 0
    cache = {}
    for name, d in rs:
        shas = [c for c in git(d, ['rev-list', '--all']).split()
                if of == 1 or int(c[:8], 16) % of == shard]
        for c in shas:
            commits_done += 1
            tree = git(d, ['ls-tree', '-r', c])
            need = []
            rows = []
            for line in tree.splitlines():
                p = line.split(None, 3)
                if len(p) < 4 or p[1] != 'blob':
                    continue
                rows.append(p[2])
                if p[2] not in cache:
                    cache[p[2]] = None
                    need.append(p[2])
            if need:
                cache.update(batch_count(d, need))
            for sha in rows:
                entries += 1
                v = cache.get(sha)
                if v and v > 0:
                    lines += v
        print('  entries %-30s %12s entries, %14s lines'
              % (name, format(entries, ','), format(lines, ',')), file=sys.stderr)
    return entries, lines, commits_done

def write_tsv(path, d):
    with open(path, 'w', encoding='utf-8', newline='\n') as f:
        for sha in sorted(d):
            v = d[sha]
            if v is not None and v >= 0:
                f.write('%s\t%d\n' % (sha, v))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--roots', default='.')
    ap.add_argument('--depth', default='head', choices=['head', 'history', 'authored', 'entries', 'all'])
    ap.add_argument('--out', default='data')
    ap.add_argument('--shard', type=int, default=0, help='0-based shard index')
    ap.add_argument('--of', type=int, default=1, help='total shards; the set is split by SHA')
    a = ap.parse_args()

    rs = find_repos([r for r in a.roots.split(',') if r])
    if not rs:
        print('FAIL: zero repositories. A check that examines nothing refuses.')
        return 1
    if a.of < 1 or not (0 <= a.shard < a.of):
        print('FAIL: --shard must be 0 <= shard < --of')
        return 1
    # Sharding is deterministic and by CONTENT, not by repository: a blob belongs to the shard
    # given by its own SHA. Every shard therefore sees a disjoint slice, no blob is counted twice,
    # and the shards sum exactly to the whole. Re-running any shard reproduces the same slice.
    global MINE
    MINE = (lambda sha: int(sha[:8], 16) % a.of == a.shard) if a.of > 1 else (lambda sha: True)

    now = datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds')
    run = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    os.makedirs(a.out, exist_ok=True)
    os.makedirs('proof', exist_ok=True)
    global SUF
    SUF = '' if a.of == 1 else '-%02d-of-%02d' % (a.shard, a.of)

    counts = {
        'shard': a.shard,
        'of': a.of,
        'run': run,
        'asof': now,
        'repositories': len(rs),
        'command': 'python tools/count_lines.py ' + ' '.join(sys.argv[1:]),
        'note': 'GitLab adds nothing: the mirror holds the same objects with the same SHAs.',
    }

    if a.depth in ('head', 'all'):
        seen = {}
        counts['tracked_paths'] = do_head(rs, seen)
        counts['head_blobs'] = len(seen)
        counts['head_text_blobs'] = sum(1 for v in seen.values() if v is not None and v >= 0)
        counts['head_binary_blobs'] = sum(1 for v in seen.values() if v == -1)
        counts['head_lines'] = sum(v for v in seen.values() if v and v > 0)
        write_tsv(os.path.join(a.out, 'blob-lines%s.tsv' % SUF), seen)

    if a.depth in ('history', 'all'):
        seen = {}
        do_history(rs, seen)
        counts['history_blobs'] = len(seen)
        counts['history_text_blobs'] = sum(1 for v in seen.values() if v is not None and v >= 0)
        counts['history_binary_blobs'] = sum(1 for v in seen.values() if v == -1)
        counts['history_lines'] = sum(v for v in seen.values() if v and v > 0)
        write_tsv(os.path.join(a.out, 'blob-lines-history%s.tsv' % SUF), seen)

    if a.depth in ('entries', 'all'):
        e, l, c = do_entries(rs, a.shard, a.of)
        counts['entries_ever'] = e
        counts['entry_lines_ever'] = l
        counts['commits_walked'] = c

    if a.depth in ('authored', 'all'):
        rows = do_authored(rs)
        with open(os.path.join(a.out, 'authored.tsv'), 'w', encoding='utf-8', newline='\n') as f:
            for n, ad, de, c in sorted(rows):
                f.write('%s\t%d\t%d\t%d\n' % (n, ad, de, c))
        counts['authored_added'] = sum(r[1] for r in rows)
        counts['authored_deleted'] = sum(r[2] for r in rows)
        counts['commits'] = sum(r[3] for r in rows)

    with open(os.path.join(a.out, 'counts%s.json' % SUF), 'w', encoding='utf-8', newline='\n') as f:
        f.write(json.dumps(counts, indent=1, sort_keys=True))

    digests = {}
    for fn in ('blob-lines.tsv', 'blob-lines-history.tsv', 'authored.tsv', 'counts.json'):
        p = os.path.join(a.out, fn)
        if os.path.exists(p):
            digests[fn] = hashlib.sha256(open(p, 'rb').read()).hexdigest()
    with open(os.path.join('proof', run + '-counts.json'), 'w', encoding='utf-8', newline='\n') as f:
        json.dump({'run': run, 'asof': now, 'digests': digests, 'counts': counts},
                  f, indent=1, sort_keys=True)

    for k in sorted(counts):
        if k in ('command', 'note'):
            continue
        v = counts[k]
        print('%-22s %s' % (k, format(v, ',') if isinstance(v, int) else v))
    print('\ndigests:')
    for k in sorted(digests):
        print('  %-28s %s' % (k, digests[k]))
    return 0


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