GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / seed-data / experiments/economical-seeds

State Compare and 6 more files

A Python command-line tool in the next compose folder of Seed Data that opens capture (`open_capture`).

683 lines of Python and JavaScript from seed-data, in 7 files. Topic: Websites and apps. Section 2010 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. Magnets storage · seed-data / experiments/economical-seeds/magnets.py lines 1–151
  2. Bench State Compare other · seed-data / experiments/economical-seeds/next-compose/bench_state_compare.py lines 1–109
  3. Fixture storage · seed-data / experiments/economical-seeds/next-compose/fixture.py lines 1–71
  4. State Compare other · seed-data / experiments/economical-seeds/next-compose/state_compare.py lines 1–191
  5. State Compare Baseline storage · seed-data / experiments/economical-seeds/next-compose/state_compare_baseline.py lines 1–54
  6. Rare Limb other · seed-data / experiments/economical-seeds/next-invention/rare/rare-limb.mjs lines 1–87
  7. Invoke ingest · seed-data / experiments/economical-seeds/next-invention/reduction/invoke.mjs lines 1–20

Magnets

A Python command-line tool in the economical seeds folder of Seed Data that reads objectives, using SHA-256.

storageseed-data / experiments/economical-seeds/magnets.py · lines 1–151 of 151 · Entry point · pattern file_sha (shared by 2 files)

What it does
It loads objectives. Defines 8 functions or classes, including read_json, connect, file_sha, line_ids, field. Uses libraries argparse, os, hashlib, json, math. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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 objectives.json; SQLite database; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 7 files: Experiment A (seed-data); Experiment B (seed-data); History (seed-data); State Compare (seed-data); and 3 more. Reached from 5 other entry points, including Seed Regressions Workflow (seed-data); Bench State Compare (seed-data); Test State Compare (seed-data).
What it achieves
It reads JSON (`read_json`) and is built from the connect step (`connect`) and the file sha helper (`file_sha`). Search observable-effect cues across the complete pinned corpus. It accepts `--db`, `--objectives` and `--feedback`.
Why it matters
Imported by 7 files, including Experiment A, Experiment B and History.
Application
seed-data · experiments/economical-seeds · Python CLI
Uses
argparse, os, hashlib, json, math, re, sqlite3, struct
Used by
imported by Experiment A (import), imported by Experiment B (import), imported by History (import), imported by State Compare (sys.path import), imported by Seed Discover (import), imported by Seed Plan (import), imported by Teleprint Index (import)
Produces
read_json, connect, file_sha, line_ids, field, rank, main
Defines here
read_json, connect, file_sha, line_ids, field, mask, rank, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/magnets.py:1-151 · blob db608234b34ada36dc1f6257d149fbb2c568c97d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: experimental · users: none · canonical: supporting_data
"""Search observable-effect cues across the complete pinned corpus."""
import argparse
import os
import hashlib
import json
import math
import re
import sqlite3
import struct
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent
DB = Path(os.environ.get("SEED_STARS_DB", "modular.sqlite"))


def read_json(path):
    return json.loads(path.read_text(encoding="utf-8-sig"))


def connect(path):
    connection = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
    connection.execute("pragma query_only=on")
    return connection


def file_sha(path):
    with path.open("rb") as stream:
        from functools import partial
        digest = hashlib.sha256()
        for chunk in iter(partial(stream.read, 1024 * 1024), b""):
            digest.update(chunk)
        return digest.hexdigest()


def line_ids(blob):
    return [value for (value,) in struct.iter_unpack("<I", blob)]


def field(connection, objectives):
    patterns = [re.compile(s) for groups in objectives.values() for s in groups]
    vocabulary = re.compile("|".join(f"(?:{pattern.pattern})" for pattern in patterns))
    # Find each alternative's hits independently after the cheap union prefilter.
    def mask(value):
        value = value.lower()
        if not vocabulary.search(value):
            return 0
        return sum(1 << i for i, pattern in enumerate(patterns) if pattern.search(value))

    lines = {n: mask(raw.decode("utf-8", "replace")) for n, raw in
             connection.execute("select n,text from line")}
    placements = defaultdict(list)
    query = """select t.tablet,t.element,e.family,t.first,t.last,t.name,e.needs
               from tablet_element t join element e on t.element=e.n"""
    element_cues = {}
    for tablet, element, family, first, last, name, needs in connection.execute(query):
        if element not in element_cues:
            element_cues[element] = mask((name or "") + " " + (needs or ""))
        placements[tablet].append((element, family, first, last, name, needs))
    history = {}
    for tablet, total, repos, repo, path in connection.execute("""
          select tablet,count(*),count(distinct repo),min(repo),min(path)
          from occurrence group by tablet"""):
        history[tablet] = (total, repos)
    candidates = defaultdict(list)
    line_positions = 0
    for tablet, git_blob, blob in connection.execute("select n,git_blob,lines from tablet"):
        ids = line_ids(blob)
        line_positions += len(ids)
        masks = [lines[n] for n in ids]
        combined = 0
        for value in set(masks):
            combined |= value
        members = placements[tablet]
        for element, *_ in members:
            combined |= element_cues[element]
        for index, objective in enumerate(objectives):
            offset = index * 3
            if (combined >> offset) & 7 != 7:
                continue
            witnesses = [next((n for n, value in zip(ids, masks) if value & (1 << (offset + j))), None)
                         for j in range(3)]
            supporting = []
            for element, family, first, last, name, needs in members:
                if element_cues[element] & (7 << offset):
                    supporting.append([element, family, first, last, name, json.loads(needs or "[]")])
            occurrences, repos = history.get(tablet, (0, 0))
            features = [sum(n is not None for n in witnesses)/3,
                        min(len(supporting), 5)/5, min(repos, 4)/4]
            candidates[objective].append({
                "tablet": tablet, "git_blob": git_blob, "line_witnesses": witnesses,
                "elements": supporting[:12], "occurrences": occurrences,
                "repositories": repos, "features": features, "status": "inferred"})
    return candidates, line_positions


