GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/tools

Wafer Development Environment — Proof 2 Page and 3 more files

A web page in the testcode folder of GlobalGrid2050 that converts to world (`toWorld`), steps anim (`stepAnim`), calculates planar distances and draws on a canvas. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609191305-proof-2/.

698 lines of Python and HTML from globalgrid2050, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1467 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. Key storage · globalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/tools/key.py lines 1–189
  2. Wafer Keys storage · globalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/tools/wafer_keys.py lines 1–88
  3. Wafer Development Environment — Proof 2 Page render · globalgrid2050 / testcode/wafer-development-environment/202609191305-proof-2/index.html lines 1–325
  4. Permanence storage · globalgrid2050 / testcode/wafer-development-environment/202609191305-proof-2/tools/permanence.py lines 1–96

Key

A Python command-line tool in the tools folder of GlobalGrid2050 that loads cache (`load_cache`), covering prove keys.

storageglobalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/tools/key.py · lines 1–189 of 189 · version 2026-09-19 12:55 · Entry point · pattern prove (shared by 3 files)

What it does
Defines 9 functions or classes, including rows, lines_of, load_cache, blob_lines, load. Uses libraries argparse, io, os, random, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file PROVE-KEYS.json; command-line arguments. Out: JSON file.
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 rows step (`rows`), the lines of helper (`lines_of`) and the blob lines helper (`blob_lines`). Turn a key into the actual line of text it stands for, using git alone. It accepts `--random` and `--prove-until`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · testcode/wafer-development-environment/202609191255-one-wafer/tools · Python CLI
Uses
argparse, io, os, random, subprocess, sys, bisect, json
Used by
none found
Produces
rows, lines_of, load_cache, blob_lines, load, key_of_line, resolve, prove, main
Defines here
rows, lines_of, load_cache, blob_lines, load, key_of_line, resolve, prove, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191255-one-wafer/tools/key.py:1-189 · blob d016b7b1f0ce4b28518de11d9990401c0d553632 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
"""tools/key.py - turn a key into the actual line of text it stands for, using git alone.

THE PROOF THAT THE COUNT AND THE MAP ARE REAL. The wafer claims that every line in every file in
every commit has one key, 0 to N-1. A claim like that is only worth something if any key, chosen
by anybody, can be followed to the line it names. This does that with no index of its own:

    key -> repository   binary search over cosmos/belt.tsv            (measured counts)
        -> commit       binary search over cosmos/commits/NN.tsv      (measured counts)
        -> file, line   walking `git ls-tree -r <commit>` in git's own order, counting lines
        -> the text     `git cat-file blob <sha>`, that line

If the counts were wrong anywhere, the walk inside the commit would not land where the shard says
the commit ends, and this says so and exits non zero instead of printing a line.

    python tools/key.py 23118447901          one key
    python tools/key.py --random 5           five keys chosen uniformly from the whole

Keys run oldest first: the oldest repository's oldest commit holds key 0. A repository that is not
public is measured but not named, and its lines are not printed.
"""
import argparse
import io
import os
import random
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
COSMOS = os.path.join(HERE, '..', 'cosmos')
ROOTS = 'C:/Users/vikra/Documents/GitHub'


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 lines_of(body):
    if b'\x00' in body[:8000]:
        return -1
    return body.count(b'\n') + (1 if body and not body.endswith(b'\n') else 0)


CACHE = {}


def load_cache():
    """sha -> lines for text blobs, measured earlier. Never trusted blind: the one blob a key lands
    in is always read for real and its count compared, and a mismatch refuses."""
    path = os.path.join(HERE, '..', 'data', 'blob-lines-history.tsv')
    if os.path.exists(path):
        for l in io.open(path, encoding='utf-8'):
            p = l.rstrip('\n').split('\t')
            if len(p) == 2:
                CACHE[p[0]] = int(p[1])


def blob_lines(d, sha):
    if sha in CACHE:
        return CACHE[sha], True
    body = subprocess.run(['git', 'cat-file', 'blob', sha], cwd=d, capture_output=True).stdout
    n = lines_of(body)
    CACHE[sha] = n
    return n, False


def load():
    """The wafer's own key law (tools/wafer_keys.py): every commit in time order, with the unissued
    keys of silence before it. Returns the commits, the address space, and the issued count."""
    names = {int(p[0]): p[1] for p in rows(os.path.join(COSMOS, 'repos.tsv'))}
    commits, k, issued = [], 0, 0
    for p in rows(os.path.join(COSMOS, 'wafer.tsv')):
        k += int(p[4])
        c = {'lines': int(p[1]), 'name': names[int(p[2])], 'sha': p[3], 'k0': k, 'cum': issued}
        k += c['lines']
        issued += c['lines']
        commits.append(c)
    return commits, k, issued


def key_of_line(commits, j):
    """the address key of the j-th line ever issued, 0 based"""
    import bisect
    c = commits[bisect.bisect_right([x['cum'] for x in commits], j) - 1]
    return c['k0'] + (j - c['cum'])


def resolve(commits, space, k):
    import bisect
    if not 0 <= k < space:
        return 'key %d is outside 0..%d' % (k, space - 1), 1
    c = commits[max(0, bisect.bisect_right([x['k0'] for x in commits], k) - 1)]
    if not c['k0'] <= k < c['k0'] + c['lines']:
        return 'key %s was never issued: it is silence between commits' % format(k, ','), 0
    repo = {'name': c['name']}
    sha12, lines, m = c['sha'], c['lines'], k - c['k0']          # line within the commit, 0 based
    head = 'key %s -> %s / %s / line %s of %s' % (format(k, ','), repo['name'], sha12,
                                                  format(m + 1, ','), format(lines, ','))
    if repo['name'].startswith('unnamed-'):
        return head + '\n  (not public: measured, not named, not printed)', 0
    d = os.path.join(ROOTS, repo['name'])
    if not os.path.isdir(os.path.join(d, '.git')):
        return head + '\n  REFUSED: no local clone at %s to verify against' % d, 2
    tree = subprocess.run(['git', 'ls-tree', '-r', sha12], cwd=d, capture_output=True).stdout
    seen = 0
    for entry in tree.split(b'\n'):
        if not entry:
            continue
        meta, _, path = entry.partition(b'\t')
        f = meta.split()
        if len(f) < 3 or f[1] != b'blob':
            continue
        n_lines, cached = blob_lines(d, f[2].decode())
        if n_lines <= 0:
            continue
        if m < seen + n_lines:
            body = subprocess.run(['git', 'cat-file', 'blob', f[2].decode()], cwd=d,
                                  capture_output=True).stdout
            if lines_of(body) != n_lines:
                return (head + '\n  REFUSED: the cache says %d lines for blob %s and git says %d'
                        % (n_lines, f[2].decode()[:12], lines_of(body))), 2
            text = body.split(b'\n')[m - seen].decode('utf-8', 'replace').rstrip('\r')
            return ('%s\n  %s : %d   (blob %s)\n  | %s'
                    % (head, path.decode('utf-8', 'replace'), m - seen + 1,
                       f[2].decode()[:12], text[:200])), 0
        seen += n_lines
    return head + '\n  REFUSED: walked the whole commit and found only %d lines; the shard says ' \
                  '%d. The count is wrong somewhere.' % (seen, lines), 2


