GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/uxtests

Journeys and 1 more file

A Python command-line tool in the uxtests folder of Cosmic that reads cables, using haversine. It maps live (`map_live`), adds port (`add_port`) and checks GitHub (`check_github`).

595 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1166 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. Journeys render · cosmic / tools/explore/uxtests/journeys.py lines 1–532
  2. Ownership ingest · cosmic / tools/explore/verify/ownership.py lines 1–63

Journeys

A Python command-line tool in the uxtests folder of Cosmic that reads cables, using haversine. It maps live (`map_live`), adds port (`add_port`) and checks GitHub (`check_github`).

rendercosmic / tools/explore/uxtests/journeys.py · lines 1–532 of 532 · Entry point · pattern QuietHandler (shared by 3 files)

What it does
It loads cables. Defines 27 functions or classes, including local_targets, QuietHandler, log_message, end_headers, free_port. Uses libraries argparse, json, mimetypes, os, re. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: DuckDB queries; command-line arguments. Out: JSON file results.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Walk Vikram's journeys on phone, tablet, laptop and desktop, screenshot every step, measure UX faults. It accepts `--out`, `--only` and `--viewports`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/uxtests · Python CLI
Uses
argparse, json, mimetypes, os, re, socket, subprocess, sys
Used by
none found
Produces
local_targets, QuietHandler, free_port, serve, map_live, install_routes, Walker, LinkChecker, check_github, first, explore_journey, generic_journey
Defines here
local_targets, QuietHandler, log_message, end_headers, free_port, serve, map_live, install_routes, handler, Walker, __init__, tap, tap_nav, goto, settle, step, fail, scroll_end, LinkChecker, __init__, add_port, __call__, check_github, first, explore_journey, generic_journey, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/uxtests/journeys.py:1-532 · blob a155f1baf63fdc8a3234d951a53d6019c3277a74 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Walk Vikram's journeys on phone, tablet, laptop and desktop, screenshot every step, measure UX faults.

Usage:
    python3 journeys.py [--out /tmp/vk/9/runs] [--only live,site7,...] [--viewports phone,tablet,...]

Journeys
  live    https://globalgrid2050.com/ -> section 13 Explore Code -> Explore Code index -> topic -> repo ->
          section -> GitHub link (checked, not followed) -> back; Visualiser; Search "haversine"; Words A-Z;
          llms.txt; journeys/a.html.  The real hosts are not reachable from the test sandbox, so the browser
          keeps the real URLs and Playwright answers them from local copies (see LIVE_* below).
  site7 / site8   the same Explore Code journey on local builds served with python -m http.server.
  clarity / kuiper / chess / lab   generic walk: open, scroll, open the first internal links, tap buttons.