def rank(candidates, labels, limit):
    """Learn a regularized linear reranker from append-only usefulness labels."""
    import numpy as np
    known = {(objective, entry["git_blob"]): entry["features"]
             for objective, entries in candidates.items() for entry in entries}
    observed = {(e["objective"], e["git_blob"]): e["outcome"] for e in labels}
    training = [(known[key], outcome) for key, outcome in observed.items() if key in known]
    weights = np.array([0.50, 0.35, 0.15])
    if training:
        inputs = np.asarray([features for features, _ in training])
        outcomes = np.asarray([outcome for _, outcome in training])
        prior = 2 * np.eye(len(weights))
        weights = np.linalg.solve(inputs.T @ inputs + prior, inputs.T @ outcomes + prior @ weights)
    for objective, entries in candidates.items():
        for entry in entries:
            entry["score"] = round(float(weights @ entry["features"]), 6)
        candidates[objective] = sorted(entries, key=lambda e: (-e["score"], e["tablet"]))[:limit]
    return weights.tolist(), len(training)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--db", type=Path, default=DB)
    parser.add_argument("--objectives", type=Path, default=ROOT / "objectives.json")
    parser.add_argument("--feedback", type=Path, default=ROOT / "feedback.jsonl")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--limit", type=int, default=20)
    args = parser.parse_args()
    objectives = read_json(args.objectives)
    if any(len(group) != 3 for group in objectives.values()):
        parser.error("Each objective needs three independent regular expressions")
    labels = [json.loads(line) for line in args.feedback.read_text(encoding="utf-8-sig").splitlines()
              if line.strip()] if args.feedback.exists() else []
    before = file_sha(args.db)
    with connect(args.db) as db:
        census = {table: db.execute(f"select count(*) from {table}").fetchone()[0] for table in
                  ("line", "tablet", "family", "element", "tablet_element", "occurrence",
                   "scan", "commit_info", "wander")}
        candidates, positions = field(db, objectives)
        totals = {objective: len(entries) for objective, entries in candidates.items()}
        weights, learned = rank(candidates, labels, args.limit)
        for entries in candidates.values():
            for entry in entries:
                entry["source"] = db.execute("""select repo,commit_sha,path from occurrence
                    where tablet=? order by repo,commit_sha,path limit 1""", (entry["tablet"],)).fetchone()
    if file_sha(args.db) != before:
        raise RuntimeError("Original database changed during experiment")
    with args.output.open("x", encoding="utf-8") as stream:
        json.dump(dict(snapshot_sha256=before, census=census, line_positions=positions,
                       candidate_counts=totals, training_examples=learned, weights=weights,
                       objectives=objectives, candidates=candidates), stream, indent=2)


if __name__ == "__main__":
    main()

Bench State Compare

A Python command-line tool in the next compose folder of Seed Data that runs equivalent captured-state comparison arms in interleaved fresh workers.

otherseed-data / experiments/economical-seeds/next-compose/bench_state_compare.py · lines 1–109 of 109 · Entry point · pattern preflight (shared by 2 files)

What it does
Defines sample, preflight, run, main. Uses libraries argparse, json, statistics, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `sample`, `preflight` and `run`. It accepts `--scope`, `--mechanism` and `--limit`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
seed-data · experiments/economical-seeds/next-compose · Python CLI
Uses
State Compare (import), Fixture (import), State Compare Baseline (import), argparse, json, statistics, subprocess, sys, time, contextlib, pathlib
Used by
none found
Produces
sample, preflight, run, main
Defines here
sample, preflight, run, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-compose/bench_state_compare.py:1-109 · blob de08acb8c04b57191d47ef5a67337c19ab4fbd6f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
"""Run equivalent captured-state comparison arms in interleaved fresh workers."""
import argparse
import json
import statistics
import subprocess
import sys
import time
from contextlib import ExitStack
from pathlib import Path
from tempfile import TemporaryDirectory

from state_compare import compare, open_capture
from experiment_b import process_peak
from fixture import MECHANISM, SCOPE, make_fixture
from magnets import file_sha
from state_compare_baseline import compare as direct