def prove(belt, n, until, space):
    """THE UNATTENDED PROOF. Random keys, uniformly from the whole, each followed to its line.
    SAFEGUARDS: a hard stop at the stated UTC time; a hard stop at the first REFUSED, because one
    wrong key is worth more than a thousand right ones; one process, a pause between keys so the
    machine stays cool; a heartbeat file so anyone can see it is alive; append only logging."""
    import json, time
    from datetime import datetime, timezone
    out = r'E:\particles-runs'
    hh, mm = [int(x) for x in until.split(':')]
    ok = private = 0
    t0 = time.time()
    while True:
        now = datetime.now(timezone.utc)
        if (now.hour, now.minute) >= (hh, mm):
            break
        k = key_of_line(belt, random.randrange(n))
        msg, code = resolve(belt, space, k)
        with io.open(os.path.join(out, 'prove-keys.log'), 'a', encoding='utf-8') as f:
            f.write(now.strftime('%Y-%m-%dT%H:%M:%SZ ') + msg.replace('\n', ' || ')[:400] + '\n')
        if code:
            state = 'REFUSED'
        else:
            state = 'RUNNING'
            ok += 1
            private += 'not public' in msg
        json.dump({'state': state, 'keys_proved': ok, 'of_which_unnamed': private, 'wafer_keys': n,
                   'since': round(time.time() - t0), 'last': now.isoformat(timespec='seconds')},
                  io.open(os.path.join(out, 'PROVE-KEYS.json'), 'w', encoding='utf-8'), indent=1)
        if code:
            return 2
        time.sleep(0.3)
    return 0


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('key', nargs='?', type=int)
    ap.add_argument('--random', type=int, default=0)
    ap.add_argument('--prove-until', default='', help='HH:MM UTC. Random keys until then, logged.')
    a = ap.parse_args()
    load_cache()
    belt, space, n = load()
    if a.prove_until:
        return prove(belt, n, a.prove_until, space)
    keys = [a.key] if a.key is not None else [key_of_line(belt, random.randrange(n))
                                              for _ in range(a.random or 1)]
    print('the wafer issued %s keys in %d commits, inside %s addresses'
          % (format(n, ','), len(belt), format(space, ',')))
    worst = 0
    for k in keys:
        msg, code = resolve(belt, space, k)
        print(msg)
        worst = max(worst, code)
    return worst


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

Wafer Keys

A Python command-line tool in the tools folder of GlobalGrid2050 covering wafer meta. It is built from the rows step (`rows`).

storageglobalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/tools/wafer_keys.py · lines 1–88 of 88 · version 2026-09-19 12:55 · Entry point

What it does
Defines rows, main. Uses libraries io, json, os, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Out: JSON file wafer-meta.json.
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
Issue every line ever written its key, in the order time issued it.
Why it matters
Loaded by the What Is Kuiper page in Kuiper Belt at https://ventusltd.github.io/kuiper-belt/what-is-kuiper.html.
Application
globalgrid2050 · testcode/wafer-development-environment/202609191255-one-wafer/tools · Python CLI
Uses
io, json, os, sys
Used by
linked from What Is Kuiper (link)
Produces
rows, main
Defines here
rows, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191255-one-wafer/tools/wafer_keys.py:1-88 · blob d30dfec04bfa7f5ab240d240d4297575de5a3a02 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
"""tools/wafer_keys.py - issue every line ever written its key, in the order time issued it.

THE RINGS ARE TIME. The CPU wafer is beautiful because of its dark rings, and those rings are
numbers that were never issued. This estate has a measured source of exactly that: silence. Every
commit in every repository is put in one order, by its own timestamp, and before each commit a run
of keys is left UNISSUED in proportion to the time since the commit before it. A night is a dark
ring. A fortnight away is a wide one. Nothing is drawn in: the rings are commit times.

    issued keys      one per line in every file in every commit. Their count is the measurement.
    unissued keys    GAP_KEYS_PER_SECOND x the seconds of silence, capped at CAP_SECONDS.

GAP_KEYS_PER_SECOND is a DECLARED CONSTANT, frozen here. It is not fitted on each run, because a
constant that moved whenever a commit arrived would move every key after it.

A line not yet written already has its place: the next issued key, on the rim. That is what makes
the surface unbounded rather than merely large, and it is the same property RAM has: the address
exists before anything is stored at it.

Reads   cosmos/belt.tsv, cosmos/commits/NN.tsv          (measured, redacted where not public)
Writes  cosmos/wafer.tsv   unix  lines  repo_index  sha12  gap_before     in time order
        cosmos/wafer-meta.json
and refuses if the commits do not sum to the belt, or the belt to itself.
"""
import io
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
COSMOS = os.path.join(HERE, '..', 'cosmos')

