GLOBALGRID2050 / EXPLORE CODE

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

Element Keys and 1 more file

A Python command-line tool in the tools folder of Kuiper Belt that reads blocks and elements, using SHA-256. It copies graph (`copy_graph`) and loads rows (`load_rows`).

505 lines of Python and JavaScript from kuiper-belt, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1550 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. Element Keys storage · kuiper-belt / tools/element_keys.py lines 1–378
  2. Entangle Hosts storage · kuiper-belt / tools/entangle_hosts.mjs lines 1–127

Element Keys

A Python command-line tool in the tools folder of Kuiper Belt that reads blocks and elements, using SHA-256. It copies graph (`copy_graph`) and loads rows (`load_rows`).

storagekuiper-belt / tools/element_keys.py · lines 1–378 of 378 · Entry point · pattern load_rows (shared by 5 files)

What it does
It loads blocks and elements. Defines 11 functions or classes, including private, redact, sub, copy_graph, live_register. Uses libraries argparse, bisect, hashlib, io, json. 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 blocks.json; JSON file elements.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Apps Registry (kuiper-belt).
What it achieves
Give every element of the periodic table its key on the wafer, by the wafer's own law. It accepts `--elements`, `--roots` and `--out`.
Why it matters
Imported by Apps Registry.
Application
kuiper-belt · tools · Python CLI
Uses
Edition Keys (import), Check Proof (import), argparse, bisect, hashlib, io, json, os, re, subprocess
Used by
imported by Apps Registry (import)
Produces
private, redact, copy_graph, live_register, sha256_file, git, holders, clone_with, load_rows, main
Defines here
private, redact, sub, copy_graph, live_register, sha256_file, git, holders, clone_with, load_rows, 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/element_keys.py:1-378 · blob 6042a7770853d3af63ab0d0a215444b549fa64cb · 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
"""tools/element_keys.py - give every element of the periodic table its key on the wafer, by the wafer's own law.

    python3 tools/element_keys.py --elements <elements clone> --roots /home/user/estate,/home/user[,<more>] \\
        --out editions/202611012135/data/elements.json [--check 3]

The key of an element is the key of line 1 of the first file the register lists for it (`files[0]`), at the
register's recorded commit (NL-010 ROADMAP step 7, 7.3; team-4/STEPS.md 7.3). It is computed exactly as
tools/edition_keys.py computes a verified line's key, with that tool's own functions (imported, not copied):

    commit -> wafer row      the row of cosmos/wafer.tsv whose sha12 is commit[:12] (same repository preferred)
    row    -> k0             cumulative gap_before + lines over the whole wafer, in order (key.py load())
    path   -> lines_before   walking `git ls-tree -r <commit>` in git's own order, summing lines_of() per blob
    key    =  k0 + lines_before + (1 - 1)

The walk is always finished and must land where the wafer row says the commit ends; the file's own blob is read for
real and must hold at least one text line. Otherwise the element is `placed: false` with the reason (`why`), and it is
not placed. An element whose register lists no files is counted and named, never placed (the seventh law,
editions/202611012027/README.md:34-35). `--check N` resolves N keyed elements back the other way, as
tools/key.py resolve() does (key -> wafer row by k0 -> walk -> path, line), and refuses on any disagreement.

What is copied from the catalogue: only `block:<Sym>` (as `sym`), the catalogue `number`, and the register's file
address (repo, commit, path). Never a title, a description or a category word: the elements repository states no
licence (ROADMAP "Open questions" Q1: copy only keys until the owner answers; handoff/07-apps/PLAN.md).
A clone is any directory, bare or not, that holds the commit; `--roots` lists directories whose children are clones.
"""
import argparse
import bisect
import hashlib
import io
import json
import os
import re
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import edition_keys as EK                                   # noqa: E402  the walk, the cache, the wafer: one law
from check_proof import NOT_PUBLIC                          # noqa: E402  K1's digests (tools/ci_check.py K1)

TOKEN = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*')          # check_proof.leaks()'s own token rule
REDACTED = 'not-public'