MODES = {"composition": compare, "conventional_indexed": direct}


def sample(mode, inputs, scope, mechanism, limit, budget):
    start, cpu = time.perf_counter_ns(), time.process_time_ns()
    evidence, measured = MODES[mode](*inputs, scope, mechanism, limit, budget)
    cpu_ns = time.process_time_ns()-cpu
    elapsed_ns = time.perf_counter_ns()-start
    return evidence, dict(**measured, cpu_ns=cpu_ns, elapsed_ns=elapsed_ns,
                          peak_rss_bytes=process_peak())


def preflight(inputs):
    start, cpu = time.perf_counter_ns(), time.process_time_ns()
    for capture, index_path in zip(inputs[::2][:2], inputs[1::2]):
        witness = open_capture(capture,index_path)
        if file_sha(capture) != witness.digest:
            raise ValueError("Capture preflight digest differs from index")
    return dict(elapsed_ns=time.perf_counter_ns()-start, cpu_ns=time.process_time_ns()-cpu,
                logical_capture_bytes=inputs[0].stat().st_size+inputs[2].stat().st_size)


def run(inputs, scope, mechanism, limit, budget, repeat):
    check = preflight(inputs)
    rounds = {key:[] for key in MODES}
    args = [*map(str,inputs),"--scope",scope,"--limit",str(limit),"--byte-budget",str(budget)]
    if mechanism:
        args += ["--mechanism",mechanism]
    expected = None
    for i in range(repeat):
        schedule = list(MODES) if i % 2 == 0 else list(reversed(MODES))
        for mode in schedule:
            start = time.perf_counter_ns()
            command = [sys.executable, str(Path(__file__).resolve()), *args, "--worker", mode]
            response = subprocess.run(command, check=True, text=True, capture_output=True, encoding="utf-8")
            fresh_ns = time.perf_counter_ns()-start
            evidence, usage = json.loads(response.stdout)
            if expected is None:
                expected = evidence
            elif expected != evidence:
                raise ValueError("Arms produced different evidence")
            rounds[mode].append(dict(**usage, fresh_process_ns=fresh_ns))
    medians = {mode:{key:statistics.median(sample[key] for sample in samples)
                     if samples[0][key] is not None else None for key in samples[0]}
               for mode,samples in rounds.items()}
    return dict(evidence=expected, preflight=check, medians=medians, rounds=rounds,
                interpretation=dict(cache="Filesystem cache uncontrolled",
                    physical_io="Unmeasured. Byte counters count logical index and selected payload reads.",
                    peak_rss="Fresh interpreter peak resident working set includes startup",
                    energy="Unmeasured because no validated meter was available",
                    gpu="Unused", execution_inference_calls=0, execution_human_interventions=0,
                    database_identity="Recorded identity from both indexes. STARS file digest verification is a prior prerequisite.",
                    authoring="Both arms use the same disclosure and evidence orchestration. Compared the state classifier and attribution implementation.",
                    timing="Timer granularity can report zero CPU time for short Windows operations."))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("inputs", type=Path, nargs="*")
    parser.add_argument("--scope")
    parser.add_argument("--mechanism")
    parser.add_argument("--limit", default=2, type=int)
    parser.add_argument("--byte-budget", default=1_000_000, type=int)
    parser.add_argument("--repeat", default=7, type=int)
    parser.add_argument("--fixture", action="store_true")
    parser.add_argument("--worker", choices=MODES, help=argparse.SUPPRESS)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    with ExitStack() as stack:
        if args.fixture and not args.inputs:
            folder = stack.enter_context(TemporaryDirectory())
            inputs = make_fixture(Path(folder))
            scope, mechanism = SCOPE, MECHANISM
        elif len(args.inputs) == 5 and args.scope and not args.fixture:
            inputs, scope, mechanism = args.inputs, args.scope, args.mechanism
        else:
            parser.error("provide --fixture or both captures, both indexes, a STARS database and --scope")
        if args.repeat < 1:
            parser.error("repeat must be positive")
        result = (sample(args.worker, inputs, scope, mechanism, args.limit, args.byte_budget)
                  if args.worker else run(inputs, scope, mechanism, args.limit, args.byte_budget, args.repeat))
    serialized = json.dumps(result, indent=2)
    if args.output:
        with args.output.open("x", encoding="utf-8") as file:
            file.write(serialized+"\n")
    else:
        print(serialized)


if __name__ == "__main__":
    main()

Fixture

A Python module in the next compose folder of Seed Data that reads unread, before, after and stable. It creates capture (`create_capture`).

storageseed-data / experiments/economical-seeds/next-compose/fixture.py · lines 1–71 of 71 · pattern make_fixture (shared by 3 files)