GAP_KEYS_PER_SECOND = 600         # declared, frozen. About three tenths of the wafer is silence.
CAP_SECONDS = 14 * 86400          # no silence counts for more than a fortnight


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 main():
    belt = [(p[0], int(p[1])) for p in rows(os.path.join(COSMOS, 'belt.tsv'))]
    commits = []
    for i, (name, lines) in enumerate(belt):
        path = os.path.join(COSMOS, 'commits', '%02d.tsv' % i)
        if not os.path.exists(path):
            if lines:
                print('REFUSED: %s holds lines and has no commit shard' % name)
                return 2
            continue
        shard = [(int(p[0]), int(p[1]), p[3]) for p in rows(path)]
        if sum(c[1] for c in shard) != lines:
            print('REFUSED: shard %02d sums to %d, belt says %d' % (i, sum(c[1] for c in shard), lines))
            return 2
        commits += [(unix, n, i, sha) for unix, n, sha in shard if n > 0]

    commits.sort(key=lambda c: (c[0], c[2], c[3]))            # time, then a stable tiebreak
    issued = sum(c[1] for c in commits)
    if issued != sum(l for _, l in belt):
        print('REFUSED: commits hold %d lines, belt holds %d' % (issued, sum(l for _, l in belt)))
        return 2

    out, unissued, prev = [], 0, None
    for unix, n, i, sha in commits:
        gap = 0 if prev is None else GAP_KEYS_PER_SECOND * min(max(unix - prev, 0), CAP_SECONDS)
        unissued += gap
        out.append('%d\t%d\t%d\t%s\t%d' % (unix, n, i, sha, gap))
        prev = unix

    with io.open(os.path.join(COSMOS, 'wafer.tsv'), 'w', encoding='utf-8', newline='\n') as f:
        f.write('# unix\tlines\trepo_index\tsha12\tgap_before\n' + '\n'.join(out) + '\n')
    with io.open(os.path.join(COSMOS, 'repos.tsv'), 'w', encoding='utf-8', newline='\n') as f:
        f.write('# repo_index\tname\tlines\n'
                + '\n'.join('%d\t%s\t%d' % (i, n, l) for i, (n, l) in enumerate(belt)) + '\n')
    meta = {'issued_keys': issued, 'unissued_keys': unissued, 'address_space': issued + unissued,
            'silence_share': round(unissued / (issued + unissued), 4), 'commits': len(commits),
            'repositories': len(belt), 'first_unix': commits[0][0], 'last_unix': commits[-1][0],
            'gap_keys_per_second': GAP_KEYS_PER_SECOND, 'cap_seconds': CAP_SECONDS,
            'law': 'r = sqrt(key), theta = 2 pi frac(key x 2654435769 / 2^32)'}
    json.dump(meta, io.open(os.path.join(COSMOS, 'wafer-meta.json'), 'w', encoding='utf-8',
                            newline='\n'), indent=1)
    print(json.dumps(meta, indent=1))
    return 0


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

Wafer Development Environment — Proof 2 Page

A web page in the testcode folder of GlobalGrid2050 that converts to world (`toWorld`), steps anim (`stepAnim`), calculates planar distances and draws on a canvas. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609191305-proof-2/.

renderglobalgrid2050 / testcode/wafer-development-environment/202609191305-proof-2/index.html · lines 1–325 of 325 · version 2026-09-19 13:05 · Entry point · pattern keyAt (shared by 25 files)

What it does
It draws its content. Defines 22 functions or classes, including fmt, words, prog, U, tsv. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: form fields (user input). Out: web page; WebGL/WebGPU drawing.
Downstream impact
Used directly by 5 files: GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); Homepage V123 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v123.html); Homepage V124 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v124.html); and 1 more. Reached from 83 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609191305-proof-2/.
What it achieves
It shows new (`showNew`) and is built from the tsv step (`tsv`) and the resize step (`resize`). Defines `fmt`, `words`, `prog` and 18 more. It responds to webglcontextlost, resize and pointerdown events.
Why it matters
Loaded by the GlobalGrid2050 Homepage Before Four Nests page at https://globalgrid2050.com/homepage-before-four-nests-20260925.html and 4 other pages.
Application
globalgrid2050 · testcode/wafer-development-environment/202609191305-proof-2 · page
Uses
none found
Used by
linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
Produces
fmt, words, prog, U, tsv, resize, flyTo, home, keyPlace, findBy, address, describe
Defines here
fmt, words, prog, U, tsv, resize, flyTo, home, keyPlace, findBy, address, describe, keyAt, frame, draw, read, toWorld, show, goKey, showNew, stepAnim, finishSelftest
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191305-proof-2/index.html:1-325 · blob b1f488b0eceed5015be8f0910c34aec77df5b63c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Kuiper belt</title>
<style>
  :root{--bg:#090c13;--ink:#d5dcea;--dim:#7d8799;--line:#1a2030;--hot:#e8b36a}
  *{box-sizing:border-box}
  html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);
    font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow:hidden}
  canvas{position:fixed;inset:0;width:100%;height:100%;display:block}
  #c{z-index:1} #o{z-index:3;pointer-events:none}
  #top{position:fixed;top:0;left:0;padding:10px 14px;z-index:10;pointer-events:none;max-width:60vw;background:#090c13d9;border-bottom-right-radius:6px}
  #big{font-size:19px;letter-spacing:.03em} #sub{color:var(--dim);margin-top:2px}
  #hud{position:fixed;top:0;right:0;padding:10px 14px;z-index:10;color:var(--dim);text-align:right;white-space:pre-line;max-width:38vw;background:#090c13d9;border-bottom-left-radius:6px}
  #card{position:fixed;left:14px;bottom:64px;z-index:10;color:var(--ink);background:#090c13ee;
    border:1px solid var(--line);padding:9px 12px;white-space:pre-line;display:none;max-width:min(680px,92vw)}
  #card b{color:var(--hot);font-weight:600}
  #foot{position:fixed;left:0;right:0;bottom:0;padding:8px 14px;color:var(--dim);border-top:1px solid var(--line);
    background:#090c13ee;z-index:10;line-height:1.7}
  #foot b{color:var(--ink);font-weight:600} a{color:#66ccff}
  #goto{position:fixed;left:50%;top:38%;transform:translateX(-50%);z-index:20;display:none;background:var(--bg);
    border:1px solid var(--dim);padding:10px 12px;min-width:min(520px,86vw)}
  #goto input{width:100%;background:var(--bg);color:var(--ink);border:0;outline:0;font:14px ui-monospace,Consolas,monospace}
</style>
</head>
<body>
<canvas id="c"></canvas><canvas id="o"></canvas>
<div id="top"><div id="big">loading</div><div id="sub">&nbsp;</div></div>
<div id="hud">starting</div>
<div id="card"></div>
<div id="goto"><input id="gotoin" autocomplete="off" spellcheck="false" placeholder="a key, or a repository name to send light through"></div>
<div id="foot">
  <b>n</b> show new code &middot; <b>r</b> random line &middot; <b>/</b> a key, or a repository to light &middot; <b>click</b> lights the repository under the
  pointer through all of time &middot; drag &middot; scroll &middot; <b>backspace</b> whole wafer &middot; one law at every zoom:
  r = &radic;key, &theta; = key &times; golden angle &middot; dark rings are silence between commits, measured &middot; unresolved
  pixels are computed from the law, not drawn &middot; provided as is, without warranty of any kind; a chart, not a design
  &middot; <a href="https://github.com/Ventusltd/law">the laws</a>