def private(tok):
    return any(hashlib.sha256(t.lower().encode()).hexdigest()[:24] in NOT_PUBLIC
               for t in {tok, tok.rstrip('.'), tok.split('/')[-1]})


def redact(text):
    """K1: a token whose digest names a repository that is not public is replaced, never written. A folder can
    carry such a name inside a public repository; its key is still computed from the real path, and only the
    written text is redacted. Returns (text, how many tokens were replaced)."""
    n = [0]

    def sub(m):
        t = m.group(0)
        if private(t):
            n[0] += 1
            return REDACTED + ('.' if t.endswith('.') else '')
        return t
    return TOKEN.sub(sub, text), n[0]


def copy_graph(src, dst):
    """a spider graph into the edition: byte for byte, unless K1 finds a non-public name in it; then that token
    alone is replaced (bytes otherwise identical) and both digests are printed for the record"""
    raw = open(src, 'rb').read()
    text, n = redact(raw.decode('utf-8'))
    out = text.encode('utf-8')
    json.loads(text)
    with open(dst, 'wb') as f:
        f.write(out)
    return {'source': src, 'source_sha256': hashlib.sha256(raw).hexdigest(), 'source_bytes': len(raw),
            'copy': dst, 'copy_sha256': hashlib.sha256(out).hexdigest(), 'copy_bytes': len(out),
            'redacted_tokens': n, 'byte_for_byte': n == 0}

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


def live_register(roots, commit='cbca125bb5eeb7d0ffb02f4546d60eb5d47dadc9', path='blocks/blocks.json'):
    """count the blocks of the live register (stars) at the recorded commit, from git's bytes; None without a clone"""
    for root in roots:
        d = os.path.join(root, 'stars')
        if os.path.isdir(os.path.join(d, '.git')):
            r = subprocess.run(['git', 'show', '%s:%s' % (commit, path)], cwd=d, capture_output=True)
            if r.returncode == 0:
                j = json.loads(r.stdout)
                return {'blocks': len(j['blocks']), 'source': 'stars@%s %s (generated_utc %s, sha256 %s)'
                        % (commit[:7], path, j.get('generated_utc'), hashlib.sha256(r.stdout).hexdigest())}
    return None


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for b in iter(lambda: f.read(1 << 20), b''):
            h.update(b)
    return h.hexdigest()


def git(d, *args):
    r = subprocess.run(['git'] + list(args), cwd=d, capture_output=True)
    return r.stdout.decode('utf-8', 'replace').strip() if r.returncode == 0 else None


def holders(roots, name):
    """every directory under the roots named like the repository (exact, then case-insensitive), bare or not"""
    out = []
    for root in roots:
        if not os.path.isdir(root):
            continue
        for n in sorted(os.listdir(root)):
            if n == name or n.lower() == name.lower():
                d = os.path.join(root, n)
                if os.path.isdir(os.path.join(d, '.git')) or os.path.isfile(os.path.join(d, 'HEAD')):
                    out.append(d)
    return out


def clone_with(roots, name, commit):
    for d in holders(roots, name):
        if subprocess.run(['git', 'cat-file', '-e', commit + '^{commit}'], cwd=d,
                          stderr=subprocess.DEVNULL).returncode == 0:
            return d, None
    h = holders(roots, name)
    return None, ('a clone of %s exists (%s) but does not hold commit %s' % (name, ', '.join(h), commit[:12])
                  if h else 'no clone of %s under %s' % (name, ', '.join(roots)))


def load_rows():
    """key.py load() order, as a list, for the reverse check"""
    names = {int(p[0]): p[1] for p in EK.rows(os.path.join(COSMOS, 'repos.tsv'))}
    out, k = [], 0
    for p in EK.rows(os.path.join(COSMOS, 'wafer.tsv')):
        k += int(p[4])
        out.append({'name': names[int(p[2])], 'sha': p[3], 'lines': int(p[1]), 'k0': k})
        k += int(p[1])
    return out


