GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / wire-frame-scanner / tests

Check No Private Paths and 5 more files

A Python command-line tool in the scripts folder of Worlds that works with env rules (`env_rules`).

629 lines of Python and YAML from wire-frame-scanner, worlds-, in 6 files. Topic: Automation and CI. Section 1876 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. Test Known Answer test · wire-frame-scanner / tests/test_known_answer.py lines 1–79
  2. Test Pylon test · wire-frame-scanner / tests/test_pylon.py lines 1–82
  3. Test Structures test · wire-frame-scanner / tests/test_structures.py lines 1–56
  4. Test Vlidar Loop test · wire-frame-scanner / tests/test_vlidar_loop.py lines 1–50
  5. Weekly Gates Workflow automation · worlds- / .github/workflows/weekly-gates.yml lines 1–89
  6. Check No Private Paths other · worlds- / scripts/check_no_private_paths.py lines 1–273

Test Known Answer

A test in the tests folder of Wire Frame Scanner that checks Wire Frame Scanner — Scanner.

testwire-frame-scanner / tests/test_known_answer.py · lines 1–79 of 79 · Entry point · pattern measure (shared by 35 files)

What it does
It tests its inputs. Defines farm, measure, ang_diff, run. Uses libraries math, os, sys, json, numpy. Side effects: starts processes.
Why it exists in the grid workflow
README: "tests/test_known_answer.py: passes 12/12 on both engines, and the two engines agree exactly."
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It is built from the farm step (`farm`), the measure step (`measure`) and the ang diff helper (`ang_diff`). Known-answer tests: synthetic 'farms' with EXACTLY known row direction and pitch.
Why it matters
Guards the behaviour of Wire Frame Scanner — Scanner.
Application
wire-frame-scanner · tests · test
Uses
Wire Frame Scanner — Scanner (import), math, os, sys, json, numpy
Used by
none found
Produces
farm, measure, ang_diff, run
Defines here
farm, measure, ang_diff, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_known_answer.py:1-79 · blob 8aee2d0b7e7e29d1be55d099a924ed5f873336d9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""Known-answer tests: synthetic 'farms' with EXACTLY known row direction and pitch. The scanner must recover them,
on the GPU (CuPy) when present and on the CPU (NumPy), and both must agree. Measured reality, not made-up numbers:
the answer is fixed by construction, so a pass means the maths measures what it claims.