</div>
<script type="module">
// THE KUIPER BELT AS ONE WAFER. Every line in every file in every commit, one key each, in the
// order time issued them.
//
// THE LAW, and there is only one, at every zoom:
//     key k  ->  r = sqrt(k),  theta = 2 pi frac(k G / 2^32),  G = 2654435769
// It inverts, k = r squared, so the number of keys in any annulus is arithmetic. Nothing is ever
// drawn 38,000 times into a pixel to discover a number the law already states.
//
// THE RINGS ARE TIME. Before each commit a run of keys is left UNISSUED in proportion to the
// silence since the commit before it (tools/wafer_keys.py, a declared constant). A night is a dark
// ring. The dark fraction of every pixel is computed exactly from a prefix sum of issued keys, so
// even the rings are arithmetic. A line not yet written already has its place, on the rim, the
// way an address in RAM exists before anything is stored at it.
//
// UNRESOLVED pixels state a computed count as a shade. RESOLVED fields draw exactly the issued keys
// whose radius can be on screen, each at its own place. There is no sampling and no white flash,
// because a pixel is never asked to be more than it is.
const G32 = 2654435769, TW = 4096;
const cv = document.getElementById('c'), ov = document.getElementById('o'), o2 = ov.getContext('2d');
const gl = cv.getContext('webgl2', { antialias:false, alpha:false, powerPreference:'high-performance' });
const hud = document.getElementById('hud'), big = document.getElementById('big'),
      sub = document.getElementById('sub'), card = document.getElementById('card');
const fmt = n => Math.round(n).toLocaleString('en-GB');
function words(n){ if (n >= 1e9) return (n/1e9).toFixed(2)+' billion'; if (n >= 1e6) return (n/1e6).toFixed(2)+' million';
  if (n >= 1e3) return (n/1e3).toFixed(1)+' thousand'; return n >= 10 ? n.toFixed(0) : n.toFixed(2); }
if (!gl) { hud.textContent = 'WebGL2 is not available. Refusing rather than drawing a fraction.'; throw 0; }

const VS_FULL = `#version 300 es
void main(){ vec2 p = vec2(float((gl_VertexID<<1)&2), float(gl_VertexID&2)); gl_Position = vec4(p*2.0-1.0,0.0,1.0); }`;
const FS_FIELD = `#version 300 es
precision highp float; precision highp sampler2D;
uniform vec2 u_res, u_center; uniform float u_zoom, u_R, u_points;
uniform sampler2D u_commits; uniform int u_n, u_litRepo; uniform float u_pulse, u_flash, u_newR;
out vec4 o;
vec4 C(int i){ return texelFetch(u_commits, ivec2(i % ${TW}, i / ${TW}), 0); }   // k0, k1, issued before, repo
int find(float k){ int lo = 0, hi = u_n - 1;
  for (int s = 0; s < 16; ++s){ if (lo >= hi) break; int m = (lo+hi+1)/2; if (C(m).r <= k) lo = m; else hi = m-1; } return lo; }
// how many ISSUED keys lie below address k: a prefix sum, so any annulus is one subtraction
float issuedBelow(float k){ vec4 c = C(find(k)); return c.b + clamp(k - c.r, 0.0, c.g - c.r); }
void main(){
  vec2 w = u_center + (gl_FragCoord.xy - 0.5*u_res) / u_zoom;
  float r = length(w), h = 0.75 / u_zoom;
  vec3 bg = vec3(0.035,0.047,0.075), dust = vec3(0.79,0.83,0.90);
  if (r > u_R + h) { float rim = smoothstep(2.5/u_zoom, 0.0, abs(r - u_R)); o = vec4(bg + rim*0.10, 1.0); return; }
  float ka = max(r-h, 0.0), kb = r+h; ka *= ka; kb *= kb;
  float cov = clamp((issuedBelow(kb) - issuedBelow(ka)) / max(kb - ka, 1.0), 0.0, 1.0);   // issued share of this pixel
  float perPx = cov / (3.14159265 * u_zoom * u_zoom);                                      // issued keys in this pixel
  float v = (u_points > 0.5) ? 0.0 : clamp(0.24 + 0.13*log(1.0+perPx)/2.302585, 0.0, 0.88) * pow(cov, 0.55);
  vec3 col = mix(bg, dust, v);
  // THE LIGHT. Which repository owns the key at the centre of this pixel. This one is a tap, not
  // a count: it says where a repository's work lies in time, and no number is read off it.
  if (u_litRepo >= 0) { float kc = r*r; vec4 c = C(find(kc)); if (kc <= c.g && int(c.a + 0.5) == u_litRepo)
    col = mix(col, vec3(0.95,0.72,0.40), u_points > 0.5 ? 0.10 : 0.72); }
  // THE PULSE travels outward from the centre, which on this wafer is forward through time. It is
  // the instrument's sweep, not data, so it is faint over silence and bright over work.
  if (u_pulse >= 0.0) { float d = abs(r - u_pulse) * u_zoom; col += vec3(0.95,0.90,0.75) * exp(-d*d/160.0) * (0.25 + 0.75*cov); }
  // THE FLASH lights only keys issued at or after the boundary, and only where keys were issued.
  if (u_flash > 0.0 && r + h >= u_newR && cov > 0.0) col = mix(col, vec3(1.0,0.78,0.42), u_flash);
  o = vec4(col, 1.0);
}`;
const VS_KEYS = `#version 300 es
precision highp float;
uniform uint u_k0lo; uniform float u_R0, u_zoom, u_hot; uniform vec2 u_center, u_res;
out float v_hot;
void main(){
  float d = float(gl_VertexID);
  float r = u_R0 + (d + 0.5) / (u_R0 + sqrt(u_R0*u_R0 + d + 0.5) + 1e-9);      // sqrt(k0+d+.5), kept precise
  uint m = (u_k0lo + uint(gl_VertexID)) * ${G32}u;
  float A = 6.283185307179586 * float(m >> 16) / 65536.0, B = 6.283185307179586 * float(m & 0xFFFFu) / 4294967296.0;
  vec2 cs = vec2(cos(A)*cos(B) - sin(A)*sin(B), sin(A)*cos(B) + cos(A)*sin(B));
  gl_Position = vec4((r*cs - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0);
  gl_PointSize = clamp(u_zoom * 0.34, 1.0, 9.0); v_hot = u_hot;
}`;
const FS_KEYS = `#version 300 es
precision highp float; in float v_hot; out vec4 o;
void main(){ if (length(gl_PointCoord-0.5) > 0.5) discard;
  o = vec4(mix(vec3(0.79,0.83,0.90), vec3(0.97,0.74,0.40), v_hot), 1.0); }`;