def main():
    if len(sys.argv) > 1 and sys.argv[1] == '--copy-graph':
        if len(sys.argv) != 4:
            print('usage: element_keys.py --copy-graph <source graph.json> <edition data/graphs/x.json>')
            return 2
        print(json.dumps(copy_graph(sys.argv[2], sys.argv[3]), indent=1))
        return 0
    ap = argparse.ArgumentParser()
    ap.add_argument('--elements', required=True, help='the elements clone (reads catalogue/elements.json)')
    ap.add_argument('--roots', required=True, help='comma separated directories holding the clones')
    ap.add_argument('--out', required=True)
    ap.add_argument('--edition', default='202611012135')
    ap.add_argument('--check', type=int, default=3, help='resolve this many keys back (key.py direction)')
    ap.add_argument('--keypy-root', default='', help='a directory of working clones: run tools/key.py itself, its '
                    'ROOTS set to this directory, on --check placed elements (smallest commits first)')
    a = ap.parse_args()
    t0 = time.time()
    roots = [r for r in a.roots.split(',') if r]
    src = os.path.join(a.elements, 'catalogue', 'elements.json')
    head = git(a.elements, 'rev-parse', 'HEAD')
    tracked = git(a.elements, 'ls-files', '--error-unmatch', 'catalogue/elements.json') is not None
    E = json.load(io.open(src, encoding='utf-8'))
    cache_present = EK.load_cache()
    by_sha, space = EK.load_wafer()

    walks = {}
    out = []
    for e in E:
        rec = {'sym': e['key'], 'number': e.get('number'), 'key': None, 'placed': False, 'repo': None,
               'commit': None, 'path': None, 'line': None, 'line_text': None, 'k0': None, 'wafer_row': None,
               'lines_before': None, 'commit_lines_measured': None, 'commit_lines_wafer': None, 'blob': None,
               'files_listed': len(e.get('files') or []), 'github': None, 'why': None}
        if not e.get('files'):
            rec['why'] = 'no register files: counted and named, not placed'
            out.append(rec)
            continue
        f = e['files'][0]
        name = f['repo'].split('/')[-1]
        rec.update({'repo': name, 'commit': f['commit'], 'path': f['path'], 'line': 1,
                    'github': 'https://github.com/%s/blob/%s/%s' % (f['repo'], f['commit'], f['path'])})
        cands = by_sha.get(f['commit'][:12], [])
        if not cands:
            rec['why'] = 'commit not on the wafer'
            out.append(rec)
            continue
        same = [c for c in cands if c['name'] == name] or \
               [c for c in cands if c['name'].lower() == name.lower()] or cands
        c = same[0]
        rec.update({'k0': c['k0'], 'wafer_row': c['row'], 'commit_lines_wafer': c['lines']})
        if c['name'] != name:
            rec['repo_on_wafer'] = c['name']
        d, why = clone_with(roots, name, f['commit'])
        if not d:
            rec['why'] = 'on the wafer (row %d) but not walked: %s' % (c['row'], why)
            out.append(rec)
            continue
        wk = (d, f['commit'])
        if wk not in walks:
            t1 = time.time()
            ents, err = EK.walk_commit(d, f['commit'])
            if ents is None:
                walks[wk] = (None, None, err)
            else:
                idx, cum = {}, 0
                for p, s, n in ents:
                    if p not in idx:
                        idx[p] = (cum, s, n)
                    if n > 0:
                        cum += n
                walks[wk] = (idx, cum, None)
            print('  walked %-34s %s %8.1fs %s' % (name, f['commit'][:12], time.time() - t1,
                  'lines=%s' % format(walks[wk][1], ',') if ents is not None else err), file=sys.stderr)
        idx, total, err = walks[wk]
        if idx is None:
            rec['why'] = 'git ls-tree failed: %s' % err
            out.append(rec)
            continue
        rec['commit_lines_measured'] = total
        if f['path'] not in idx:
            rec['why'] = 'path not in the commit tree'
            out.append(rec)
            continue
        before, sha, n = idx[f['path']]
        rec.update({'lines_before': before, 'blob': sha})
        got = {}
        EK.batch_read(d, [sha], lambda s, body: got.__setitem__(s, body))
        real = EK.lines_of(got[sha])
        problems = []
        if real != n:
            problems.append('the walk says %d lines for blob %s and git says %d' % (n, sha[:12], real))
        if real <= 0:
            problems.append('blob %s holds no text lines (%d); a key cannot land in it' % (sha[:12], real))
        else:
            rec['line_text'] = got[sha].split(b'\n')[0].decode('utf-8', 'replace').rstrip('\r')
        if total != c['lines']:
            problems.append('the walk measured %d lines in the commit, the wafer row says %d' % (total, c['lines']))
        if problems:
            rec['why'] = '; '.join(problems)
        else:
            rec['key'] = c['k0'] + before
            rec['placed'] = True
        out.append(rec)

    # the other direction, as tools/key.py resolve(): key -> row by k0 -> walk -> path and line
    rows = load_rows()
    k0s = [r['k0'] for r in rows]
    keyed = [r for r in out if r['placed']]
    step = max(1, len(keyed) // max(1, a.check)) if a.check else 0
    checks = []
    for r in (keyed[::step][:a.check] if a.check else []):
        k = r['key']
        row = rows[max(0, bisect.bisect_right(k0s, k) - 1)]
        m = k - row['k0']
        res = {'sym': r['sym'], 'key': k, 'row_repo': row['name'], 'row_sha12': row['sha'],
               'line_in_commit': m + 1}
        d, _ = clone_with(roots, r['repo'], r['commit'])
        seen, landed = 0, None
        for p, s, n in EK.walk_commit(d, r['commit'])[0]:
            if n <= 0:
                continue
            if m < seen + n:
                landed = (p, m - seen + 1)
                break
            seen += n
        res['landed'] = landed
        res['ok'] = (row['sha'] == r['commit'][:12] and landed == (r['path'], 1)
                     and row['k0'] <= k < row['k0'] + row['lines'])
        checks.append(res)
        print('  check %s %s -> %s / %s / %s:%s %s' % (r['sym'], format(k, ','), row['name'], row['sha'],
              landed and landed[0], landed and landed[1], 'OK' if res['ok'] else 'REFUSED'), file=sys.stderr)

    # tools/key.py itself, unmodified, its ROOTS (a Windows path in the file) set to --keypy-root at import
    keypy = []
    if a.keypy_root and a.check:
        picks, used = [], set()
        for r in sorted(keyed, key=lambda r: (r['commit_lines_wafer'], r['number'])):
            d = os.path.join(a.keypy_root, r['repo'])
            if r['repo'] in used or not os.path.isdir(os.path.join(d, '.git')):
                continue
            if subprocess.run(['git', 'cat-file', '-e', r['commit'] + '^{commit}'], cwd=d,
                              stderr=subprocess.DEVNULL).returncode:
                continue
            used.add(r['repo'])
            picks.append(r)
            if len(picks) == a.check:
                break
        for r in picks:
            code = ('import sys; sys.path.insert(0, %r); import key; key.ROOTS = %r; sys.argv = ["key.py", "%d"]; '
                    'sys.exit(key.main())' % (HERE, a.keypy_root, r['key']))
            pr = subprocess.run([sys.executable, '-B', '-c', code], capture_output=True, text=True)
            want = '%s / %s / ' % (r['repo'], r['commit'][:12])
            ok = pr.returncode == 0 and want in pr.stdout and ('\n  %s : 1 ' % r['path']) in pr.stdout
            keypy.append({'sym': r['sym'], 'key': r['key'], 'command': 'python tools/key.py %d' % r['key'],
                          'roots': a.keypy_root, 'exit': pr.returncode, 'output': pr.stdout.strip().split('\n'),
                          'ok': ok})
            print('  key.py %s %d -> exit %d %s' % (r['sym'], r['key'], pr.returncode, 'OK' if ok else 'REFUSED'),
                  file=sys.stderr)

    # K1 before a byte is written: path, github and line_text are redacted token by token; keys are untouched
    for r in out:
        hit = []
        for f in ('path', 'github', 'line_text'):
            if isinstance(r.get(f), str):
                r[f], n = redact(r[f])
                if n:
                    hit.append(f)
        if hit:
            r['redacted'] = hit
            r['redacted_why'] = 'K1: a token naming a repository that is not public, replaced by `%s`' % REDACTED

    from collections import Counter
    unplaced = [r for r in out if not r['placed']]
    no_files = [r for r in unplaced if r['files_listed'] == 0]
    kinds = {e['key']: e.get('kind') for e in E}
    counts = {
        'total': len(out),
        'with_files': len(out) - len(no_files),
        'placeable': sum(r['k0'] is not None for r in out),
        'placed': sum(r['placed'] for r in out),
        'named': len(unplaced),
        'no_files': len(no_files),
        'by_kind_unplaced': dict(Counter(kinds[r['sym']] for r in unplaced)),
        'distinct_commits_walked': len(walks),
        'redacted_records': sum(1 for r in out if r.get('redacted')),
    }
    # the live register, measured (the launcher's readout "<n> in the live register, 244 catalogued"; lead, 23:57)
    lr = live_register(roots)
    if lr:
        counts['live_register'] = lr['blocks']
        counts['live_register_source'] = lr['source']
    readout = '%d elements placed, %d counted, not placed' % (counts['placed'], counts['named'])
    doc = {
        'schema': 'kuiper.elements.v1',
        'edition': a.edition,
        'built_by': 'tools/element_keys.py',
        'source': {'repo': 'elements', 'commit': head or 'UNKNOWN', 'path': 'catalogue/elements.json',
                   'tracked': tracked, 'sha256': sha256_file(src)},
        'licence_note': 'keys only (Q1): elements@%s states no licence (no LICENSE or NOTICE file), so only '
                        '`block:<Sym>`, the catalogue number and the register\'s file address (repo, commit, path) are '
                        'carried; never a title, a description or a category word. line_text is line 1 of that file '
                        'at that commit, licensed by its own repository, as keys.json carries line_text.'
                        % ((head or 'UNKNOWN')[:7]),
        'register_note': 'the catalogue is pinned to the register of 2026-09-15 (244 blocks, elements CATALOGUE.md:3); '
                         'the live register holds 606 (stars@cbca125 blocks/blocks.json:2)',
        'law': 'key = k0(wafer row of files[0].commit) + lines before files[0].path in `git ls-tree -r <commit>` + '
               '(1 - 1), by tools/edition_keys.py walk_commit(); placed only when the walk lands on the wafer '
               'row\'s lines and the file holds a text line',
        'wafer': {'wafer_tsv_sha256': sha256_file(os.path.join(COSMOS, 'wafer.tsv')),
                  'repos_tsv_sha256': sha256_file(os.path.join(COSMOS, 'repos.tsv')),
                  'address_space': space,
                  'cache': ('data/blob-lines-history.tsv, %d blobs' % len(EK.CACHE)) if cache_present
                  else 'data/blob-lines-history.tsv absent: every blob counted from git'},
        'counts': counts,
        'readout': readout,
        'checks': checks,
        'checks_ok': all(c['ok'] for c in checks) if checks else None,
        'checks_keypy': keypy,
        'checks_keypy_ok': all(c['ok'] for c in keypy) if keypy else None,
        'command': ' '.join(['python3', 'tools/element_keys.py'] + sys.argv[1:]),
        'built_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
        'seconds': round(time.time() - t0, 1),
        'elements': out,
    }
    with io.open(a.out, 'w', encoding='utf-8', newline='\n') as fh:
        json.dump(doc, fh, indent=1, ensure_ascii=False)
        fh.write('\n')
    print(json.dumps(counts, indent=1))
    print(readout)
    for r in unplaced:
        print('  not placed: %-9s %s' % (r['sym'], r['why']), file=sys.stderr)
    return 0 if doc['checks_ok'] is not False and doc['checks_keypy_ok'] is not False else 2


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

Entangle Hosts

A JavaScript module in the tools folder of Kuiper Belt that works with try git (`tryGit`), using SHA-256.

storagekuiper-belt / tools/entangle_hosts.mjs · lines 1–127 of 127 · Entry point · pattern observe (shared by 13 files)

What it does
It loads data. Defines 6 functions or classes, including arg, has, git, tryGit, observe. Uses libraries node:child_process, node:crypto, node:fs, node:path. 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
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It is built from the try git helper (`tryGit`), the observe step (`observe`) and the sha256 step (`sha256`). Defines `arg`, `has`, `git` and 3 more. It writes `DRIFT.md`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · tools · JavaScript module
Uses
node:child_process, node:crypto, node:fs, node:path
Used by
none found
Produces
arg, has, git, tryGit, observe, sha256
Defines here
arg, has, git, tryGit, observe, sha256
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/entangle_hosts.mjs:1-127 · blob 2bd1cdd398b89942f672ab420c78830682e18597 · 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
#!/usr/bin/env node
// tools/entangle_hosts.mjs
// Pair every repository across two hosts and reconcile them under LAWS.md L10.
//
//   node tools/entangle_hosts.mjs --roots <dir> --namespace <gitlab-namespace> [--push] [--asof <iso>]
//
// Without --push it observes and reconciles only. Nothing is ever force pushed:
// a divergence is evidence, and overwriting evidence destroys the witness.

import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readdirSync, existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join, basename } from 'node:path';