Run: python tests/test_known_answer.py   (exit code 0 = all pass)
"""
import math, os, sys, json
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner import core

MPP = 0.746                              # metres per pixel at z17, latitude about 51
CASES = [  # (row_bearing_deg: direction the rows run, measured from image x-axis; pitch_m; table_depth_m; block w,h px)
    (90.0, 7.5, 4.0, 300, 220), (0.0, 9.0, 5.0, 260, 260), (17.0, 6.0, 3.2, 320, 240),
    (63.0, 11.0, 5.5, 280, 300), (135.0, 8.2, 4.4, 300, 200), (104.0, 13.5, 6.0, 360, 260),
]
TOL_PITCH_M, TOL_DIR_DEG = 0.25, 1.0


def farm(xp, bearing_deg, pitch_m, depth_m, w, h, noise=0.0, seed=0):
    """A block of parallel stripes (tables) at a known bearing and pitch, inside an irregular (sheared) outline."""
    yy, xx = xp.mgrid[0:h, 0:w].astype(xp.float32)
    th = math.radians(bearing_deg) + math.pi / 2                      # normal to the rows
    off = (xx * math.cos(th) + yy * math.sin(th)) * MPP
    stripes = (off % pitch_m) < depth_m
    outline = (xx > 10 + 0.15 * yy) & (xx < w - 10) & (yy > 10) & (yy < h - 10 - 0.1 * xx)
    m = stripes & outline
    if noise:
        rng = np.random.default_rng(seed)
        flip = xp.asarray(rng.random((h, w)) < noise)
        m = m ^ (flip & outline)
    return m


def measure(xp, mask):
    th = core.refine_normal(xp, mask, core.row_normal(xp, mask), MPP)
    r = core.row_pitch(xp, mask, th, MPP)
    if r is None:
        return None
    pitch_px, phase, lo = r
    rows_bearing = (math.degrees(th) - 90) % 180
    return rows_bearing, pitch_px * MPP


def ang_diff(a, b):
    d = abs(a - b) % 180
    return min(d, 180 - d)


def run(xp):
    out = []
    for (bdeg, p, d, w, h) in CASES:
        for noise in (0.0, 0.05):
            got = measure(xp, farm(xp, bdeg, p, d, w, h, noise))
            ok = got is not None and ang_diff(got[0], bdeg) <= TOL_DIR_DEG and abs(got[1] - p) <= TOL_PITCH_M
            out.append({'bearing': bdeg, 'pitch': p, 'noise': noise, 'got_bearing': got and round(got[0], 2),
                        'got_pitch': got and round(got[1], 3), 'pass': bool(ok)})
    return out


if __name__ == '__main__':
    engines = [('numpy', np)]
    try:
        import cupy as cp; cp.cuda.runtime.getDeviceCount(); engines.insert(0, ('cupy', cp))
    except Exception:
        pass
    results = {name: run(m) for name, m in engines}
    agree = True
    if len(engines) == 2:
        for a, b in zip(results['cupy'], results['numpy']):
            if a['got_bearing'] != b['got_bearing'] or a['got_pitch'] != b['got_pitch']:
                agree = False
    for name, rs in results.items():
        for r in rs:
            print(f"{name:5s} {'PASS' if r['pass'] else 'FAIL'}  rows {r['bearing']:6.1f} deg, pitch {r['pitch']:5.2f} m, noise {r['noise']:.2f}"
                  f"  ->  got {r['got_bearing']} deg, {r['got_pitch']} m")
    npass = sum(r['pass'] for r in results[engines[0][0]]); ntot = len(results[engines[0][0]])
    print(f"\n{engines[0][0]}: {npass}/{ntot} pass; GPU and CPU agree: {agree if len(engines) == 2 else 'n/a (no GPU)'}")
    sys.exit(0 if npass == ntot and agree else 1)

Test Pylon

A test in the tests folder of Wire Frame Scanner that checks Pylon. It is built from the check step (`check`) and the on leg helper (`on_leg`).

testwire-frame-scanner / tests/test_pylon.py · lines 1–82 of 82 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines check, on_leg. Uses libraries os, sys, numpy, matplotlib, matplotlib.pyplot. Side effects: reads or writes files; starts processes.
Inputs & outputs
Out: figure image.
What it achieves
Lattice pylon skeleton: geometry and determinism checks, then renders `test-output/pylon.png`.
Why it matters
Guards the behaviour of Pylon.
Application
wire-frame-scanner · tests · test
Uses
Pylon (import), os, sys, numpy, matplotlib, matplotlib.pyplot
Used by
none found
Produces
check, on_leg
Defines here
check, on_leg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_pylon.py:1-82 · blob ececb6a7755bdb4bd48022696416333abe5f4a87 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Lattice pylon skeleton: geometry and determinism checks, then renders test-output/pylon.png.
Run: python tests/test_pylon.py
"""
import os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner.pylon import lattice_pylon, leg_point, half_width, panel_levels, _ASSUMED_DIMS, CORNERS, ASSUMED_SRC

TOL = 1e-9
results = []


def check(name, ok, detail=''):
    results.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name}  {detail}")


def on_leg(p, d):
    x, y, z = p
    if z < -TOL or z > d['h_top'] + TOL:
        return False
    h = half_width(z, d)
    return any(abs(x - sx * h) < 1e-6 and abs(y - sy * h) < 1e-6 for sx, sy in CORNERS)