For every step it records: console errors, page errors, failed requests, horizontal overflow (and the
elements causing it), tap targets under 44 CSS px, text under 14 px on phone, inputs under 16 px (iOS
zooms on focus), interactive elements off-screen, load time, broken images and broken internal links.
Results: <out>/<stamp>/results.json and screenshots under <out>/<stamp>/shots/; <out>/latest -> <stamp>.
Chromium only: WebKit could not be installed in the sandbox, so the phone is Chromium with the
"iPhone 13" descriptor (Safari UA, touch, DPR 3, isMobile).
"""
import argparse, json, mimetypes, os, re, socket, subprocess, sys, time, traceback, urllib.parse
from functools import partial
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
import threading

from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout

HERE = os.path.dirname(os.path.abspath(__file__))
LIVE_HOME_ROOT = os.environ.get('LIVE_HOME_ROOT', '/tmp/vk/9/mirror/hp')          # globalgrid2050-homepage @ pinned commit
LIVE_EXPLORE_ROOT = os.environ.get('LIVE_EXPLORE_ROOT', '/tmp/site7/explore-code')  # stand-in for code.globalgrid2050.com/explore-code
DUCKDB_ESM = '/tmp/vk/9/duckdb/duckdb-esm.mjs'
DUCKDB_DIST = '/tmp/vk/9/duckdb/node_modules/@duckdb/duckdb-wasm/dist'

VIEWPORTS = {
    'phone':   dict(label='iPhone 13 (390x844)', base='iPhone 13', viewport={'width': 390, 'height': 844},
                    screen={'width': 390, 'height': 844}),
    'tablet':  dict(label='iPad portrait (820x1180)', base='iPad (gen 7)', viewport={'width': 820, 'height': 1180},
                    screen={'width': 820, 'height': 1180}),
    'laptop':  dict(label='Laptop (1366x768)', viewport={'width': 1366, 'height': 768}, device_scale_factor=1),
    'desktop': dict(label='Desktop (1920x1080)', viewport={'width': 1920, 'height': 1080}, device_scale_factor=1),
}
TOUCH = {'phone', 'tablet'}

def local_targets():
    """Local builds as they exist right now: name -> (root to serve, start path, kind)."""
    t = {}
    for name, root in (('site7', '/tmp/site7'), ('site8', '/tmp/site8')):
        if os.path.isfile(os.path.join(root, 'explore-code', 'index.html')):
            t[name] = (root, '/explore-code/index.html', 'explore')
        elif os.path.isfile(os.path.join(root, 'index.html')):
            t[name] = (root, '/index.html', 'explore' if os.path.isdir(os.path.join(root, 'topics')) else 'generic')
    for name, root in (('clarity', '/tmp/vk/2/clarity'), ('kuiper', '/tmp/vk/3/kuiper'), ('chess', '/tmp/vk/6/chess')):
        if os.path.isdir(root):
            start = '/index.html' if os.path.isfile(os.path.join(root, 'index.html')) else None
            if not start:
                htmls = sorted(f for f in os.listdir(root) if f.endswith('.html'))
                start = '/' + htmls[0] if htmls else '/'
            t[name] = (root, start, 'generic')
    if os.path.isfile('/tmp/lab-out/lab.html'):
        t['lab'] = ('/tmp/lab-out', '/lab.html', 'generic')
    return t

# ---------------------------------------------------------------- serving
class QuietHandler(SimpleHTTPRequestHandler):
    def log_message(self, *a): pass
    def end_headers(self):
        self.send_header('Cache-Control', 'no-store')
        super().end_headers()

def free_port():
    s = socket.socket(); s.bind(('127.0.0.1', 0)); p = s.getsockname()[1]; s.close(); return p

def serve(root):
    port = free_port()
    httpd = ThreadingHTTPServer(('127.0.0.1', port), partial(QuietHandler, directory=root))
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    return httpd, port

# Routed hosts for the "live" journey: URL prefix -> local root
LIVE_MAP = [
    ('https://globalgrid2050.com/', LIVE_HOME_ROOT),
    ('https://www.globalgrid2050.com/', LIVE_HOME_ROOT),
    ('https://code.globalgrid2050.com/explore-code/', LIVE_EXPLORE_ROOT),
    ('https://code.globalgrid2050.com/explore-code/', LIVE_EXPLORE_ROOT),
]

def map_live(url):
    u = url.split('#')[0].split('?')[0]
    for pre, root in LIVE_MAP:
        if u.startswith(pre) or u + '/' == pre:
            rel = urllib.parse.unquote(u[len(pre):]) if u.startswith(pre) else ''
            p = os.path.join(root, rel)
            if os.path.isdir(p) or rel == '' or rel.endswith('/'):
                p = os.path.join(p, 'index.html')
            return p
    return None

CT = {'.txt': 'text/plain; charset=utf-8', '.html': 'text/html; charset=utf-8', '.json': 'application/json',
      '.css': 'text/css', '.js': 'application/javascript', '.mjs': 'application/javascript',
      '.parquet': 'application/octet-stream', '.xml': 'application/xml', '.wasm': 'application/wasm',
      '.md': 'text/markdown; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png'}

def install_routes(ctx, external_log):
    def handler(route):
        url = route.request.url
        if url.startswith('http://127.0.0.1') or url.startswith('data:') or url.startswith('blob:'):
            return route.continue_()
        if url.startswith('https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/'):
            rest = url.split('@1.29.0/', 1)[1].split('?')[0]
            p = DUCKDB_ESM if rest.startswith('+esm') else os.path.join(DUCKDB_DIST, rest.replace('dist/', '', 1))
            if os.path.isfile(p):
                return route.fulfill(path=p, headers={'Content-Type': CT.get(os.path.splitext(p)[1], 'application/octet-stream'),
                                                      'Access-Control-Allow-Origin': '*'})
        p = map_live(url)
        if p is not None:
            if os.path.isfile(p):
                return route.fulfill(path=p, headers={'Content-Type': CT.get(os.path.splitext(p)[1].lower(),
                                     mimetypes.guess_type(p)[0] or 'application/octet-stream'), 'Access-Control-Allow-Origin': '*'})
            return route.fulfill(status=404, body='Not Found (no such file in the mirror)', headers={'Content-Type': 'text/plain'})
        external_log.append(url)
        return route.abort('blockedbyclient')
    ctx.route('**/*', handler)

# ---------------------------------------------------------------- measuring
METRICS_JS = r"""
(isPhone) => {
  const vw = window.innerWidth, vh = window.innerHeight, de = document.documentElement, body = document.body;
  const sw = Math.max(de.scrollWidth, body ? body.scrollWidth : 0);
  const sel = el => { let s = el.tagName.toLowerCase(); if (el.id) s += '#' + el.id;
    else if (typeof el.className === 'string' && el.className.trim()) s += '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.');
    const t = (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || '').trim().replace(/\s+/g, ' ').slice(0, 40);
    return t ? s + ' "' + t + '"' : s; };
  const visible = el => { const cs = getComputedStyle(el); if (cs.visibility === 'hidden' || cs.display === 'none' || +cs.opacity === 0) return false;
    const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
  const scrollAncestor = el => { for (let p = el.parentElement; p && p !== body && p !== de; p = p.parentElement) {
    const ox = getComputedStyle(p).overflowX; if (ox === 'auto' || ox === 'scroll' || ox === 'hidden' || ox === 'clip') return p; } return null; };
  const out = {vw, vh, scrollWidth: sw, scrollHeight: Math.max(de.scrollHeight, body ? body.scrollHeight : 0),
    overflow: sw > vw + 1, overflowBy: Math.max(0, sw - vw), title: document.title, url: location.href,
    viewportMeta: !!document.querySelector('meta[name=viewport]'), offenders: [], smallTaps: [], smallText: [], smallCode: [],
    zoomInputs: [], offscreen: [], brokenImages: [], links: [], github: [], mojibake: false, textChars: 0};
  if (!body) return out;
  if (out.overflow) {
    for (const el of body.querySelectorAll('*')) { const r = el.getBoundingClientRect();
      if (r.right > vw + 1 && r.width > 0 && visible(el) && !scrollAncestor(el)) {
        const p = el.parentElement, pr = p ? p.getBoundingClientRect() : null;
        if (!pr || pr.right <= vw + 1 || p === body) out.offenders.push({sel: sel(el), right: Math.round(r.right), width: Math.round(r.width)}); }
      if (out.offenders.length >= 12) break; } }
  const inter = body.querySelectorAll('a[href],button,input:not([type=hidden]),select,textarea,summary,[role=button],[role=tab],label[for]');
  for (const el of inter) { if (!visible(el)) continue; const r = el.getBoundingClientRect();
    if (r.width < 44 || r.height < 44) {
      let inline = false;
      if (el.tagName === 'A') { const p = el.closest('p,li,dd,td,th,figcaption,blockquote,span.k,small,pre');
        if (p && (p.innerText || '').trim().length > (el.innerText || '').trim().length + 3) inline = true; }
      // a small control whose tappable parent (label/summary/li link) is big enough is fine
      out.smallTaps.push({sel: sel(el), w: Math.round(r.width), h: Math.round(r.height), inline}); }
    const sa = scrollAncestor(el);
    if ((r.right > vw + 1 || r.left < -1) && !sa) out.offscreen.push({sel: sel(el), left: Math.round(r.left), right: Math.round(r.right)});
    if (/^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName)) { const fs = parseFloat(getComputedStyle(el).fontSize);
      if (fs < 16) out.zoomInputs.push({sel: sel(el), px: fs}); } }
  if (isPhone) { const seen = new Set(); const w = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
    let n, count = 0; while ((n = w.nextNode()) && count < 20000) { count++;
      const t = n.nodeValue.trim(); if (t.length < 2) continue; const el = n.parentElement; if (!el || seen.has(el)) continue; seen.add(el);
      if (el.closest('script,style,noscript,svg,canvas')) continue; if (!visible(el)) continue;
      const fs = parseFloat(getComputedStyle(el).fontSize);
      if (fs < 14) { const rec = {sel: sel(el), px: fs, chars: t.length};
        (el.closest('pre,code') ? out.smallCode : out.smallText).push(rec); } } }
  for (const im of body.querySelectorAll('img')) if (im.complete && im.naturalWidth === 0 && im.getAttribute('src')) out.brokenImages.push(im.currentSrc || im.src);
  const L = new Set();
  for (const a of body.querySelectorAll('a[href]')) { const h = a.href; if (!h || h.startsWith('javascript:') || h.startsWith('mailto:')) continue;
    if (/^https:\/\/github\.com\//.test(h)) out.github.push(h); L.add(h.split('#')[0]); if (L.size > 600) break; }
  out.links = [...L];
  const txt = body.innerText || ''; out.textChars = txt.length; out.mojibake = /â€|Ã[\u0080-¿]/.test(txt.slice(0, 200000));
  const nav = performance.getEntriesByType('navigation')[0];
  if (nav) out.timing = {dcl: Math.round(nav.domContentLoadedEventEnd), load: Math.round(nav.loadEventEnd), bytes: nav.transferSize || nav.encodedBodySize || 0};
  return out;
}
"""

class Walker:
    def __init__(self, page, vpname, target, shotdir, link_checker):
        self.page, self.vp, self.target, self.shotdir = page, vpname, target, shotdir
        self.check_link = link_checker
        self.steps, self.n = [], 0
        self.console, self.pageerrors, self.failed = [], [], []
        page.on('console', lambda m: self.console.append({'type': m.type, 'text': m.text[:500], 'url': (m.location or {}).get('url', '')}) if m.type in ('error', 'warning') else None)
        page.on('pageerror', lambda e: self.pageerrors.append(str(e)[:500]))
        page.on('requestfailed', lambda r: self.failed.append({'url': r.url, 'err': (r.failure or '')}))
        page.on('response', lambda r: self.failed.append({'url': r.url, 'err': 'HTTP %d' % r.status}) if r.status >= 400 else None)
        self.t0 = time.time()

    def tap(self, loc):
        loc.scroll_into_view_if_needed(timeout=5000)
        if self.vp in TOUCH: loc.tap(timeout=8000)
        else: loc.click(timeout=8000)

    def tap_nav(self, loc, timeout=30000):
        t = time.time()
        with self.page.expect_navigation(timeout=timeout, wait_until='load'):
            self.tap(loc)
        self.settle(); return time.time() - t

    def goto(self, url, timeout=45000):
        t = time.time(); resp = self.page.goto(url, wait_until='load', timeout=timeout); self.settle()
        return time.time() - t, resp

    def settle(self, ms=600):
        try: self.page.wait_for_load_state('networkidle', timeout=4000)
        except PWTimeout: pass
        self.page.wait_for_timeout(ms)

    def step(self, name, note='', elapsed=None, ok=True, problem='', extra=None):
        self.n += 1
        fn = '%02d-%s.png' % (self.n, re.sub(r'[^a-z0-9]+', '-', name.lower()).strip('-')[:50])
        path = os.path.join(self.shotdir, fn)
        try: self.page.screenshot(path=path, timeout=20000)
        except Exception as e: path = None; problem = (problem + '; screenshot failed: ' + str(e)[:120]).strip('; ')
        try: m = self.page.evaluate(METRICS_JS, self.vp == 'phone')
        except Exception as e: m = {'error': str(e)[:300], 'url': self.page.url, 'links': [], 'github': []}
        broken = [l for l in m.get('links', []) if self.check_link(l) is False]
        m['brokenLinks'] = broken[:50]; m['linkCount'] = len(m.get('links', [])); m.pop('links', None)
        rec = dict(step=self.n, name=name, note=note, ok=ok, problem=problem, shot=path, url=self.page.url,
                   elapsed=round(elapsed, 2) if elapsed is not None else None, metrics=m,
                   console=self.console, pageerrors=self.pageerrors, failed=self.failed, extra=extra or {})
        self.console, self.pageerrors, self.failed = [], [], []
        self.steps.append(rec); return rec

    def fail(self, name, exc):
        return self.step(name, ok=False, problem='%s: %s' % (type(exc).__name__, str(exc).splitlines()[0][:300]))

    def scroll_end(self, name):
        self.page.evaluate('window.scrollTo(0, document.documentElement.scrollHeight)'); self.page.wait_for_timeout(400)
        r = self.step(name); self.page.evaluate('window.scrollTo(0,0)'); return r

# ---------------------------------------------------------------- link checking
class LinkChecker:
    """Internal links only: live hosts map to the mirror roots; 127.0.0.1:<port> maps to the served root."""
    def __init__(self):
        self.cache, self.ports = {}, {}
    def add_port(self, port, root): self.ports[port] = root
    def __call__(self, url):
        if url in self.cache: return self.cache[url]
        res = None
        p = map_live(url)
        if p is None:
            m = re.match(r'http://127\.0\.0\.1:(\d+)(/[^?#]*)', url)
            if m and int(m.group(1)) in self.ports:
                rel = urllib.parse.unquote(m.group(2)).lstrip('/')
                p = os.path.join(self.ports[int(m.group(1))], rel)
                if os.path.isdir(p): p = os.path.join(p, 'index.html')
        if p is not None:
            # links to homepage areas outside the mirrored files (other apps) are not checkable
            if p.startswith(LIVE_HOME_ROOT) and not os.path.exists(p) and not url.rstrip('/').endswith('globalgrid2050.com'):
                res = None
            else:
                res = os.path.exists(p)
        self.cache[url] = res; return res

GH = re.compile(r'^https://github\.com/(Ventusltd)/([^/]+)/blob/([0-9a-f]{7,40})/([^#]+)(?:#L(\d+)(?:-L(\d+))?)?$')
_ghcache = {}
def check_github(url):
    """Validate the shape; confirm the file exists at that commit via the repo-scoped contents API."""
    m = GH.match(url)
    if not m: return {'url': url, 'shape_ok': False}
    key = m.group(2, 3, 4)
    if key not in _ghcache:
        try:
            r = subprocess.run(['gh', 'api', '-H', 'Accept: application/vnd.github.object',
                                'repos/%s/%s/contents/%s?ref=%s' % (m.group(1), m.group(2), m.group(4), m.group(3)),
                                '--jq', '.size'], capture_output=True, text=True, timeout=30)
            _ghcache[key] = r.stdout.strip() if r.returncode == 0 else ('ERR ' + (r.stderr or r.stdout).strip()[:160])
        except Exception as e:
            _ghcache[key] = 'ERR ' + str(e)[:100]
    return {'url': url, 'shape_ok': True, 'repo': m.group(2), 'commit': m.group(3), 'path': m.group(4),
            'lines': [m.group(5), m.group(6)], 'api': _ghcache[key]}

# ---------------------------------------------------------------- journeys
def first(page, selectors):
    for s in selectors:
        loc = page.locator(s)
        try:
            n = loc.count()
        except Exception:
            continue
        for i in range(min(n, 8)):
            el = loc.nth(i)
            try:
                if el.is_visible(): return el
            except Exception: pass
        if n: return loc.first
    return None

def explore_journey(w, base, homepage=None):
    """base: Explore Code root URL ending in '/'.  homepage: start at the GlobalGrid2050 homepage first."""
    page = w.page
    if homepage:
        try:
            el, resp = w.goto(homepage)
            w.step('Homepage', 'globalgrid2050.com as it loads', el, extra={'status': resp.status if resp else None})
            sec = page.locator('details#explore-code')
            if sec.count() == 0:
                w.step('Find section 13', ok=False, problem='details#explore-code not found on homepage')
            else:
                summ = sec.locator('summary').first
                summ.scroll_into_view_if_needed(); page.wait_for_timeout(300)
                w.step('Section 13 in view (closed)')
                w.tap(summ); page.wait_for_timeout(500)
                link = sec.locator('a.launch').first
                link.scroll_into_view_if_needed()
                w.step('Section 13 open', extra={'href': link.get_attribute('href')})
                el = w.tap_nav(link)
                w.step('Explore Code index (from homepage)', elapsed=el)
        except Exception as e:
            w.fail('Homepage journey', e)
            try: w.goto(base + 'index.html')
            except Exception as e2: w.fail('Open index', e2); return
    else:
        try:
            el, resp = w.goto(base + 'index.html')
            w.step('Explore Code index', elapsed=el, extra={'status': resp.status if resp else None})
        except Exception as e:
            w.fail('Open index', e); return
    index_url = page.url
    w.scroll_end('Index, end of page')
    # topic -> repo -> section -> GitHub link -> back
    try:
        t = first(page, ['main a[href*="topics/cables"]', 'a[href*="topics/"]'])
        el = w.tap_nav(t); w.step('Topic page', elapsed=el)
        r = first(page, ['main a[href*="../repos/"]', 'a[href*="repos/"]'])
        el = w.tap_nav(r); w.step('Repository page', elapsed=el)
        repo_url = page.url
        s = first(page, ['main a[href*="../s/"]', 'a[href*="/s/"]', 'a[href*="s/0"]'])
        el = w.tap_nav(s); w.step('Section page', elapsed=el)
        gh = page.locator('a[href^="https://github.com/"]')
        n = gh.count()
        if n:
            g = gh.first; g.scroll_into_view_if_needed(); page.wait_for_timeout(300)
            hrefs = list(dict.fromkeys(gh.evaluate_all('els => els.map(e => e.href)')))[:200]
            checks = [check_github(h) for h in hrefs[:3]]
            bad_shape = [h for h in hrefs if not GH.match(h)]
            box = g.bounding_box()
            w.step('GitHub link on section page', 'link checked, not followed',
                   extra={'github_links': len(hrefs), 'checked': checks, 'bad_shape': bad_shape[:10],
                          'first_link_box': box, 'target': g.get_attribute('target'), 'rel': g.get_attribute('rel')})
        else:
            w.step('GitHub link on section page', ok=False, problem='no github.com link on the section page')
        page.go_back(wait_until='load'); w.settle()
        w.step('Back (to repository page)', ok=page.url.split('#')[0] == repo_url.split('#')[0],
               problem='' if page.url.split('#')[0] == repo_url.split('#')[0] else 'back went to ' + page.url)
    except Exception as e:
        w.fail('Topic/repo/section walk', e)
    # Visualiser
    try:
        w.goto(index_url)
        v = first(page, ['a[href$="visual/index.html"]', 'a[href*="visual/"]'])
        el = w.tap_nav(v); page.wait_for_timeout(1200)
        w.step('Visualiser opens', elapsed=el)
        for b in ['pipeline', 'map', 'flow']:
            btn = page.locator('#tabs button[data-view="%s"]' % b)
            if btn.count():
                w.tap(btn.first); page.wait_for_timeout(900); w.step('Visualiser view: ' + b)
        modes = page.locator('#mode option').evaluate_all('o => o.map(x => [x.value, x.textContent])') if page.locator('#mode').count() else []
        mb = page.locator('#tabs button[data-view="map"]')
        if mb.count(): w.tap(mb.first); page.wait_for_timeout(500)
        for val, label in modes:
            page.select_option('#mode', val); page.wait_for_timeout(700); w.step('Colour mode: ' + label.strip())
        if modes: page.select_option('#mode', modes[0][0])
        pb = page.locator('#tabs button[data-view="pipeline"]')
        if pb.count(): w.tap(pb.first); page.wait_for_timeout(800)
        # tap a dot: scan a grid over the canvas until the info panel opens
        cv = page.locator('#cv'); box = cv.bounding_box() if cv.count() else None
        hit = None
        if box:
            for fy in [0.5, 0.4, 0.6, 0.3, 0.7, 0.45, 0.55, 0.35, 0.65, 0.25, 0.75]:
                for fx in [0.5, 0.4, 0.6, 0.3, 0.7, 0.2, 0.8, 0.45, 0.55, 0.35, 0.65, 0.15, 0.85]:
                    x, y = box['x'] + box['width'] * fx, box['y'] + box['height'] * fy
                    if w.vp in TOUCH: page.touchscreen.tap(x, y)
                    else: page.mouse.click(x, y)
                    page.wait_for_timeout(120)
                    if page.locator('#info a.open').count() and page.locator('#info').is_visible():
                        hit = (round(x), round(y)); break
                if hit: break
        w.step('Tap a dot', ok=bool(hit), problem='' if hit else 'no dot found by tapping a 13x11 grid', extra={'at': hit})
        if hit:
            op = page.locator('#info a.open', has_text='Open section').first
            if op.count():
                el = w.tap_nav(op); w.step('Dot -> its section page', elapsed=el)
                page.go_back(wait_until='load'); w.settle(); page.wait_for_timeout(800)
                w.step('Back to Visualiser', extra={'hash': page.evaluate('location.hash')})
    except Exception as e:
        w.fail('Visualiser journey', e)
    # Search
    try:
        w.goto(index_url)
        s = first(page, ['a[href$="search.html"]'])
        el = w.tap_nav(s); w.step('Search page', elapsed=el)
        q = page.locator('#q'); w.tap(q); page.keyboard.type('haversine', delay=40)
        w.step('Typed "haversine"')
        t = time.time()
        btn = page.locator('#f button').first
        w.tap(btn)
        try:
            page.wait_for_function("() => /matches|failed/i.test(document.getElementById('st').textContent)", timeout=90000)
        except PWTimeout: pass
        st = page.locator('#st').inner_text()
        nres = page.locator('#res li').count()
        w.step('Search results', elapsed=time.time() - t, ok=nres > 0, problem='' if nres else 'status: ' + st,
               extra={'status': st, 'results': nres, 'note': 'DuckDB-WASM served from npm copy (CDN unreachable in sandbox)'})
        if nres:
            a = page.locator('#res li a').first; href = a.get_attribute('href')
            el = w.tap_nav(a)
            frag = page.evaluate("() => { const id = location.hash.slice(1); const e = id && document.getElementById(id); if (!e) return null; const r = e.getBoundingClientRect(); return {top: Math.round(r.top), h: Math.round(r.height)}; }")
            w.step('Search result -> section', elapsed=el, ok=frag is not None,
                   problem='' if frag is not None else 'result anchor %s not found on page' % href, extra={'href': href, 'anchor': frag})
    except Exception as e:
        w.fail('Search journey', e)
    # Words A-Z
    try:
        w.goto(index_url)
        a = first(page, ['a[href$="words/index.html"]'])
        el = w.tap_nav(a); w.step('Words A-Z', elapsed=el)
        word = first(page, ['main a[href*="cable"]', 'main a[href$=".html"]:not([href*="index"])'])
        if word:
            el = w.tap_nav(word); w.step('A word page', elapsed=el)
    except Exception as e:
        w.fail('Words journey', e)
    # llms.txt
    try:
        el, resp = w.goto(base + 'llms.txt')
        hdr = resp.headers if resp else {}
        w.step('llms.txt', elapsed=el, extra={'content_type': hdr.get('content-type'), 'status': resp.status if resp else None})
    except Exception as e:
        w.fail('llms.txt', e)
    # journey page
    try:
        el, resp = w.goto(base + 'journeys/a.html')
        w.step('Journey page a.html', elapsed=el, ok=bool(resp and resp.status < 400), extra={'status': resp.status if resp else None})
        w.scroll_end('Journey page, end')
    except Exception as e:
        w.fail('Journey page', e)

def generic_journey(w, start):
    page = w.page
    try:
        el, resp = w.goto(start)
        w.step('Opens', elapsed=el, ok=bool(resp and resp.status < 400), extra={'status': resp.status if resp else None})
    except Exception as e:
        w.fail('Opens', e); return
    page.wait_for_timeout(1000)
    w.scroll_end('End of page')
    origin = re.match(r'(https?://[^/]+)', page.url).group(1)
    hrefs = page.locator('a[href]').evaluate_all('els => els.map(e => e.href)')
    internal = [h for h in dict.fromkeys(hrefs) if h.startswith(origin) and h.split('#')[0] != page.url.split('#')[0]]
    for h in internal[:3]:
        try:
            el, resp = w.goto(h); w.step('Internal link: ' + h[len(origin):][:40], elapsed=el, ok=bool(resp and resp.status < 400))
        except Exception as e:
            w.fail('Internal link ' + h[len(origin):][:40], e)
    try:
        w.goto(start)
        btns = page.locator('button:visible, [role=button]:visible, [role=tab]:visible')
        n = btns.count()
        for i in range(min(n, 4)):
            b = btns.nth(i); label = (b.inner_text() or b.get_attribute('aria-label') or 'button').strip()[:30]
            try:
                url0 = page.url; w.tap(b); page.wait_for_timeout(700)
                w.step('Tap button: ' + label)
                if page.url.split('#')[0] != url0.split('#')[0]: w.goto(start)
            except Exception as e:
                w.fail('Tap button: ' + label, e)
    except Exception as e:
        w.fail('Buttons', e)

# ---------------------------------------------------------------- runner
def run(out, only, vps):
    stamp = time.strftime('%Y%m%d-%H%M%S'); rd = os.path.join(out, stamp); os.makedirs(rd, exist_ok=True)
    checker = LinkChecker(); servers = []
    targets = {}
    if 'live' in only or not only:
        targets['live'] = ('live', None)
    for name, (root, start, kind) in local_targets().items():
        if only and name not in only: continue
        httpd, port = serve(root); servers.append(httpd); checker.add_port(port, root)
        targets[name] = (kind, 'http://127.0.0.1:%d%s' % (port, start))
    results = {'stamp': stamp, 'started': time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()), 'targets': {},
               'browser': 'chromium', 'live_roots': {'home': LIVE_HOME_ROOT, 'explore': LIVE_EXPLORE_ROOT}}
    with sync_playwright() as p:
        browser = p.chromium.launch()
        for tname, (kind, start) in targets.items():
            results['targets'][tname] = {'kind': kind, 'start': start, 'runs': {}}
            for vp in vps:
                spec = VIEWPORTS[vp]; opts = dict(p.devices[spec['base']]) if spec.get('base') else {}
                opts.pop('default_browser_type', None)
                for k in ('viewport', 'screen', 'device_scale_factor'):
                    if k in spec: opts[k] = spec[k]
                ctx = browser.new_context(**opts, ignore_https_errors=False)
                ext = []; install_routes(ctx, ext)
                page = ctx.new_page(); page.set_default_timeout(20000)
                shotdir = os.path.join(rd, 'shots', tname, vp); os.makedirs(shotdir, exist_ok=True)
                w = Walker(page, vp, tname, shotdir, checker)
                t0 = time.time()
                try:
                    if tname == 'live':
                        explore_journey(w, 'https://code.globalgrid2050.com/explore-code/', homepage='https://globalgrid2050.com/')
                    elif kind == 'explore':
                        explore_journey(w, start.rsplit('/', 1)[0] + '/')
                    else:
                        generic_journey(w, start)
                except Exception as e:
                    w.fail('journey crashed', e); traceback.print_exc()
                results['targets'][tname]['runs'][vp] = {'label': spec['label'], 'steps': w.steps, 'seconds': round(time.time() - t0, 1),
                                                         'external_blocked': sorted(set(ext))[:200]}
                print('%-8s %-8s %3d steps %5.1fs  problems=%d' % (tname, vp, len(w.steps), time.time() - t0,
                      sum(1 for s in w.steps if not s['ok'])), flush=True)
                ctx.close()
        browser.close()
    for s in servers: s.shutdown()
    results['finished'] = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())
    json.dump(results, open(os.path.join(rd, 'results.json'), 'w'), indent=1, default=str)
    latest = os.path.join(out, 'latest')
    if os.path.islink(latest): os.unlink(latest)
    os.symlink(stamp, latest)
    return rd

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('--out', default='/tmp/vk/9/runs')
    ap.add_argument('--only', default='', help='comma list: live,site7,site8,clarity,kuiper,chess,lab')
    ap.add_argument('--viewports', default='phone,tablet,laptop,desktop')
    a = ap.parse_args()
    rd = run(a.out, [x for x in a.only.split(',') if x], [x for x in a.viewports.split(',') if x])
    print(rd)

Ownership

A Python command-line tool in the verify folder of Cosmic that compares `git status` in the cosmic repo with the owners in the Neural Link roster (`/tmp/vk/neural/ROSTER.md`).

ingestcosmic / tools/explore/verify/ownership.py · lines 1–63 of 63 · Entry point · pattern expand (shared by 9 files)

What it does
It loads data. Defines expand, owners, main. Uses libraries argparse, re, subprocess. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `expand` and `owners`. It accepts `--repo` and `--roster`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/verify · Python CLI
Uses
argparse, re, subprocess
Used by
none found
Produces
expand, owners, main
Defines here
expand, owners, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/verify/ownership.py:1-63 · blob b4ad44d7402994a17bbb080c577df2004a100022 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""tools/explore/verify/ownership.py - compare `git status` in the cosmic repo with the owners in the Neural Link
roster (/tmp/vk/neural/ROSTER.md). Prints every changed path with its owner(s); UNOWNED = no roster entry claims it.
    python ownership.py [--repo /home/claude/cosmic] [--roster /tmp/vk/neural/ROSTER.md]"""
import argparse
import re
import subprocess


def expand(spec):
    m = re.search(r'\{([^}]*)\}', spec)
    if not m:
        return [spec]
    return [x for alt in m.group(1).split(',') for x in expand(spec[:m.start()] + alt.strip() + spec[m.end():])]


def owners(roster):
    res = []
    last_prefix = ''
    for line in open(roster, encoding='utf-8'):
        parts = [p.strip() for p in line.split('|')]
        if len(parts) < 3:
            continue
        name = parts[0]
        for spec in re.split(r',\s*(?![^{]*\})', parts[2]):
            spec = spec.strip().split(' (')[0].strip()
            if not spec or spec.startswith('/tmp') or spec == 'all':
                continue
            tests = ' + tests' in spec
            spec = spec.split(' + ')[0].strip()
            spec = re.sub(r'^cosmic/', '', spec)
            if '/' not in spec and last_prefix:
                spec = last_prefix + spec  # bare "GRAPH-CONTRACT.md" after a tools/explore/ entry
            if not spec.startswith('tools/') and not spec.startswith('essays') and '/' in spec and last_prefix:
                spec = last_prefix + spec  # "clean/test_noise.py" after "cosmic/tools/explore/clean/noise.py"
            if spec.startswith('tools/explore/'):
                last_prefix = 'tools/explore/'
            for s in expand(spec):
                res.append((name, s.rstrip('/')))
                if tests and s.endswith('.py'):
                    d, f = s.rsplit('/', 1)
                    res.append((name, d + '/test_' + f))
    return res


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--repo', default='/home/claude/cosmic')
    ap.add_argument('--roster', default='/tmp/vk/neural/ROSTER.md')
    a = ap.parse_args()
    out = subprocess.run(['git', '-C', a.repo, 'status', '--porcelain', '--untracked-files=all'], capture_output=True, text=True).stdout
    own = owners(a.roster)
    for line in out.splitlines():
        st, path = line[:2], line[3:]
        if '__pycache__' in path:
            continue
        who = sorted({n for n, s in own if path == s or path.startswith(s + '/') or
                      (s.endswith('.py') is False and '.' not in s.rsplit('/', 1)[-1] and path.startswith(s))})
        print('%s %-70s %s' % (st, path, ', '.join(who) if who else 'UNOWNED'))


if __name__ == '__main__':
    main()