const argv = process.argv.slice(2);
const arg = (k, d) => { const i = argv.indexOf(k); return i < 0 ? d : argv[i + 1]; };
const has = (k) => argv.includes(k);

const ROOTS = (arg('--roots', 'C:/Users/vikra/Documents/GitHub')).split(',');
const NS = arg('--namespace', '');
const PUSH = has('--push');
const ASOF = arg('--asof', new Date().toISOString());
const RULES = { host_a: 'github', host_b: 'gitlab', tolerance: 'exact', push: PUSH, asof: ASOF };

if (!NS) { console.error('FAIL: --namespace is required'); process.exit(1); }

const git = (cwd, args) =>
  execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
const tryGit = (cwd, args) => { try { return git(cwd, args); } catch { return null; } };

// A body is a repository with a git directory and a github origin.
const bodies = [];
for (const root of ROOTS) {
  for (const name of readdirSync(root)) {
    const dir = join(root, name);
    if (!existsSync(join(dir, '.git'))) continue;
    const origin = tryGit(dir, ['remote', 'get-url', 'origin']);
    if (!origin || !/github\.com/i.test(origin)) continue;
    bodies.push({ name, dir, origin });
  }
}
if (bodies.length === 0) { console.error('FAIL: zero bodies. A check that examines nothing refuses.'); process.exit(1); }