What it does
It loads unread, before, after and stable. Defines create_capture, make_fixture. Uses libraries gc, json, sqlite3, struct, contextlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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 unread.json; JSON file before.json; JSON file after.json; JSON file stable.json; JSON file same-url.json; SQLite database.
Downstream impact
Used directly by 2 files: Test State Compare (seed-data); Bench State Compare (seed-data).
What it achieves
Generate a small synthetic capture pair and read-only STARS witness inputs.
Why it matters
Imported by Bench State Compare. Checked by Test State Compare.
Application
seed-data · experiments/economical-seeds/next-compose · Python module
Uses
State Compare (import), gc, json, sqlite3, struct, contextlib, pathlib, teleprint_index
Used by
imported by Test State Compare (import), imported by Bench State Compare (import)
Produces
create_capture, make_fixture
Defines here
create_capture, make_fixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-compose/fixture.py:1-71 · blob 7e684526b6c25f0c74d35c33d9484f91aa799b63 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: experimental · users: none · canonical: supporting_data
"""Generate a small synthetic capture pair and read-only STARS witness inputs."""
import gc
import json
import sqlite3
import struct
from contextlib import closing
from pathlib import Path

from state_compare import git_blob
from teleprint_index import index

SCOPE = "https://example.invalid/history/"
MECHANISM = "https://example.invalid/overlay.js"
UNAVAILABLE = SCOPE + "unread.json"
CODE = b'const DATASET = "https://example.invalid/history/";\n'
RULE = "=" * 78


