In this section
- Self Test test · chatgpt-audits / automation/202608310322-gpt-reasoning-timer/self_test.py lines 1–233
- Clicker interaction · claude / familiars/clicker.py lines 1–467
Self Test
A test in the automation folder of ChatGPT Audits that uses SHA-256. It is built from the run step (`run`) and the valid payload helper (`valid_payload`).
testchatgpt-audits / automation/202608310322-gpt-reasoning-timer/self_test.py · lines 1–233 of 233 · version 2026-08-31 03:22 · Entry point
- What it does
- It tests its inputs. Defines run, valid_payload, main. Uses libraries __future__, argparse, json, subprocess, sys. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file response.json; JSON file MODEL-REVIEW.json; JSON file MODEL-METADATA.json; command-line arguments.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Deterministic local tests for the GPT reasoning timer controller. It accepts `--renderer`, `--assembler` and `--recorder`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- chatgpt-audits · automation/202608310322-gpt-reasoning-timer · test
- Uses
- __future__, argparse, json, subprocess, sys, tempfile, pathlib
- Used by
- none found
- Produces
- run, valid_payload, main
- Defines here
- run, valid_payload, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310322-gpt-reasoning-timer/self_test.py:1-233 · blob 23bcffda2f59b07574b4bd27cbcca2ef37b16531 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Deterministic local tests for the GPT reasoning timer controller.
REVIEW STATUS: UNREVIEWED.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import tempfile
from pathlib import Path
EXPECTED_RUNTIME_SHA = "37fa67686a9e4ed8d46dcd6a9c80ab524dea840ecaa0a3f7edf8d09f961b97a9"
EXPECTED_KEYS = {
"overall_assessment",
"what_happened",
"good",
"bad",
"recommended_improvement",
"deterministic_tests",
"do_not_change",
"uncertainties",
}
def run(command: list[str], expected: int = 0) -> subprocess.CompletedProcess[str]:
completed = subprocess.run(command, text=True, capture_output=True, check=False)
if completed.returncode != expected:
raise RuntimeError(
f"command returned {completed.returncode}, expected {expected}: {' '.join(command)}\n"
f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
)
return completed
def valid_payload() -> dict[str, object]:
return {
"overall_assessment": "Synthetic renderer self-test.",
"what_happened": [
{
"claim": "A test ran.",
"evidence": "Synthetic fixture.",
"classification": "observed",
}
],
"good": [
{
"claim": "The fixture is bounded.",
"evidence": "Local temporary files only.",
"classification": "observed",
}
],
"bad": [
{
"issue": "This is not production evidence.",
"evidence": "The payload is synthetic.",
"classification": "observed",
"impact": "It cannot support a product claim.",
}
],
"recommended_improvement": {
"kind": "python",
"name": "synthetic_test.py",
"purpose": "Exercise the renderer.",
"evidence_basis": "Local fixture.",
"algorithm": "Parse and validate strict fields.",
"inputs": ["Synthetic JSON"],
"outputs": ["Rendered Markdown"],
"rejection_conditions": ["Missing required field"],
},
"deterministic_tests": [
{"name": "parse", "fixture": "Valid JSON", "assertion": "Exit zero"},
{"name": "schema", "fixture": "Missing key", "assertion": "Reject"},
{"name": "boundary", "fixture": "Temporary output", "assertion": "No product path"},
],
"do_not_change": ["Product repositories"],
"uncertainties": ["None relevant to this synthetic fixture"],
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--renderer", required=True)
parser.add_argument("--assembler", required=True)
parser.add_argument("--recorder", required=True)
parser.add_argument("--schema", required=True)
parser.add_argument("--runtime-source", required=True)
args = parser.parse_args()
renderer = Path(args.renderer)
assembler = Path(args.assembler)
recorder = Path(args.recorder)
schema_path = Path(args.schema)
runtime_path = Path(args.runtime_source)
for path in (renderer, assembler, recorder, schema_path, runtime_path):
if not path.is_file():
raise SystemExit(f"missing controller input: {path}")
schema = json.loads(schema_path.read_text(encoding="utf-8"))
if schema.get("type") != "object" or schema.get("additionalProperties") is not False:
raise SystemExit("response schema is not strict at the root")
if set(schema.get("required", [])) != EXPECTED_KEYS:
raise SystemExit("response schema required keys changed")
source = json.loads(runtime_path.read_text(encoding="utf-8"))
if source.get("version") != "1.0.82" or source.get("sha256") != EXPECTED_RUNTIME_SHA:
raise SystemExit("Copilot runtime source card changed without updating tests")
if source.get("network_classification") != "SUPERVISED_SOURCE_CARDED_RUNTIME_FETCH":
raise SystemExit("Copilot runtime fetch is not source-carded")
with tempfile.TemporaryDirectory(prefix="chatgpt-audits-gpt-timer-") as temporary:
root = Path(temporary)
response = root / "response.json"
prompt = root / "prompt.txt"
evidence = root / "evidence.md"
previous = root / "previous.md"
assembled = root / "assembled.txt"
rendered = root / "rendered"
response.write_text(json.dumps(valid_payload()), encoding="utf-8")
prompt.write_text("synthetic prompt\n", encoding="utf-8")
evidence.write_text("synthetic evidence\n", encoding="utf-8")
previous.write_text("synthetic previous review\n", encoding="utf-8")
run(
[
sys.executable,
str(assembler),
"--sequence",
"1",
"--evidence",
str(evidence),
"--schema",
str(schema_path),
"--previous",
str(previous),
"--output",
str(assembled),
]
)
assembled_text = assembled.read_text(encoding="utf-8")
if "<CURRENT_EVIDENCE_PACKET>" not in assembled_text or "synthetic evidence" not in assembled_text:
raise SystemExit("assembler omitted bounded evidence delimiters")
run(
[
sys.executable,
str(renderer),
"--response",
str(response),
"--prompt",
str(prompt),
"--output",
str(rendered),
"--sequence",
"1",
"--model",
"gpt-5",
"--provider",
"github-copilot-cli",
"--runtime",
"copilot-cli/1.0.82",
]
)
for name in ("MODEL-REVIEW.md", "MODEL-REVIEW.json", "MODEL-METADATA.json"):
if not (rendered / name).is_file():
raise SystemExit(f"renderer did not create {name}")
invalid = valid_payload()
invalid.pop("bad")
response.write_text(json.dumps(invalid), encoding="utf-8")
completed = subprocess.run(
[
sys.executable,
str(renderer),
"--response",
str(response),
"--prompt",
str(prompt),
"--output",
str(root / "invalid"),
"--sequence",
"1",
"--model",
"gpt-5",
"--provider",
"github-copilot-cli",
"--runtime",
"copilot-cli/1.0.82",
],
text=True,
capture_output=True,
check=False,
)
if completed.returncode == 0:
raise SystemExit("renderer accepted an invalid response missing a required key")
run(
[
sys.executable,
str(recorder),
"--output",
str(root / "blocked"),
"--sequence",
"1",
"--provider",
"github-copilot-cli",
"--model",
"gpt-5",
"--runtime",
"copilot-cli/1.0.82",
"--inference-outcome",
"failure",
"--created",
"false",
"--reason",
"SYNTHETIC_BLOCK",
]
)
if (root / "blocked" / "MODEL-REVIEW.json").exists():
raise SystemExit("blocked provider attempt manufactured a validated review")
if not (root / "blocked" / "PROVIDER-BLOCKED.md").is_file():
raise SystemExit("blocked provider attempt was not retained")
print("all deterministic GPT timer self-tests passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())Clicker
A Python command-line tool in the familiars folder of Claude that works with journey world (`journey_world`) and journey summary (`journey_summary`) (units: MW).
interactionclaude / familiars/clicker.py · lines 1–467 of 599 · Entry point · pattern _connect (shared by 2 files)
- What it does
- It fetches data. Defines 16 functions or classes, including Browser, __init__, _connect, send, setup. Uses libraries argparse, json, os, shutil, subprocess. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: 400kV.
- Inputs & outputs
- In: data source: %s:%d; command-line arguments. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Runners (claude).
- What it achieves
- It is built from the browser class (`Browser`), the send step (`send`) and the setup step (`setup`). Eyes on this machine's hardware, not in the model's context. Its code works with 400 kV. It accepts `--port`, `--url` and `--journey`.
- Why it matters
- Run by Runners.
- Application
- claude · familiars · Python CLI
- Uses
- argparse, json, os, shutil, subprocess, sys, tempfile, time
- Used by
- run by Runners (script call)
- Produces
- Browser, journey_world, journey_summary, journey_atlas_rest, journey_maplink, journey_arrival, main
- Defines here
- Browser, __init__, _connect, send, setup, arm, go, js, shot, close, journey_world, journey_summary, journey_atlas_rest
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 familiars/clicker.py:1-467 · blob f0e7dae4f85eebc4350a40b8ba9d797eba0e8ab5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""clicker - eyes on this machine's hardware, not in the model's context.
WHY THIS EXISTS
Three things went wrong today that this single tool answers.
An agent reported a UI as fixed on the strength of coordinates - `overlap: 0 px2`,
`fullyInViewport: true` - on a screen the architect found unusable. A proof reported
104/104 checks passed against the same screen. **A UI cannot be signed off from geometry,
and a check can only test what someone thought to assert.**
Three agents fought over one shared browser: tabs were created and switched under each
other, one agent's tab left its group mid-session, and every measurement taken while a
tab was hidden reproduced the exact rendering failure being investigated. **Each clicker
launches its OWN Chrome, on its OWN port, with its OWN profile.** Two of them on two
ports is the architect's acceptance rule - *"at least two agents on different browsers
clicked and checked that it works"* - mechanised, and they cannot corrupt one another.
And every browser observation cost model tokens. This costs none. It runs here.
python familiars/clicker.py --port 9411 --url https://... --journey world
python familiars/clicker.py --port 9412 --url https://... --journey world --mobile
WHAT IT REFUSES TO DO
It never reports a measurement taken while `document.hidden` is true. That state stalls
MapLibre on this estate and produces confident false failures - one agent lost thirteen
minutes to it and my own first look at the Atlas was invalid for the same reason. If the
page will not come to the front, the clicker says so and fails rather than guessing.
It reports what it observed. It does not diagnose. The eyes are not the mind.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
import websocket
CHROME = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
class Browser:
"""One Chrome, one port, one profile. Nothing shared with anybody."""
def __init__(self, port, mobile=False, headless=True):
self.port = port
self.mobile = mobile
self.profile = tempfile.mkdtemp(prefix='clicker-%d-' % port)
args = [CHROME,
'--remote-debugging-port=%d' % port,
# Chrome 152 rejects the CDP websocket without this and says so
# clearly - which only became visible once its stderr stopped
# going to DEVNULL. The symptom was 'did not expose a page'.
'--remote-allow-origins=*',
'--user-data-dir=' + self.profile,
'--no-first-run', '--no-default-browser-check',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'about:blank']
if headless:
args.insert(1, '--headless=new')
# Chrome's own words are kept. Swallowing them into DEVNULL meant a
# launch that died instantly was polled for thirty seconds and reported
# as "did not expose a page", which named the symptom and hid the cause.
self._log = tempfile.NamedTemporaryFile(
prefix='clicker-%d-' % port, suffix='.log', delete=False)
self.proc = subprocess.Popen(args, stdout=self._log, stderr=self._log)
self.ws = None
self._id = 0
self._connect()
def _connect(self, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
# Chrome binds IPv4 or IPv6 depending on what is free. When 127.0.0.1
# was already held it listened on [::1] alone and the IPv4 probe saw
# nothing, which read as "no page" rather than "wrong stack".
for host in ('127.0.0.1', '[::1]'):
try:
with urllib.request.urlopen(
'http://%s:%d/json' % (host, self.port), timeout=2) as r:
tabs = json.load(r)
page = [t for t in tabs if t.get('type') == 'page']
if page:
self.ws = websocket.create_connection(
page[0]['webSocketDebuggerUrl'], timeout=90,
origin='http://%s:%d' % (host, self.port))
return
except Exception:
pass
if self.proc.poll() is not None:
self._log.flush()
with open(self._log.name, 'r', errors='replace') as fh:
said = fh.read().strip()[-400:]
raise RuntimeError('chrome exited %s before serving port %d: %s'
% (self.proc.returncode, self.port,
said or '(said nothing)'))
time.sleep(0.4)
self._log.flush()
with open(self._log.name, 'r', errors='replace') as fh:
said = fh.read().strip()[-400:]
raise RuntimeError('chrome did not expose a page on port %d in %ss: %s'
% (self.port, timeout, said or '(said nothing)'))
def send(self, method, **params):
self._id += 1
self.ws.send(json.dumps({'id': self._id, 'method': method, 'params': params}))
while True:
msg = json.loads(self.ws.recv())
if msg.get('id') == self._id:
if 'error' in msg:
raise RuntimeError('%s: %s' % (method, msg['error']))
return msg.get('result', {})
def setup(self):
self.send('Page.enable')
self.send('Runtime.enable')
if self.mobile:
self.send('Emulation.setDeviceMetricsOverride', width=393, height=852,
deviceScaleFactor=3, mobile=True)
self.send('Emulation.setUserAgentOverride', userAgent=(
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) '
'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 '
'Safari/604.1'))
self.send('Emulation.setTouchEmulationEnabled', enabled=True,
maxTouchPoints=5)
self.send('Emulation.setEmitTouchEventsForMouse', enabled=True,
configuration='mobile')
else:
self.send('Emulation.setDeviceMetricsOverride', width=1400, height=900,
deviceScaleFactor=1, mobile=False)
def arm(self):
"""Listeners must exist BEFORE the page's own scripts run.
The first version installed them after navigation and therefore caught
nothing thrown during load - which is exactly the window where a map
fails. Page.addScriptToEvaluateOnNewDocument runs first, every time."""
self.send('Page.addScriptToEvaluateOnNewDocument', source=(
"window.__errs=[];"
"addEventListener('error',e=>window.__errs.push("
" (e.message||'')+' @'+(e.filename||'').split('/').pop()+':'+(e.lineno||0)));"
"addEventListener('unhandledrejection',e=>window.__errs.push("
" 'promise: '+((e.reason&&e.reason.message)||e.reason)));"
"window.__log=[];"
"['warn','error'].forEach(k=>{const o=console[k].bind(console);"
" console[k]=(...a)=>{window.__log.push(k+': '+a.map(String).join(' ').slice(0,220));o(...a);};});"
))
def go(self, url, settle=6.0):
self.send('Page.navigate', url=url)
time.sleep(settle)
try:
self.send('Page.bringToFront')
except Exception:
pass
def js(self, expr):
r = self.send('Runtime.evaluate', expression=expr, awaitPromise=True,
returnByValue=True)
if r.get('exceptionDetails'):
return {'_error': str(r['exceptionDetails'].get('text'))[:160]}
return r.get('result', {}).get('value')
def shot(self, path):
r = self.send('Page.captureScreenshot', format='png')
import base64
with open(path, 'wb') as fh:
fh.write(base64.b64decode(r['data']))
return path
def close(self):
try:
if self.ws:
self.ws.close()
except Exception:
pass
try:
self.proc.terminate()
self.proc.wait(timeout=10)
except Exception:
try:
self.proc.kill()
except Exception:
pass
shutil.rmtree(self.profile, ignore_errors=True)
# ── journeys ────────────────────────────────────────────────────────────────
PROBE_VISIBLE = "({hidden: document.hidden, w: innerWidth, h: innerHeight})"
def journey_world(b, shots_dir):
"""Open the world, open every menu, click through it, and say what happened."""
out = {'steps': [], 'shots': []}
vis = b.js(PROBE_VISIBLE)
out['viewport'] = vis
if not isinstance(vis, dict) or vis.get('hidden') is not False:
out['ABORT'] = ('document.hidden was not false - every measurement from here '
'would be worthless on this product')
return out
out['title'] = b.js("document.title")
out['menus'] = b.js(
"[...document.querySelectorAll('#bar .t')].map(e=>e.textContent.trim())")
out['hud'] = b.js(
"({fps:(document.getElementById('fps')||{}).textContent,"
" circuits:(document.getElementById('nlines')||{}).textContent,"
" carriers:(document.getElementById('nparts')||{}).textContent,"
" cores:(document.getElementById('cores')||{}).textContent,"
" gpu:(document.getElementById('gpu')||{}).textContent})")
out['map_canvas'] = b.js(
"(()=>{const c=document.querySelector('#map canvas');"
"if(!c)return null;const r=c.getBoundingClientRect();"
"return Math.round(r.width)+'x'+Math.round(r.height)+' @'+Math.round(r.top);})()")
out['shots'].append(b.shot(os.path.join(shots_dir, 'world-01-open.png')))
# open each menu in turn and record what is inside it
names = out['menus'] or []
contents = {}
for i, name in enumerate(names):
b.js("document.querySelectorAll('#bar .t')[%d].click()" % i)
time.sleep(0.35)
contents[name] = b.js(
"[...document.querySelectorAll('#bar .m.open .p > *')]"
".map(e=>e.textContent.trim()).filter(Boolean)")
if i == 0:
out['shots'].append(b.shot(os.path.join(shots_dir, 'world-02-menu.png')))
out['menu_contents'] = contents
# only one open at a time?
out['one_open_at_a_time'] = b.js(
"document.querySelectorAll('#bar .m.open').length")
# does a click elsewhere close it? (self-minimising)
b.js("document.body.click()")
time.sleep(0.3)
out['closes_on_outside_click'] = b.js(
"document.querySelectorAll('#bar .m.open').length === 0")
# is it alive? sample the frame counter twice
f1 = b.js("(document.getElementById('fps')||{}).textContent")
time.sleep(2.0)
f2 = b.js("(document.getElementById('fps')||{}).textContent")
out['fps_samples'] = [f1, f2]
out['is_moving'] = bool(f1 and f2 and f1 != '—' and f2 != '—')
out['console_errors'] = b.js("(window.__errs||[]).slice(0,6)")
out['console_log'] = b.js("(window.__log||[]).slice(0,6)")
out['shots'].append(b.shot(os.path.join(shots_dir, 'world-03-after.png')))
return out
SUMMARY_READ = """(() => {
const t = e => e ? (e.textContent || '').trim() : null;
const meta = document.getElementById('resultsMeta');
const arc = id => { const c = document.getElementById(id);
return c && c.toDataURL ? c.toDataURL().slice(-48) : null; };
return {
counter: t(meta),
filteredCount: meta ? meta.dataset.filteredCount : null,
totalCount: meta ? meta.dataset.totalCount : null,
v1: t(document.getElementById('v1')),
v2: t(document.getElementById('v2')),
v3: t(document.getElementById('v3')),
arcs: [arc('g1'), arc('g2'), arc('g3')].join('|'),
exportMeta: t(document.getElementById('exportMeta')),
rows: document.querySelectorAll('#results tbody tr').length,
widerOptions: document.getElementById('widerTechnology')
? document.getElementById('widerTechnology').options.length : 0
};
})()"""
def journey_summary(b, shots_dir):
"""Pipeline News: does one summary drive every surface it is supposed to?
The defect this exists to catch is silent. A wider-fleet cut writes the
three gauge NUMBERS and nothing else, so the record counter, the gauge
ARCS and the CSV keep the previous technology's answer while the screen
looks correct. Nothing throws, nothing logs, and the export leaves the
building with the wrong rows under a confident heading.
So this reads all five surfaces before and after a technology switch and
reports both states. It does not decide whether the product is right -
it makes the divergence visible. The eyes are not the mind."""
out = {'steps': [], 'shots': []}
vis = b.js(PROBE_VISIBLE)
out['viewport'] = vis
if not isinstance(vis, dict) or vis.get('hidden') is not False:
out['ABORT'] = ('document.hidden was not false - a backgrounded tab stalls '
'this estate and every reading below would be worthless')
return out
out['title'] = b.js('document.title')
out['before'] = b.js(SUMMARY_READ)
out['shots'].append(b.shot(os.path.join(shots_dir, 'summary-01-spine.png')))
if not out['before'] or not out['before'].get('widerOptions'):
out['ABORT'] = 'no #widerTechnology control on this page - nothing to switch'
return out
# pick the wider-fleet technology by NAME, so the reading names its subject
out['technology'] = b.js(
"(()=>{const s=document.getElementById('widerTechnology');"
"s.selectedIndex=1;s.dispatchEvent(new Event('change',{bubbles:true}));"
"return s.options[1].textContent.trim();})()")
time.sleep(1.2)
out['after'] = b.js(SUMMARY_READ)
out['shots'].append(b.shot(os.path.join(shots_dir, 'summary-02-wider.png')))
# The export is the surface that leaves the building, so it is the one
# surface a reading of the screen cannot cover. Clicking it is safe ONLY
# where the seam is installed: there `downloadCsv` answers in words and
# returns before a blob exists. On a release without the seam the same
# click writes a real file to disk, so this is opt-in per run rather than
# something the journey decides for itself.
if os.environ.get('CLICKER_EXPORT_CLICK') == '1':
b.js("document.getElementById('exportInline').click()")
time.sleep(1.0)
out['export_after_click'] = b.js(
"(()=>{const m=document.getElementById('exportMeta');return m?{"
"text:(m.textContent||'').trim(),"
"declined:m.classList.contains('is-declined'),"
"missing:m.dataset.exportDeclinedColumns||null}:null;})()")
out['shots'].append(b.shot(os.path.join(shots_dir, 'summary-03-export.png')))
a, c = out['before'], out['after']
out['moved'] = {k: (a.get(k) != c.get(k))
for k in ('counter', 'filteredCount', 'totalCount',
'v1', 'v2', 'v3', 'arcs', 'exportMeta')}
out['counter_and_gauges_disagree'] = bool(
c.get('counter') and c.get('v3') and c.get('v3') not in c.get('counter'))
out['console_errors'] = b.js('(window.__errs||[]).slice(0,6)')
out['console_log'] = b.js('(window.__log||[]).slice(0,6)')
return out
# every control a reader could reach for, and whether it has a box to click
CONTROLS = r"""(() => {
const els = [...document.querySelectorAll('button, a[role=button], input[type=checkbox], select, [role=button]')];
const zero = [], live = [];
for (const el of els) {
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
const name = (el.id ? '#' + el.id : (el.textContent || el.getAttribute('aria-label') || el.tagName)
.replace(/\s+/g, ' ').trim().slice(0, 28)) || el.tagName;
const hidden = cs.display === 'none' || cs.visibility === 'hidden';
(r.width < 1 || r.height < 1 ? zero : live).push(
name + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + (hidden ? ' display:none' : ''));
}
return {live: live.length, zero: zero.length, zero_named: zero.slice(0, 20)};
})()"""
# how much of the screen is the product, and how much is its controls
SCREEN_SHARE = r"""(() => {
const W = innerWidth, H = innerHeight, cols = 40, rows = 80;
const canvas = document.querySelector('canvas.maplibregl-canvas, #map canvas, canvas');
let map = 0, chrome = 0, none = 0;
const owners = {};
for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
const x = (i + 0.5) * W / cols, y = (j + 0.5) * H / rows;
const el = document.elementFromPoint(x, y);
if (!el) { none++; continue; }
if (canvas && (el === canvas || el.contains(canvas))) { map++; continue; }
chrome++;
let node = el, name = '';
while (node && node !== document.body) {
if (node.id) { name = '#' + node.id; break; }
if (node.className && typeof node.className === 'string' && node.className.trim()) {
name = '.' + node.className.trim().split(/\s+/)[0]; break;
}
node = node.parentElement;
}
name = name || el.tagName.toLowerCase();
owners[name] = (owners[name] || 0) + 1;
}
const total = cols * rows;
return {
viewport: W + 'x' + H,
map_percent: +(100 * map / total).toFixed(1),
chrome_percent: +(100 * chrome / total).toFixed(1),
nothing_percent: +(100 * none / total).toFixed(1),
chrome_owners: Object.entries(owners).sort((a, b) => b[1] - a[1]).slice(0, 12)
.map(([k, v]) => k + ' ' + (100 * v / total).toFixed(1) + '%')
};
})()"""
BANDS = r"""(() => {
const out = [];
for (const el of document.querySelectorAll('body *')) {
const cs = getComputedStyle(el);
if (!['fixed', 'absolute', 'sticky'].includes(cs.position)) continue;
if (cs.display === 'none' || cs.visibility === 'hidden' || +cs.opacity === 0) continue;
const r = el.getBoundingClientRect();
if (r.width < 24 || r.height < 12) continue;
if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth) continue;
if (el.querySelector('canvas')) continue;
out.push({
what: (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string'
? '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.') : ''),
rect: [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)],
text: (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 70)
});
}
return out.sort((a, b) => a.rect[1] - b.rect[1]).slice(0, 24);
})()"""
def journey_atlas_rest(b, shots_dir):
"""What does the Atlas look like when nobody has touched it?
The directive of 2026-09-03 said roughly sixty per cent of the screen is
menu before any content, and nobody had ever measured it: every check that
night asked whether the answer was REACHABLE, which is a coordinate
question that got fixed, and never asked how much of the screen the product
got, which is the same kind of question and just as easy.
So this samples 3,200 points of the viewport and asks the DOM which element
is on top at each one. A point whose topmost element is the map canvas is
product. Everything else is chrome. It reports the split and names the
elements holding the chrome, and it repeats both on a deep-link arrival,
where the identity is known to appear more than once."""
out = {'shots': []}
vis = b.js(PROBE_VISIBLE)
out['viewport'] = vis
if not isinstance(vis, dict) or vis.get('hidden') is not False:
out['ABORT'] = 'document.hidden was not false - MapLibre stalls and every reading lies'
return out
time.sleep(3.0) # the map draws before anything is measured
out['at_rest'] = b.js(SCREEN_SHARE)
out['bands_at_rest'] = b.js(BANDS)
out['search_value_at_rest'] = b.js(
"(()=>{const i=[...document.querySelectorAll('input')]"
".filter(e=>e.offsetParent!==null&&e.type!=='hidden');"
"return i.map(e=>({ph:e.placeholder||'',v:e.value||''}));})()")
out['shots'].append(b.shot(os.path.join(shots_dir, 'atlas-01-rest.png')))
out['controls_at_rest'] = b.js(CONTROLS)
# the panel must come BACK. A minimise that cannot be undone is a deletion.
out['toggle_label'] = b.js(
"(document.getElementById('gridatlas-dash-toggle')||{}).textContent")
b.js("(document.getElementById('gridatlas-dash-toggle')||{click(){}}).click()")
time.sleep(1.2)
out['after_toggle'] = b.js(SCREEN_SHARE)
out['controls_after_toggle'] = b.js(CONTROLS)
out['toggle_label_after'] = b.js(
"(document.getElementById('gridatlas-dash-toggle')||{}).textContent")
out['shots'].append(b.shot(os.path.join(shots_dir, 'atlas-02-expanded.png')))
out['console_errors'] = b.js('(window.__errs||[]).slice(0,6)')
return out