GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / testcode / sandbox/202609151802-galaxy-bond

Bond Validator and 5 more files

A Python command-line tool in the sandbox folder of Testcode that reads u32 (`read_u32`), using SHA-256.

688 lines of Python and JavaScript and HTML from testcode, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1586 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. Bond Validator ingest · testcode / sandbox/202609151802-galaxy-bond/bond_validator.py lines 1–398
  2. Sandbox — Galaxy Bond Page render · testcode / sandbox/202609151802-galaxy-bond/index.html lines 1–31
  3. Test Bond Validator test · testcode / sandbox/202609151802-galaxy-bond/test_bond_validator.py lines 1–198
  4. Browser Check render · testcode / sandbox/202609151943-galaxy-profile/browser-check.mjs lines 1–24
  5. Model render · testcode / sandbox/202609151943-galaxy-profile/model.mjs lines 1–21
  6. Model Test test · testcode / sandbox/202609151943-galaxy-profile/model.test.mjs lines 1–16

Bond Validator

A Python command-line tool in the sandbox folder of Testcode that reads u32 (`read_u32`), using SHA-256.

ingesttestcode / sandbox/202609151802-galaxy-bond/bond_validator.py · lines 1–398 of 398 · version 2026-09-15 18:02 · Entry point · pattern _anchors_and_routes (shared by 2 files)