for v in (132, 275, 400):
    d = _ASSUMED_DIMS[v]
    for br in ('K', 'X'):
        lines, m = lattice_pylon(v, bracing=br)
        tag = f"{v} kV {br}"
        base = [leg_point(i, 0.0, d) for i in range(4)]
        want = {(sx * d['base_half'], sy * d['base_half'], 0.0) for sx, sy in CORNERS}
        check(f"{tag} legs meet ground at base corners", {tuple(round(c, 9) for c in p) for p in base} == want)
        waist = [leg_point(i, d['h_waist'], d) for i in range(4)]
        conv = all(abs(abs(p[0]) - d['waist_half']) < TOL and abs(abs(p[1]) - d['waist_half']) < TOL for p in waist)
        mono = all(half_width(z1, d) <= half_width(z0, d) + TOL for z0, z1 in zip(panel_levels(d)[:-1], panel_levels(d)[1:]))
        check(f"{tag} legs converge to waist and never widen", conv and mono)
        # bracing: lines whose endpoints are at different legs and different heights within the body/top panels
        n_p = d['n_body'] + d['n_top']
        brace = []
        for k in range(n_p):
            s = 4 + k * 16 + 8
            brace += lines[s:s + 8]
        allon = all(on_leg(a, d) and on_leg(b, d) for a, b in brace)
        check(f"{tag} every bracing endpoint lies on a leg", allon and len(brace) == 8 * n_p, f"({len(brace)} members)")
        exp = n_p * 16 + 4 + 2 * 3 * 5
        again, m2 = lattice_pylon(v, bracing=br)
        check(f"{tag} panel/line count deterministic and match formula",
              m['n_panels']['value'] == n_p and len(lines) == exp == m['n_lines']['value'] and again == lines,
              f"(panels {n_p}, lines {len(lines)})")
        drops = m['insulator_drops']['value']
        r = {(q['level']): q['tip'] for q in drops if q['side'] == 1}
        l = {(q['level']): q['tip'] for q in drops if q['side'] == -1}
        sym = len(r) == len(l) == 3 and all(abs(r[k][0] + l[k][0]) < TOL and r[k][2] == l[k][2] for k in r)
        arm_roots_on_leg = all(on_leg(a, d) for a, b in lines[4 + n_p * 16:] if abs(abs(a[0]) - d['waist_half']) < TOL)
        check(f"{tag} cross-arm tips symmetric, roots on legs", sym and arm_roots_on_leg)
        prov = all(m[k]['source'] == ASSUMED_SRC for k in ('height_top_m', 'base_width_m', 'waist_width_m', 'arm_lengths_m'))
        check(f"{tag} dimensions tagged assumed", prov)

hs = [lattice_pylon(v)[1]['height_top_m']['value'] for v in (132, 275, 400)]
ws = [lattice_pylon(v)[1]['base_width_m']['value'] for v in (132, 275, 400)]
check("heights ordered by voltage class", hs[0] < hs[1] < hs[2], f"(top {hs} m, base width {ws} m)")

# render
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
out = os.path.join(os.path.dirname(__file__), '..', 'test-output')
os.makedirs(out, exist_ok=True)
fig = plt.figure(figsize=(12, 5))
for k, (v, br) in enumerate([(132, 'K'), (275, 'X'), (400, 'K')]):
    ax = fig.add_subplot(1, 3, k + 1, projection='3d')
    for a, b in lattice_pylon(v, bracing=br)[0]:
        ax.plot([a[0], b[0]], [a[1], b[1]], [a[2], b[2]], lw=0.6, color='#333')
    ax.set_title(f"{v} kV, {br} bracing (assumed dims)", fontsize=9)
    ax.set_box_aspect((1, 1, 3)); ax.set_xlim(-8, 8); ax.set_ylim(-8, 8); ax.set_zlim(0, 50)
png = os.path.abspath(os.path.join(out, 'pylon.png'))
fig.savefig(png, dpi=110); plt.close(fig)
check("rendered", os.path.getsize(png) > 0, png)

print(f"\n{sum(results)}/{len(results)} pass")
sys.exit(0 if all(results) else 1)

Test Structures

A test in the tests folder of Wire Frame Scanner that checks Structures. It is built from the check step (`check`).

testwire-frame-scanner / tests/test_structures.py · lines 1–56 of 56 · Entry point