function prog(vs, fs){ const p = gl.createProgram();
  for (const [t,s] of [[gl.VERTEX_SHADER,vs],[gl.FRAGMENT_SHADER,fs]]) { const sh = gl.createShader(t);
    gl.shaderSource(sh,s); gl.compileShader(sh);
    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh)); gl.attachShader(p,sh); }
  gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p)); return p; }
const PF = prog(VS_FULL, FS_FIELD), PK = prog(VS_KEYS, FS_KEYS);
const U = (p, n) => gl.getUniformLocation(p, n);
gl.bindVertexArray(gl.createVertexArray());
let lost = false;
cv.addEventListener('webglcontextlost', e => { e.preventDefault(); lost = true;
  hud.textContent = 'CONTEXT LOST. Nothing on screen is a count. Reload.'; });

// --------------------------------------------------------------------------------- the data
// cosmos/wafer.tsv: every commit in time order with its measured lines and the unissued keys
// before it. One file, about 400 kB, and then nothing else is ever fetched to draw the whole.
let N = 0, SPACE = 0, repos = [], commits = [];
async function tsv(url){ const r = await fetch(url); if (!r.ok) throw new Error(url);
  return (await r.text()).split('\n').filter(l => l && l[0] !== '#').map(l => l.split('\t')); }
Promise.all([tsv('cosmos/repos.tsv'), tsv('cosmos/wafer.tsv')]).then(([rr, ww]) => {
  repos = rr.map(p => ({ i:+p[0], name:p[1], lines:+p[2], seen:0, commits:0 }));
  let k = 0, issued = 0;
  commits = ww.map(p => { k += +p[4]; const c = { unix:+p[0], lines:+p[1], repo:+p[2], sha:p[3], gap:+p[4], k0:k, cum:issued };
    k += c.lines; issued += c.lines; c.k1 = k; repos[c.repo].seen += c.lines; repos[c.repo].commits++; return c; });
  const bad = repos.find(r => r.seen !== r.lines);
  if (bad) { hud.textContent = 'REFUSED: the commits of ' + bad.name + ' sum to ' + fmt(bad.seen) + ', the belt says ' + fmt(bad.lines); return; }
  N = issued; SPACE = k;
  const H = Math.ceil(commits.length / TW), a = new Float32Array(TW * H * 4);
  commits.forEach((c, i) => { a[i*4] = c.k0; a[i*4+1] = c.k1; a[i*4+2] = c.cum; a[i*4+3] = c.repo; });
  gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, TW, H, 0, gl.RGBA, gl.FLOAT, a);
  big.textContent = words(N) + ' lines · one wafer';
  sub.textContent = fmt(N) + ' keys issued, one per line in every file in every commit · ' + fmt(commits.length) + ' commits in '
    + repos.length + ' repositories, in the order time issued them · ' + words(SPACE - N) + ' keys left unissued as silence · '
    + new Date(commits[0].unix*1000).toISOString().slice(0,10) + ' at the centre, ' + new Date(commits[commits.length-1].unix*1000).toISOString().slice(0,10)
    + ' at the rim, and the next line ever written lands beyond it';
  home(); dirty = true;
  if (new URLSearchParams(location.search).get('selftest') === 'new') { selftest = {}; tween = null; setTimeout(() => showNew(24), 300); }
}).catch(() => { hud.textContent = 'cosmos/wafer.tsv did not load. The wafer will not invent its keys.'; });

// ------------------------------------------------------------------------ camera and address
let cx = 0, cy = 0, zoom = 1, dirty = true, tween = null, litRepo = -1, target = null;
let pulse = -1, flash = 0, newFrom = -1, anim = null, selftest = null;
function resize(){ cv.width = ov.width = innerWidth; cv.height = ov.height = innerHeight; gl.viewport(0,0,cv.width,cv.height); dirty = true; }
addEventListener('resize', resize); resize();
function flyTo(x, y, z){ tween = { t0:performance.now(), x0:cx, y0:cy, z0:zoom, x1:x, y1:y, z1:z, dur:900 }; }
function home(){ flyTo(0, 0, (Math.min(cv.width, cv.height)/2) * 0.80 / Math.sqrt(SPACE)); }
function keyPlace(k){ const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0, th = 2*Math.PI*m/4294967296, r = Math.sqrt(k + 0.5);
  return [r*Math.cos(th), r*Math.sin(th)]; }
function findBy(field, v){ let lo = 0, hi = commits.length - 1; while (lo < hi) { const m = (lo+hi+1)>>1; if (commits[m][field] <= v) lo = m; else hi = m-1; } return lo; }
// an address key resolves to a commit by binary search; no walking, and silence is an answer too
function address(k){ if (!(k >= 0) || k >= SPACE) return null; const i = findBy('k0', k), c = commits[i];
  return (k >= c.k0 && k < c.k1) ? { k, i, c, m:k - c.k0 } : { k, i, c, silent:true, next:commits[i + (k < c.k0 ? 0 : 1)] }; }
function describe(a){
  if (!a) return '';
  if (a.silent) { const n = a.next; return 'key <b>' + fmt(a.k) + '</b> was never issued\nsilence' + (n ? ' of ' + words((n.gap/ (n.gap ? 1 : 1))) + ' keys before ' + repos[n.repo].name + ' / ' + n.sha + ', '
      + new Date(n.unix*1000).toISOString().slice(0,16) + 'Z' : ''); }
  const r = repos[a.c.repo];
  return 'key <b>' + fmt(a.k) + '</b> · line ' + fmt(a.c.cum + a.m + 1) + ' of ' + fmt(N) + ' ever issued\n' + r.name + '  (' + words(r.lines) + ' lines in ' + fmt(r.commits) + ' commits)'
    + '\ncommit <b>' + a.c.sha + '</b>  ' + new Date(a.c.unix*1000).toISOString().slice(0,16) + 'Z  ·  line ' + fmt(a.m + 1) + ' of ' + fmt(a.c.lines)
    + '\nthe text itself:  python tools/key.py ' + a.k;
}
function keyAt(wx, wy){ const r = Math.hypot(wx, wy), kc = Math.round(r*r), span = Math.ceil(6*r + 8); let best = -1, bd = 0.6;
  for (let k = Math.max(0, kc - span); k <= Math.min(SPACE-1, kc + span); k++) { const p = keyPlace(k), d = Math.hypot(p[0]-wx, p[1]-wy); if (d < bd) { bd = d; best = k; } }
  return best; }

