GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / star-solar-star / testcode/202609150503

Test Publication and 4 more files

A test in the tests folder of Star Solar Star that checks Issue to Star and Publish Main, using SHA-256. It sets up (`setUp`) and writes other (`write_other`).

468 lines of Python and JavaScript from star-solar-star, teleprinter, in 5 files. Topic: Solar and storage design. Section 261 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. Browser render · star-solar-star / testcode/202609150503/browser.mjs lines 1–77
  2. Test Integrity test · star-solar-star / testcode/202609150503/test_integrity.py lines 1–149
  3. Vectors ingest · star-solar-star / testcode/202609150503/vectors.py lines 1–41
  4. Test Publication test · star-solar-star / tests/test_publication.py lines 1–188
  5. Codex Layers Panel Policy Test test · teleprinter / drivers/codex/layers-panel-policy.test.mjs lines 1–13

Browser

A JavaScript module in the testcode folder of Star Solar Star.

renderstar-solar-star / testcode/202609150503/browser.mjs · lines 1–77 of 77 · version 2026-09-15 05:03 · Entry point

What it does
It loads data. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: Solar Integrity Workflow (star-solar-star).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by Solar Integrity Workflow.
Application
star-solar-star · testcode/202609150503 · JavaScript module
Uses
Vectors (script call), node:assert/strict, node:http, node:fs/promises, node:path, node:url, node:child_process, ./contract.js
Used by
run by Solar Integrity Workflow (workflow run)
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
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e testcode/202609150503/browser.mjs:1-77 · blob 60ca7b90cfd9c821cd1dab194ee1424e8fe7cbfd · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unknown
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFile, writeFile} from 'node:fs/promises';
import {resolve, extname, sep} from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {execFileSync} from 'node:child_process';

