GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / editions/202611012135/handoff/08-drift

Drift Test and 1 more file

A test in the handoff folder of Kuiper Belt that checks Drift, using SHA-256.

610 lines of Python and JavaScript from kuiper-belt, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1511 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. Drift Test test · kuiper-belt / editions/202611012135/handoff/08-drift/drift_test.py lines 1–362
  2. Test test · kuiper-belt / editions/202611012135/handoff/08-drift/test.cjs lines 1–248

Drift Test

A test in the handoff folder of Kuiper Belt that checks Drift, using SHA-256.

testkuiper-belt / editions/202611012135/handoff/08-drift/drift_test.py · lines 1–362 of 362 · version 2026-11-01 21:35 · Entry point · pattern clone (shared by 15 files)

What it does
It tests its inputs. Defines 10 functions or classes, including sh, sha, decode, main, info. Uses libraries argparse, collections, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'handoff'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file drift.json; JSON file keys.json; JSON file empty-heads.json; JSON file never.json; JSON file recorded-heads.json; JSON file p5-mini.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It runs tool (`run_tool`) and is built from the sha step (`sha`) and the decode step (`decode`). `ROADMAP.md` step 8 "Acceptance test", the parts that live off the page (P4's page half is `test.cjs`): files, and both equal `data/drift.json` byte for byte. It accepts `--root`, `--edition` and `--estate`.
Why it matters
Guards the behaviour of Drift.
Application
kuiper-belt · editions/202611012135/handoff/08-drift · test
Uses
Drift (script call), argparse, collections, hashlib, json, os, re, shutil, subprocess
Used by
none found
Produces
sh, sha, decode, main
Defines here
sh, sha, decode, main, info, ok, clone, run_tool, show, walk
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 editions/202611012135/handoff/08-drift/drift_test.py:1-362 · blob e388cb8fa3bf399cfcd3ae1de237a0cc652c58a6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""drift_test.py: the tester's independent check of tools/drift.py and data/drift.json (Opus team 8, step 8). Apache-2.0.

ROADMAP.md step 8 "Acceptance test", the parts that live off the page (P4's page half is test.cjs):
  P1 determinism   two runs against the recorded heads, under two different PYTHONHASHSEEDs, write byte-identical
                   files, and both equal data/drift.json byte for byte.
  P2 refusal       (a) every repository of keys.json without a clone is UNVERIFIED in data/drift.json, never SAME;
                   (b) a clone removed (an estate of symlinks without it) makes every one of its rows UNVERIFIED,
                   leaves every other row byte-identical, drops the denominator by exactly its verified rows, and the
                   tool prints REFUSED; (c) heads emptied: exit non-zero and nothing written.
  P3 ground truth  re-derived here, not through the tool: every row's head is the clone's refs/remotes/origin/HEAD
                   now; every SAME row's `git show <head>:<path>` holds line_text at `line`; every MOVED row's at
                   `head_line` (its first occurrence, delta = head_line - line, and no longer at `line`); every GONE
                   row's `git grep -F -x` is empty; every FILE_GONE row's `git cat-file -e` fails; every UNVERIFIED
                   row's reason is true, and no row that could be verified is UNVERIFIED. Each row is classified
                   again from `git show` and the class must agree.
  P4 the counts    summary.counts are the class counts of rows; the share and its denominator follow; the README
                   paragraph (handoff/08-drift/README.md) prints the same five counts and share.
  P5 the law       drift.json names no repository outside cosmos/repos.tsv and no key outside keys.json, rows are
                   the bodies one to one in order, and no line text is quoted; and the tool READS nothing else:
                   (i) under strace every file it opens under /home/user is repos.tsv, keys.json, the tool, the heads
                   file, its output, or inside a clone, and it opens no socket; (ii) from a root that holds only
                   cosmos/repos.tsv, editions/<stamp>/keys.json and tools/drift.py it writes the same bytes.

  python3 drift_test.py [--root KB] [--estate DIR] [--scratch DIR] [--json OUT]      exit 0 only when all pass
"""
import argparse
import collections
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
CLASSES = ['SAME', 'MOVED', 'GONE', 'FILE_GONE', 'UNVERIFIED']


def sh(args, cwd=None, env=None):
    r = subprocess.run(args, cwd=cwd, capture_output=True, env=env)
    return r.returncode, r.stdout, r.stderr


def sha(b):
    return hashlib.sha256(b).hexdigest()


def decode(raw):                       # the edition's own rule, tools/edition_keys.py:250
    return raw.decode('utf-8', 'replace').rstrip('\r')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--root', default=os.path.abspath(os.path.join(HERE, '..', '..', '..', '..')))
    ap.add_argument('--edition', default=os.path.basename(os.path.abspath(os.path.join(HERE, '..', '..'))))
    ap.add_argument('--estate', default=None)
    ap.add_argument('--scratch', default='/tmp/nl010-opus/team-8/tester')
    ap.add_argument('--json', default=None, help='write the results as JSON here')
    a = ap.parse_args()
    root = os.path.abspath(a.root)
    estate = os.path.abspath(a.estate or os.path.dirname(root))
    ed = a.edition
    tool = os.path.join(root, 'tools', 'drift.py')
    target = os.path.join(root, 'editions', ed, 'data', 'drift.json')
    keys_path = os.path.join(root, 'editions', ed, 'keys.json')
    tsv_path = os.path.join(root, 'cosmos', 'repos.tsv')
    os.makedirs(a.scratch, exist_ok=True)
    tmp = tempfile.mkdtemp(prefix='drift-test-', dir=a.scratch)
    results, infos = [], []

    def info(msg):
        infos.append(msg)
        print('INFO ' + msg, flush=True)

    def ok(name, cond, detail):
        results.append({'test': name, 'pass': bool(cond), 'detail': detail})
        print('%s %-34s %s' % ('PASS' if cond else 'FAIL', name, detail), flush=True)

    for p in (tool, target, keys_path, tsv_path):
        if not os.path.exists(p):
            print('REFUSED: %s does not exist; nothing tested' % p)
            return 2
    base = open(target, 'rb').read()
    D = json.loads(base)
    bodies = json.load(open(keys_path, encoding='utf-8'))['bodies']
    tsv_raw = [l.rstrip('\n').split('\t')[1] for l in open(tsv_path, encoding='utf-8') if l.strip() and not l.startswith('#')]
    tsv = {x.lower() for x in tsv_raw}         # GitHub repository names are case-insensitive (repos.tsv: Kuiper-belt)
    case_only = sorted({b['repo'] for b in bodies if b['repo'] not in tsv_raw and b['repo'].lower() in tsv})

    def clone(repo):
        d = os.path.join(estate, repo)
        return d if os.path.isdir(os.path.join(d, '.git')) else None

    def run_tool(extra, env_extra=None, prefix=None, r=root):
        env = dict(os.environ)
        env.update(env_extra or {})
        return sh((prefix or []) + [sys.executable, os.path.join(r, 'tools', 'drift.py'), '--root', r,
                                    '--edition', ed] + extra, env=env)

    # ---------------------------------------------------------------- P1 determinism
    outs = []
    for seed in ('1', '4242'):
        o = os.path.join(tmp, 'p1-seed%s.json' % seed)
        rc, so, se = run_tool(['--estate', estate, '--heads', target, '--out', o], {'PYTHONHASHSEED': seed})
        outs.append((rc, open(o, 'rb').read() if os.path.exists(o) else b''))
    (r1, b1), (r2, b2) = outs
    ok('P1 two runs byte-identical', r1 == 0 and r2 == 0 and b1 and b1 == b2,
       'PYTHONHASHSEED 1 / 4242: exit %d / %d, %d / %d bytes, sha256 %s / %s' % (
           r1, r2, len(b1), len(b2), sha(b1)[:16], sha(b2)[:16]))
    ok('P1 re-run equals data/drift.json', b1 == base,
       'data/drift.json %d bytes sha256 %s; re-run %s' % (len(base), sha(base), 'identical' if b1 == base else
                                                           'DIFFERS at byte %s' % next((i for i in range(min(len(b1), len(base))) if b1[i] != base[i]), min(len(b1), len(base)))))

    # ---------------------------------------------------------------- P2 refusal
    repos = sorted({b['repo'] for b in bodies})
    absent = [r for r in repos if not clone(r)]
    bad_abs = [r['id'] for r in D['rows'] if r['repo'] in absent and r['class'] != 'UNVERIFIED']
    ok('P2a no clone -> UNVERIFIED', not bad_abs and all(D['heads'][r].get('sha') is None for r in absent),
       'repositories of keys.json without a clone in %s: %s; their %d rows all UNVERIFIED, head null%s' % (
           estate, absent or 'none', sum(1 for r in D['rows'] if r['repo'] in absent),
           (' (NOT: %s)' % bad_abs[:3]) if bad_abs else ''))
    per = collections.Counter(r['repo'] for r in D['rows'] if r['class'] != 'UNVERIFIED')
    for victim in [per.most_common(1)[0][0], 'data-grid-gb' if 'data-grid-gb' in per else per.most_common(2)[1][0]]:
        est2 = os.path.join(tmp, 'estate-without-' + victim)
        os.makedirs(est2)
        for n in sorted(os.listdir(estate)):
            if n != victim and os.path.isdir(os.path.join(estate, n, '.git')):
                os.symlink(os.path.join(estate, n), os.path.join(est2, n))
        o = os.path.join(tmp, 'p2-without-%s.json' % victim)
        rc, so, se = run_tool(['--estate', est2, '--heads', target, '--out', o])
        W = json.load(open(o)) if os.path.exists(o) else None
        lost = per[victim]
        allun = W is not None and all(r['class'] == 'UNVERIFIED' and r.get('reason') for r in W['rows'] if r['repo'] == victim)
        others = W is not None and all(x == y for x, y in zip(D['rows'], W['rows']) if x['repo'] != victim) \
            and len(W['rows']) == len(D['rows'])
        den = W and W['summary']['denominator']
        ok('P2b clone %s removed' % victim, rc == 0 and allun and others and den == D['summary']['denominator'] - lost
           and ('REFUSED: no clone of %s' % victim).encode() in so,
           'exit %d; its %d rows UNVERIFIED: %s; other rows unchanged: %s; denominator %d -> %s (drop %d expected); '
           'printed "%s"' % (rc, sum(1 for r in D['rows'] if r['repo'] == victim), allun, others,
                             D['summary']['denominator'], den, lost,
                             next((l for l in so.decode().splitlines() if victim in l and 'REFUSED' in l), 'no REFUSED line')))
    for label, body in (('{"heads": {}}', '{"heads": {}}\n'), ('{}', '{}\n')):
        e = os.path.join(tmp, 'empty-heads.json')
        open(e, 'w').write(body)
        o = os.path.join(tmp, 'never.json')
        rc, so, se = run_tool(['--estate', estate, '--heads', e, '--out', o])
        ok('P2c heads emptied %s' % label, rc != 0 and not os.path.exists(o) and not os.path.exists(o + '.tmp'),
           'exit %d, file written: %s; "%s"' % (rc, os.path.exists(o), (so + se).decode().strip().splitlines()[-1:]))

    # ---------------------------------------------------------------- P3 ground truth, independently
    keyed = {b['id']: b for b in bodies}
    shows, bad, n = {}, [], collections.Counter()
    held, moved_since = {}, []         # the recorded head, held by the clone; and where origin/HEAD is now
    for repo in repos:
        d, h = clone(repo), (D['heads'].get(repo) or {}).get('sha')
        if d and h:
            rc, _, _ = sh(['git', 'cat-file', '-e', h + '^{commit}'], cwd=d)
            held[repo] = h if rc == 0 else None
            rc, out, _ = sh(['git', 'rev-parse', '-q', '--verify', 'refs/remotes/origin/HEAD^{commit}'], cwd=d)
            now = out.decode().strip()
            if now != h:
                moved_since.append('%s %s -> %s' % (repo, h[:12], now[:12]))
                rc, out, _ = sh(['git', 'merge-base', '--is-ancestor', h, now], cwd=d)
                if rc != 0:
                    bad.append((repo, 'recorded head %s is not an ancestor of origin/HEAD %s' % (h[:12], now[:12])))
        elif h:
            bad.append((repo, 'a head recorded without a clone'))

    def show(d, spec):
        if spec not in shows:
            rc, out, _ = sh(['git', 'show', spec], cwd=d)
            shows[spec] = out if rc == 0 else None
        return shows[spec]

    for r in D['rows']:
        k = keyed.get(r['id'])
        if k is None:
            bad.append((r['id'], 'not in keys.json'))
            continue
        cl, d, text = r['class'], clone(r['repo']), k.get('line_text')
        n[cl] += 1
        verifiable = bool(d and held.get(r['repo']) and r.get('head') == held.get(r['repo']) and text and k.get('on_wafer') is not False
                          and k.get('key') is not None and r['repo'].lower() in tsv)
        if cl == 'UNVERIFIED':
            why = r.get('reason') or ''
            if verifiable:
                bad.append((r['id'], 'UNVERIFIED (%s) but clone, head, text and key all exist' % why))
            elif why.startswith('no clone') and d:
                bad.append((r['id'], 'reason "no clone" but %s has a clone' % r['repo']))
            elif why == 'empty line_text' and text:
                bad.append((r['id'], 'reason "empty line_text" but keys.json has text'))
            elif why.startswith('key not on the wafer') and k.get('on_wafer') is not False and k.get('key') is not None:
                bad.append((r['id'], 'reason "not on the wafer" but keys.json says on_wafer'))
            elif not why:
                bad.append((r['id'], 'UNVERIFIED without a reason'))
            if r.get('head') and not d:
                bad.append((r['id'], 'a head without a clone'))
            continue
        if not verifiable:
            bad.append((r['id'], '%s claimed for an unverifiable row' % cl))
            continue
        spec = '%s:%s' % (r['head'], r['path'])
        body = show(d, spec)
        rc_e, _, _ = sh(['git', 'cat-file', '-e', spec], cwd=d) if body is None or cl == 'FILE_GONE' else (0, b'', b'')
        if body is None:
            mine = 'FILE_GONE' if rc_e != 0 else '?'
        else:
            ls = [decode(x) for x in body.split(b'\n')]
            hits = [i + 1 for i, x in enumerate(ls) if x == text]
            mine = 'SAME' if r['line'] <= len(ls) and ls[r['line'] - 1] == text else ('MOVED' if hits else 'GONE')
        if mine != cl:
            bad.append((r['id'], 'tool says %s, git show says %s' % (cl, mine)))
            continue
        if cl == 'MOVED':
            if r.get('head_line') != hits[0] or r.get('delta') != hits[0] - r['line'] or r.get('occurrences') != len(hits):
                bad.append((r['id'], 'MOVED head_line/delta/occurrences %s/%s/%s, git show %s/%s/%s' % (
                    r.get('head_line'), r.get('delta'), r.get('occurrences'), hits[0], hits[0] - r['line'], len(hits))))
        if cl == 'GONE':
            pf = os.path.join(tmp, 'pat')
            open(pf, 'wb').write(text.encode('utf-8') + b'\n' + text.encode('utf-8') + b'\r\n')
            rc, out, _ = sh(['git', 'grep', '-F', '-x', '-f', pf, r['head'], '--', r['path']], cwd=d)
            if out.strip():
                bad.append((r['id'], 'GONE but git grep -F -x finds %s' % out[:80]))
        if cl == 'FILE_GONE' and rc_e == 0:
            bad.append((r['id'], 'FILE_GONE but git cat-file -e finds the path'))
    ok('P3 ground truth by git show', not bad and sum(n.values()) == len(bodies),
       '%s re-derived from %d `git show` blobs at the recorded heads (each held by its clone and an ancestor of its '
       'origin/HEAD); %d disagreements%s' % (dict(n), len(shows), len(bad),
                                            (': ' + '; '.join('%s %s' % x for x in bad[:4])) if bad else ''))
    info('heads moved since drift.json was written (fetched later; the drift is as of its recorded heads): %s'
         % ('; '.join(moved_since) or 'none'))

    # ---------------------------------------------------------------- P4 the five counts (data half)
    c = collections.Counter(r['class'] for r in D['rows'])
    s = D['summary']
    den = len(D['rows']) - c['UNVERIFIED']
    st = '%d SAME / %d (rows %d - UNVERIFIED %d)' % (c['SAME'], den, len(D['rows']), c['UNVERIFIED'])
    ok('P4 summary = rows', all(s['counts'][k] == c[k] for k in CLASSES) and s['rows'] == len(D['rows'])
       and s['denominator'] == den and s['share_text'] == st and set(c) <= set(CLASSES),
       ' / '.join('%d %s' % (c[k], k) for k in CLASSES) + '; ' + st)
    readme = os.path.join(HERE, 'README.md')
    if os.path.exists(readme):
        t = re.sub(r'\s+', ' ', open(readme, encoding='utf-8').read())
        want = '%d SAME, %d MOVED, %d GONE, %d FILE_GONE, %d UNVERIFIED' % tuple(c[k] for k in CLASSES)
        sh_txt = '%d SAME / %d (rows %d − UNVERIFIED %d)' % (c['SAME'], den, len(D['rows']), c['UNVERIFIED'])
        ok('P4 README paragraph = drift.json', want in t and sh_txt in t, '"%s" %s; "%s" %s' % (
            want, 'present' if want in t else 'ABSENT', sh_txt, 'present' if sh_txt in t else 'ABSENT'))

    # ---------------------------------------------------------------- P5 the law
    stray_repo = sorted(x for x in ({r['repo'] for r in D['rows']} | set(D['heads'])) if x.lower() not in tsv)
    order = [b['id'] for b in bodies] == [r['id'] for r in D['rows']]
    stray_key = [r['id'] for r in D['rows'] if r['id'] not in keyed or keyed[r['id']].get('key') != r['key']
                 or keyed[r['id']]['path'] != r['path'] or int(keyed[r['id']]['line']) != r['line']
                 or keyed[r['id']]['commit'] != r['edition_commit'] or keyed[r['id']]['repo'] != r['repo']]
    texts = {b.get('line_text') for b in bodies if b.get('line_text') and len(b['line_text']) >= 12} | \
            {b.get('quote') for b in bodies if b.get('quote') and len(b['quote']) >= 12}
    strings = set()

    def walk(x):
        if isinstance(x, dict):
            for v in x.values():
                walk(v)
        elif isinstance(x, list):
            for v in x:
                walk(v)
        elif isinstance(x, str):
            strings.add(x)
    walk(D)
    quoted = sorted(strings & texts)
    textkeys = [k for r in D['rows'] for k in r if k in ('line_text', 'quote', 'text')]
    ok('P5 drift.json inside the law', not stray_repo and not stray_key and order and len(D['rows']) == len(bodies)
       and not quoted and not textkeys,
       '%d rows = %d bodies in keys.json order: %s; repositories outside repos.tsv: %s (matched by case only: %s); '
       'keys outside keys.json: %s; line texts quoted: %d' % (len(D['rows']), len(bodies), order, stray_repo or 'none',
                                                              case_only or 'none', stray_key[:3] or 'none',
                                                              len(quoted) + len(textkeys)))

    # (i) what the tool opens, under strace (observe mode, the mode that cuts an edition, and --heads mode)
    allowed_files = {os.path.realpath(p) for p in (tsv_path, keys_path, tool, target)}
    clone_dirs = [os.path.realpath(os.path.join(estate, x)) for x in os.listdir(estate)
                  if os.path.isdir(os.path.join(estate, x, '.git'))]
    if shutil.which('strace'):
        for mode, extra in (('observe', []), ('--heads', ['--heads', target])):
            o = os.path.join(tmp, 'p5-%s.json' % mode.strip('-'))
            tr = os.path.join(tmp, 'p5-%s.strace' % mode.strip('-'))
            rc, so, se = run_tool(['--estate', estate, '--out', o] + extra,
                                  prefix=['strace', '-f', '-qq', '-e', 'trace=open,openat,openat2,connect,socket',
                                          '-o', tr])
            here_home, sockets, sysfiles, listed = set(), [], set(), set()
            for line in open(tr, errors='replace'):
                if re.search(r'\b(socket|connect)\(', line) and ' = -1' not in line:
                    if 'AF_UNIX' not in line or 'connect(' in line:
                        sockets.append(line.strip()[:120])
                m = re.search(r'open(?:at2?)?\((?:[^,]*, )?"([^"]*)"', line)
                if not m or ' = -1 ' in line:
                    continue
                p = m.group(1)
                if not p.startswith('/'):
                    continue                     # relative opens are resolved by git inside its clone (cwd)
                rp = os.path.realpath(p)
                if rp.startswith('/home/user'):
                    if 'O_DIRECTORY' in line and rp in (os.path.realpath(estate), os.path.dirname(os.path.realpath(tool))):
                        listed.add(rp)
                    else:
                        here_home.add(rp)
                else:
                    sysfiles.add(rp.split('/')[1])
            out_real = os.path.realpath(o)
            allowed = allowed_files if extra else allowed_files - {os.path.realpath(target)}
            stray = sorted(p for p in here_home if p not in allowed and not p.startswith(out_real)
                           and not any(p == cd or p.startswith(cd + '/') for cd in clone_dirs)
                           and not p.startswith(os.path.realpath(tmp)))
            in_clones = sorted({cd for cd in clone_dirs if any(p.startswith(cd + '/') for p in here_home)})
            ok('P5 reads (%s, strace)' % mode, rc == 0 and not stray and not sockets,
               'exit %d; opened under /home/user: %d files = repos.tsv, keys.json, tools/drift.py%s + %d clones; '
               'directories listed: %s; outside /home/user only system dirs %s; sockets: %d; stray: %s' % (
                   rc, len(here_home), ', data/drift.json (the recorded heads)' if extra else '', len(in_clones),
                   sorted(listed) or 'none', sorted(sysfiles), len(sockets), stray[:5] or 'none'))
            if mode == 'observe' and os.path.exists(o):
                ob = open(o, 'rb').read()
                O = json.loads(ob)
                diff = [(x['id'][:12], x['repo'], x['class'], y['class']) for x, y in zip(D['rows'], O['rows'])
                        if x['class'] != y['class']]
                info('observing the heads now instead of the recorded ones: %s; counts now %s; rows whose class '
                     'would change: %d %s' % ('byte-identical' if ob == base else 'differs',
                                              ' / '.join('%d %s' % (v, k) for k, v in O['summary']['counts'].items()),
                                              len(diff), diff[:6]))
    else:
        ok('P5 reads (strace)', False, 'strace not installed: the read trace was not measured')

    # (ii) a root that holds only the three inputs writes the same bytes
    mini = os.path.join(tmp, 'mini-root')
    for rel in ('cosmos/repos.tsv', 'editions/%s/keys.json' % ed, 'tools/drift.py'):
        os.makedirs(os.path.dirname(os.path.join(mini, rel)), exist_ok=True)
        shutil.copyfile(os.path.join(root, rel), os.path.join(mini, rel))
    hp = os.path.join(tmp, 'recorded-heads.json')
    shutil.copyfile(target, hp)
    o = os.path.join(tmp, 'p5-mini.json')
    rc, so, se = run_tool(['--estate', estate, '--heads', hp, '--out', o], r=mini)
    mb = open(o, 'rb').read() if os.path.exists(o) else b''
    ok('P5 minimal root, same bytes', rc == 0 and mb == base,
       'root = repos.tsv + keys.json + tools/drift.py only (%s): exit %d, %d bytes, %s data/drift.json' % (
           mini, rc, len(mb), 'identical to' if mb == base else 'DIFFERENT from'))

    shutil.rmtree(tmp, ignore_errors=True)
    fails = [x for x in results if not x['pass']]
    summary = {'drift_json_sha256': sha(base), 'tool_sha256': sha(open(tool, 'rb').read()),
               'keys_json_sha256': sha(open(keys_path, 'rb').read()), 'counts': dict(c), 'results': results, 'info': infos,
               'result': 'FAIL' if fails else 'PASS'}
    if a.json:
        with open(a.json, 'w') as f:
            json.dump(summary, f, indent=1)
    print('RESULT: %s (%d of %d)' % (summary['result'], len(results) - len(fails), len(results)))
    return 1 if fails else 0


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

Test

A JavaScript module in the handoff folder of Kuiper Belt that tests drift, using SHA-256.

testkuiper-belt / editions/202611012135/handoff/08-drift/test.cjs · lines 1–248 of 248 · version 2026-11-01 21:35 · Entry point · pattern overlay (shared by 4 files)

What it does
It tests drift. Defines 7 functions or classes, including sleep, manifest, overlay, run, ok. Uses libraries playwright, fs, path, crypto, child_process. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'handoff'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "The test is `handoff/02-card/test.cjs` (B1–B7, Pixel 7 and Galaxy S24, all 344 placed bodies)."
Inputs & outputs
In: JSON file modules.json; JSON file drift.json; JSON file MODULE.json; JSON file keys-min.json; JSON file keys.json; JSON file drift_test.json; command-line arguments. Out: JSON file report.json; canvas drawing.
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 sleep step (`sleep`), the manifest step (`manifest`) and the overlay step (`overlay`). The README says: The test is `handoff/02-card/test.cjs` (B1–B7, Pixel 7 and Galaxy S24, all 344 placed bodies).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · editions/202611012135/handoff/08-drift · JavaScript module
Uses
playwright, fs, path, crypto, child_process
Used by
none found
Produces
sleep, manifest, overlay, run, ok, ins, barOf
Defines here
sleep, manifest, overlay, run, ok, ins, barOf
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 editions/202611012135/handoff/08-drift/test.cjs:1-248 · blob 54bd09e2dcff81e2b5f414144bd4918568e32720 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env node
// Apache-2.0 (kuiper-belt code), kuiper-belt@018b46a README.md:156-157; the LICENCES.md row is handoff/08-drift/LICENCE.txt.
// test.cjs — Opus team 8, step 8 the drift: P4 on Android (ROADMAP.md step 8 "Acceptance test on Android"), in the
// form of FIXES/NL-009/android-journey.cjs: Playwright, devices['Pixel 7'] and devices['Galaxy S24'] (360 px), real
// touch (page.touchscreen.tap), zero console errors, a measured assertion per step, report.json, exit 0 only when every
// step on every device passed.
//
//   node test.cjs <edition-url> <outdir> [--handoff] [--device "Pixel 7"|"Galaxy S24"] [--no-py]
//   e.g. node test.cjs http://127.0.0.1:8482/editions/202611012135/ /tmp/nl010-opus/team-8/tester/out1
//   --device runs one device (a loaded machine: one device at a time); each device's steps go to
//   <outdir>/steps-<device>.json and TEST.md / report.json are written from every device file present in <outdir>.
//   P1, P2, P3, P5 and the data half of P4 are drift_test.py (run here first unless --no-py; its JSON is folded into
//   report.json and TEST.md), so one RESULT covers P1-P5.
//
// The manifest: when modules.json already admits `drift` the page is tested as served. Until then (pre-integration)
// the test routes modules.json to the served one plus line-card (handoff/02-card/MODULE.json) and drift (sha256 and
// bytes measured from the file on disk at the start), and says "pre-integration" in the report.
// Scenarios per device: A no drift module (the baseline wafer), B drift admitted, C drift admitted and data/drift.json
// answering 404. --handoff writes ../img/*.png (CSS-pixel PNGs) and ../TEST.md.
'use strict';
const { chromium, devices } = require('playwright');
const fs = require('fs'), path = require('path'), crypto = require('crypto');

const argv = process.argv.slice(2), pos = argv.filter((a, i) => !a.startsWith('--') && argv[i - 1] !== '--device');
if (pos.length < 2) { console.error('usage: node test.cjs <edition-url> <outdir> [--handoff]'); process.exit(2); }
const URL0 = pos[0].replace(/\/?$/, '/'), OUT = path.resolve(pos[1]), HANDOFF = argv.includes('--handoff');
const HERE = __dirname, ED = path.resolve(HERE, '..', '..');
const ALL_DEVICES = ['Pixel 7', 'Galaxy S24'];
const devArg = argv.indexOf('--device') >= 0 ? process.argv[process.argv.indexOf('--device') + 1] : null;
const DEVICES = devArg ? [devArg] : ALL_DEVICES;
if (devArg && !ALL_DEVICES.includes(devArg)) { console.error('unknown device ' + devArg); process.exit(2); }
const sleep = ms => new Promise(r => setTimeout(r, ms));
fs.mkdirSync(OUT, { recursive: true });

const served = JSON.parse(fs.readFileSync(path.join(ED, 'modules.json'), 'utf8'));
const DRIFT = JSON.parse(fs.readFileSync(path.join(ED, 'data', 'drift.json'), 'utf8'));
const modFile = fs.readdirSync(path.join(ED, 'modules')).filter(f => /^\d{12}-drift\.js$/.test(f)).sort().pop();
const modBytes = fs.readFileSync(path.join(ED, 'modules', modFile));
const modSha = crypto.createHash('sha256').update(modBytes).digest('hex');
const src = modBytes.toString('utf8');
const REQ = (src.match(/var REQUIRES = \[([^\]]*)\]/) || [, ''])[1].split(',').map(s => s.trim().replace(/'/g, '')).filter(Boolean);
const PRE = !(served.order || []).includes('drift');
function manifest(withDrift) {
  const m = JSON.parse(JSON.stringify(served));
  if (!PRE) { if (!withDrift) { m.order = m.order.filter(x => x !== 'drift'); m.modules = m.modules.filter(x => x.id !== 'drift'); } return m; }
  // pre-integration: other teams' modules are re-hashed from disk (they are being revised while we test; their
  // admission is the integrator's test, not ours)
  m.modules.forEach(x => { try { const b = fs.readFileSync(path.join(ED, x.path)); x.sha256 = crypto.createHash('sha256').update(b).digest('hex'); x.bytes = b.length; if (x.byte_budget < b.length) x.byte_budget = b.length; } catch (e) {} });
  if (!m.order.includes('line-card')) {
    const lc = JSON.parse(fs.readFileSync(path.join(ED, 'handoff', '02-card', 'MODULE.json'), 'utf8'));
    m.modules.push(lc); m.order.push('line-card');
  }
  if (withDrift) {
    m.modules.push({ id: 'drift', generation: modFile.slice(0, 12), path: 'modules/' + modFile, sha256: modSha, bytes: modBytes.length,
      byte_budget: 65536, requires: REQ, provides: ['drift'], reads: ['data/drift.json', 'keys-min.json', 'keys.json'],
      writes: ['#ky-drift', '#ky-drift-css', '#card .ky-drift-cl'], creates_controls: 'the drift section of the WAFER panel: five class filters and its list',
      licence: 'Apache-2.0', team: '08', step: 8, proof: 'handoff/08-drift/' });
    m.order.push('drift');
  }
  return m;
}
const MOVED = DRIFT.rows.filter(r => r.class === 'MOVED');
const BASEBAR = {};
const C = DRIFT.summary.counts;

async function overlay(page, x, y, rad) {   // classify overlay pixels in a box (or the whole canvas)
  return page.evaluate(([x, y, rad]) => {
    const ov = document.querySelector('#o'), ctx = ov.getContext('2d');
    const x0 = rad ? Math.max(0, Math.round(x - rad)) : 0, y0 = rad ? Math.max(0, Math.round(y - rad)) : 0;
    const w = rad ? Math.min(ov.width - x0, 2 * rad + 1) : ov.width, h = rad ? Math.min(ov.height - y0, 2 * rad + 1) : ov.height;
    const d = ctx.getImageData(x0, y0, w, h).data; let amber = 0, green = 0;
    for (let i = 0; i < d.length; i += 4) { const r = d[i], g = d[i + 1], b = d[i + 2], a = d[i + 3]; if (a < 60) continue;
      if (r > 200 && g > 120 && g < 200 && b < 70) amber++; else if (g > 180 && r < 90 && b < 150 && g > b + 60) green++; }
    return { amber, green, w: ov.width, cssW: innerWidth };
  }, [x, y, rad || 0]);
}

async function run(devName, scen) {
  const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
  const ctx = await browser.newContext({ ...devices[devName] });
  const page = await ctx.newPage();
  const errors = [], steps = [];
  page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
  page.on('pageerror', e => errors.push('pageerror ' + e.message));
  await page.route('**/editions/202611012135/modules.json', r => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(manifest(scen !== 'A')) }));
  if (scen === 'C') await page.route('**/editions/202611012135/data/drift.json', r => r.fulfill({ status: 404, contentType: 'text/plain', body: 'not found' }));
  const ok = (name, pass, detail) => { steps.push({ device: devName, scenario: scen, step: name, pass: !!pass, detail }); console.log((pass ? 'PASS ' : 'FAIL ') + devName + ' ' + scen + ' ' + name + ' · ' + detail); };
  await page.goto(URL0, { waitUntil: 'load', timeout: 180000 });
  await page.waitForFunction(() => window.__KUIPER_EDITION__ && window.__KUIPER_EDITION__.done !== false && document.querySelector('#big') && /verified lines lit/.test(document.querySelector('#big').textContent), null, { timeout: 180000 }).catch(() => {});
  if (scen !== 'A') await page.waitForFunction(() => { const m = window.KY && KY.modules && KY.modules.drift; const s = m && m.api && m.api.inspect(); return s && (s.status === 'OK' || s.status === 'REFUSED'); }, null, { timeout: 180000 }).catch(() => {});
  await sleep(7000);
  const ins = () => page.evaluate(() => { const m = window.KY && KY.modules && KY.modules.drift; return m && m.api ? m.api.inspect() : null; });
  const base = await overlay(page);
  const barOf = () => page.evaluate(() => { const shell = !!document.querySelector('#kuiper-menu-bar');
    const ts = shell ? [...document.querySelectorAll('#kuiper-menu-bar .gm-menu>.gm-title')] : [...document.querySelectorAll('#bar > *')].filter(e => e.getBoundingClientRect().width > 0);
    const tops = new Set(ts.map(t => Math.round(t.getBoundingClientRect().top)));
    const b = document.querySelector(shell ? '#kuiper-menu-bar' : '#bar'); return { bar: shell ? '#kuiper-menu-bar (the shell)' : '#bar (the page, no shell admitted)', shell, titles: ts.map(t => t.textContent.trim()), rows: tops.size, h: b ? Math.round(b.getBoundingClientRect().height) : null, sw: b ? b.scrollWidth : 0, cw: b ? b.clientWidth : 0 }; });
  const bar = await barOf();
  const res = { device: devName, scenario: scen, base, bar };
  if (scen === 'A') { BASEBAR[devName] = bar; ok('baseline wafer', base.green > 0, base.green + ' green overlay px, no drift module; bar ' + bar.bar + ' ' + bar.rows + ' row(s): ' + bar.titles.join('|')); }
  if (scen === 'B') {
    let s = await ins();
    const hud = await page.evaluate(() => document.querySelector('#hud').textContent);
    const dl = hud.split('\n').find(l => /^DRIFT since the cut/.test(l)) || '';
    const got = {}; for (const m of dl.matchAll(/(?:^|· )([\d,]+) (SAME|MOVED|GONE|FILE_GONE|UNVERIFIED)\b/g)) got[m[2]] = +m[1].replace(/,/g, '');
    const want = ['SAME', 'MOVED', 'GONE', 'FILE_GONE', 'UNVERIFIED'];
    ok('admitted', s && s.status === 'OK', s ? 'status ' + s.status + ' registry ' + s.registry + ' marks ' + s.marks : 'drift not in KY.modules: ' + JSON.stringify(await page.evaluate(() => window.__KUIPER_EDITION__ && window.__KUIPER_EDITION__.refused)));
    ok('readout five counts = drift.json', want.every(k => got[k] === C[k]) && Object.keys(got).length === 5 && dl.includes(DRIFT.summary.share_text),
      (dl || 'no DRIFT line') + ' · page ' + JSON.stringify(got) + ' · drift.json ' + JSON.stringify(C));
    // the drift adds no bar title and does not change the bar (ROADMAP step 8 "no new bar title"; "the bar stays one
    // row"): B's bar equals A's bar; with the shell admitted it is one row. Without the shell the page's own bar is two
    // rows at 360-412 px before any module (ADMISSIONS.md row 0, NL-009 01-bar, team 1's to fix), so equality is the test.
    const A0 = BASEBAR[devName];
    ok('bar unchanged by drift' + (bar.shell ? ', one row' : ''), A0 && JSON.stringify(A0.titles) === JSON.stringify(bar.titles) && A0.rows === bar.rows && bar.sw <= bar.cw + 1 && (!bar.shell || bar.rows === 1),
      'with drift ' + JSON.stringify(bar) + ' · without (A) ' + JSON.stringify(A0 && { titles: A0.titles, rows: A0.rows }));
    // every MOVED spark: amber in a 9x9 box of the overlay, and nothing of the page drawn over it (elementFromPoint)
    {
      const all = [];
      for (const m of (s && s.moved || [])) {
        const p = await page.evaluate(id => KY.modules.drift.api.screen(id), m.id);
        if (!p) { all.push({ id: m.id, on: false }); continue; }
        const vis = await page.evaluate(([x, y]) => { if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) return 'off-screen';
          const e = document.elementFromPoint(x, y); return e ? (e.id ? '#' + e.id : e.tagName.toLowerCase()) : 'none'; }, p);
        const px = vis === 'off-screen' ? { amber: 0 } : await overlay(page, p[0], p[1], 4);
        all.push({ id: m.id, repo: m.repo, at: p.map(v => Math.round(v)), top: vis, amber: px.amber });
      }
      const onScreen = all.filter(x => x.top && x.top !== 'off-screen');
      const good = onScreen.filter(x => x.amber >= 4 && /^#(o|c|gl|cv)$|^canvas$/.test(x.top));
      ok('every MOVED spark amber and visible', all.length === MOVED.length && onScreen.length >= 1 && good.length === onScreen.length,
        good.length + ' of ' + onScreen.length + ' on-screen MOVED sparks amber (>=4 px in 9x9) with a canvas on top; ' + (all.length - onScreen.length) + ' off-screen; ' +
        all.map(x => x.repo + ' ' + (x.at ? x.at.join(',') : '-') + ' ' + x.top + ' ' + x.amber + 'px').join('; '));
      res.moved = all;
      if (HANDOFF && devName === 'Pixel 7') await page.screenshot({ path: path.join(HERE, 'img', '4-moved-sparks-Pixel_7.png'), scale: 'css', timeout: 180000 });
    }
    // the amber spark at its new key, and its card
    const mv = (s && s.moved || []).find(m => m.atNew);
    ok('MOVED placed at a new key', !!mv && s.moved.filter(m => m.atNew).length >= 1, s ? s.moved.filter(m => m.atNew).length + ' of ' + MOVED.length + ' MOVED at their new keys; ' + s.moved.filter(m => !m.atNew).map(m => m.repo + ': ' + m.note).join('; ') : '');
    if (mv) {
      const row = MOVED.find(r => r.id === mv.id && r.repo === mv.repo);
      await page.evaluate(id => KY.modules.drift.api.open(id), mv.id); await sleep(8000);
      const card = await page.evaluate(() => { const c = document.querySelector('#card'); const d = c.querySelector('.ky-drift-cl'); return { open: c.style.display === 'block', drift: d ? d.textContent : null, first: (c.querySelector('header code') || {}).textContent }; });
      const line = 'at head ' + row.head.slice(0, 7) + ': MOVED to line ' + row.head_line + ' (' + (row.delta > 0 ? '+' : '') + row.delta + ')';
      ok('card names head and new line', card.open && card.drift && card.drift.includes(line), JSON.stringify(card.drift));
      let p = await page.evaluate(id => KY.modules.drift.api.screen(id), mv.id);
      const px = await overlay(page, p[0], p[1], 4);
      ok('MOVED spark amber', px.amber >= 4, 'at (' + p.map(v => v.toFixed(1)).join(', ') + '): ' + px.amber + ' amber px in a 9x9 box');
      if (HANDOFF && devName === 'Pixel 7') await page.screenshot({ path: path.join(HERE, 'img', '1-moved-card-Pixel_7.png'), scale: 'css', timeout: 180000 });
      // close the card, then tap within 9 px of the amber spark with a finger
      await page.evaluate(() => { const c = document.querySelector('#card'); const x = c.querySelector('.lc-x,.cx'); if (x) x.click(); }); await sleep(2500);
      p = await page.evaluate(id => KY.modules.drift.api.screen(id), mv.id);
      const before = (await ins()).taps;
      await page.touchscreen.tap(p[0] + 6, p[1] + 6); await sleep(4000);
      s = await ins();
      const card2 = await page.evaluate(() => { const c = document.querySelector('#card'); const d = c.querySelector('.ky-drift-cl'); return { open: c.style.display === 'block', drift: d ? d.textContent : null }; });
      ok('tap within 9 px opens its card', s.taps === before + 1 && card2.open && card2.drift && card2.drift.includes(line), 'tap at +6,+6 (8.5 px): taps ' + before + '→' + s.taps + ', ' + JSON.stringify(card2.drift));
      await page.evaluate(() => { const c = document.querySelector('#card'); const x = c.querySelector('.lc-x,.cx'); if (x) x.click(); }); await sleep(1500);
    }
    // the LINES filter "moved", reached the way a finger reaches it: the shell's WAFER title when the shell is admitted,
    // else the page's own LINES button (ROADMAP step 8: "LINES gains a filter by class"); no programmatic panel opening
    const w = await page.evaluate(() => { const t = document.querySelector('#kuiper-menu-bar') ? [...document.querySelectorAll('#kuiper-menu-bar .gm-title')].find(b => b.textContent.trim().toUpperCase() === 'WAFER')
        : [...document.querySelectorAll('#bar button, #bar a, #bar [role=button]')].find(b => b.textContent.trim().toUpperCase() === 'LINES');
      if (!t) return null; const r = t.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2, t.textContent.trim()]; });
    if (w) { await page.touchscreen.tap(w[0], w[1]); await sleep(2500); }
    await page.evaluate(() => { const d = document.querySelector('#ky-drift'); if (d) d.scrollIntoView({ block: 'start' }); }); await sleep(800);
    const chip = await page.evaluate(() => { const b = document.querySelector('#ky-drift .kd-c button[data-class=MOVED]'); if (!b) return null; const r = b.getBoundingClientRect(); const x = r.left + r.width / 2, y = r.top + r.height / 2;
      const e = document.elementFromPoint(x, y); return [x, y, r.height, !!(e && b.contains(e)), e ? (e.id || e.className || e.tagName) : 'none', (b.closest('.gm-panel,[id]:not(#ky-drift)') || {}).id || ''];
    });
    if (chip) { await page.evaluate(() => KY.modules.drift.api.filter('SAME')); await sleep(300);
      const c2 = await page.evaluate(() => { const r = document.querySelector('#ky-drift .kd-c button[data-class=MOVED]').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; });
      await page.touchscreen.tap(c2[0], c2[1]); await sleep(1500); }
    const listed = await page.evaluate(() => [...document.querySelectorAll('#ky-drift .kd-l [data-row]')].map(b => ({ row: +b.dataset.row, cls: b.dataset.class })));
    const wantRows = DRIFT.rows.map((r, i) => r.class === 'MOVED' ? i : -1).filter(i => i >= 0);
    ok('filter "moved" lists exactly the MOVED rows', chip && chip[2] >= 44 && chip[3] && listed.length === wantRows.length && listed.every((x, i) => x.cls === 'MOVED' && x.row === wantRows[i]),
      'opened by a tap on ' + (w ? '"' + w[2] + '"' : 'NOTHING (no WAFER title, no LINES button)') + '; chip ' + (chip ? chip[2].toFixed(0) + ' px tall, ' + (chip[3] ? 'on top' : 'COVERED by ' + chip[4]) + ', in ' + (chip[5] || 'body') : 'missing') + '; listed ' + listed.length + ' rows, drift.json MOVED ' + wantRows.length);
    if (HANDOFF && devName === 'Galaxy S24') await page.screenshot({ path: path.join(HERE, 'img', '2-filter-moved-Galaxy_S24.png'), scale: 'css', timeout: 180000 });
    const bar2 = await barOf();
    ok('bar unchanged with the panel open', bar2.rows === bar.rows && (!bar2.shell || bar2.rows === 1), bar2.bar + ' ' + bar2.rows + ' row(s)');
  }
  if (scen === 'C') {
    const s = await ins();
    const hud = await page.evaluate(() => document.querySelector('#hud').textContent);
    ok('drift.json missing: refused in words', s && s.status === 'REFUSED' && hud.includes('data/drift.json did not load. The wafer will not invent a head.'), (hud.split('\n').find(l => /^DRIFT/.test(l)) || 'no DRIFT line'));
    ok('drift.json missing: no amber drawn by drift', s && s.marks === 0, 'marks ' + (s && s.marks));
    res.hud = hud;
    if (HANDOFF && devName === 'Galaxy S24') await page.screenshot({ path: path.join(HERE, 'img', '3-drift-missing-Galaxy_S24.png'), scale: 'css', timeout: 180000 });
  }
  const errs = scen === 'C' ? errors.filter(e => !/404/.test(e) || !/Failed to load resource/.test(e)) : errors;
  ok('zero console errors', errs.length === 0, errs.length ? errs.slice(0, 3).join(' | ') : '0' + (scen === 'C' ? ' (the deliberate 404 of data/drift.json excluded: ' + (errors.length - errs.length) + ')' : ''));
  res.steps = steps;
  await browser.close();
  return res;
}

(async () => {
  let py = null;
  if (!argv.includes('--no-py')) {
    const { spawnSync } = require('child_process');
    const pj = path.join(OUT, 'drift_test.json');
    console.log('drift_test.py (P1, P2, P3, P4 data, P5) ...');
    const r = spawnSync('python3', [path.join(HERE, 'drift_test.py'), '--json', pj, '--scratch', path.join(OUT, 'py-scratch')], { encoding: 'utf8', timeout: 1800000 });
    process.stdout.write(r.stdout || ''); process.stderr.write(r.stderr || '');
    try { py = JSON.parse(fs.readFileSync(pj, 'utf8')); } catch (e) { py = { result: 'FAIL', results: [{ test: 'drift_test.py ran', pass: false, detail: 'exit ' + r.status + ', no JSON' }] }; }
  } else { try { py = JSON.parse(fs.readFileSync(path.join(OUT, 'drift_test.json'), 'utf8')); } catch (e) {} }
  const all = [];
  for (const d of DEVICES) {
    const A = await run(d, 'A'), B = await run(d, 'B'), Cc = await run(d, 'C');
    // with drift.json missing the wafer and the green sparks are unchanged (the overlay at home, same viewport)
    const same = Cc.base.green === A.base.green;
    const st = { device: d, scenario: 'A/C', step: 'drift.json missing: green sparks unchanged', pass: same && A.base.green > 0, detail: 'green overlay px at home: no module ' + A.base.green + ', drift.json 404 ' + Cc.base.green };
    console.log((st.pass ? 'PASS ' : 'FAIL ') + d + ' A/C ' + st.step + ' · ' + st.detail);
    const mine = [...A.steps, ...B.steps, ...Cc.steps, st];
    fs.writeFileSync(path.join(OUT, 'steps-' + d.replace(/ /g, '_') + '.json'), JSON.stringify({ when: new Date().toISOString(), module_sha256: modSha, steps: mine }, null, 1));
  }
  // every device run so far for THIS module (a device file of another module hash is stale and is dropped)
  const missing = [];
  for (const d of ALL_DEVICES) {
    const f = path.join(OUT, 'steps-' + d.replace(/ /g, '_') + '.json');
    let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {}
    if (j && j.module_sha256 === modSha) all.push(...j.steps); else missing.push(d);
  }
  missing.forEach(d => all.push({ device: d, scenario: '-', step: 'device run for this module', pass: false, detail: 'no run of module ' + modSha.slice(0, 12) + ' on ' + d + ' in ' + OUT }));
  (py ? py.results : [{ test: 'drift_test.py', pass: false, detail: 'not run' }]).forEach(t => all.push({ device: 'python', scenario: 'P' + (t.test.match(/^P(\d)/) || [, '?'])[1], step: t.test, pass: t.pass, detail: t.detail }));
  if (HANDOFF) {
    const imgs = fs.readdirSync(path.join(HERE, 'img')).filter(f => /\.png$/.test(f));
    const big = imgs.filter(f => fs.statSync(path.join(HERE, 'img', f)).size >= 300 * 1024);
    all.push({ device: 'files', scenario: '-', step: 'img/ at most 4 PNG, each < 300 KB', pass: imgs.length <= 4 && !big.length,
      detail: imgs.map(f => f + ' ' + Math.round(fs.statSync(path.join(HERE, 'img', f)).size / 1024) + ' KB').join(', ') });
  }
  const fails = all.filter(s => !s.pass);
  const report = { when: new Date().toISOString(), url: URL0, pre_integration: PRE, module: { file: modFile, sha256: modSha, bytes: modBytes.length },
    drift: { sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(ED, 'data', 'drift.json'))).digest('hex'), counts: C }, steps: all,
    result: fails.length ? 'FAIL' : 'PASS' };
  fs.writeFileSync(path.join(OUT, 'report.json'), JSON.stringify(report, null, 1));
  if (HANDOFF) {
    const t = ['# TEST.md — Opus team 8, step 8 the drift (P1-P5: drift_test.py and P4 on Android)', '',
      'Written by `handoff/08-drift/test.cjs` (OPUS-8 tester). P1 determinism, P2 refusal, P3 ground truth by `git show`, the data half of P4 and P5 are `drift_test.py` (device `python`, independent of `tools/drift.py --check`); P4 on the page is Playwright with real touch on Pixel 7 and Galaxy S24, scenario A no drift module, B drift admitted, C drift admitted and data/drift.json answering 404.',  … [line shortened here: 404 characters; full line on GitHub]
      'tools/drift.py sha256 `' + (py && py.tool_sha256 || '?') + '`; keys.json sha256 `' + (py && py.keys_json_sha256 || '?') + '`.', '',
      'Run ' + report.when + ' · ' + URL0 + (PRE ? ' · **pre-integration** (modules.json routed: served records re-hashed from disk + line-card + drift)' : ' · as served'),
      'Module `modules/' + modFile + '` sha256 `' + modSha + '` (' + modBytes.length + ' bytes); data/drift.json sha256 `' + report.drift.sha256 + '`.', '',
      '| device | scenario | step | result | measured |', '|---|---|---|---|---|',
      ...all.map(s => '| ' + s.device + ' | ' + s.scenario + ' | ' + s.step + ' | ' + (s.pass ? 'PASS' : 'FAIL') + ' | ' + String(s.detail).replace(/\|/g, '\\|').slice(0, 300) + ' |'), '',
      'RESULT: ' + report.result + ' (' + (all.length - fails.length) + ' of ' + all.length + ')', '',
      ...((py && py.info || []).length ? ['Measured, not pass/fail (drift_test.py):', '', ...py.info.map(x => '- ' + x), ''] : [])];
    fs.writeFileSync(path.join(HERE, 'TEST.md'), t.join('\n'));
  }
  console.log('RESULT: ' + report.result + ' (' + (all.length - fails.length) + ' of ' + all.length + ')' + (PRE ? ' pre-integration' : '') + (fails.length ? ' · failing: ' + fails.map(f => f.device + ' ' + f.step).join('; ') : ''));
  process.exit(fails.length ? 1 : 0);
})().catch(e => { console.error('harness error', e); process.exit(2); });