// --------------------------------------------------------------------------------- the frame
const POINTS_FROM = 1.0, MAX_CALLS = 3000;
function frame(){
  if (lost) return;
  if (tween) { const u = Math.min(1, (performance.now()-tween.t0)/tween.dur), e = u<0.5 ? 2*u*u : 1-Math.pow(-2*u+2,2)/2;
    zoom = Math.exp(Math.log(tween.z0) + (Math.log(tween.z1)-Math.log(tween.z0))*e);
    cx = tween.x0 + (tween.x1-tween.x0)*e; cy = tween.y0 + (tween.y1-tween.y0)*e; dirty = true; if (u >= 1) tween = null; }
  if (anim) stepAnim();
  if (dirty && N) { draw(); dirty = false; }
  requestAnimationFrame(frame);
}
function draw(){
  const R = Math.sqrt(SPACE), W = cv.width, H = cv.height;
  const x0 = cx - W/2/zoom, x1 = cx + W/2/zoom, y0 = cy - H/2/zoom, y1 = cy + H/2/zoom;
  const dx = x0 > 0 ? x0 : (x1 < 0 ? -x1 : 0), dy = y0 > 0 ? y0 : (y1 < 0 ? -y1 : 0);
  const rmin = Math.hypot(dx, dy), rmax = Math.max(Math.hypot(x0,y0), Math.hypot(x1,y0), Math.hypot(x0,y1), Math.hypot(x1,y1));
  const ka = Math.min(SPACE, Math.floor(rmin*rmin)), kb = Math.min(SPACE, Math.ceil(rmax*rmax));
  // the screen's radii are a contiguous run of addresses; the issued ones among them are whole commits and two part commits
  let i0 = findBy('k0', ka), segs = [], total = 0;
  if (zoom >= POINTS_FROM) for (let i = i0; i < commits.length && commits[i].k0 < kb && segs.length <= MAX_CALLS; i++) {
    const s0 = Math.max(commits[i].k0, ka), s1 = Math.min(commits[i].k1, kb); if (s1 > s0) { segs.push([s0, s1, commits[i].repo, i]); total += s1 - s0; } }
  const points = zoom >= POINTS_FROM && segs.length <= MAX_CALLS && total < 1.6e9;

  gl.useProgram(PF);
  gl.uniform2f(U(PF,'u_res'), W, H); gl.uniform2f(U(PF,'u_center'), cx, cy); gl.uniform1f(U(PF,'u_zoom'), zoom);
  gl.uniform1f(U(PF,'u_R'), R); gl.uniform1f(U(PF,'u_points'), points ? 1 : 0);
  gl.uniform1f(U(PF,'u_pulse'), pulse); gl.uniform1f(U(PF,'u_flash'), flash);
  gl.uniform1f(U(PF,'u_newR'), newFrom >= 0 ? Math.sqrt(commits[newFrom].k0) : 1e30);
  gl.uniform1i(U(PF,'u_commits'), 0); gl.uniform1i(U(PF,'u_n'), commits.length); gl.uniform1i(U(PF,'u_litRepo'), litRepo);
  gl.drawArrays(gl.TRIANGLES, 0, 3);

  if (selftest && selftest.wantPixels && flash > 0.5 && !points) {
    const px = new Uint8Array(4), R0 = Math.sqrt(commits[newFrom].k0), rm = (R0 + R) / 2;
    const read = (wx) => { gl.readPixels(Math.round(W/2 + (wx - cx)*zoom), Math.round(H/2 + (0 - cy)*zoom), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); return [px[0], px[1], px[2]]; };
    selftest.newBandPixel = read(rm); selftest.pupilPixel = read(0); selftest.wantPixels = false; }
  let ms = 0;
  if (points) { const t0 = performance.now(); gl.useProgram(PK);
    gl.uniform1f(U(PK,'u_zoom'), zoom); gl.uniform2f(U(PK,'u_center'), cx, cy); gl.uniform2f(U(PK,'u_res'), W, H);
    for (const [s0, s1, rp, ci] of segs) { gl.uniform1f(U(PK,'u_hot'), (newFrom >= 0 ? ci >= newFrom : rp === litRepo) ? 1 : 0);
      for (let off = s0; off < s1; off += 4000000) {                       // bounded calls; the driver watchdog is real
        gl.uniform1ui(U(PK,'u_k0lo'), (off % 4294967296) >>> 0); gl.uniform1f(U(PK,'u_R0'), Math.sqrt(off));
        gl.drawArrays(gl.POINTS, 0, Math.min(4000000, s1 - off)); } }
    gl.finish(); ms = performance.now() - t0; }

  const L = [];
  L.push(points ? 'RESOLVED · every issued key whose radius is in the field, drawn at its own place'
                : 'UNRESOLVED · up to ' + words(1/(Math.PI*zoom*zoom)) + ' keys to a pixel · each pixel’s issued count is computed from the law, not drawn');
  if (points) L.push(fmt(total) + ' issued keys from ' + fmt(segs.length) + ' commits passed to the GPU in ' + ms.toFixed(0) + ' ms');
  L.push('the whole · ' + fmt(N) + ' issued + ' + fmt(SPACE - N) + ' silent = ' + fmt(SPACE) + ' addresses');
  if (litRepo >= 0) L.push('LIGHT · ' + repos[litRepo].name + ' · ' + words(repos[litRepo].lines) + ' lines in ' + fmt(repos[litRepo].commits) + ' commits, wherever in time they fall');
  L.push(zoom >= 1 ? 'zoom ' + zoom.toFixed(1) + ' px per key spacing' : 'zoom 1 px = ' + words(1/zoom) + ' units');
  hud.textContent = L.join('\n');
  o2.clearRect(0,0,ov.width,ov.height);
  if (target && target.boundary && zoom >= POINTS_FROM) {
    // at this zoom the boundary circle is straight across the screen: perpendicular to the radius
    const x = (target.x - cx)*zoom + ov.width/2, y = ov.height/2 - (target.y - cy)*zoom, rr = Math.hypot(target.x, target.y) || 1;
    const tx = -target.y/rr, ty = target.x/rr, Lp = Math.hypot(ov.width, ov.height);
    o2.strokeStyle = 'rgba(255,199,107,.95)'; o2.lineWidth = 2; o2.setLineDash([10,6]); o2.beginPath();
    o2.moveTo(x - tx*Lp, y + ty*Lp); o2.lineTo(x + tx*Lp, y - ty*Lp); o2.stroke(); o2.setLineDash([]);
    o2.font = '12px ui-monospace,Consolas,monospace'; o2.fillStyle = 'rgba(255,199,107,1)';
    // outward is newer, and which way outward points on screen depends on where this key sits, so
    // the words are placed along the real radius rather than assumed to read left to right
    const ox = target.x/rr, oy = -target.y/rr;
    o2.textAlign = 'center';
    o2.fillText('NEW CODE', x + ox*110, y + oy*110); o2.fillStyle = 'rgba(213,220,234,.85)';
    o2.fillText('older', x - ox*110, y - oy*110); o2.fillStyle = 'rgba(255,199,107,1)';
    o2.fillText('the boundary', x + tx*150, y - ty*150 - 8); o2.textAlign = 'start'; }
  if (target) { const x = (target.x - cx)*zoom + ov.width/2, y = ov.height/2 - (target.y - cy)*zoom;
    o2.strokeStyle = 'rgba(232,179,106,.95)'; o2.lineWidth = 1; o2.beginPath();
    for (const [a,b,c,d] of [[-16,0,-6,0],[6,0,16,0],[0,-16,0,-6],[0,6,0,16]]) { o2.moveTo(x+a,y+b); o2.lineTo(x+c,y+d); } o2.stroke(); }
}