const root = resolve(fileURLToPath(new URL('../../', import.meta.url)));
const cases = JSON.parse(execFileSync(process.env.PYTHON || 'python', [resolve(root, 'testcode/202609150503/vectors.py')], {encoding:'utf8'}));
const {default:puppeteer} = await import(process.env.PUPPETEER_MODULE ? pathToFileURL(process.env.PUPPETEER_MODULE).href : 'puppeteer');
const server = createServer(async (req, res) => {
  try {
    const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
    const path = resolve(root, '.' + (pathname.endsWith('/') ? pathname + 'index.html' : pathname));
    if (!path.startsWith(root + sep)) throw new Error('outside root');
    res.setHeader('Content-Type', {'.html':'text/html', '.js':'text/javascript', '.json':'application/json'}[extname(path)] || 'text/plain');
    res.end(await readFile(path));
  } catch { res.writeHead(404); res.end(); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let browser;
const results = {pass:false, cases:[], errors:[], viewport:{width:430,height:900,deviceScaleFactor:1}, physicalPhone:false};
try {
  browser = await puppeteer.launch({headless:true, executablePath:process.env.CHROME_PATH || undefined, args:['--no-sandbox']});
  const page = await browser.newPage();
  await page.setViewport(results.viewport);
  page.on('pageerror', error => results.errors.push(error.message));
  const url = `http://127.0.0.1:${server.address().port}/create/`;
  await page.goto(url, {waitUntil:'networkidle0'});
  results.browser = await browser.version();
  for (const vector of cases) {
    const direct = await page.evaluate(async observations => {
      const {observationBytes, prepareDefinition} = await import('./contract.js');
      return {bytes:observationBytes(observations), seed:(await prepareDefinition({sources:[{}], observations})).seed.value};
    }, vector.star.observations);
    assert.equal(direct.bytes, vector.bytes, vector.name + ' bytes');
    assert.equal(direct.seed, vector.star.seed.value, vector.name + ' seed');
    await page.$eval('#editor', (editor, value) => {editor.value=JSON.stringify(value)}, vector.star);
    await page.click('#prepare');
    await page.waitForFunction(() => document.querySelector('#status').textContent.startsWith('Prepared.'));
    const prepared = await page.$eval('#editor', editor => JSON.parse(editor.value));
    assert.deepEqual(prepared.seed, vector.star.seed, vector.name + ' actual UI');
    assert.deepEqual(JSON.parse(new URL(page.url()).searchParams.get('star')), prepared);
    await page.reload({waitUntil:'networkidle0'});
    assert.deepEqual(await page.$eval('#editor', editor => JSON.parse(editor.value)), prepared);
    results.cases.push(vector.name);
  }
  const rejected = await page.evaluate(async () => {
    const {canonical, prepareDefinition} = await import('./contract.js');
    const values = [Infinity, NaN, 2**53, -(2**53), '\ud800', {['\ud800']:1}, undefined];
    return Promise.all(values.map(async value => {
      try { canonical(value); return false; } catch { return true; }
    }));
  });
  assert(rejected.every(Boolean), 'invalid domain must fail closed');
  const changed = structuredClone(cases[0].star);
  changed.observations[0].value += 10;
  const changedSeed = await page.evaluate(async star => (await (await import('./contract.js')).prepareDefinition(star)).seed.value, changed);
  assert.notEqual(changedSeed, cases[0].star.seed.value);
  await page.$eval('#editor', editor => {editor.value='{"sources":[],"observations":[]}'});
  const previous = page.url();
  await page.click('#copy');
  await page.waitForFunction(() => document.querySelector('#status').textContent.startsWith('Not prepared:'));
  assert.equal(page.url(), previous, 'failed preparation does not replace URL');
  assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), '430px overflow');
  for (const box of await page.$$eval('button,a.button', nodes => nodes.map(node => ({height:node.getBoundingClientRect().height})))) assert(box.height >= 48);
  assert.deepEqual(results.errors, []);
  results.invalidVectors = rejected.length;
  results.changedMeasurementChangesSeed = true;
  results.urlReload = true;
  results.pass = true;
} finally {
  await browser?.close();
  await new Promise(resolve => server.close(resolve));
  if (process.env.PROOF_OUTPUT) await writeFile(process.env.PROOF_OUTPUT, JSON.stringify(results,null,2)+'\n');
  console.log(JSON.stringify(results,null,2));
}

Test Integrity

A test in the testcode folder of Star Solar Star that checks Build Sun and Star Contract.

teststar-solar-star / testcode/202609150503/test_integrity.py · lines 1–149 of 149 · version 2026-09-15 05:03 · Entry point

What it does
It tests its inputs. Defines 13 functions or classes, including pv_day, ProductionIntegrity, test_imports_are_production, test_legacy_reference_identity_and_immutable_publication, test_jcs_known_bytes_and_version. Uses libraries copy, datetime, json, sys, tempfile. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file global-solar-2025.star.json; JSON file history.json; JSON file today.json; JSON file uk-solar.json.
Downstream impact
Used directly by 1 file: Solar Integrity Workflow (star-solar-star).
What it achieves
It is built from the PV day helper (`pv_day`) and the production integrity class (`ProductionIntegrity`). Exercise published production modules, never historical candidate copies.
Why it matters
Run by Solar Integrity Workflow.
Application
star-solar-star · testcode/202609150503 · test
Uses
Build Sun (import), Star Contract (import), Validate Sun (sys.path import), Issue to Star (import), copy, datetime, json, sys, tempfile, unittest, pathlib, unittest.mock
Used by
run by Solar Integrity Workflow (workflow run)
Produces
pv_day, ProductionIntegrity
Defines here
pv_day, ProductionIntegrity, test_imports_are_production, test_legacy_reference_identity_and_immutable_publication, test_jcs_known_bytes_and_version, test_jcs_rejects_invalid_domain, test_interval_end_day_and_reordering, test_request_bounds_follow_official_interval_end_convention, test_duplicate_missing_and_off_grid_intervals_fail, test_nonfinite_invalid_power_and_capacity_fail, test_fallback_distinguishes_requested_and_observation_dates, test_validator_recomputes_all_summary_fields, test_preserves_real_project_null_geometry
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e testcode/202609150503/test_integrity.py:1-149 · blob 2da1bd507df592cd524f5a474f7fc3ef37e05584 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unknown
"""Exercise published production modules, never historical candidate copies."""
import copy
import datetime as dt
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts"))
import build_sun as builder
import star_contract as contract
import validate_sun
from issue_to_star import publish


def pv_day(date=dt.date(2026, 9, 14)):
    start = dt.datetime.combine(date, dt.time(), dt.timezone.utc)
    return {"meta": ["gsp_id", "datetime_gmt", "generation_mw", "installedcapacity_mwp"],
            "data": [[0, (start + dt.timedelta(minutes=30*n)).strftime("%Y-%m-%dT%H:%M:%SZ"), 1.0, 10.0] for n in range(1, 49)]}


class ProductionIntegrity(unittest.TestCase):
    def test_imports_are_production(self):
        for module in (builder, contract, validate_sun):
            self.assertEqual(Path(module.__file__).parent, ROOT / "scripts")

    def test_legacy_reference_identity_and_immutable_publication(self):
        star = json.loads((ROOT / "stars/global-solar-2025.star.json").read_text())
        self.assertEqual(contract.validate(star)["seed"], "a8696b5b9286966a43af65e3556ff3805df60542ed08f6fbc841d7bfed92dffa")
        with tempfile.TemporaryDirectory() as temp:
            first = publish(star, Path(temp))
            original = first.read_bytes()
            self.assertEqual(publish(copy.deepcopy(star), Path(temp)).read_bytes(), original)
            star["description"] += " Updated."
            with self.assertRaises(FileExistsError):
                publish(star, Path(temp))

    def test_jcs_known_bytes_and_version(self):
        rows = [{"key": "a", "value": 1.0}, {"key": "A", "value": -0.0}, {"key": "small", "value": 1e-6}]
        expected = b'[{"key":"A","value":0},{"key":"a","value":1},{"key":"small","value":0.000001}]'
        self.assertEqual(contract.observation_bytes(rows, contract.JCS_CANONICALIZATION), expected)
        self.assertNotEqual(contract.seed_for(rows), contract.seed_for(rows, contract.JCS_CANONICALIZATION))
        self.assertEqual(contract.seed_for(rows, contract.JCS_CANONICALIZATION), contract.seed_for(rows[::-1], contract.JCS_CANONICALIZATION))
        with self.assertRaises(ValueError):
            contract.seed_for(rows, "unknown-version")

    def test_jcs_rejects_invalid_domain(self):
        for value in (float("inf"), float("nan"), 2**53, float(2**53), -(2**53), "\ud800"):
            with self.subTest(value=repr(value)), self.assertRaises((ValueError, UnicodeError)):
                contract.seed_for([{"key": "x", "value": value}], contract.JCS_CANONICALIZATION)

    def test_interval_end_day_and_reordering(self):
        payload = pv_day()
        today, history = builder.parse_pvlive(payload, dt.date(2026, 9, 14))
        self.assertEqual(today["energy_mwh"], 24)
        self.assertEqual(today["series"][0]["timestamp_utc"], "2026-09-14T00:30:00Z")
        self.assertEqual(today["series"][-1]["timestamp_utc"], "2026-09-15T00:00:00Z")
        payload["data"].reverse()
        self.assertEqual(builder.parse_pvlive(payload, dt.date(2026, 9, 14)), (today, history))

    def test_request_bounds_follow_official_interval_end_convention(self):
        from urllib.parse import parse_qs, urlsplit
        query = parse_qs(urlsplit(builder.pv_url(dt.date(2026, 9, 14), 2)).query)
        self.assertEqual(query["start"], ["2026-09-13T00:30:00Z"])
        self.assertEqual(query["end"], ["2026-09-15T00:00:00Z"])

    def test_duplicate_missing_and_off_grid_intervals_fail(self):
        changes = [lambda p: p["data"].__setitem__(1, p["data"][0]),
                   lambda p: p["data"].pop(),
                   lambda p: p["data"][0].__setitem__(1, "2026-09-14T00:31:00Z"),
                   lambda p: p["data"][0].__setitem__(1, "2026-09-14T00:30:00+00:00"),
                   lambda p: p["data"][0].__setitem__(0, 1)]
        for change in changes:
            payload = pv_day()
            change(payload)
            with self.assertRaises(ValueError):
                builder.parse_pvlive(payload, dt.date(2026, 9, 14))
        payload = pv_day()
        payload["data"] = [payload["data"][0]] * 48
        with self.assertRaisesRegex(ValueError, "duplicate"):
            builder.parse_pvlive(payload, dt.date(2026, 9, 14))

    def test_nonfinite_invalid_power_and_capacity_fail(self):
        for value in (None, True, "1", -1, float("inf"), float("nan")):
            for column in (2, 3):
                if value is None and column == 3:
                    continue
                payload = pv_day()
                payload["data"][0][column] = value
                with self.subTest(value=value, column=column), self.assertRaises(ValueError):
                    builder.parse_pvlive(payload, dt.date(2026, 9, 14))

    def test_fallback_distinguishes_requested_and_observation_dates(self):
        today, _ = builder.parse_pvlive(pv_day(), dt.date(2026, 9, 15))
        self.assertEqual(today["requested_date"], "2026-09-15")
        self.assertEqual(today["data_date"], "2026-09-14")
        self.assertTrue(today["used_latest_available"])
        with self.assertRaises(ValueError):
            builder.parse_pvlive(pv_day(), dt.date(2026, 9, 13))
        payload = pv_day(dt.date(2026, 9, 12))
        payload["data"] += pv_day()["data"]
        with self.assertRaisesRegex(ValueError, "missing UTC days"):
            builder.parse_pvlive(payload, dt.date(2026, 9, 14))

    def test_validator_recomputes_all_summary_fields(self):
        payloads = {name: json.loads((ROOT / "sun" / name).read_text()) for name in validate_sun.NAMES}
        today, history = builder.parse_pvlive(pv_day(), dt.date(2026, 9, 14))
        payloads["history.json"] = history
        payloads["today.json"] = {"schema": "star-solar-star.today.v2", "seed": today["seed_sha256"],
                                  "pv_live": today, "london_solar_geometry": {"date": "2026-09-14"}}
        with patch.object(validate_sun, "load", side_effect=lambda root, name: payloads[name]):
            self.assertEqual(validate_sun.validate(ROOT / "sun")["date"], "2026-09-14")
            for key, value in {"energy_mwh": 25, "seed_sha256": "0"*64, "intervals": 47,
                               "complete": False, "date": "2026-09-13", "peak_mw": 2,
                               "peak_at_utc": "2026-09-14T01:00:00Z"}.items():
                original = history["days"][0][key]
                history["days"][0][key] = value
                with self.subTest(key=key), self.assertRaises(ValueError):
                    validate_sun.validate(ROOT / "sun")
                history["days"][0][key] = original
            for key, value in {"data_date": "2026-09-15", "requested_date": "2026-09-13", "used_latest_available": True}.items():
                original = today[key]
                today[key] = value
                with self.subTest(key=key), self.assertRaises(ValueError):
                    validate_sun.validate(ROOT / "sun")
                today[key] = original
            original_seed = today["seed_sha256"]
            payloads["today.json"]["seed"] = today["seed_sha256"] = history["days"][0]["seed_sha256"] = "0"*64
            with self.assertRaisesRegex(ValueError, "recomputed series"):
                validate_sun.validate(ROOT / "sun")
            payloads["today.json"]["seed"] = today["seed_sha256"] = history["days"][0]["seed_sha256"] = original_seed
            # These rows are shared by today's selected day and history. Corrupting
            # both still fails recomputation, even though all declared seeds agree.
            today["series"][1]["timestamp_utc"] = today["series"][0]["timestamp_utc"]
            with self.assertRaisesRegex(ValueError, "unique ordered"):
                validate_sun.validate(ROOT / "sun")

    def test_preserves_real_project_null_geometry(self):
        projects = json.loads((ROOT / "sun/uk-solar.json").read_text())
        missing = [p["repd_ref"] for p in projects["projects"] if p["latitude"] is None or p["longitude"] is None]
        self.assertEqual(len(projects["projects"]), 3563)
        self.assertEqual(sorted(missing), ["14773", "1613", "1616", "17120", "17260"])


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

Vectors

A Python command-line tool in the testcode folder of Star Solar Star that reads global solar star, using SHA-256. It is built from the vectors step (`vectors`).

ingeststar-solar-star / testcode/202609150503/vectors.py · lines 1–41 of 41 · version 2026-09-15 05:03 · Entry point

What it does
It loads global solar star. Defines vectors. Uses libraries copy, json, sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file global-solar-2025.star.json.
Downstream impact
Used directly by 1 file: Browser (star-solar-star). Reached from 1 other entry point, including Solar Integrity Workflow (star-solar-star).
What it achieves
Expected bytes/seeds computed by the production Python contract.
Why it matters
Run by Browser.
Application
star-solar-star · testcode/202609150503 · Python CLI
Uses
Star Contract (import), copy, json, sys, pathlib
Used by
run by Browser (script call)
Produces
vectors
Defines here
vectors
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e testcode/202609150503/vectors.py:1-41 · blob d46a0c03eca4eb9a6702ae4c0dfe7fb6ba3de787 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unknown
"""Expected bytes/seeds computed by the production Python contract."""
import copy
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts"))
from star_contract import JCS_CANONICALIZATION, observation_bytes, seed_for, validate


def vectors():
    base = json.loads((ROOT / "stars/global-solar-2025.star.json").read_text())
    cases = []
    for name, keys, values in [
        ("mixed case", ["a", "A", "z", "Z"], [1.0, -0.0, 0, 1.5]),
        ("unicode ordering", ["\ue000", "\U0001f600", "\u00e9", "e\u0301"], [1, 2, 3, 4]),
        ("fraction exponents", ["a", "b", "c", "d", "e"], [1e-6, 1e-7, 0.0000010000000000000002, 5e-324, 333333333.3333333]),
        ("safe bounds", ["a", "b", "c"], [9007199254740991, -9007199254740991, 1.2345678901234567]),
    ]:
        star = copy.deepcopy(base)
        star["observations"] = []
        for key, value in zip(keys, values):
            row = copy.deepcopy(base["observations"][0])
            row.update(key=key, value=value)
            row["metadata"] = {"\ue000": "BMP", "\U0001f600": "non-BMP", "A": "\t\n\"\\", "a": True}
            star["observations"].append(row)
        for variant in ("ordered", "reversed"):
            if variant == "reversed":
                star["observations"] = [dict(reversed(list(row.items()))) for row in reversed(star["observations"])]
            star["seed"] = {"algorithm": "sha256", "canonicalization": JCS_CANONICALIZATION,
                            "inputs": sorted(keys, key=lambda key: key.encode("utf-16be")), "url_parameter": "seed",
                            "value": seed_for(star["observations"], JCS_CANONICALIZATION)}
            validate(star)
            cases.append({"name": name + "/" + variant, "star": copy.deepcopy(star),
                          "bytes": observation_bytes(star["observations"], JCS_CANONICALIZATION).decode()})
    return cases


if __name__ == "__main__":
    print(json.dumps(vectors(), ensure_ascii=True))

Test Publication

A test in the tests folder of Star Solar Star that checks Issue to Star and Publish Main, using SHA-256. It sets up (`setUp`) and writes other (`write_other`).

teststar-solar-star / tests/test_publication.py · lines 1–188 of 188 · Entry point · pattern regenerate (shared by 2 files)

What it does
It tests its inputs. Defines 20 functions or classes, including at, git, PublicationTests, setUp, write_other. Uses libraries contextlib, functools, http.server, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file data.json; JSON file example.star.json; JSON file publication.json; JSON file proof.json. Out: JSON file data.json.
Downstream impact
Used directly by 1 file: Publication CI Workflow (star-solar-star).
What it achieves
Exercise production publication against a real temporary Git remote. It writes `unrelated.txt`.
Why it matters
Run by Publication CI Workflow.
Application
star-solar-star · tests · test
Uses
Issue to Star (sys.path import), Publish Main (sys.path import), Verify Pages (sys.path import), contextlib, functools, http.server, json, os, pathlib, subprocess, sys
Used by
run by Publication CI Workflow (workflow run)
Produces
at, git, PublicationTests
Defines here
at, git, PublicationTests, setUp, write_other, test_concurrent_push_rebuilds_against_fresh_main, regenerate, test_identical_immutable_record_is_idempotent, regenerate, test_concurrent_immutable_id_collision_rejected, regenerate, test_dirty_tracked_checkout_rejected, test_push_failures_are_bounded, run, regenerate, test_pages_requires_built_descendant_with_same_bytes, test_served_bytes_must_match, test_pages_resolves_new_build_and_writes_success_proof, test_pages_error_writes_failed_proof_and_raises, pages_orchestration
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e tests/test_publication.py:1-188 · blob 6b6e3250b689fb56e4c7a2d3704daccacc779697 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Exercise production publication against a real temporary Git remote."""
import contextlib
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import unittest
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import issue_to_star
import publish_main
import verify_pages


@contextlib.contextmanager
def at(path):
    previous = Path.cwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(previous)


def git(path, *args):
    return subprocess.check_output(["git", "-C", str(path), *args], stderr=subprocess.DEVNULL).decode().strip()


class PublicationTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        root = Path(self.temp.name)
        self.remote = root / "remote.git"
        self.repo = root / "worker"
        self.other = root / "other"
        subprocess.run(["git", "init", "--bare", "--initial-branch=main", str(self.remote)],
                       check=True, capture_output=True)
        subprocess.run(["git", "clone", str(self.remote), str(self.repo)], check=True, capture_output=True)
        git(self.repo, "config", "user.name", "Publication test")
        git(self.repo, "config", "user.email", "publication@example.invalid")
        (self.repo / "initial.txt").write_bytes(b"initial\n")
        git(self.repo, "add", ".")
        git(self.repo, "commit", "-m", "initial")
        git(self.repo, "push", "origin", "main")
        subprocess.run(["git", "clone", str(self.remote), str(self.other)], check=True, capture_output=True)
        git(self.other, "config", "user.name", "Other publisher")
        git(self.other, "config", "user.email", "other@example.invalid")

    def write_other(self, path, content):
        target = self.other / path
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(content)
        git(self.other, "add", path)
        git(self.other, "commit", "-m", "concurrent change")
        git(self.other, "push", "origin", "main")

    def test_concurrent_push_rebuilds_against_fresh_main(self):
        bases = []
        def regenerate():
            bases.append(git(self.repo, "rev-parse", "HEAD"))
            Path("data.json").write_text('{"valid":true}\n')
            if len(bases) == 1:
                self.write_other("unrelated.txt", "preserve this\n")
            return ["data.json"]
        with at(self.repo):
            result = publish_main.publish(regenerate, "publish data")
        self.assertEqual(result["attempts"], 2)
        self.assertNotEqual(bases[0], bases[1])
        self.assertEqual(git(self.remote, "show", "main:unrelated.txt"), "preserve this")
        self.assertEqual(result["published_commit"], git(self.remote, "rev-parse", "main"))

    def test_identical_immutable_record_is_idempotent(self):
        record = {"id": "example", "value": 1}
        def regenerate():
            return [issue_to_star.publish(record, Path("stars")).as_posix()]
        with at(self.repo):
            first = publish_main.publish(regenerate, "publish")
            second = publish_main.publish(regenerate, "publish")
        self.assertTrue(first["changed"])
        self.assertFalse(second["changed"])
        self.assertEqual(first["published_commit"], second["published_commit"])

    def test_concurrent_immutable_id_collision_rejected(self):
        calls = []
        def regenerate():
            path = issue_to_star.publish({"id": "example", "value": 1}, Path("stars"))
            calls.append(True)
            self.write_other("stars/example.star.json", '{"id":"example","value":2}\n')
            return [path.as_posix()]
        with at(self.repo), self.assertRaises(FileExistsError):
            publish_main.publish(regenerate, "publish")
        self.assertEqual(len(calls), 1)
        self.assertEqual(json.loads(git(self.remote, "show", "main:stars/example.star.json"))["value"], 2)

    def test_dirty_tracked_checkout_rejected(self):
        (self.repo / "initial.txt").write_text("user change\n")
        with at(self.repo), self.assertRaisesRegex(RuntimeError, "clean disposable"):
            publish_main.publish(lambda: ["initial.txt"], "publish")

    def test_push_failures_are_bounded(self):
        original = publish_main.run
        attempts = []
        def run(*args, **kwargs):
            if args[:2] == ("git", "push"):
                attempts.append(True)
                return subprocess.CompletedProcess(args, 1, "", "remote unavailable")
            return original(*args, **kwargs)
        def regenerate():
            Path("data.json").write_text("{}\n")
            return ["data.json"]
        with at(self.repo), patch.object(publish_main, "run", run), self.assertRaisesRegex(RuntimeError, "bounded retries"):
            publish_main.publish(regenerate, "publish")
        self.assertEqual(len(attempts), 3)
        self.assertEqual(git(self.remote, "rev-list", "--count", "main"), "1")

    def test_pages_requires_built_descendant_with_same_bytes(self):
        published = git(self.repo, "rev-parse", "HEAD")
        self.write_other("other.txt", "unrelated")
        with at(self.repo):
            git(self.repo, "fetch", "origin")
            descendant = git(self.repo, "rev-parse", "origin/main")
            expected = verify_pages.committed_payloads(published, ["initial.txt"])
            self.assertTrue(verify_pages.verify_build({"commit": descendant, "status": "built"}, published, expected))
            self.assertFalse(verify_pages.verify_build({"commit": descendant, "status": "building"}, published, expected))
            self.write_other("initial.txt", "changed")
            git(self.repo, "fetch", "origin")
            self.assertFalse(verify_pages.verify_build({"commit": git(self.repo, "rev-parse", "origin/main"),
                                                       "status": "built"}, published, expected))

    def test_served_bytes_must_match(self):
        handler = partial(SimpleHTTPRequestHandler, directory=str(self.repo))
        server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
        thread = threading.Thread(target=server.serve_forever, daemon=True)
        thread.start()
        try:
            base = f"http://127.0.0.1:{server.server_port}/"
            result = verify_pages.verify_served(base, {"initial.txt": b"initial\n"}, "abc")
            self.assertEqual(result["initial.txt"]["bytes"], 8)
            with self.assertRaisesRegex(ValueError, "served bytes"):
                verify_pages.verify_served(base, {"initial.txt": b"wrong"}, "abc")
        finally:
            server.shutdown()
            server.server_close()
            thread.join()

    def test_pages_resolves_new_build_and_writes_success_proof(self):
        self.pages_orchestration("built")

    def test_pages_error_writes_failed_proof_and_raises(self):
        self.pages_orchestration("errored")

    def pages_orchestration(self, status):
        publication = Path(self.temp.name) / "publication.json"
        proof = Path(self.temp.name) / "proof.json"
        published = git(self.repo, "rev-parse", "HEAD")
        publication.write_text(json.dumps({"published_commit": published, "paths": ["initial.txt"]}))
        old = {"url": "builds/1", "status": "built", "commit": published}
        build = {"url": "builds/2", "status": status, "commit": published}
        responses = [
            {"source": {"branch": "main", "path": "/"}, "build_type": "legacy", "html_url": "https://example.invalid"},
            old, {"url": "builds/latest", "status": "queued"}, old, build,
        ]
        with at(self.repo), patch.dict(os.environ, {"GITHUB_REPOSITORY": "example/repo"}), \
             patch.object(sys, "argv", ["verify_pages", "--publication", str(publication), "--result", str(proof)]), \
             patch.object(verify_pages, "api", side_effect=responses) as mocked_api, \
             patch.object(verify_pages.time, "sleep"), \
             patch.object(verify_pages, "verify_served", return_value={"initial.txt": {"sha256": "test"}}):
            if status == "errored":
                with self.assertRaisesRegex(RuntimeError, "Pages build failed"):
                    verify_pages.main()
            else:
                verify_pages.main()
        result = json.loads(proof.read_text())
        self.assertEqual(result["pass"], status == "built")
        self.assertEqual(result["pages_build"]["url"], "builds/2")
        self.assertEqual(mocked_api.call_args_list[2].args, ("repos/example/repo/pages/builds", "POST"))


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

Codex Layers Panel Policy Test

A test in the drivers folder of Teleprinter that checks Layers Panel Policy.

testteleprinter / drivers/codex/layers-panel-policy.test.mjs · lines 1–13 of 13 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:test, node:assert/strict. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Guards the behaviour of Layers Panel Policy.
Application
teleprinter · drivers/codex · test
Uses
Layers Panel Policy (import), node:test, node:assert/strict
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
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/layers-panel-policy.test.mjs:1-13 · blob e7552a32cb4b7c6615820b7fe5db07effa30bf74 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {collapseInitialLayers} from './layers-panel-policy.js';
test('arrival uses existing panel action without touching map layer inputs',()=>{
  let collapsed=false,clicks=0;
  const doc={documentElement:{dataset:{}},querySelector(selector){assert.equal(selector,'.scada-wrapper');return {getAttribute:()=>collapsed?'1':null};},getElementById(id){assert.equal(id,'gridatlas-dash-toggle');return {click(){collapsed=true;clicks++;}};}};
  assert.equal(collapseInitialLayers(doc),true);assert.equal(clicks,1);
  collapseInitialLayers(doc);assert.equal(clicks,1);
  assert.equal(doc.documentElement.dataset.codexLayersArrival,'collapsed');
});
test('late controls remain pending instead of hiding the map wrapper',()=>{
  assert.equal(collapseInitialLayers({querySelector:()=>null,getElementById:()=>null}),false);
});