def create_capture(path, resources, generation, unread=()):
    assert all(isinstance(value, bytes) for value in resources.values())
    bodies = {key: value.decode("utf-8") for key, value in resources.items()}
    lengths = {url: len(body.encode("utf-16-le"))//2 for url, body in bodies.items()}
    content = [RULE, "THE SCREEN THIS CAME FROM", RULE, json.dumps({"generation":generation}),
               RULE, f"CONTENTS -- {len(bodies)} file(s), {sum(lengths.values())} characters", RULE]
    for n, url in enumerate(bodies, 1):
        content.append(f"{n}. {url}\n  {lengths[url]} chars · fixture")
    if unread:
        content.extend([RULE, f"NOT READ -- {len(unread)} resource(s)", RULE])
        content.extend(f"- {url}\n  Controlled refusal" for url in unread)
    for url, body in bodies.items():
        content.extend([RULE, "FILE: "+url, f"{lengths[url]} chars · fixture", RULE, body, ""])
    content.extend([RULE, "END OF TELEPRINT", RULE])
    path.write_text("\n".join(content), encoding="utf-8", newline="\n")


def make_fixture(directory: Path, alternate_mechanism=False):
    alternate = CODE+b"const CAP = 2;\n" if alternate_mechanism else CODE
    database = directory/"stars.sqlite"
    with closing(sqlite3.connect(database)) as db:
        db.executescript("""
          create table tablet(n integer,git_blob text unique,lines blob);
          create table line(n integer primary key,text blob);
          create table occurrence(repo text,commit_sha text,path text,tablet integer);
          create table commit_info(repo text,sha text,date text);
        """)
        db.execute("insert into line values(?,?)",(9,CODE))
        db.execute("insert into tablet values(?,?,?)",(7740,git_blob(CODE),struct.pack("<I",9)))
        db.execute("insert into occurrence values(?,?,?,?)",("fixture","ab"*20,"overlay.js",7740))
        db.execute("insert into commit_info values(?,?,?)",("fixture","ab"*20,"2026-01-01"))
        if alternate_mechanism:
            db.execute("insert into line values(?,?)",(10,alternate))
            db.execute("insert into tablet values(?,?,?)",(7741,git_blob(alternate),struct.pack("<I",10)))
            db.execute("insert into occurrence values(?,?,?,?)",("fixture","cd"*20,"overlay.js",7741))
        db.commit()
    before = directory/"before.txt"
    after = directory/"after.txt"
    first_idx = directory/"before.json"
    second_idx = directory/"after.json"
    common = {MECHANISM: CODE, SCOPE+"stable.json":b"[]"}
    create_capture(before, dict(common, **{SCOPE+"same-url.json":b"[1]", SCOPE+"before.json":b"[2]",
                                          UNAVAILABLE:b"[5]"}), "before-fixture")
    create_capture(after, dict(common, **{SCOPE+"same-url.json":b"[4]", SCOPE+"after.json":b"[3]", MECHANISM:alternate}),
                   "after-fixture", (UNAVAILABLE,))
    for target,capture in ((first_idx,before),(second_idx,after)):
        receipt = index(capture,database)
        # The retained pre-publication indexer leaves connection disposal to GC.
        gc.collect()
        receipt.pop("input",None)
        target.write_text(json.dumps(receipt),encoding="utf-8")
    return before, first_idx, after, second_idx, database

State Compare

A Python command-line tool in the next compose folder of Seed Data that opens capture (`open_capture`).

otherseed-data / experiments/economical-seeds/next-compose/state_compare.py · lines 1–191 of 191 · Entry point · pattern payload (shared by 6 files)

What it does
Defines 8 functions or classes, including Capture, open_capture, classify, selected_source, from_captures. Uses libraries __future__, argparse, json, re, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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 4 files: Test State Compare (seed-data); Bench State Compare (seed-data); Fixture (seed-data); State Compare Baseline (seed-data).
What it achieves
It is built from the capture class (`Capture`), the classify step (`classify`) and the selected source helper (`selected_source`). Compare captured resource states, then inspect selected evidence by exact identity. It accepts `--scope`, `--mechanism` and `--limit`.
Why it matters
Imported by Bench State Compare, Fixture and State Compare Baseline. Checked by Test State Compare.
Application
seed-data · experiments/economical-seeds/next-compose · Python CLI
Uses
Experiment B (sys.path import), History (sys.path import), Magnets (sys.path import), Teleprint Index (sys.path import), __future__, argparse, json, re, sys, dataclasses, pathlib
Used by
imported by Test State Compare (import), imported by Bench State Compare (import), imported by Fixture (import), imported by State Compare Baseline (import)
Produces
Capture, open_capture, classify, selected_source, from_captures, compare, main
Defines here
Capture, open_capture, classify, selected_source, from_captures, payload, compare, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-compose/state_compare.py:1-191 · blob f804ea8f41578269fecab0dba0dca6e46105ebdb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Compare captured resource states, then inspect selected evidence by exact identity."""
from __future__ import annotations

import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from experiment_b import composed
from history import git_blob
from magnets import file_sha
from teleprint_index import retrieve

HEX256 = re.compile(r"[0-9a-f]{64}")
HEX160 = re.compile(r"[0-9a-f]{40}")


@dataclass(frozen=True)
class Capture:
    path: Path
    index: Path
    digest: str
    database_digest: str
    generation: str | None
    captured_at: str | None
    records: dict
    unavailable: set
    index_bytes: int


def open_capture(path, index_path):
    raw = index_path.read_bytes()
    manifest = json.loads(raw)
    if (not HEX256.fullmatch(manifest["input_sha256"])
            or not HEX256.fullmatch(manifest["database_sha256"])):
        raise ValueError("Malformed capture or database digest")
    length = path.stat().st_size
    if type(manifest["bytes"]) is not int or length != manifest["bytes"]:
        raise ValueError("Capture and index lengths differ")
    rows = {}
    for row in manifest["records"]:
        url, start, size = (row[k] for k in ("url", "byte_start", "byte_length"))
        if (not isinstance(url, str) or not url or url in rows or type(start) is not int
                or type(size) is not int or start < 0 or size < 0 or start + size > length
                or not HEX256.fullmatch(row["text_sha256"]) or not HEX160.fullmatch(row["git_blob"])):
            raise ValueError("Ambiguous or malformed indexed resource")
        rows[url] = row
    unavailable = set()
    for item in manifest["not_read"]:
        if (not isinstance(item, list) or len(item) != 2
                or not all(isinstance(value, str) and value for value in item)
                or item[0] in rows or item[0] in unavailable):
            raise ValueError("Ambiguous or malformed unread resource")
        unavailable.add(item[0])
    return Capture(path, index_path, manifest["input_sha256"], manifest["database_sha256"],
                   manifest.get("screen", {}).get("generation"),
                   manifest.get("screen", {}).get("capturedAt"), rows, unavailable, len(raw))


def classify(before, after, scope_prefix):
    urls = set(before.records) | set(after.records) | before.unavailable | after.unavailable
    counts = dict(identical=0, changed=0, before_only=0, after_only=0, unread=0)
    changes = []
    for url in sorted(urls):
        if not url.startswith(scope_prefix):
            continue
        left, right = before.records.get(url), after.records.get(url)
        a = left["text_sha256"] if left else None
        b = right["text_sha256"] if right else None
        if url in before.unavailable or url in after.unavailable:
            status = "unread"
        elif left is None:
            status = "after_only"
        elif right is None:
            status = "before_only"
        else:
            status = "identical" if a == b else "changed"
        counts[status] += 1
        if status != "identical":
            changes.append(dict(url=url, status=status, before_sha256=a, after_sha256=b,
                                before_unread=url in before.unavailable,
                                after_unread=url in after.unavailable))
    return counts, changes


def selected_source(capture, url, database):
    return composed(capture.path, url, database, capture.index)


def from_captures(before, after, database, scope_prefix, mechanism_url, limit, byte_budget,
                  compare_metadata=classify, audit_source=selected_source):
    if not scope_prefix or type(limit) is not int or type(byte_budget) is not int or limit < 0 or byte_budget < 0:
        raise ValueError("Use a nonempty scope and nonnegative integer witness limits")
    if before.database_digest != after.database_digest:
        raise ValueError("Capture indexes disagree on the recorded STARS database identity")
    counts, changes = compare_metadata(before, after, scope_prefix)
    result = dict(scope=scope_prefix, before_sha256=before.digest, after_sha256=after.digest,
                  before_generation=before.generation, after_generation=after.generation,
                  before_captured_at=before.captured_at, after_captured_at=after.captured_at,
                  recorded_database_sha256=before.database_digest, counts=counts, changes=changes,
                  mechanism=None, witnesses=[], deferred_witnesses=0)
    data = dict(index_bytes=before.index_bytes + after.index_bytes,
                payload_bytes=0, sqlite_queries=0)

    def payload(capture, url):
        record = capture.records[url]
        raw = retrieve(capture.path, record)
        if git_blob(raw) != record["git_blob"]:
            raise ValueError("Index Git identity differs from digest-verified payload")
        data["payload_bytes"] += len(raw)
        return raw

    if mechanism_url:
        if mechanism_url not in before.records or mechanism_url not in after.records:
            raise ValueError("Requested mechanism must have an indexed body in both captures")
        results, inspected = [], {}
        for capture in (before, after):
            # The prior SEED verifies the bytes in each capture. Inspect a distinct
            # verified body once more for the scope literal.
            row = capture.records[mechanism_url]
            size, blob = row["byte_length"], row["git_blob"]
            extra = 0 if blob in inspected else size
            if data["payload_bytes"] + size + extra > byte_budget:
                raise ValueError("Payload budget is too small for both mechanism witnesses")
            proven, input_bytes, queries = audit_source(capture, mechanism_url, database)
            if proven["status"] != "byte-identical":
                raise ValueError("Mechanism attribution refused: " + proven["status"])
            data["index_bytes"] += capture.index_bytes
            data["payload_bytes"] += input_bytes - capture.index_bytes
            data["sqlite_queries"] += queries
            if blob not in inspected:
                inspected[blob] = scope_prefix.encode() in payload(capture, mechanism_url)
            results.append(dict(tablet=proven["tablet"], git_blob=proven["git_blob"],
                                occurrences=proven["occurrences"], scope_literal=inspected[blob]))
        result["mechanism"] = dict(url=mechanism_url, before=results[0], after=results[1],
                                   same_source=results[0]["git_blob"] == results[1]["git_blob"])
    for row in changes:
        if row["status"] == "unread":
            continue
        url = row["url"]
        sides = [(side, capture) for side, capture in (("before", before), ("after", after))
                 if url in capture.records]
        size = sum(capture.records[url]["byte_length"] for _, capture in sides)
        if (len(result["witnesses"]) >= limit or data["payload_bytes"] + size > byte_budget):
            result["deferred_witnesses"] += 1
            continue
        sample = {}
        for side, capture in sides:
            payload(capture, url)
            sample[side] = capture.records[url]["text_sha256"]
        result["witnesses"].append(dict(url=url, verified_sha256=sample))
    return result, data


def compare(before_capture: Path, before_index: Path, after_capture: Path, after_index: Path,
            database: Path, scope_prefix: str, mechanism_url: str | None = None,
            limit: int = 2, byte_budget: int = 1_000_000):
    return from_captures(open_capture(before_capture, before_index), open_capture(after_capture, after_index),
                         database, scope_prefix, mechanism_url, limit, byte_budget)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("before_capture", "before_index", "after_capture", "after_index", "database"):
        parser.add_argument(name, type=Path)
    parser.add_argument("--scope", required=True)
    parser.add_argument("--mechanism")
    parser.add_argument("--limit", type=int, default=2)
    parser.add_argument("--byte-budget", type=int, default=1_000_000)
    parser.add_argument("--verify-inputs", action="store_true",
                        help="Rehash the complete captures and STARS snapshot once before comparing")
    args = parser.parse_args()
    before = open_capture(args.before_capture, args.before_index)
    after = open_capture(args.after_capture, args.after_index)
    if args.verify_inputs:
        if any(file_sha(item.path) != item.digest for item in (before, after)):
            raise ValueError("Capture identity differs from index")
        if file_sha(args.database) != before.database_digest:
            raise ValueError("SQLite snapshot differs from the recorded source identity")
    proof, usage = from_captures(before, after, args.database, args.scope, args.mechanism,
                                 args.limit, args.byte_budget)
    print(json.dumps(dict(evidence=proof, resources=usage, full_inputs_rehashed=args.verify_inputs), indent=2))


if __name__ == "__main__":
    main()

State Compare Baseline

A Python module in the next compose folder of Seed Data that classifies SQL (`classify_sql`).

storageseed-data / experiments/economical-seeds/next-compose/state_compare_baseline.py · lines 1–54 of 54 · pattern compare (shared by 17 files)

What it does
It loads data. Defines classify_sql, standalone, compare. Uses libraries contextlib, sqlite3, economy.b_baseline. Side effects: uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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: SQLite database.
Downstream impact
Used directly by 2 files: Test State Compare (seed-data); Bench State Compare (seed-data).
What it achieves
Defines `classify_sql`, `standalone` and `compare`.
Why it matters
Imported by Bench State Compare. Checked by Test State Compare.
Application
seed-data · experiments/economical-seeds/next-compose · Python module
Uses
State Compare (import), contextlib, sqlite3, economy.b_baseline
Used by
imported by Test State Compare (import), imported by Bench State Compare (import)
Produces
classify_sql, standalone, compare
Defines here
classify_sql, standalone, compare
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-compose/state_compare_baseline.py:1-54 · blob 391207a8a016a421a3456100a10dee1bd601e5a3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: storage · domain stage: experimental · users: none · canonical: supporting_data
"""Alternative indexed implementation of the same captured-state comparison."""
from contextlib import closing
import sqlite3

from state_compare import from_captures, open_capture
from economy.b_baseline import source_audit

SQL = """
with urls as (select url from b union select url from a),
states as (
 select urls.url, b.digest as before_sha256, a.digest as after_sha256,
        coalesce(b.unread,0) as before_unread, coalesce(a.unread,0) as after_unread,
        case
         when b.unread=1 or a.unread=1 then 'unread'
         when b.url is null then 'after_only'
         when a.url is null then 'before_only'
         when b.digest = a.digest then 'identical'
         else 'changed'
        end as status
 from urls left join b using(url) left join a using(url)
 where substr(urls.url,1,length(?))=?
)
select url,status,before_sha256,after_sha256,before_unread,after_unread from states order by url
"""


def classify_sql(before, after, scope):
    counts = dict(identical=0, changed=0, before_only=0, after_only=0, unread=0)
    outcomes = []
    with closing(sqlite3.connect(":memory:")) as con:
        for table, capture in (("b", before), ("a", after)):
            con.execute(f"create table {table}(url text primary key,digest text,unread int)")
            observed = [(url, r["text_sha256"], 0) for url, r in capture.records.items()]
            unread = [(url, None, 1) for url in capture.unavailable]
            con.executemany(f"insert into {table} values(?,?,?)", observed+unread)
        for url, status, a, b, unread_left, unread_right in con.execute(SQL, (scope,scope)):
            counts[status] += 1
            if status != "identical":
                outcomes.append(dict(url=url, status=status, before_sha256=a, after_sha256=b,
                                     before_unread=bool(unread_left), after_unread=bool(unread_right)))
    return counts, outcomes


def standalone(capture, url, db):
    return source_audit(capture.path, url, db, capture.index)


def compare(before_capture, before_index, after_capture, after_index, database, scope_prefix,
            mechanism_url=None, limit=2, byte_budget=1_000_000):
    before = open_capture(before_capture, before_index)
    after = open_capture(after_capture, after_index)
    return from_captures(before, after, database, scope_prefix, mechanism_url, limit, byte_budget,
                         compare_metadata=classify_sql, audit_source=standalone)

Rare Limb

A JavaScript module in the next invention folder of Seed Data that works with require uint32 (`requireUint32`) and checked top (`checkedTop`), using SHA-256.

otherseed-data / experiments/economical-seeds/next-invention/rare/rare-limb.mjs · lines 1–87 of 87 · Entry point · pattern extract (shared by 8 files)

What it does
Defines 6 functions or classes, including identity, extract, requireUint32, checkedTop, reference. Uses libraries node:assert/strict, node:child_process, node:crypto, node:vm. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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 application and rare probe can be indexed using `seed_discover.py build` with the existing two next-stage `--record` flags and additional records `next-invention/cable-screen/instrument.json` and `next-invention/rare/rare-limb.record.json`."
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Seed Regressions Workflow (seed-data).
What it achieves
It is built from the identity step (`identity`), the extract step (`extract`) and the require uint32 helper (`requireUint32`). The README says: The application and rare probe can be indexed using `seed_discover.py build` with the existing two next-stage `--record` flags and additional records `next-invention/cable-screen/instrument.json` and `next-invention/rare/rare-limb.record.json`.
Why it matters
Run by Seed Regressions Workflow.
Application
seed-data · experiments/economical-seeds/next-invention/rare · JavaScript module
Uses
node:assert/strict, node:child_process, node:crypto, node:vm
Used by
run by Seed Regressions Workflow (workflow run)
Produces
identity, extract, requireUint32, checkedTop, reference, changedCarry
Defines here
identity, extract, requireUint32, checkedTop, reference, changedCarry
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/rare/rare-limb.mjs:1-87 · blob 4c3f974ef4c667c314ec6cbf06e8d275a6a684db · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: supporting_data
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { runInNewContext } from "node:vm";

const revision = "34153fcbd5e91e4aead765fba9e9d0cac1ebf5ec";
const sourcePath = "measurements/exactness.mjs";
const sourceBlob = "3de6ed7d81591ffa737656e229858acb278dae4f";
const expectedSha256 = "867bb83466a9dbc35e86952b496b8f498fc0cc289f9d81cd1dcebdc21552db26";
const witnessLines = [[19, 393288], [53, 393317], [54, 393318], [55, 393319]];
const identity = (algorithm, bytes) => createHash(algorithm).update(bytes).digest("hex");

function extract(checkout) {
    const input = execFileSync("git", ["-C", checkout, "show", revision + ":" + sourcePath]);
    assert.equal(identity("sha256", input), expectedSha256);
    const blobBytes = Buffer.concat([Buffer.from("blob " + input.length + "\0"), input]);
    assert.equal(identity("sha1", blobBytes), sourceBlob);
    const lines = input.toString("utf8").split("\n");
    const closure = witnessLines.map(([line]) => lines[line - 1]).join("\n");
    const selected = runInNewContext(closure + "\n;({mulhi32, top32, C64, CHI, CLO})", {}, {
        timeout: 500, contextCodeGeneration: {strings: false, wasm: false}
    });
    return {selected, inputBytes: input.length, evaluatedBytes: Buffer.byteLength(closure)};
}

function requireUint32(value) {
    if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
        throw new RangeError("Expected an unsigned 32-bit integer");
    }
}

function checkedTop(seed, slot) {
    requireUint32(slot);
    return seed.top32(slot);
}

const [, , checkout, slotArgument, ...rest] = process.argv;
if (!checkout || rest.length || (slotArgument !== undefined && !/^\d+$/.test(slotArgument))) {
    throw new Error("Usage: node rare-limb.mjs <particle-repository-checkout> [unsigned-slot]");
}
const suppliedSlot = slotArgument === undefined ? null : Number(slotArgument);
if (suppliedSlot !== null) requireUint32(suppliedSlot);
const {selected, inputBytes, evaluatedBytes} = extract(checkout);
if (suppliedSlot !== null) {
    console.log(JSON.stringify({revision, sourceBlob, inputBytes, evaluatedBytes, slot: suppliedSlot,
        highWord: checkedTop(selected, suppliedSlot)}, null, 2));
} else {
    const vectors = [
        0, 1, 2, 0x7fff, 0x8000, 0xfffe, 0xffff, 0x10000, 0x10001, 0x1ffff,
        0xffffff, 0x1000000, 0x1000001, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, 0xffffffff
    ];
    let genericProducts = 0;
    for (const a of vectors) {
        for (const b of vectors) {
            assert.equal(selected.mulhi32(a, b), Number((BigInt(a) * BigInt(b)) >> 32n));
            genericProducts += 1;
        }
    }
    const reference = slot => Number(((BigInt(slot) * selected.C64) & ((1n << 64n) - 1n)) >> 32n);
    for (const slot of vectors) assert.equal(checkedTop(selected, slot), reference(slot));
    for (const value of [-1, 2 ** 32, 0.5, NaN, Infinity]) assert.throws(() => checkedTop(selected, value));
    const changedCarry = slot => ((Math.imul(slot, selected.CHI | 0) >>> 0)
        + selected.mulhi32(slot, (selected.CLO + 1) >>> 0)) >>> 0;
    assert.notEqual(changedCarry(0xffffffff), reference(0xffffffff));
    assert.equal(Math.fround(0x1000000), Math.fround(0x1000001));
    assert.notEqual(checkedTop(selected, 0x1000000), checkedTop(selected, 0x1000001));
    console.log(JSON.stringify({
        schema: "seed.rare.unsigned-high-word.v1",
        result: "passed",
        source: {
            repository: "Ventusltd/particle-physics-drawing-engine", revision, path: sourcePath,
            gitBlob: sourceBlob, sha256: expectedSha256, tablet: 6082,
            lineWitnesses: Object.fromEntries(witnessLines),
            exactIndexedPlacementAtSourceRevision: false,
            sameBlobIndexedCommit: "027cc70c37955470fd72e9494595c89083a6f1f3"
        },
        checked: {genericProducts, phaseSlots: vectors.length, refusedInputs: 5,
            alteredConstantDetected: true, float32IntegerAliasControl: true},
        boundary: {
            slotA: 0x1000000, slotB: 0x1000001, phaseA: checkedTop(selected, 0x1000000),
            phaseB: checkedTop(selected, 0x1000001), maximumSlotPhase: checkedTop(selected, 0xffffffff)
        },
        resources: {pinnedSourceBlobBytes: inputBytes, evaluatedSourceBytes: evaluatedBytes,
            modelCalls: 0, gpuUsed: false},
        scope: "Known-answer boundary vectors in Node. A prior receipt covers a large deterministic sample. No browser, shader, cross-platform or performance replay."
    }, null, 2));
}

Invoke

A JavaScript module in the reduction folder of Seed Data.

ingestseed-data / experiments/economical-seeds/next-invention/reduction/invoke.mjs · lines 1–20 of 20 · Not reached from any entry point (candidate for review)

What it does
It loads data. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): 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.
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
seed-data · experiments/economical-seeds/next-invention/reduction · JavaScript module
Uses
Route Screen (import), Projected (import)
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
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/reduction/invoke.mjs:1-20 · blob 797c4500159c5d85c6190196e58f85eb6a497611 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import { readFileSync } from 'node:fs';
import { REVISION, SOURCES } from '../cable-screen/route-screen.mjs';
import { prepareProjectedScreen } from './projected.mjs';

const [input, checkout, ...extra] = process.argv.slice(2);
if (!input || !checkout || extra.length) {
  console.error('Usage: node invoke.mjs <declared-input.json> <engine-git-checkout>');
  process.exitCode = 2;
} else {
  try {
    const request = JSON.parse(readFileSync(input, 'utf8'));
    const screen = await prepareProjectedScreen(checkout);
    console.log(JSON.stringify({ ...screen(request),
      provenance: { provider: 'projected_numeric_contract', revision: REVISION, sources: SOURCES },
    }, null, 2));
  } catch (error) {
    console.error(error.message);
    process.exitCode = 1;
  }
}