// ------------------------------------------------------------------------------ the controls
function toWorld(px, py){ return [cx + (px - innerWidth/2)/zoom, cy - (py - innerHeight/2)/zoom]; }
function show(a){ card.style.display = 'block'; card.innerHTML = describe(a); if (a && !a.silent) litRepo = a.c.repo; dirty = true; }
function goKey(k){ const p = keyPlace(k); target = { x:p[0], y:p[1] }; show(address(k)); flyTo(p[0], p[1], 14); }
// SHOW NEW CODE. "New" is measured from the newest commit, not from the wall clock, so the same
// page gives the same answer tomorrow. Keys run in time order, so what is new is always one
// contiguous band at the rim: the boundary is a single circle, and that circle is drawn.
function showNew(hours){
  const last = commits[commits.length-1].unix, cut = last - hours*3600;
  newFrom = findBy('unix', cut - 1) + (commits[0].unix >= cut ? 0 : 1); if (newFrom >= commits.length) newFrom = commits.length - 1;
  litRepo = -1; target = null; card.style.display = 'none'; tween = null;
  const R = Math.sqrt(SPACE); cx = 0; cy = 0; zoom = (Math.min(cv.width, cv.height)/2) * 0.80 / R;
  anim_hours = hours; anim = { t0:performance.now(), hours, R }; dirty = true;
}
function stepAnim(){
  const t = (performance.now() - anim.t0) / 1000; dirty = true;
  if (t < 1.6) { const u = t/1.6; pulse = anim.R * (u*u*(3-2*u)); flash = 0; }
  else if (t < 2.5) { pulse = -1; flash = 1 - 0.45*((t-1.6)/0.9); if (selftest && selftest.wantPixels === undefined) selftest.wantPixels = true; }
  else { const c = commits[newFrom], n = commits.length - newFrom; let lines = 0; for (let i = newFrom; i < commits.length; i++) lines += commits[i].lines;
    flash = 0.35; anim = null; const p = keyPlace(c.k0); target = { x:p[0], y:p[1], boundary:true };
    card.style.display = 'block';
    card.innerHTML = 'NEW CODE · the last ' + anim_hours + ' hours before the newest commit\n<b>' + fmt(lines) + '</b> lines in <b>' + fmt(n) + '</b> commits, one band at the rim'
      + '\nbegins at key <b>' + fmt(c.k0) + '</b> · ' + repos[c.repo].name + ' / ' + c.sha + ' · ' + new Date(c.unix*1000).toISOString().slice(0,16) + 'Z'
      + '\nthe text itself:  python tools/key.py ' + c.k0;
    flyTo(p[0], p[1], 14);
    if (selftest) finishSelftest(c, n, lines); }
}
let anim_hours = 24;
// THE TESTS, run by the page on itself with ?selftest=new, so the verdict is not an opinion.
function finishSelftest(c, n, lines){
  let maxOld = 0; for (let i = 0; i < newFrom; i++) maxOld = Math.max(maxOld, commits[i].k1);
  const a = address(c.k0), nb = selftest.newBandPixel || [0,0,0], pp = selftest.pupilPixel || [0,0,0];
  const T = { T1_new_is_one_band_beyond_everything_older: c.k0 >= maxOld,
              T2_boundary_key_resolves_to_a_new_commit: !!(a && !a.silent && a.i >= newFrom && a.m === 0),
              T3_flash_is_amber_on_the_new_band: nb[0] > 150 && nb[0] > nb[2] + 40,
              T3_no_flash_on_the_silent_centre: pp[0] < 40 && pp[1] < 40,
              new_commits: n, new_lines: lines, boundary_key: c.k0, newBandPixel: nb, pupilPixel: pp };
  T.PASS = T.T1_new_is_one_band_beyond_everything_older && T.T2_boundary_key_resolves_to_a_new_commit && T.T3_flash_is_amber_on_the_new_band && T.T3_no_flash_on_the_silent_centre;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
let drag = null, moved = 0;
cv.addEventListener('pointerdown', e => { drag = [e.clientX, e.clientY]; moved = 0; });
addEventListener('pointerup', e => {
  if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
    if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
      target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
  drag = null; });
addEventListener('pointermove', e => { if (!drag) return; moved += Math.abs(e.clientX-drag[0]) + Math.abs(e.clientY-drag[1]);
  cx -= (e.clientX-drag[0])/zoom; cy += (e.clientY-drag[1])/zoom; drag = [e.clientX, e.clientY]; tween = null; dirty = true; });
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
  zoom = Math.max(1e-4, Math.min(60, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
  tween = null; dirty = true; }, { passive:true });
const gbox = document.getElementById('goto'), gin = document.getElementById('gotoin');
gin.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') { gbox.style.display = 'none'; return; }
  if (e.key !== 'Enter') return; gbox.style.display = 'none'; const raw = gin.value.trim(), q = raw.replace(/[ ,_]/g,'');
  const mnew = raw.toLowerCase().match(/^(?:show\s+)?new(?:\s+code)?(?:\s+(\d+)\s*h?)?$/);
  if (mnew) { showNew(mnew[1] ? Number(mnew[1]) : 24); return; }
  if (/^\d+$/.test(q)) goKey(Math.min(SPACE-1, Number(q)));
  else { const r = repos.find(x => x.name.toLowerCase() === raw.toLowerCase()) || repos.find(x => x.name.toLowerCase().includes(raw.toLowerCase()));
    if (r) { litRepo = r.i; target = null; card.style.display = 'none'; home(); dirty = true; } } });
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
  if (e.key === 'r' && N) { const j = Math.floor(Math.random()*N), c = commits[findBy('cum', j)]; goKey(c.k0 + (j - c.cum)); }   // uniform over issued lines
  else if (e.key === 'n' && N) showNew(24);
  else if (e.key === '/') { e.preventDefault(); gbox.style.display = 'block'; gin.value = ''; gin.focus(); }
  else if (e.key === 'Backspace') { e.preventDefault(); target = null; litRepo = -1; newFrom = -1; flash = 0; pulse = -1; card.style.display = 'none'; home(); } });