What it does
It tests its inputs. Defines check. Uses libraries math, os, sys, numpy. Side effects: reads or writes files; starts processes.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tower skeleton: PCHIP profile through measured pins, floor rings, helical diagrid on the rings.
Why it matters
Guards the behaviour of Structures.
Application
wire-frame-scanner · tests · test
Uses
Structures (import), math, os, sys, numpy
Used by
none found
Produces
check
Defines here
check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_structures.py:1-56 · blob 877de99ffde6207fcdfc56c3f2e655906b60ac03 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Tower skeleton: PCHIP profile through measured pins, floor rings, helical diagrid on the rings.
Illustrative example pins only (generic 100 m tower). Run: python tests/test_structures.py
"""
import math, os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner import structures as S

TOL = 1e-9
ROOT = os.path.join(os.path.dirname(__file__), '..')
results = []


def check(name, ok, detail=''):
    results.append(ok); print(f"{'PASS' if ok else 'FAIL'}  {name}  {detail}")


if __name__ == '__main__':
    pins, spacing, n = S.EXAMPLE_PINS, 4.0, 24
    lines, model = S.tower_skeleton(pins, spacing, n)
    prof = model['profile_fn']
    err = max(abs(prof(p['z'])[0] - p['r']) for p in pins)
    check('profile passes through every pin', err <= TOL, f'max err {err:.2e}')
    check('pins tagged measured with source field', all(p['provenance'] == 'measured' and 'source' in p for p in model['pins']))
    zs = [r['z'] for r in model['rings']]
    exp = [k * spacing for k in range(int(100 / spacing) + 1)]
    check('rings at exact heights', len(zs) == len(exp) and all(abs(a - b) <= TOL for a, b in zip(zs, exp)), f'{len(zs)} rings')
    ring_set = {(round(r['z'], 6)): r['r'] for r in model['rings']}
    worst = 0.0
    for a, b, kind in lines:
        if kind.startswith('diagrid'):
            for (x, y, z) in (a, b):
                rr = min(model['rings'], key=lambda q: abs(q['z'] - z))
                worst = max(worst, abs(rr['z'] - z), abs(math.hypot(x, y) - rr['r']))
    check('every diagrid node lies on a ring', worst <= TOL, f'max err {worst:.2e}')
    R = len(zs); formula = n * (3 * R - 2)
    lines2, _ = S.tower_skeleton(pins, spacing, n)
    check('line count deterministic and equals n*(3R-2)', len(lines) == len(lines2) == formula == model['n_lines_formula'],
          f'R={R} n={n}: {len(lines)} lines (rings {n*R}, diagrid {2*n*(R-1)}), formula {formula}')
    worst = 0.0
    for p0, p1 in zip(pins[:-1], pins[1:]):
        zz = np.linspace(p0['z'], p1['z'], 2001); rr = prof(zz)
        lo, hi = min(p0['r'], p1['r']), max(p0['r'], p1['r'])
        worst = max(worst, float(np.max(np.maximum(rr - hi, lo - rr))))
        d = np.diff(rr) * np.sign(p1['r'] - p0['r'])
        worst = max(worst, float(-d.min()) if d.min() < 0 else 0.0)
    check('no overshoot between pins (monotone)', worst <= TOL, f'max excursion {worst:.2e}')
    # odd spacing: top ring added at total height, formula still holds
    l3, m3 = S.tower_skeleton(pins, 7.0, 16)
    check('non-divisible spacing adds top ring', abs(m3['rings'][-1]['z'] - 100.0) <= TOL and len(l3) == 16 * (3 * len(m3['rings']) - 2),
          f'{len(m3["rings"])} rings, {len(l3)} lines')
    out = os.path.join(ROOT, 'test-output'); os.makedirs(out, exist_ok=True)
    png = os.path.abspath(S.render_png(lines, model, os.path.join(out, 'tower.png')))
    print(f'PNG (illustrative example): {png}')
    print(f'\n{sum(results)}/{len(results)} pass')
    sys.exit(0 if all(results) else 1)

Test Vlidar Loop

A test in the tests folder of Wire Frame Scanner that checks Wire Frame Scanner — Scanner and Vlidar.

testwire-frame-scanner / tests/test_vlidar_loop.py · lines 1–50 of 50 · Entry point · pattern ground (shared by 13 files)

What it does
It tests LiDAR terrain. Defines ground, run. Uses libraries math, os, sys, numpy. Side effects: starts processes.
Why it exists in the grid workflow
Domain terms in the code: LiDAR terrain.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It is built from the ground step (`ground`) and the run step (`run`). Closed loop: model -> virtual LiDAR -> scanner -> model.
Why it matters
Guards the behaviour of Wire Frame Scanner — Scanner and Vlidar.
Application
wire-frame-scanner · tests · test
Uses
Wire Frame Scanner — Scanner (import), Vlidar (import), math, os, sys, numpy
Used by
none found
Produces
ground, run
Defines here
ground, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_vlidar_loop.py:1-50 · blob 6766f8cfd7510362ee9780bb1a94490a0fa817c3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""Closed loop: model -> virtual LiDAR -> scanner -> model. The scanner, reading only the virtual survey's DSM minus
DTM (object heights above 1 m), must recover the model's row direction and pitch. GPU and CPU must agree.
Run: python tests/test_vlidar_loop.py
"""
import math, os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner import core, vlidar

EXTENT, CELL = 160.0, 0.5
CASES = [(90.0, 7.5, 4.0), (17.0, 6.0, 3.2), (63.0, 11.0, 5.5), (135.0, 8.2, 4.4)]


def ground(xp, x, y):  # gently rolling ground, metres
    return 5.0 + 1.5 * xp.sin(x / 37.0) + 1.0 * xp.cos(y / 29.0)