// Observe one host: the ref, the commit, and the tree, which is the Merkle root over the contents.
const observe = (dir, remote, branch) => {
  const ls = tryGit(dir, ['ls-remote', remote, `refs/heads/${branch}`]);
  if (!ls) return null;
  const commit = ls.split(/\s+/)[0];
  if (!commit) return null;
  const tree = tryGit(dir, ['rev-parse', `${commit}^{tree}`]); // null if not fetched locally
  return { host: remote, ref: branch, commit, tree, observed_at: ASOF };
};

const results = [];
for (const b of bodies) {
  const branch = tryGit(b.dir, ['rev-parse', '--abbrev-ref', 'HEAD']) || 'main';
  const gl = `git@gitlab.com:${NS}/${b.name.toLowerCase()}.git`;

  if (!tryGit(b.dir, ['remote', 'get-url', 'gitlab'])) tryGit(b.dir, ['remote', 'add', 'gitlab', gl]);
  else tryGit(b.dir, ['remote', 'set-url', 'gitlab', gl]);

  let pushed = null;
  if (PUSH) {
    // Mirror the ESTATE, not this desk. Fetch origin first, then push origin's ref.
    // Pushing the local working copy mirrors whatever staleness sits on this machine, which on
    // 2026-09-18 copied a fourteen commit old globalgrid2050 to the second host and then
    // correctly reported the divergence it had just created.
    try {
      git(b.dir, ['fetch', '--quiet', 'origin', branch]);
      git(b.dir, ['push', 'gitlab', `refs/remotes/origin/${branch}:refs/heads/${branch}`]);
      try { git(b.dir, ['push', '--tags', 'gitlab']); } catch { /* tags are best effort */ }
      pushed = 'ok';
    }
    catch (e) { pushed = 'refused: ' + String(e.stderr || e.message).split('\n')[0]; }
  }

  const a = observe(b.dir, 'origin', branch);
  const bb = observe(b.dir, 'gitlab', branch);

  // L10. The verdict is settled by pinned evidence, never by recency or plausibility.
  let verdict, detail;
  if (!a || !bb) { verdict = 'NOT EVALUATED'; detail = !a ? 'no observation from github' : 'no observation from gitlab'; }
  else if (a.commit === bb.commit) { verdict = 'HONOURED'; detail = `both hosts at ${a.commit}`; }
  else { verdict = 'OVERREACHED'; detail = `github ${a.commit} against gitlab ${bb.commit}; first deviation is the ref itself`; }

  results.push({ body: b.name, branch, verdict, detail, pushed, github: a, gitlab: bb });
  console.log(`${verdict.padEnd(13)} ${b.name}  ${detail}`);
}