requestAnimationFrame(frame);
</script>
</body>
</html>

Permanence

A Python command-line tool in the tools folder of GlobalGrid2050. It is built from the show step (`show`), the parse step (`parse`) and the keys from helper (`keys_from`).

storageglobalgrid2050 / testcode/wafer-development-environment/202609191305-proof-2/tools/permanence.py · lines 1–96 of 96 · version 2026-09-19 13:05 · Entry point

What it does
Defines show, parse, keys_from, main. Uses libraries io, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: command-line arguments. Out: JSON file permanence.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Did the lines written since this morning move any address issued before?
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · testcode/wafer-development-environment/202609191305-proof-2/tools · Python CLI
Uses
io, json, os, subprocess, sys, wafer_keys
Used by
none found
Produces
show, parse, keys_from, main
Defines here
show, parse, keys_from, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191305-proof-2/tools/permanence.py:1-96 · blob bbc56662b6a9b727ade1fd9cd83f3128a17e0a4a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
"""tools/permanence.py - did the lines written since this morning move any address issued before?

THE CLAIM. Keys are issued in the order time issued the commits, with a frozen constant for
silence. So a commit made later lands beyond the rim, and nothing that already had an address
moves. If that is true the wafer measures the future without rewriting the past, the way new data
is appended to a disk without moving what is already on it.

THE TEST, on real data and able to fail. An earlier measurement of the estate is still in git: the
belt and commit shards as they were committed in Ventusltd/cosmic. Keys are rebuilt from that older
measurement with the same law, and every commit present in both is compared:

    same address then and now  ->  kept
    different address          ->  MOVED, and the first few are printed

It fails if anything with an old timestamp arrived late: a fetch that brought in older history, a
rebase, a clock that was wrong. Those are real and this is how they would show.

    python tools/permanence.py d672e69
"""
import io
import json
import os
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from wafer_keys import GAP_KEYS_PER_SECOND, CAP_SECONDS   # the same frozen constants, imported

COSMIC = os.path.join(HERE, '..', '..', 'cosmic')
COSMOS = os.path.join(HERE, '..', 'cosmos')


def show(rev, path):
    r = subprocess.run(['git', 'show', '%s:%s' % (rev, path)], cwd=COSMIC, capture_output=True)
    return r.stdout.decode('utf-8', 'replace') if r.returncode == 0 else None


def parse(text):
    return [l.split('\t') for l in text.split('\n') if l.strip() and not l.startswith('#')]


def keys_from(commits):
    """commits: (unix, lines, tiebreak, sha12). Returns sha12 -> first address, and the totals."""
    commits.sort(key=lambda c: (c[0], c[2], c[3]))
    out, k, prev = {}, 0, None
    for unix, n, _, sha in commits:
        if prev is not None:
            k += GAP_KEYS_PER_SECOND * min(max(unix - prev, 0), CAP_SECONDS)
        out[sha] = k
        k += n
        prev = unix
    return out, k


def main():
    rev = sys.argv[1] if len(sys.argv) > 1 else 'd672e69'
    when = subprocess.run(['git', 'log', '-1', '--format=%cI', rev], cwd=COSMIC,
                          capture_output=True, text=True).stdout.strip()
    belt = parse(show(rev, 'belt.tsv') or '')
    if not belt:
        print('REFUSED: no belt.tsv at %s' % rev)
        return 2
    old = []
    for i in range(len(belt)):
        t = show(rev, 'commits/%02d.tsv' % i)
        if t:
            old += [(int(p[0]), int(p[1]), 0, p[3]) for p in parse(t) if int(p[1]) > 0]
    old_keys, old_space = keys_from(old)

    now = [(int(p[0]), int(p[1]), 0, p[3])
           for p in parse(io.open(os.path.join(COSMOS, 'wafer.tsv'), encoding='utf-8').read())]
    now_keys, now_space = keys_from(now)

    shared = [s for s in old_keys if s in now_keys]
    moved = [s for s in shared if old_keys[s] != now_keys[s]]
    gone = [s for s in old_keys if s not in now_keys]
    new = [s for s in now_keys if s not in old_keys]
    new_lines = sum(c[1] for c in now if c[3] in set(new))
    res = {'earlier_measurement': rev, 'committed': when,
           'commits_then': len(old_keys), 'commits_now': len(now_keys),
           'in_both': len(shared), 'kept_their_address': len(shared) - len(moved),
           'MOVED': len(moved), 'no_longer_present': len(gone),
           'arrived_since': len(new), 'lines_arrived_since': new_lines,
           'address_space_then': old_space, 'address_space_now': now_space,
           'rim_moved_outward_by_keys': now_space - old_space,
           'first_moved': [(s, old_keys[s], now_keys[s]) for s in moved[:5]]}
    print(json.dumps(res, indent=1))
    json.dump(res, io.open(os.path.join(COSMOS, 'permanence.json'), 'w', encoding='utf-8',
                           newline='\n'), indent=1)
    return 1 if moved else 0


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