def run(xp):
    out = []
    for (b, p, d) in CASES:
        obj = lambda xp_, x, y: vlidar.tables_height(xp_, x, y, b, p, d)
        x, y, first, last = vlidar.survey(xp, EXTENT, ground, obj, ppsm=8.0, noise_m=0.05, seed=7)
        dsm = vlidar.rasterise(xp, x, y, first, EXTENT, CELL)
        dtm = vlidar.rasterise(xp, x, y, last, EXTENT, CELL)
        mask = (dsm - dtm) > 1.0                                          # object heights above 1 m
        th = core.refine_normal(xp, mask, core.row_normal(xp, mask), CELL)
        r = core.row_pitch(xp, mask, th, CELL)
        got_b = (math.degrees(th) - 90) % 180; got_p = r[0] * CELL if r else None
        # raster y grows with survey y (north up is not assumed here), so compare direction in the raster's own frame
        dd = min(abs(got_b - b) % 180, 180 - abs(got_b - b) % 180)
        ok = got_p is not None and dd <= 1.0 and abs(got_p - p) <= 0.25
        out.append({'bearing': b, 'pitch': p, 'got_bearing': round(got_b, 2), 'got_pitch': got_p and round(got_p, 3),
                    'points': int(x.size), 'pass': bool(ok)})
    return out


if __name__ == '__main__':
    eng = [('numpy', np)]
    try:
        import cupy as cp; cp.cuda.runtime.getDeviceCount(); eng.insert(0, ('cupy', cp))
    except Exception:
        pass
    res = {n: run(m) for n, m in eng}
    agree = len(eng) < 2 or all(a['got_bearing'] == b['got_bearing'] and a['got_pitch'] == b['got_pitch'] for a, b in zip(res['cupy'], res['numpy']))
    for n, rs in res.items():
        for r in rs:
            print(f"{n:5s} {'PASS' if r['pass'] else 'FAIL'}  model rows {r['bearing']:6.1f} deg {r['pitch']:5.2f} m  ->  scanner from virtual LiDAR {r['got_bearing']} deg {r['got_pitch']} m  ({r['points']} pulses)")
    k = eng[0][0]; npass = sum(r['pass'] for r in res[k])
    print(f"\n{k}: {npass}/{len(res[k])} closed-loop pass; GPU and CPU agree: {agree}")
    sys.exit(0 if npass == len(res[k]) and agree else 1)

Weekly Gates Workflow

A GitHub Actions workflow in Worlds that builds and publishes the site. Runs on a schedule and by hand.

automationworlds- / .github/workflows/weekly-gates.yml · lines 1–89 of 89 · Entry point

What it does
It builds and publishes its content. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gates'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Weekly, hosted - the gates on this repository”; runs Check No Private Paths (`scripts/check_no_private_paths.py`) and Verdict Gate (`src/verdict_gate.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
worlds- · .github/workflows · workflow
Uses
Check No Private Paths (workflow run), Verdict Gate (workflow run)
Used by
none found
Produces
none declared
Defines here
Weekly, hosted - the gates on this repository
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
worlds-@83817c34790800d4af5057629121d83d0d67a332 .github/workflows/weekly-gates.yml:1-89 · blob 287c7ab323500f69fa3b4ff7af365da776e3f54a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
name: Weekly, hosted - the gates on this repository

# Runs once a week on a hosted runner, whatever the state of any machine of
# ours. Two gates, each of which proves it can both pass and fail before it
# judges anything, and each of which fails the run rather than warning:
#
#   private-paths  no tracked file may name a drive, a home directory or a
#                  share. Locations only are printed, never the text.
#   verdicts       no comparison that decides a verdict may report PASS
#                  when handed something that is not a number. The gate
#                  first runs itself against a broken fixture (must exit 1)
#                  and a corrected one (must exit 0), then scans src/.
#
# The third gate of this repository, provenance (where did every published
# limit come from?), needs the evidence base, which is not public. It
# refuses on a hosted runner - exit 2, nothing examined, not a pass - so it
# is not run here. It runs weekly where the evidence lives, from the site
# repository's weekly-card.yml, and its result appears in that run's summary.
#
# Nothing is committed and nothing is deployed by this workflow. A red run
# needs no one tonight: the log names the file and line, and it will say it
# again next week.

on:
  schedule:
    # Monday 05:47 UTC
    - cron: '47 5 * * 1'
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: weekly-gates
  cancel-in-progress: false