What it does
It loads data. Defines 19 functions or classes, including _int, _deviation, _predicate, _one, _neq. Uses libraries __future__, argparse, collections, hashlib, json. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): 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.
Downstream impact
Used directly by 1 file: Test Bond Validator (testcode).
What it achieves
It reads JSON (`read_json`) and is built from the integrity checks helper (`integrity_checks`) and the audit step (`audit`). The Bond v1: deterministic checks, with explicit limits to what was checked. It accepts `--manifest`, `--layers-map` and `--issued-keys`.
Why it matters
Checked by Test Bond Validator.
Application
testcode · sandbox/202609151802-galaxy-bond · Python CLI
Uses
__future__, argparse, collections, hashlib, json, pathlib, re, struct
Used by
imported by Test Bond Validator (import)
Produces
integrity_checks, audit, read_u32, main
Defines here
_int, _deviation, _predicate, _one, _neq, _lookup, _family_index, _geometry_keys, _block_index, integrity_checks, _disclosures, _structural, _anchors_and_routes, _copying, _module, audit, read_u32, main, read_json
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151802-galaxy-bond/bond_validator.py:1-398 · blob 23f5835032f3eccab268a02feb927b272693ec26 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unknown
"""The Bond v1: deterministic checks, with explicit limits to what was checked.

Pure stdlib. No network, path discovery, current timestamps, or HTML generation.
Input paths are a CLI concern and never appear in the report. Source prose is
preserved verbatim; callers must supply public, publishable source documents.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path
import re
import struct

SCHEMA = "bond.v1"
COPYING = "lines carried by 2 to 40 function families and at least 12 characters long"
BLOCKS = "the live block register, each function family a block names, placed at its first line"
STAR = "blocks in the live register with files[].path under testcode/202609142225/, each function family they name placed at its first line"
MODULE = re.compile(r"the live block register: block ([A-Za-z0-9]+) #([0-9]+), ([0-9]+) named families, ([0-9]+) numbered lines, repository (.+)")
ROUTE = "the family's lines in numbering order"
DISCLOSURES = frozenset({"unanchored", "unresolved", "unresolved_families", "why", "live_mismatch", "contract_edge", "not_computed", "NOT_COMPUTED", "limitations"})


def _int(value):
    return isinstance(value, int) and not isinstance(value, bool)


def _deviation(field, expected, actual, feature_index=None):
    return {"feature_index": feature_index, "field": field, "expected": expected, "actual": actual}


def _predicate(name, text, checks, total=None):
    """Checks are (passed, deviation); examine all to compute true denominators."""
    checks = list(checks)
    failures = [d for ok, d in checks if not ok]
    checked = len(checks)
    total = checked if total is None else total
    return {"id": name, "text": text,
            "status": "FAILED" if failures else ("NOT EVALUATED" if total > checked else "PASSED"),
            "checked": checked, "total": total, "passed": checked - len(failures),
            "failed": len(failures), "first_deviation": failures[0] if failures else None}


def _one(name, text, ok, field, expected, actual):
    return _predicate(name, text, [(bool(ok), _deviation(field, expected, actual))])


def _neq(row, field, text, reason):
    row["not_evaluated"].append({"field": field, "text": text, "reason": reason})


def _lookup(mapping, entry):
    if mapping is None:
        return None
    return mapping.get(entry.get("file"), mapping.get(entry.get("id")))


def _family_index(families, family_lines):
    if isinstance(families, dict):
        families = families.get("families", list(families.values()))
    records = list(families or [])
    duplicates = {n for n, count in Counter(f.get("n") for f in records if isinstance(f, dict) and _int(f.get("n"))).items() if count > 1}
    index, issues = {}, []
    for position, f in enumerate(records):
        if not isinstance(f, dict) or not _int(f.get("n")) or f["n"] in duplicates:
            issues.append({"record_index": position, "reason": "family identifier missing, invalid, or duplicated"})
            continue
        if isinstance(f.get("lines"), list):
            keys = f["lines"]
        else:
            offset, count = f.get("lineOffset"), f.get("lineCount")
            if not (_int(offset) and _int(count) and offset >= 0 and count >= 0 and family_lines is not None and offset + count <= len(family_lines)):
                issues.append({"record_index": position, "reason": "family slice outside supplied line array"})
                continue
            keys = family_lines[offset:offset + count]
        if not all(_int(k) and 0 < k <= 0xFFFFFFFF for k in keys):
            issues.append({"record_index": position, "reason": "family line array contains invalid key"})
            continue
        index[f["n"]] = list(keys)
    return index, issues, len(records)


def _geometry_keys(g):
    if not isinstance(g, dict):
        return None
    if g.get("type") == "Point" and _int(g.get("key")):
        return [g["key"]]
    if g.get("type") == "LineString" and isinstance(g.get("keys"), list) and len(g["keys"]) >= 2 and all(_int(k) for k in g["keys"]):
        return g["keys"]
    return None


def _block_index(register):
    if not register:
        return {}
    if isinstance(register, dict) and "blocks" in register:
        return {b["symbol"]: b for b in register["blocks"] if isinstance(b, dict) and isinstance(b.get("symbol"), str)}
    if isinstance(register, dict):
        return {symbol: {"symbol": symbol, "inside": [{"family": n} for n in ids]} for symbol, ids in register.items() if isinstance(ids, list)}
    return {}


def integrity_checks(entry, doc, raw=None, *, duplicate_id=False):
    """Check manifest facts against parsed content and optional original bytes."""
    features = doc.get("features")
    count = len(features) if isinstance(features, list) else None
    actual_id = doc.get("layer", {}).get("id") if isinstance(doc.get("layer"), dict) else None
    result = [
        _one("manifest.unique_id", "Manifest layer identifier is unique", not duplicate_id, "manifest.id", "unique identifier", "duplicate identifier" if duplicate_id else "unique identifier"),
        _one("manifest.layer_id", "Manifest identifier equals the layer identifier", entry.get("id") == actual_id and isinstance(actual_id, str), "layer.id", entry.get("id"), actual_id),
        _one("manifest.features", "Manifest feature count equals the array length", _int(entry.get("features")) and entry["features"] == count, "manifest.features", count, entry.get("features")),
    ]
    if raw is None:
        for name, text in (("manifest.bytes", "Manifest byte length equals the original file length"), ("manifest.sha256", "Manifest SHA-256 equals the original file digest")):
            result.append(_predicate(name, text, [], 1))
    else:
        digest = hashlib.sha256(raw).hexdigest()
        result.extend([
            _one("manifest.bytes", "Manifest byte length equals the original file length", _int(entry.get("bytes")) and entry["bytes"] == len(raw), "manifest.bytes", len(raw), entry.get("bytes")),
            _one("manifest.sha256", "Manifest SHA-256 equals the original file digest", entry.get("sha256") == digest, "manifest.sha256", digest, entry.get("sha256")),
        ])
        try:
            decoded = json.loads(raw)
            same = decoded == doc
        except (ValueError, UnicodeError):
            same = False
        result.append(_one("manifest.raw_matches_parsed", "Checked bytes decode to the supplied layer document", same, "layer", "same parsed document", "same parsed document" if same else "different or invalid document"))
    return result


def _disclosures(row, doc, features):
    stats = doc.get("stats", {})
    if isinstance(stats, dict):
        for key in sorted(DISCLOSURES & stats.keys()):
            if stats[key] not in (None, "", [], {}):
                row["disclosed"].append({"field": "stats." + key, "value": stats[key], "status": "DISCLOSED"})
    for i, f in enumerate(features):
        props = f.get("properties", {}) if isinstance(f, dict) else {}
        if isinstance(props, dict) and props.get("runtime_replayed") is False:
            row["disclosed"].append({"field": f"features[{i}].properties.runtime_replayed", "value": False, "status": "DISCLOSED"})


def _structural(row, doc, features, issued):
    predicates = row["predicates"]
    predicates.append(_one("collection.format", "Layer is a CodeFeatureCollection on wafer.v1 with a feature array", doc.get("type") == "CodeFeatureCollection" and doc.get("substrate") == "wafer.v1" and isinstance(doc.get("features"), list), "collection", "CodeFeatureCollection / wafer.v1 / array", {"type": doc.get("type"), "substrate": doc.get("substrate"), "feature_array": isinstance(doc.get("fe  … [line shortened here: 418 characters; full line on GitHub]
    stats = doc.get("stats", {})
    stats_count = stats.get("features") if isinstance(stats, dict) else None
    predicates.append(_one("stats.features", "stats.features equals the feature array length", _int(stats_count) and stats_count == len(features), "stats.features", len(features), stats_count))
    geometry_checks, key_checks, feature_checks = [], [], []
    all_keys, valid_features = [], set()
    ids = [f.get("id") for f in features if isinstance(f, dict) and "id" in f]
    id_counts = Counter(json.dumps(v, sort_keys=True) for v in ids)
    id_checks = []
    for i, f in enumerate(features):
        is_feature = isinstance(f, dict) and f.get("type") == "Feature"
        feature_checks.append((is_feature, _deviation("type", "Feature", f.get("type") if isinstance(f, dict) else None, i)))
        g = f.get("geometry") if isinstance(f, dict) else None
        keys = _geometry_keys(g)
        allowed = {"type", "key"} if isinstance(g, dict) and g.get("type") == "Point" else {"type", "keys"}
        valid_geometry = keys is not None and set(g) == allowed
        geometry_checks.append((valid_geometry, _deviation("geometry", "Point {type,key} or LineString {type,keys}; no coordinates", {"type": g.get("type"), "fields": sorted(g.keys())} if isinstance(g, dict) else None, i)))
        if keys is not None:
            all_keys.extend(keys)
            feature_keys_valid = True
            for j, key in enumerate(keys):
                exists = key in issued
                feature_keys_valid &= exists
                field = "geometry.key" if g["type"] == "Point" else f"geometry.keys[{j}]"
                key_checks.append((exists, _deviation(field, "issued line key", key, i)))
            if valid_geometry and is_feature and feature_keys_valid:
                valid_features.add(i)
        if isinstance(f, dict) and "id" in f:
            unique = id_counts[json.dumps(f["id"], sort_keys=True)] == 1
            id_checks.append((unique, _deviation("id", "unique feature identifier", f["id"], i)))
    predicates.extend([
        _predicate("features.type", "Each feature declares type Feature", feature_checks),
        _predicate("geometry.key_only", "Every geometry uses only issued-key geometry fields", geometry_checks),
        _predicate("geometry.issued_keys", "Every named geometry key exists in the supplied numbered database", key_checks),
        _predicate("features.unique_ids", "Present feature identifiers are unique within the layer", id_checks),
    ])
    row["coverage"].update({"features": len(features), "structurally_valid_features": len(valid_features), "key_references": len(all_keys), "issued_key_references": sum(k in issued for k in all_keys), "distinct_keys": len(set(all_keys))})


def _anchors_and_routes(row, features, family_index):
    first_checks, route_checks = [], []
    points, routes, aligned = 0, 0, set()
    for i, f in enumerate(features):
        if not isinstance(f, dict):
            continue
        g, props = f.get("geometry", {}), f.get("properties", {})
        if not isinstance(g, dict) or not isinstance(props, dict):
            continue
        family_field = "family" if "family" in props else "anchor_family" if "anchor_family" in props else None
        if family_field is None:
            continue
        family = props[family_field]
        keys = family_index.get(family) if _int(family) else None
        if g.get("type") == "Point":
            points += 1
            if keys:
                ok = g.get("key") == keys[0]
                first_checks.append((ok, _deviation("geometry.key", keys[0], g.get("key"), i)))
                if ok:
                    aligned.add(i)
            else:
                _neq(row, f"features[{i}].properties.{family_field}", family, "No unique nonempty family line array is available for this exact family identifier.")
        if props.get("route") == ROUTE:
            routes += 1
            if keys is not None:
                actual = g.get("keys")
                ok = g.get("type") == "LineString" and actual == keys
                field = "geometry.keys"
                expected_deviation, actual_deviation = keys, actual
                if isinstance(actual, list):
                    at = next((j for j in range(min(len(actual), len(keys))) if actual[j] != keys[j]), None)
                    if at is not None:
                        field, expected_deviation, actual_deviation = f"geometry.keys[{at}]", keys[at], actual[at]
                    elif len(actual) != len(keys):
                        field, expected_deviation, actual_deviation = "geometry.keys.length", len(keys), len(actual)
                route_checks.append((ok, _deviation(field, expected_deviation, actual_deviation, i)))
                if ok:
                    aligned.add(i)
            else:
                _neq(row, f"features[{i}].properties.route", ROUTE, "No unique family line array is available for the stated family.")
        elif isinstance(props.get("route"), str):
            _neq(row, f"features[{i}].properties.route", props["route"], "Route prose is outside the exact v1 allowlist.")
    if points:
        row["predicates"].append(_predicate("family.first_line", "Point key equals the first entry of its exact family line array", first_checks, points))
    if routes:
        row["predicates"].append(_predicate("family.numbering_order", "Route exactly follows its family's supplied line array, including repeated keys", route_checks, routes))
    row["coverage"].update({"family_point_candidates": points, "family_points_checked": len(first_checks), "family_route_candidates": routes, "family_routes_checked": len(route_checks), "family_aligned_features": len(aligned)})


def _copying(row, features, independent_lines):
    checks = {"owners": [], "chars": []}
    totals = len(features)
    for i, f in enumerate(features):
        g = f.get("geometry", {}) if isinstance(f, dict) else {}
        key = g.get("key") if isinstance(g, dict) else None
        evidence = independent_lines.get(key, independent_lines.get(str(key), {})) if independent_lines else {}
        owners, chars = evidence.get("owners"), evidence.get("chars")
        if isinstance(owners, (list, tuple, set)) and all(_int(n) for n in owners):
            count = len(set(owners))
            checks["owners"].append((g.get("type") == "Point" and 2 <= count <= 40, _deviation("geometry.key.owner_count", "2 to 40 distinct families", count, i)))
        if _int(chars):
            checks["chars"].append((g.get("type") == "Point" and chars >= 12, _deviation("geometry.key.char_length", "at least 12 characters", chars, i)))
    row["predicates"].extend([
        _predicate("copying.owner_count", "Independent owner membership contains 2 to 40 distinct families", checks["owners"], totals),
        _predicate("copying.minimum_length", "Independent line length is at least 12 characters", checks["chars"], totals),
    ])
    if not features or len(checks["owners"]) < totals or len(checks["chars"]) < totals:
        _neq(row, "layer.evidence", COPYING, "Copying requires independent owner memberships and line lengths for every feature; same-feature families/chars fields are not proof. Empty output does not establish copying completeness.")


def _module(row, doc, features, match, blocks, family_index):
    symbol, number, named, lines, repos = match.groups()
    claimed_count, claimed_lines = int(named), int(lines)
    block = blocks.get(symbol)
    if block is None:
        _neq(row, "layer.evidence", match.group(), "Module named-family count, total lines, block number and repository need an independent block register; feature properties and stats alone are insufficient.")
        return
    inside = block.get("inside")
    if not isinstance(inside, list) or any(not isinstance(x, dict) or not _int(x.get("family")) for x in inside):
        _neq(row, "layer.evidence", match.group(), "Independent block membership is missing or malformed.")
        return
    ids = [x["family"] for x in inside]
    p = row["predicates"]
    p.append(_one("module.named_families", "Claimed named-family count equals independent block membership count", claimed_count == len(ids), "layer.evidence.named_families", len(ids), claimed_count))
    stats = doc.get("stats", {})
    if isinstance(stats, dict) and "families" in stats:
        p.append(_one("module.stats_families", "stats.families equals independent block membership count", _int(stats["families"]) and stats["families"] == len(ids), "stats.families", len(ids), stats["families"]))
    if all(n in family_index for n in ids):
        total_lines = sum(len(family_index[n]) for n in ids)
        p.append(_one("module.numbered_lines", "Claimed numbered-line count equals independent family array lengths", total_lines == claimed_lines, "layer.evidence.numbered_lines", total_lines, claimed_lines))
        if isinstance(stats, dict) and "lines" in stats:
            p.append(_one("module.stats_lines", "stats.lines equals independent family array lengths", _int(stats["lines"]) and stats["lines"] == total_lines, "stats.lines", total_lines, stats["lines"]))
    else:
        _neq(row, "layer.evidence", match.group(), "Some registered families have no supplied line array; total numbered-line count is not evaluated.")
    membership = []
    for i, f in enumerate(features):
        props = f.get("properties", {}) if isinstance(f, dict) else {}
        family = props.get("family") if isinstance(props, dict) else None
        membership.append((family in ids, _deviation("properties.family", "a member of the independent block register", family, i)))
    p.append(_predicate("module.feature_membership", "Every feature names an independently registered module family", membership))
    if "number" in block and "repos" in block:
        expected_repos = ", ".join(block["repos"]) or "unstated"
        p.append(_one("module.block_number", "Claimed block number equals independent register", _int(block["number"]) and int(number) == block["number"], "layer.evidence.block_number", block["number"], int(number)))
        p.append(_one("module.repositories", "Claimed repository list equals independent register", repos == expected_repos, "layer.evidence.repositories", expected_repos, repos))
    else:
        _neq(row, "layer.evidence", match.group(), "Supplied block membership does not establish the block number or repository list.")


def audit(manifest, layers, issued_keys, families=None, family_lines=None, *, raw_bytes=None, independent_lines=None, block_register=None):
    """Audit public documents; see API.md for the report and evidence contracts.

    layers/raw_bytes: mappings by manifest file or id. Array indexes are zero
    based. independent_lines must come from independent complete owner/length
    data, never the layer being audited. Input objects are not mutated.
    """
    issued_values = list(issued_keys)
    issued = {k for k in issued_values if _int(k) and 0 < k <= 0xFFFFFFFF}
    family_index, family_issues, family_records = _family_index(families, family_lines)
    blocks = _block_index(block_register)
    entries = manifest.get("layers", []) if isinstance(manifest, dict) else []
    if not isinstance(entries, list):
        entries = []
    ids = Counter(e.get("id") for e in entries if isinstance(e, dict) and isinstance(e.get("id"), str))
    rows = []
    for position, entry in enumerate(entries):
        if not isinstance(entry, dict):
            entry = {}
        doc = _lookup(layers, entry)
        row = {"manifest_index": position, "layer_id": entry.get("id"), "label": entry.get("label", entry.get("id")), "claim_text": "", "status": "NOT EVALUATED", "predicates": [], "disclosed": [], "not_evaluated": [], "first_deviation": None, "coverage": {}}
        if not isinstance(doc, dict):
            row["predicates"].append(_one("layer.available", "Manifest layer document is available", False, "layer", "parsed layer document", None))
            doc = {}
        metadata = doc.get("layer", {})
        if not isinstance(metadata, dict):
            metadata = {}
        evidence = metadata.get("evidence", "")
        row["claim_text"] = evidence
        row["predicates"].extend(integrity_checks(entry, doc, _lookup(raw_bytes, entry), duplicate_id=ids[entry.get("id")] > 1))
        features = doc.get("features", [])
        if not isinstance(features, list):
            features = []
        _structural(row, doc, features, issued)
        _disclosures(row, doc, features)
        _anchors_and_routes(row, features, family_index)
        match = MODULE.fullmatch(evidence) if isinstance(evidence, str) else None
        if evidence == COPYING:
            _copying(row, features, independent_lines)
        elif match:
            _module(row, doc, features, match, blocks, family_index)
        elif evidence in (BLOCKS, STAR):
            _neq(row, "layer.evidence", evidence, "Exact-family first-line alignment is checked where a family array is supplied; register membership, selection and completeness are not evaluated by this pattern.")
        elif evidence:
            _neq(row, "layer.evidence", evidence, "This evidence text is outside the exact v1 allowlist. Structural or anchor checks do not prove it.")
        else:
            _neq(row, "layer.evidence", evidence, "No evidence statement was supplied.")
        if metadata.get("note"):
            _neq(row, "layer.note", metadata["note"], "Explanatory prose is retained verbatim and is not evaluated by v1.")
        for p in row["predicates"]:
            if p["status"] == "NOT EVALUATED":
                _neq(row, p["id"], p["text"], f"Required independent inputs are available for {p['checked']} of {p['total']} checks.")
        failed = [p for p in row["predicates"] if p["status"] == "FAILED"]
        semantic = [p for p in row["predicates"] if p["id"].startswith(("family.", "module.", "copying.")) and p["checked"]]
        row["status"] = "CONTRADICTED" if failed else "PARTIALLY EVALUATED" if row["not_evaluated"] and semantic else "NOT EVALUATED" if row["not_evaluated"] else "HONOURED"
        row["first_deviation"] = failed[0]["first_deviation"] if failed else None
        row["coverage"].update({"predicates": len(row["predicates"]), "predicates_passed": sum(p["status"] == "PASSED" for p in row["predicates"]), "predicates_failed": len(failed), "checks_evaluated": sum(p["checked"] for p in row["predicates"]), "checks_total": sum(p["total"] for p in row["predicates"]), "not_evaluated_items": len(row["not_evaluated"]), "disclosure_items": len(row["disclosed"])}  … [line shortened here: 401 characters; full line on GitHub]
        rows.append(row)
    manifest_ok = isinstance(manifest, dict) and manifest.get("substrate") == "wafer.v1" and isinstance(manifest.get("layers"), list)
    input_checks = [
        _one("manifest.format", "Manifest names wafer.v1 and contains a layer array", manifest_ok, "manifest", "wafer.v1 and layer array", "valid" if manifest_ok else "invalid"),
        _one("inputs.issued_keys", "Issued keys are unique positive uint32 integers", len(issued) == len(issued_values), "issued_keys", "unique positive uint32 integers", {"records": len(issued_values), "unique_valid_keys": len(issued)}),
    ]
    statuses = Counter(r["status"] for r in rows)
    return {"schema": SCHEMA, "scope": "Explicit v1 predicates only; disclosures do not waive contradictions; unsupported prose is not proved.", "input_checks": input_checks, "inputs": {"issued_keys": len(issued), "family_records": family_records, "usable_family_arrays": len(family_index), "family_input_issues": family_issues}, "coverage": {"manifest_entries": len(entries), "layers_reported": len(  … [line shortened here: 802 characters; full line on GitHub]


def read_u32(path):
    """Decode the explicitly supplied little-endian uint32 file."""
    raw = Path(path).read_bytes()
    if len(raw) % 4:
        raise ValueError("uint32 data length is not divisible by four")
    return [value[0] for value in struct.iter_unpack("<I", raw)]


def main(argv=None):
    parser = argparse.ArgumentParser(description="The Bond v1 offline audit; input paths are explicit and never published.")
    parser.add_argument("--manifest", required=True)
    parser.add_argument("--layers-map", required=True, help="JSON mapping manifest file/id to an explicit layer JSON path")
    parser.add_argument("--issued-keys", required=True, help="little-endian uint32 binary")
    parser.add_argument("--families")
    parser.add_argument("--family-lines", help="little-endian uint32 binary")
    parser.add_argument("--independent-lines", help="JSON mapping issued key to independent owners and chars")
    parser.add_argument("--block-register", help="independent register or block-to-family-ID mapping")
    parser.add_argument("--output", required=True)
    args = parser.parse_args(argv)
    if Path(args.output).exists():
        parser.exit(2, "Output already exists; supply a new output filename.\n")
    def read_json(path):
        return json.loads(Path(path).read_text(encoding="utf-8-sig")) if path else None
    try:
        mapping = read_json(args.layers_map)
        raw = {key: Path(path).read_bytes() for key, path in mapping.items()}
        layers = {key: json.loads(value) for key, value in raw.items()}
        report = audit(read_json(args.manifest), layers, read_u32(args.issued_keys), read_json(args.families), read_u32(args.family_lines) if args.family_lines else None, raw_bytes=raw, independent_lines=read_json(args.independent_lines), block_register=read_json(args.block_register))
        with Path(args.output).open("x", encoding="utf-8") as output:
            output.write(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
    except (OSError, ValueError, TypeError, KeyError):
        parser.exit(2, "Input could not be decoded or output could not be written. Check the explicit input mapping and formats.\n")
    return 1 if any(p["status"] == "FAILED" for p in report["input_checks"]) or any(r["status"] == "CONTRADICTED" for r in report["rows"]) else 0


if __name__ == "__main__":
    raise SystemExit(main())

Sandbox — Galaxy Bond Page

A web page in Testcode that reads inputs for status.

rendertestcode / sandbox/202609151802-galaxy-bond/index.html · lines 1–31 of 31 · version 2026-09-15 18:02 · Entry point

What it does
It draws its content. Uses libraries style.css. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "Required browser files are `index.html`, `style.css`, `app.mjs`, `report.json`, and the unchanged `wafer.mjs`."
Inputs & outputs
In: JSON file report.json; form fields (user input). Out: web page.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
The Bond — inspect the evidence behind a layer.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · sandbox/202609151802-galaxy-bond · page
Uses
Sandbox — Galaxy Bond (script src), style.css
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151802-galaxy-bond/index.html:1-31 · blob 08bfb595a7a75a674f50489ed6969b188a0e2a17 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta name="color-scheme" content="dark">
  <link rel="icon" href="data:,">
  <title>The Bond — inspect the evidence behind a layer</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header><div><p class="eyebrow">CODE GALAXY · EVIDENCE</p><h1>The Bond</h1></div><a id="source" href="https://github.com/Ventusltd/galaxies-wafers">Pinned source</a></header>
  <p class="intro">Read a layer's promise. Inspect what is checked, what contradicts it, and what remains unknown.</p>
  <p id="load" role="status">Reading the audit…</p>
  <main id="workspace" hidden>
    <section class="overview" aria-label="Audit overview">
      <dl id="totals" class="totals"></dl>
      <div class="map"><canvas id="wafer" aria-label="Sampled issued anchors on the frozen code wafer"></canvas><p id="map-note"></p></div>
      <article id="inspection" aria-live="polite"><h2>Select a layer</h2><p>Its claim, evaluated predicates and gaps appear here.</p></article>
    </section>
    <section class="catalogue" aria-label="Layers">
      <div class="controls"><label>Find a layer<input id="search" type="search" placeholder="Name or claim" autocomplete="off"></label><label>Result<select id="status"><option value="">Every result</option><option>CONTRADICTED</option><option>PARTIALLY EVALUATED</option><option>NOT EVALUATED</option><option>HONOURED</option></select></label></div>
      <p class="scope">A pass covers named predicates only. Disclosed gaps are not penalties; unsupported prose is not a pass.</p>
      <p id="shown" role="status"></p>
      <div id="layers"></div>
    </section>
  </main>
  <footer><p id="provenance"></p><p>Code-evidence inspection, not an engineering design or certification. The preview samples issued anchors; it is not the full numbered database.</p><a href="report.json">Read the full audit data</a> · <a href="README.md">Scope and reproduction</a></footer>
  <script type="module" src="app.mjs"></script>
</body>
</html>

Test Bond Validator

A test in the sandbox folder of Testcode that checks Bond Validator, using SHA-256.

testtestcode / sandbox/202609151802-galaxy-bond/test_bond_validator.py · lines 1–198 of 198 · version 2026-09-15 18:02 · Entry point · pattern test_duplicate_family_metadata_is_not_resolved_arbitrarily (shared by 2 files)

What it does
It tests its inputs. Defines 31 functions or classes, including feature, fixture, run, predicate, BondTests. Uses libraries copy, hashlib, json, pathlib, unittest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): 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 example.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It is built from the predicate step (`predicate`), the bond tests class (`BondTests`) and the corrupt step (`corrupt`). Defines `feature`, `fixture`, `run` and 28 more.
Why it matters
Guards the behaviour of Bond Validator.
Application
testcode · sandbox/202609151802-galaxy-bond · test
Uses
Bond Validator (import), copy, hashlib, json, pathlib, unittest
Used by
none found
Produces
feature, fixture, run, predicate, BondTests
Defines here
feature, fixture, run, predicate, BondTests, test_known_valid_point, test_unissued_key, test_family_number_is_not_key, test_family_number_can_be_issued_but_wrong_anchor, test_first_line_mismatch, test_anchor_family, test_coordinates_forbidden_even_with_valid_key, test_stale_manifest_count_hash_bytes, corrupt, test_duplicate_manifest_ids, duplicate, test_duplicate_feature_ids, test_honest_empty_disclosed, test_disclosure_does_not_waive_bad_key, test_unresolved_disclosure_exact_field, test_issued_keys_reject_non_uint32_values, test_cli_refuses_existing_output_before_reading_inputs, test_unsupported_prose_is_verbatim_and_not_honoured, test_copying_does_not_trust_same_feature_fields, test_copying_independent_both_predicates, test_copying_independent_detects_short_and_one_owner, test_route_numbering_array_not_numeric_sort, test_module_counts_need_independent_register, test_unknown_family_is_unevaluated, test_duplicate_family_metadata_is_not_resolved_arbitrarily
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151802-galaxy-bond/test_bond_validator.py:1-198 · blob 40d51c205b47f3b72f907e9b1defec20f03865f4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unknown
import copy
import hashlib
import json
from pathlib import Path
import unittest

from bond_validator import audit, main, COPYING, BLOCKS, ROUTE


def feature(key=101, family=9):
    return {"type": "Feature", "geometry": {"type": "Point", "key": key}, "properties": {"family": family}}


def fixture(features=None, evidence=BLOCKS, note=""):
    features = [feature()] if features is None else features
    doc = {"type": "CodeFeatureCollection", "substrate": "wafer.v1", "layer": {"id": "example", "evidence": evidence, "note": note}, "stats": {"features": len(features)}, "features": features}
    return doc


def run(doc, *, manifest_edit=None, families=None, keys=None, independent_lines=None, block_register=None):
    raw = json.dumps(doc, separators=(",", ":")).encode()
    entry = {"id": "example", "file": "layers/example.json", "features": len(doc["features"]), "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}
    manifest = {"substrate": "wafer.v1", "layers": [entry]}
    if manifest_edit:
        manifest_edit(manifest)
    return audit(manifest, {"example": doc}, [101, 102, 103] if keys is None else keys, [{"n": 9, "lineOffset": 0, "lineCount": 3}] if families is None else families, [101, 102, 103], raw_bytes={"example": raw}, independent_lines=independent_lines, block_register=block_register)


def predicate(report, name):
    return next(p for p in report["rows"][0]["predicates"] if p["id"] == name)


class BondTests(unittest.TestCase):
    def test_known_valid_point(self):
        report = run(fixture())
        self.assertEqual(predicate(report, "geometry.issued_keys")["status"], "PASSED")
        self.assertEqual(predicate(report, "family.first_line")["status"], "PASSED")
        self.assertEqual(report["rows"][0]["coverage"]["features"], 1)
        self.assertEqual(report["rows"][0]["status"], "PARTIALLY EVALUATED")

    def test_unissued_key(self):
        report = run(fixture([feature(999)]))
        p = predicate(report, "geometry.issued_keys")
        self.assertEqual(p["status"], "FAILED")
        self.assertEqual(p["first_deviation"]["feature_index"], 0)
        self.assertEqual(p["first_deviation"]["field"], "geometry.key")
        self.assertEqual(report["rows"][0]["status"], "CONTRADICTED")

    def test_family_number_is_not_key(self):
        report = run(fixture([feature(9)]))
        self.assertEqual(predicate(report, "geometry.issued_keys")["failed"], 1)
        self.assertEqual(predicate(report, "family.first_line")["failed"], 1)

    def test_family_number_can_be_issued_but_wrong_anchor(self):
        report = run(fixture([feature(9)]), keys=[9, 101, 102, 103])
        self.assertEqual(predicate(report, "geometry.issued_keys")["status"], "PASSED")
        self.assertEqual(predicate(report, "family.first_line")["status"], "FAILED")

    def test_first_line_mismatch(self):
        report = run(fixture([feature(102)]))
        self.assertEqual(predicate(report, "family.first_line")["first_deviation"]["expected"], 101)

    def test_anchor_family(self):
        f = feature()
        f["properties"] = {"anchor_family": 9}
        self.assertEqual(predicate(run(fixture([f])), "family.first_line")["status"], "PASSED")

    def test_coordinates_forbidden_even_with_valid_key(self):
        f = feature()
        f["geometry"]["coordinates"] = [0, 0]
        report = run(fixture([f]))
        self.assertEqual(predicate(report, "geometry.key_only")["status"], "FAILED")
        self.assertEqual(report["rows"][0]["coverage"]["structurally_valid_features"], 0)

    def test_stale_manifest_count_hash_bytes(self):
        def corrupt(m):
            m["layers"][0].update(features=2, bytes=1, sha256="0" * 64)
        report = run(fixture(), manifest_edit=corrupt)
        for name in ("manifest.features", "manifest.bytes", "manifest.sha256"):
            self.assertEqual(predicate(report, name)["status"], "FAILED")

    def test_duplicate_manifest_ids(self):
        def duplicate(m):
            m["layers"].append(copy.deepcopy(m["layers"][0]))
        report = run(fixture(), manifest_edit=duplicate)
        self.assertEqual(len(report["rows"]), 2)
        self.assertTrue(all(r["status"] == "CONTRADICTED" for r in report["rows"]))

    def test_duplicate_feature_ids(self):
        f, g = feature(), feature(102)
        f["id"] = g["id"] = "a"
        report = run(fixture([f, g]))
        self.assertEqual(predicate(report, "features.unique_ids")["failed"], 2)

    def test_honest_empty_disclosed(self):
        doc = fixture([], evidence="The register has no exact anchor; no marks are placed.")
        doc["stats"]["why"] = "No exact numbered anchor exists in the supplied register."
        report = run(doc)
        row = report["rows"][0]
        self.assertEqual(row["coverage"]["features"], 0)
        self.assertEqual(row["status"], "NOT EVALUATED")
        self.assertEqual(row["disclosed"][0]["status"], "DISCLOSED")
        self.assertEqual(predicate(report, "stats.features")["status"], "PASSED")

    def test_disclosure_does_not_waive_bad_key(self):
        doc = fixture([feature(999)])
        doc["stats"]["unanchored"] = [{"reason": "The target is unknown"}]
        report = run(doc)
        self.assertEqual(report["rows"][0]["status"], "CONTRADICTED")
        self.assertEqual(len(report["rows"][0]["disclosed"]), 1)

    def test_unresolved_disclosure_exact_field(self):
        doc = fixture()
        doc["stats"]["unresolved"] = [12, 13]
        self.assertEqual(run(doc)["rows"][0]["disclosed"][0]["field"], "stats.unresolved")

    def test_issued_keys_reject_non_uint32_values(self):
        report = run(fixture(), keys=[101, 102, 103, 0x100000000, True, -1])
        self.assertEqual(report["input_checks"][1]["status"], "FAILED")
        self.assertEqual(report["inputs"]["issued_keys"], 3)

    def test_cli_refuses_existing_output_before_reading_inputs(self):
        existing = Path(__file__)
        before = existing.read_bytes()
        with self.assertRaises(SystemExit) as result:
            main(["--manifest", "unused", "--layers-map", "unused", "--issued-keys", "unused", "--output", str(existing)])
        self.assertEqual(result.exception.code, 2)
        self.assertEqual(existing.read_bytes(), before)

    def test_unsupported_prose_is_verbatim_and_not_honoured(self):
        prose = "Every function is safe and all outcomes have been established."
        report = run(fixture(evidence=prose))
        row = report["rows"][0]
        self.assertNotEqual(row["status"], "HONOURED")
        self.assertEqual(row["not_evaluated"][0]["text"], prose)

    def test_copying_does_not_trust_same_feature_fields(self):
        f = feature()
        f["properties"] = {"families": 2, "chars": 30}
        report = run(fixture([f], COPYING))
        self.assertEqual(predicate(report, "copying.owner_count")["status"], "NOT EVALUATED")
        self.assertEqual(predicate(report, "copying.minimum_length")["status"], "NOT EVALUATED")

    def test_copying_independent_both_predicates(self):
        f = feature()
        f["properties"] = {"families": 2, "chars": 30}
        report = run(fixture([f], COPYING), independent_lines={101: {"owners": [9, 10], "chars": 15}})
        self.assertEqual(report["rows"][0]["status"], "HONOURED")
        self.assertNotIn("UNDERCLAIMED", json.dumps(report))

    def test_copying_independent_detects_short_and_one_owner(self):
        report = run(fixture(evidence=COPYING), independent_lines={101: {"owners": [9], "chars": 4}})
        self.assertEqual(predicate(report, "copying.owner_count")["status"], "FAILED")
        self.assertEqual(predicate(report, "copying.minimum_length")["status"], "FAILED")

    def test_route_numbering_array_not_numeric_sort(self):
        route = {"type": "Feature", "geometry": {"type": "LineString", "keys": [103, 101, 103]}, "properties": {"family": 9, "route": ROUTE}}
        report = run(fixture([route]), families=[{"n": 9, "lines": [103, 101, 103]}])
        self.assertEqual(predicate(report, "family.numbering_order")["status"], "PASSED")
        route["geometry"]["keys"] = [101, 103, 103]
        p = predicate(run(fixture([route]), families=[{"n": 9, "lines": [103, 101, 103]}]), "family.numbering_order")
        self.assertEqual(p["status"], "FAILED")
        self.assertEqual(p["first_deviation"]["field"], "geometry.keys[0]")

    def test_module_counts_need_independent_register(self):
        text = "the live block register: block Ga #14, 1 named families, 3 numbered lines, repository Public/repo"
        doc = fixture(evidence=text)
        doc["stats"].update(families=1, lines=3)
        report = run(doc)
        self.assertTrue(any("independent block register" in x["reason"] for x in report["rows"][0]["not_evaluated"]))
        independent = {"blocks": [{"symbol": "Ga", "number": 14, "inside": [{"family": 9}], "repos": ["Public/repo"]}]}
        report = run(doc, block_register=independent)
        self.assertEqual(predicate(report, "module.named_families")["status"], "PASSED")
        self.assertEqual(predicate(report, "module.numbered_lines")["status"], "PASSED")

    def test_unknown_family_is_unevaluated(self):
        report = run(fixture([feature(family=10)]))
        p = predicate(report, "family.first_line")
        self.assertEqual((p["checked"], p["total"], p["status"]), (0, 1, "NOT EVALUATED"))

    def test_duplicate_family_metadata_is_not_resolved_arbitrarily(self):
        report = run(fixture(), families=[{"n": 9, "lines": [101]}, {"n": 9, "lines": [102]}])
        self.assertEqual(predicate(report, "family.first_line")["status"], "NOT EVALUATED")
        self.assertEqual(len(report["inputs"]["family_input_issues"]), 2)

    def test_deterministic_json_and_inputs_unchanged(self):
        doc = fixture()
        before = copy.deepcopy(doc)
        a, b = run(doc), run(doc)
        self.assertEqual(json.dumps(a, sort_keys=True, allow_nan=False), json.dumps(b, sort_keys=True, allow_nan=False))
        self.assertEqual(doc, before)
        serialized = json.dumps(a)
        self.assertNotIn("C:\\", serialized)
        self.assertNotIn("AppData", serialized)


if __name__ == "__main__":
    unittest.main()

Browser Check

A JavaScript module in the sandbox folder of Testcode that uses SHA-256.

rendertestcode / sandbox/202609151943-galaxy-profile/browser-check.mjs · lines 1–24 of 24 · version 2026-09-15 19:43 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): 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 receipt.json.
What it achieves
Its code works with 0 kWh.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/202609151943-galaxy-profile · JavaScript module
Uses
Model (script call)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151943-galaxy-profile/browser-check.mjs:1-24 · blob 90b131c10a271be96bb15b1e6e6c4c0cea545dc9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: experimental · users: none · canonical: unreached_review
import{spawn}from'node:child_process';import{mkdir,writeFile,readFile}from'node:fs/promises';import path from'node:path';import{createHash}from'node:crypto';import assert from'node:assert/strict';import{SOURCE,MODULE_URL}from'./model.mjs';
const playwright=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');const output=process.env.PROOF_OUTPUT || path.resolve('browser-evidence');await mkdir(output,{recursive:true});const url=process.env.PAGE_URL || 'http://127.0.0.1:8779/';const server=process.env.PAGE_URL?null:spawn(process.platform==='win32'?'python':'python3',['-m','http.server','8779','--bind','127.0.0.1'],{stdio:'ignor  … [line shortened here: 422 characters; full line on GitHub]
try{
  for(let n=0;n<30;n++){try{if((await fetch(url)).ok)break;}catch{}if(n===29)throw Error('Preview unavailable');await new Promise(r=>setTimeout(r,100));}
  for(const name of(process.env.BROWSER_ENGINES || 'chromium,webkit').split(',')){
    const browser=await playwright[name].launch({headless:true,...(name==='chromium' && process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
    try{for(const width of[390,1400]){
      const context=await browser.newContext({viewport:{width,height:width===390?844:900},deviceScaleFactor:width===390?3:1,isMobile:width===390,hasTouch:width===390,acceptDownloads:true});const page=await context.newPage();page.setDefaultTimeout(12000);const errors=[],failed=[],responses=[];let negative=false;const receipt={engine:name,version:browser.version(),width,dpr:width===390?3:1,started:n  … [line shortened here: 466 characters; full line on GitHub]
      page.on('pageerror',e=>{if(!negative)errors.push(e.message);});page.on('console',m=>{if(!negative && m.type()==='error')errors.push(m.text());});page.on('requestfailed',r=>{if(!negative)failed.push(r.url());});page.on('response',r=>{if(negative)return;if(r.status()>=400)failed.push(r.url());if(r.url()===MODULE_URL)responses.push(r.body().then(bytes=>({status:r.status(),sha256:createHash('sha  … [line shortened here: 441 characters; full line on GitHub]
      try{
        await page.goto(url);await page.waitForFunction(()=>document.querySelector('#energy').textContent==='9,000 kWh');assert.equal(await page.locator('#peak').innerText(),'12,000 kW');assert.equal(await page.locator('.bar').count(),4);assert.equal(await page.locator('.axis').evaluate(e=>getComputedStyle(e).fill),'none');await page.waitForFunction(()=>document.getAnimations().every(a=>a.playStat  … [line shortened here: 510 characters; full line on GitHub]
        await page.locator('#interval').fill('2');assert.match(await page.locator('#intervalDetail').innerText(),/6,000 kWh above cap/);
        await page.getByRole('button',{name:'Same-peak spike',exact:true}).click();assert.equal(await page.locator('#peak').innerText(),'12,000 kW');assert.equal(await page.locator('#energy').innerText(),'6,000 kWh');await page.getByRole('button',{name:'Same-peak plateau',exact:true}).click();assert.equal(await page.locator('#peak').innerText(),'12,000 kW');assert.equal(await page.locator('#energy  … [line shortened here: 429 characters; full line on GitHub]
        await page.getByRole('button',{name:'Zero profile',exact:true}).click();assert.equal(await page.locator('#energy').innerText(),'0 kWh');assert.match(await page.locator('#loadFactor').innerText(),/undefined/);assert.equal(await page.locator('.above').count(),0);
        await page.getByText('Machine detail',{exact:true}).click();const promise=page.waitForEvent('download');await page.locator('#download').click();const download=await promise;const filename=path.join(output,`${name}-${width}-zero.json`);await download.saveAs(filename);const record=JSON.parse(await readFile(filename,'utf8'));assert.equal(record.summary.siteLoadFactor.value,'NaN');assert.equal  … [line shortened here: 433 characters; full line on GitHub]
        await page.locator('#profile').fill('20,,30');assert.match(await page.locator('#error').innerText(),/finite number/);assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);await page.locator('#profile').fill('30000,42000');await page.locator('#hours').fill('25');assert.match(await page.locator('#error').innerText(),/at   … [line shortened here: 562 characters; full line on GitHub]
        await page.getByRole('button',{name:'Four intervals',exact:true}).click();await page.getByRole('button',{name:'RUN · stated profile',exact:true}).click();assert.equal(await page.locator('#energy').innerText(),'9,000 kWh');await page.locator('#wafer').click();assert.match(await page.locator('#handoff').innerText(),/No numbered line established/);assert.equal(await page.locator('#code').getA  … [line shortened here: 497 characters; full line on GitHub]
        await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.bar').first().evaluate(e=>getComputedStyle(e).animationName),'none');receipt.overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(receipt.overflow,false);await page.screenshot({path:path.join(output,`${name}-${width}-details.png`),fullPage:true});receipt.source_re  … [line shortened here: 642 characters; full line on GitHub]
        negative=true;await page.route(MODULE_URL,r=>r.abort('failed'));await page.reload();await page.waitForFunction(()=>document.querySelector('#quick').textContent.includes('module unavailable'));assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);receipt.module_unavailable_refused=true;receipt.native_webmcp='Not exercis  … [line shortened here: 453 characters; full line on GitHub]
      }catch(error){receipt.pass=false;receipt.error=error.stack;}finally{receipt.finished=new Date().toISOString();results.push(receipt);await context.close();}
    }}finally{await browser.close();}
  }
}finally{server?.kill();await writeFile(path.join(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA || null,url,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(r=>r.pass).length}));if(!results.length || results.some(r=>!r.pass))process.exitCode=1;

Model

A JavaScript module in the sandbox folder of Testcode that parses profile (`parseProfile`) (units: kW), using SHA-256. It parses number (`parseNumber`) and parses profile (`parseProfile`).

rendertestcode / sandbox/202609151943-galaxy-profile/model.mjs · lines 1–21 of 21 · version 2026-09-15 19:43 · Not reached from any entry point (candidate for review) · pattern parseNumber (shared by 2 files)

What it does
Defines parseNumber, parseProfile, record, calculate.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "The module digest is recorded in `model.mjs` and checked before test execution and in browser response evidence."
Downstream impact
Used directly by 1 file: Browser Check (testcode).
What it achieves
The README says: The module digest is recorded in `model.mjs` and checked before test execution and in browser response evidence.
Why it matters
Run by Browser Check.
Application
testcode · sandbox/202609151943-galaxy-profile · JavaScript module
Uses
none found
Used by
run by Browser Check (script call)
Produces
SOURCE, MODULE_URL, parseNumber, parseProfile, PRESETS, calculate
Defines here
parseNumber, parseProfile, record, calculate
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151943-galaxy-profile/model.mjs:1-21 · blob be7a88cba6c1ab7e09d517214be96d9491b8c5bf · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
export const SOURCE={repository:'Ventusltd/ventus-grid-engine',commit:'d9cd18b0e2034325814924e6e4a0e958014f2748',file:'engine/connection-capacity.js',sha256:'249fcf78bf61aa1056d82ba081890f348e57ef76f4442e6a8c4974eefcf0d93b'};
export const MODULE_URL=`https://cdn.jsdelivr.net/gh/${SOURCE.repository}@${SOURCE.commit}/${SOURCE.file}`;
export const parseNumber=text=>text.trim()===''?undefined:Number(text);
export const parseProfile=text=>text.split(',').map(parseNumber);
export const PRESETS=Object.freeze({four:[20000,42000,36000,20000],spike:[30000,42000,30000,30000,30000,30000,30000,30000],plateau:Array(8).fill(42000),zero:[0,0,0,0]});
function record(result){
  const{basis,...values}=result;
  for(const[key,value]of Object.entries(values))if(typeof value==='number' && !Number.isFinite(value)){
    if(key==='siteLoadFactor' && Number.isNaN(value) && values.peakKw===0 && values.siteEnergyKwh===0)values[key]={kind:'undefined',value:'NaN',reason:'Zero energy divided by zero peak times duration; a zero profile has no defined load factor.'};
    else throw new RangeError(`Interface policy: nonfinite output ${key} refused`);
  }
  return values;
}
export function calculate(engine,{profileKw,capKw,intervalHours}){
  if(!Array.isArray(profileKw) || !profileKw.length || profileKw.length>48 || Array.from({length:profileKw.length},(_,i)=>i).some(i=>!Object.hasOwn(profileKw,i)))throw new TypeError('Interface policy: one to 48 dense interval values required');
  for(const value of [...profileKw,capKw])if(typeof value==='number' && Number.isFinite(value) && (value>1e7 || (value>0 && value<.001)))throw new RangeError('Interface policy: positive power values must be 0.001 to 10,000,000 kW');
  if(typeof intervalHours==='number' && intervalHours>0 && intervalHours<1/3600)throw new RangeError('Interface policy: an interval must be at least one second');
  const summary=record(engine.exceedance({profileKw,capKw,intervalHours}));
  const intervals=profileKw.map(value=>record(engine.exceedance({profileKw:[value],capKw,intervalHours})));
  return{schema:'galaxy-profile-lab.v1',source:SOURCE,fixture:'Synthetic equal-duration interval-average active power; no actual site or connection agreement selected.',inputs:{profileKw:[...profileKw],capKw,intervalHours},summary,intervals,moduleCalls:1+profileKw.length,notComputed:['available connection capacity','battery sufficiency or dispatch','cost','sub-interval peaks','reactive power or MV  … [line shortened here: 579 characters; full line on GitHub]
}

Model Test

A test in the sandbox folder of Testcode that uses SHA-256.

testtestcode / sandbox/202609151943-galaxy-profile/model.test.mjs · lines 1–16 of 16 · version 2026-09-15 19:43 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:test. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/202609151943-galaxy-profile · test
Uses
node:test
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151943-galaxy-profile/model.test.mjs:1-16 · blob 642ff3eb92a368014f964ca3ace82bbad1ec927c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
import test from'node:test';import assert from'node:assert/strict';import{createHash}from'node:crypto';import{readFile}from'node:fs/promises';import{SOURCE,MODULE_URL,PRESETS,parseProfile,calculate}from'./model.mjs';
const bytes=process.env.ENGINE_FILE?await readFile(process.env.ENGINE_FILE):await(async()=>{const r=await fetch(MODULE_URL,{signal:AbortSignal.timeout(15000)});assert.equal(r.status,200);return Buffer.from(await r.arrayBuffer());})();assert.equal(createHash('sha256').update(bytes).digest('hex'),SOURCE.sha256);const engine=await import(`data:text/javascript;base64,${bytes.toString('base64')}`);cons  … [line shortened here: 511 characters; full line on GitHub]
test('explicit kW fixture returns12000kW and9000kWh, not12/9',()=>{const s=run().summary;assert.equal(s.peakKw,42000);assert.equal(s.peakExcessKw,12000);assert.equal(s.energyAboveCapKwh,9000);assert.equal(s.siteEnergyKwh,59000);assert.equal(s.spanHours,2);assert.equal(s.intervalsAboveCap,2);assert.equal(s.siteLoadFactor,59/84);});
test('spike and plateau share peak, differ8x energy without cost inference',()=>{const a=run(PRESETS.spike),b=run(PRESETS.plateau);assert.equal(a.summary.peakExcessKw,b.summary.peakExcessKw);assert.equal(a.summary.energyAboveCapKwh,6000);assert.equal(b.summary.energyAboveCapKwh,48000);assert.ok(!('basis'in b.summary));assert.ok(b.notComputed.includes('cost'));});
test('doubling duration doubles energy, not power',()=>{const a=run(),b=run(PRESETS.four,30000,1);assert.equal(a.summary.peakExcessKw,b.summary.peakExcessKw);assert.equal(b.summary.energyAboveCapKwh,a.summary.energyAboveCapKwh*2);});
test('zero profile loadfactorNaN tagged, all other numeric outputs exact',()=>{const r=run(PRESETS.zero);assert.equal(r.summary.siteLoadFactor.kind,'undefined');assert.equal(r.summary.siteLoadFactor.value,'NaN');assert.equal(r.summary.energyAboveCapKwh,0);assert.equal(r.summary.peakExcessKw,0);assert.equal(r.summary.withinCap,true);assert.deepEqual(JSON.parse(JSON.stringify(r)),r);});
test('zero individual interval tagged while aggregate loadfactor finite',()=>{const r=run([0,40000]);assert.equal(r.intervals[0].siteLoadFactor.value,'NaN');assert.equal(r.summary.siteLoadFactor,.5);});
test('interval records are direct source values and sum to source total',()=>{const r=run();assert.equal(r.moduleCalls,5);assert.equal(r.intervals[1].peakExcessKw,12000);assert.equal(r.intervals[2].energyAboveCapKwh,3000);assert.equal(r.intervals.reduce((s,r)=>s+r.energyAboveCapKwh,0),r.summary.energyAboveCapKwh);});
test('exact cap counts no exceedance',()=>{const r=run([30000,30000]);assert.equal(r.summary.withinCap,true);assert.equal(r.summary.intervalsAboveCap,0);});
test('sparse array refused before source skips hole',()=>assert.throws(()=>run(Array(2)),/dense interval/));
test('empty comma component stays missing',()=>{assert.deepEqual(parseProfile('20,,30'),[20,undefined,30]);assert.throws(()=>run(parseProfile('20,,30')),/finite number/);});
test('source refuses negative and nonfinite readings',()=>{for(const value of[-1,Infinity,NaN,'42',null])assert.throws(()=>run([value]));});
test('source refuses zero/missing caps and invalid duration',()=>{assert.throws(()=>run([1],0),/greater than zero/);assert.throws(()=>calculate(engine,{profileKw:[1],intervalHours:.5}),/finite number/);assert.throws(()=>run([1],1,0),/greater than zero/);assert.throws(()=>run([1],1,25),/at most 24/);});
test('interface bounds avoid unstable sums and dense unbounded drawing',()=>{assert.throws(()=>run(Array(49).fill(1)),/Interface policy/);assert.throws(()=>run([1e8]),/Interface policy/);assert.throws(()=>run([1e-20]),/Interface policy/);assert.throws(()=>run([1],1,1e-20),/one second/);});
test('valid upper boundary finite and serializable',()=>{const r=run(Array(48).fill(1e7),.001,24);assert.ok(Number.isFinite(r.summary.siteEnergyKwh));assert.deepEqual(JSON.parse(JSON.stringify(r)),r);});
test('source implementation called1+n without mutating inputs',()=>{let calls=0;const tracked={exceedance:args=>{calls++;return engine.exceedance(args);}};const inputs={profileKw:[10,20],capKw:15,intervalHours:.5};const r=calculate(tracked,inputs);assert.equal(calls,3);assert.deepEqual(inputs.profileKw,[10,20]);assert.equal(r.source.sha256,SOURCE.sha256);});