// Record, then hash the record. The digest is the key the claim carries.
mkdirSync('data', { recursive: true }); mkdirSync('proof', { recursive: true });
const runId = ASOF.replace(/[-:]/g, '').slice(0, 15) + 'Z';
const record = { schema: 'twin-register-v1', rules: RULES, run: runId, bodies: results.sort((x, y) => x.body.localeCompare(y.body)) };
const json = JSON.stringify(record, null, 1);
writeFileSync(join('data', `twins-${runId}.json`), json);

const sha256 = (s) => createHash('sha256').update(s).digest('hex');
const counts = results.reduce((m, r) => (m[r.verdict] = (m[r.verdict] || 0) + 1, m), {});
const proof = { run: runId, asof: ASOF, digest: sha256(json), bodies: results.length, verdicts: counts,
  command: 'node tools/entangle_hosts.mjs ' + argv.join(' '), rules: RULES };
writeFileSync(join('proof', `${runId}.json`), JSON.stringify(proof, null, 1));

// The drift log, written between markers so it is idempotent and revertible.
const START = '<!-- DRIFT:START -->', END = '<!-- DRIFT:END -->';
const drift = [START,
  `### Host entanglement, ${ASOF}`, '',
  `Run \`${runId}\`, digest \`${proof.digest}\`. ${results.length} bodies. ` +
  Object.entries(counts).map(([k, v]) => `${v} ${k}`).join(', ') + '.', '',
  ...results.filter(r => r.verdict !== 'HONOURED').map(r => `- **${r.verdict}** \`${r.body}\`: ${r.detail}`),
  results.every(r => r.verdict === 'HONOURED') ? 'No divergence. Every body is paired on both hosts.' : '',
  '', `Reconciled under LAWS.md L10: settled by pinned evidence, never by recency or plausibility.`, END].join('\n');

for (const r of results) {
  const readme = join(bodies.find(b => b.name === r.body).dir, 'README.md');
  if (!existsSync(readme)) continue;
  const cur = readFileSync(readme, 'utf8');
  const one = [START, `### Host entanglement, ${ASOF}`, '',
    `**${r.verdict}.** ${r.detail}`, '', `Run \`${runId}\`, digest \`${proof.digest}\`. LAWS.md L10.`, END].join('\n');
  const next = cur.includes(START) ? cur.replace(new RegExp(`${START}[\s\S]*?${END}`), one) : cur.trimEnd() + '\n\n' + one + '\n';
  if (next !== cur) writeFileSync(readme, next);
}
writeFileSync('DRIFT.md', drift + '\n');

const bad = results.filter(r => r.verdict === 'OVERREACHED').length;
console.log(`\nrun ${runId} digest ${proof.digest}`);
console.log(Object.entries(counts).map(([k, v]) => `${k}: ${v}`).join('  |  '));
process.exit(bad > 0 ? 1 : 0);