jobs:
  private-paths:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 1
      - name: No tracked file may name a drive, a home directory or a share
        env:
          GRID_PRIVATE_MARKERS: ${{ secrets.GRID_PRIVATE_MARKERS }}
          GRID_PRIVATE_ROOTS: ${{ secrets.GRID_PRIVATE_ROOTS }}
        run: |
          python3 scripts/check_no_private_paths.py | tee report.txt
          code=${PIPESTATUS[0]}
          {
            echo "## No private paths"
            echo
            echo '```'
            grep -v '^    ' report.txt
            n=$(grep -c '^    ' report.txt || true)
            echo "locations listed in the job log: $n"
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
          exit "$code"

  verdicts:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 1
      - name: No verdict may pass a non-number
        run: |
          python3 src/verdict_gate.py --run --ci | tee report.txt
          code=${PIPESTATUS[0]}
          {
            echo "## Verdicts fed a non-number"
            echo
            echo '```'
            tail -n 40 report.txt
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
          exit "$code"
      - name: Keep the evidence
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: verdict-gate
          path: night-results/verdict-gate.json
          if-no-files-found: warn
          retention-days: 90

Check No Private Paths

A Python command-line tool in the scripts folder of Worlds that works with env rules (`env_rules`).

otherworlds- / scripts/check_no_private_paths.py · lines 1–273 of 273 · Entry point · pattern self_test (shared by 2 files)

What it does
It lists and searches its content. Defines 7 functions or classes, including env_rules, tracked, scan, _git, self_test. Uses libraries argparse, io, os, re, shutil. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Weekly Gates Workflow (worlds-).
What it achieves
It is built from the tracked step (`tracked`), the scan step (`scan`) and the self test helper (`self_test`). An absolute path typed into a source file names a drive, a machine and an account. It accepts `--list`, `--self-test` and `--skip-self-test`.
Why it matters
Run by Weekly Gates Workflow.
Application
worlds- · scripts · Python CLI
Uses
Paths (script call), argparse, io, os, re, shutil, subprocess, sys, tempfile
Used by
run by Weekly Gates Workflow (workflow run)
Produces
env_rules, tracked, scan, self_test, main
Defines here
env_rules, tracked, scan, _git, self_test, run, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
worlds-@83817c34790800d4af5057629121d83d0d67a332 scripts/check_no_private_paths.py:1-273 · blob d40bdefafa18b4fb248c3264f72b7d881e038a25 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""THE GATE THAT NAMES NOBODY.

WHY THIS FILE EXISTS
An absolute path typed into a source file names a drive, a machine and an
account. This repository is public, so every such line publishes a fact about
a person that has nothing to do with the work. That leak was scrubbed once in
5f42946 and reintroduced by 4a4524e, the very next commit, and reported closed
both times - because nobody re-ran the search afterwards. A scrub is not a
commit, it is a check that keeps running.

THE TRAP THIS FILE HAS TO AVOID
A checker that hunts for a private string has to hold that string. Write the
pattern into the source and the gate becomes the leak it was built to catch,
published forever in the repository it guards. So:

  * THE PATTERNS COME FROM THE ENVIRONMENT. Nothing private is written here.
  * THE OUTPUT IS LOCATIONS ONLY - path, line number, and which rule fired.
    Never the offending text. CI logs are public too, and a gate that prints
    what it found publishes it a second time, more loudly, to more people.

CONFIGURE IT (the values are examples of shape, not of content):

  GRID_PRIVATE_MARKERS   ;-separated literals that must never appear.
                         Typically the account name and the trail directory.
  GRID_PRIVATE_ROOTS     ;-separated absolute roots that must never appear
                         (matched case-insensitively, either slash).

With neither set, the gate still enforces the rules that need no secret: no
Windows drive-letter path, no /home/<name> or /Users/<name>, no UNC share.
Those catch a new leak that no list of remembered strings would have known to
look for.

    python scripts/check_no_private_paths.py          # self-test, then scan
    python scripts/check_no_private_paths.py --list   # what it enforces
    python scripts/check_no_private_paths.py --self-test   # the fixtures only

THE GATE PROVES IT CAN DO BOTH BEFORE IT JUDGES ANYTHING. Every scan first
builds a throwaway repository containing this file and one line in the shape
of a drive-letter path, and runs itself there: that run must exit 1. The line
is then removed and the run must exit 0. A gate never observed to pass AND to
fail has not been shown to gate anything, so if either fixture misbehaves the
scan does not happen and the exit is 2.

Exit 0 clean, 1 on any hit, 2 if it could not scan (which is not a pass).
"""
import argparse
import io
import os
import re
import shutil
import subprocess
import sys
import tempfile

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Files whose whole job is to talk about this problem. They are allowed to
# describe the shape of a private path; they must still not contain one, so
# they are scanned by the environment-supplied rules and exempted only from
# the generic shape rules below.
SHAPE_EXEMPT = {
    "scripts/check_no_private_paths.py",
    "src/paths.py",
}

# Binary and generated things a text scan cannot say anything useful about.
SKIP_EXT = {".png", ".jpg", ".jpeg", ".gif", ".ico", ".pdf", ".zip", ".gz",
            ".7z", ".exe", ".dll", ".pyc", ".woff", ".woff2", ".ttf", ".mp4"}

# The rules that need no secret to state. A drive letter, a home directory or
# a share is a private location whoever it belongs to.
SHAPE_RULES = [
    ("drive-letter path",
     re.compile(r"(?<![A-Za-z0-9])[A-Za-z]:[\\/](?![\\/])")),
    ("posix home directory",
     # not preceded by a hostname or path character: "site.example/home/x"
     # is a URL route, "/home/x" at the start of a token is a directory
     re.compile(r"(?<![A-Za-z0-9.:_-])/(?:home|Users)/[A-Za-z0-9._-]+")),
    ("UNC share",
     re.compile(r"\\\\[A-Za-z0-9._-]+\\[A-Za-z0-9._$-]+")),
]


def env_rules():
    """The private patterns, built at run time from the environment so that
    this file never holds one. A marker is matched case-insensitively; a root
    is matched with either slash, because the same location written two ways
    is the same location."""
    rules = []
    for raw in (os.environ.get("GRID_PRIVATE_MARKERS") or "").split(";"):
        s = raw.strip()
        if s:
            rules.append(("private marker (from the environment)",
                          re.compile(re.escape(s), re.I)))
    for raw in (os.environ.get("GRID_PRIVATE_ROOTS") or "").split(";"):
        s = raw.strip()
        if s:
            pat = "[\\\\/]".join(re.escape(p) for p in re.split(r"[\\/]+", s)
                                 if p)
            rules.append(("private root (from the environment)",
                          re.compile(pat, re.I)))
    return rules


def tracked():
    """Every file git tracks. Not a directory walk: an untracked scratch file
    is not published, and a tracked file hidden by .gitignore still is."""
    try:
        out = subprocess.run(["git", "-C", ROOT, "ls-files", "-z"],
                             capture_output=True, text=True, timeout=60)
    except Exception as e:
        raise SystemExit("COULD NOT SCAN: git ls-files failed (%s: %s). "
                         "A gate that read nothing is not a pass."
                         % (type(e).__name__, e))
    if out.returncode != 0:
        raise SystemExit("COULD NOT SCAN: git ls-files exit %d. A gate that "
                         "read nothing is not a pass." % out.returncode)
    return [p for p in out.stdout.split("\0") if p]


def scan(files, rules, shape_rules):
    """Locations only. The matched text is deliberately never carried out of
    this function - not into a message, not into a return value."""
    hits, read, skipped = [], 0, 0
    for rel in files:
        if os.path.splitext(rel)[1].lower() in SKIP_EXT:
            skipped += 1
            continue
        p = os.path.join(ROOT, rel.replace("/", os.sep))
        try:
            text = io.open(p, encoding="utf-8", errors="replace").read()
        except Exception:
            skipped += 1
            continue
        read += 1
        use = rules if rel in SHAPE_EXEMPT else rules + shape_rules
        for n, line in enumerate(text.splitlines(), 1):
            for why, rx in use:
                if rx.search(line):
                    hits.append((rel, n, why))
    return hits, read, skipped


def _git(cwd, *args):
    r = subprocess.run(["git", "-C", cwd] + list(args), capture_output=True,
                       text=True, timeout=60,
                       env=dict(os.environ, GIT_AUTHOR_NAME="gate",
                                GIT_AUTHOR_EMAIL="gate@localhost",
                                GIT_COMMITTER_NAME="gate",
                                GIT_COMMITTER_EMAIL="gate@localhost"))
    if r.returncode != 0:
        raise SystemExit("COULD NOT SELF-TEST: git %s exit %d\n%s"
                         % (" ".join(args), r.returncode, r.stderr.strip()))
    return r.stdout


def self_test():
    """Two fixtures in a throwaway repository: one that must fail, one that
    must pass. Returns True only if both outcomes were observed. The dirty
    line is assembled at run time so that this source holds no drive-letter
    path itself."""
    me = os.path.abspath(__file__)
    tmp = tempfile.mkdtemp(prefix="no-private-paths-")
    try:
        os.makedirs(os.path.join(tmp, "scripts"))
        copy = os.path.join(tmp, "scripts", "check_no_private_paths.py")
        shutil.copyfile(me, copy)
        _git(tmp, "init", "-q")
        dirty = os.path.join(tmp, "fixture.txt")
        with io.open(dirty, "w", encoding="utf-8") as fh:
            fh.write("a line naming a drive: " + "Q:" + "\\" + "fixture\n")
        _git(tmp, "add", "-A")
        _git(tmp, "commit", "-q", "-m", "fixture with a private shape")

        def run():
            env = dict(os.environ)
            env.pop("GRID_PRIVATE_MARKERS", None)
            env.pop("GRID_PRIVATE_ROOTS", None)
            r = subprocess.run([sys.executable, copy, "--skip-self-test"],
                               capture_output=True, text=True, timeout=120,
                               env=env, cwd=tmp)
            return r.returncode

        e_dirty = run()
        os.remove(dirty)
        _git(tmp, "add", "-A")
        _git(tmp, "commit", "-q", "-m", "fixture cleaned")
        e_clean = run()
    finally:
        shutil.rmtree(tmp, ignore_errors=True)

    print("SELF-TEST (a throwaway repository, two commits)")
    print("  with one drive-letter line     exit %d, expected 1   %s"
          % (e_dirty, "as expected" if e_dirty == 1 else "WRONG"))
    print("  with that line removed          exit %d, expected 0   %s"
          % (e_clean, "as expected" if e_clean == 0 else "WRONG"))
    ok = (e_dirty == 1 and e_clean == 0)
    print("  %s" % ("both outcomes observed: this gate discriminates"
                    if ok else "NOT BOTH OUTCOMES: this gate has not been "
                    "shown to gate anything"))
    return ok


def main():
    ap = argparse.ArgumentParser(
        description="refuse a private path in a public repository")
    ap.add_argument("--list", action="store_true",
                    help="what this gate enforces, and what it cannot see")
    ap.add_argument("--self-test", action="store_true",
                    help="run the two fixtures and stop")
    ap.add_argument("--skip-self-test", action="store_true",
                    help="scan without the fixtures (used by the self-test "
                         "itself)")
    a = ap.parse_args()

    if a.self_test:
        return 0 if self_test() else 2

    rules = env_rules()
    if a.list:
        print("NO PRIVATE PATHS - what this gate enforces")
        for why, _ in SHAPE_RULES:
            print("  always      %s" % why)
        print("  configured  %d pattern(s) from GRID_PRIVATE_MARKERS and "
              "GRID_PRIVATE_ROOTS" % len(rules))
        if not rules:
            print("              NONE SET. The shape rules still run, but a "
                  "leak\n              that looks like nothing in particular "
                  "will pass.")
        print("\n  WHAT A PASS DOES NOT COVER")
        print("    the history. This reads the working tree only. A path "
              "removed from")
        print("    the tip stays fetchable by commit SHA for anyone who "
              "clones.")
        print("    binary files, and anything git does not track.")
        return 0

    if not a.skip_self_test:
        if not self_test():
            print("\nREFUSED TO SCAN: the gate did not prove it can both pass "
                  "and fail.")
            return 2
        print("")

    files = tracked()
    hits, read, skipped = scan(files, rules, SHAPE_RULES)

    print("NO PRIVATE PATHS")
    print("  %d tracked file(s), %d read, %d skipped" % (len(files), read,
                                                         skipped))
    print("  %d always-on rule(s), %d from the environment"
          % (len(SHAPE_RULES), len(rules)))
    if not rules:
        print("  NOTE: no configured patterns. Set GRID_PRIVATE_MARKERS and "
              "GRID_PRIVATE_ROOTS\n        or this gate can only catch the "
              "generic shapes.")

    if not hits:
        print("\n  CLEAN on the tip. This says nothing about the history.")
        return 0

    print("\n  %d LOCATION(S). The offending text is NOT printed - this "
          "output is\n  public too, and a gate that quotes what it found "
          "publishes it again." % len(hits))
    for rel, n, why in hits:
        print("    %s:%d   %s" % (rel, n, why))
    print("\n  REFUSED. Take the value from the environment instead; "
          "src/paths.py is the pattern.")
    return 1


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