GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / sessions/202609031559-skin-architecture/prototype

Ab and 5 more files

A Python command-line tool in the sessions folder of Claude that runs release (`run_release`). It is built from the scroll to table helper (`scroll_to_table`).

681 lines of Python and HTML from claude, in 6 files. Topic: AI agents and coordination. Section 1617 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. Skin Architecture — Prototype Page render · claude / sessions/202609031559-skin-architecture/prototype/index.html lines 701–710
  2. Audit Harvest storage · claude / sessions/202609032310-coaching/audit_harvest.py lines 1–168
  3. Verify Redboard ingest · claude / sessions/202609032310-coaching/verify_redboard.py lines 1–57
  4. Verify Rows ingest · claude / sessions/202609032310-coaching/verify_rows.py lines 1–58
  5. Ab render · claude / sessions/202609040030-ab-discovery/ab.py lines 1–260
  6. Maphref render · claude / sessions/202609040030-ab-discovery/maphref.py lines 1–128

Skin Architecture — Prototype Page

A web page in the sessions folder of Claude that draws desktop, glanceable, tenfoot and broken compact. It paints switcher (`paintSwitcher`), applies tokens (`applyTokens`) and renders shell (`renderShell`).

renderclaude / sessions/202609031559-skin-architecture/prototype/index.html · lines 701–710 of 710 · version 2026-09-03 15:59 (continued from section 1616) · Entry point · pattern drawMap (shared by 3 files)

What it does
It draws desktop, glanceable, tenfoot and broken compact. Defines 20 functions or classes, including $, cls, show, fill, paintSwitcher. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV.
Inputs & outputs
In: JSON file desktop.json; JSON file glanceable.json; JSON file tenfoot.json; JSON file broken-compact.json; JSON file substations.json; form fields (user input). Out: web page; canvas drawing. Voltage levels named: 400kV.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
Defines `cls`, `show`, `fill` and 15 more. Its code works with 400 kV. It reads `substations.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609031559-skin-architecture/prototype · page
Uses
Engine (script src)
Used by
none found
Produces
$, cls, show, fill, paintSwitcher, applyTokens, renderShell, drawMap, px, currentReading, render, sync
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609031559-skin-architecture/prototype/index.html:701-710 · blob 20e60bdce94e726d1cfcb0d5492f9f0e1c2ecf71 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unknown
  for (const s of skins) {
    const bad = E.validateSkin(s);
    console[bad.length ? 'error' : 'log']('skin ' + s.id + ': '
      + (bad.length ? bad.join(' | ') : 'contract satisfied'));
  }
  window.__PROTO = { E, registry, skins, SUBS, currentReading, P, choice: () => choice };
})();
</script>
</body>
</html>

Audit Harvest

A Python command-line tool in the sessions folder of Claude that fetches wider fleet, grid proximity and audit rows.

storageclaude / sessions/202609032310-coaching/audit_harvest.py · lines 1–168 of 168 · version 2026-09-03 23:10 · Entry point · pattern score (shared by 17 files)

What it does
It fetches wider fleet, grid proximity and audit rows. Defines ask, load, strict_grounded, main, score. Uses libraries json, os, re, sys, time. Side effects: 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).
Inputs & outputs
In: JSON file 202609030009-wider-fleet.json; JSON file 202608311610-grid-proximity.json; JSON file audit_rows.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the ask step (`ask`), the load step (`load`) and the strict grounded helper (`strict_grounded`). Independent audit of `familiars/harvest.py`'s precision claim.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609032310-coaching · Python CLI
Uses
json, os, re, sys, time, urllib.request
Used by
none found
Produces
ask, load, strict_grounded, main
Defines here
ask, load, strict_grounded, main, score
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609032310-coaching/audit_harvest.py:1-168 · blob 0741c985f4115257db709134f443ee679a805b7f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Independent audit of familiars/harvest.py's precision claim.

Does not trust harvest's scoring. Re-runs the same prompt against the same rows and
scores each answer THREE ways:

  A. harvest's own rule  - grounded = substring of the name (low in name.lower())
  B. strict grounding    - the answer must appear as a WHOLE WORD sequence in the name.
                           A truncation ("Kintor" from "Kintore") or a fragment is NOT
                           grounded. This is the invention class harvest cannot see:
                           its substring test only catches INSERTIONS, never TRUNCATIONS.
  C. abstention audit    - for every row the model said NONE on, does the name in fact
                           contain a settlement? harvest counts abstentions but never
                           checks them, so its denominator excludes every row the model
                           declined - which is where a cautious model hides its misses.

Every row is written out with the verbatim source name so a reader can check the
quoted evidence against the file it came from.
"""
import json, os, re, sys, time, urllib.request

OLLAMA = "http://127.0.0.1:11434/api/generate"
MODEL = "qwen3:4b-instruct-2507-q4_K_M"
REL = ("C:/Users/vikra/OneDrive/Documents/GitHub/pipelinenews/"
       "releases/202609032159-pipelinenews/data/")

BOILER = re.compile(
    r"^(the|a|an)?\s*(solar|wind|hydro|hydrogen|biomass|tidal|geothermal|battery|bess|"
    r"energy|power|farm|park|plant|project|station|storage|extension|scheme|site|ltd|"
    r"limited|repowering|onshore|offshore|anaerobic|digestion|landfill|gas|efw|"
    r"incineration|sewage|sludge|pumped|small|large|stream|wave|advanced|conversion)"
    r"[\s\-]*", re.I)


def ask(name, timeout=90):
    body = json.dumps({
        "model": MODEL,
        "prompt": (
            "Extract the SETTLEMENT (town, village or hamlet) from this UK energy project "
            "name. Reply with the settlement only, nothing else. If the name states no "
            "settlement, reply exactly: NONE\n\n"
            f"Name: {name}\nSettlement:"),
        "stream": False,
        "options": {"num_ctx": 16384, "temperature": 0, "num_predict": 16},
    }).encode()
    req = urllib.request.Request(OLLAMA, body, {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)["response"].strip().strip('."').split("\n")[0]


def load(n):
    """Identical to harvest.load, but a missing file is a hard failure, not a skip."""
    rows = []
    for fn, namekey, authkey in (
        ("202609030009-wider-fleet.json", "n", "cty"),
        ("202608311610-grid-proximity.json", "name", "town"),
    ):
        p = os.path.join(REL, fn)
        if not os.path.exists(p):
            raise SystemExit(f"MISSING INPUT {p} - refusing to report a model result")
        d = json.load(open(p, encoding="utf-8"))
        rs = d if isinstance(d, list) else next(
            v for v in d.values() if isinstance(v, list) and v and isinstance(v[0], dict))
        got = 0
        for r in rs:
            if r.get(namekey):
                rows.append((r[namekey], str(r.get(authkey) or ""), fn))
                got += 1
        print(f"  loaded {got:>6} rows from {fn}", file=sys.stderr)
    step = max(1, len(rows) // n)
    return rows[::step][:n]


def strict_grounded(answer, name):
    """Whole-word-sequence containment. 'Kintor' is not grounded in 'Kintore ...'."""
    a = answer.strip()
    if not a:
        return False
    pat = r"(?<![A-Za-z])" + r"[\s\-,'`]+".join(
        re.escape(tok) for tok in re.split(r"[\s\-,]+", a) if tok) + r"(?![A-Za-z])"
    try:
        return re.search(pat, name, re.I) is not None
    except re.error:
        return a.lower() in name.lower()


def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 60
    rows = load(n)
    print(f"\naudit of harvest.py: {len(rows)} rows, model {MODEL}\n", file=sys.stderr)

    out = []
    failed_requests = 0
    t0 = time.time()
    for i, (name, auth, src) in enumerate(rows):
        try:
            a = ask(name)
        except Exception as e:
            failed_requests += 1
            out.append({"name": name, "auth": auth, "src": src,
                        "answer": None, "error": str(e)})
            continue
        low = a.lower()
        abstain = low in ("none", "n/a", "unknown", "") or low.startswith("none")
        rec = {
            "name": name, "auth": auth, "src": src, "answer": a,
            "abstained": abstain,
            "harvest_grounded": low in name.lower(),
            "strict_grounded": strict_grounded(a, name),
            "is_auth_exact": bool(auth) and low == auth.lower(),
            "is_auth_substr": bool(auth) and (low in auth.lower() or auth.lower() in low),
            "is_boiler": bool(BOILER.match(a)) or low in ("uk", "england", "scotland", "wales"),
        }
        out.append(rec)
        if (i + 1) % 10 == 0:
            print(f"  {i+1}/{len(rows)}  {time.time()-t0:.0f}s", file=sys.stderr)

    dt = time.time() - t0
    ans = [r for r in out if r.get("answer") is not None and not r["abstained"]]
    abst = [r for r in out if r.get("answer") is not None and r["abstained"]]

    def score(rows_, ground_key):
        hit = inv = ech = boi = 0
        for r in rows_:
            if not r[ground_key]:
                inv += 1
            elif r["is_auth_exact"]:
                ech += 1
            elif r["is_boiler"]:
                boi += 1
            else:
                hit += 1
        return hit, inv, ech, boi

    h1, i1, e1, b1 = score(ans, "harvest_grounded")
    h2, i2, e2, b2 = score(ans, "strict_grounded")
    v = len(ans)
    print("\n" + "=" * 72)
    print(f"rows sampled            {len(rows)}")
    print(f"request failures        {failed_requests}   (harvest drops these from every counter)")
    print(f"volunteered an answer   {v}")
    print(f"abstained (said NONE)   {len(abst)}   (harvest excludes ALL of these from precision)")
    print()
    print(f"  A. harvest's own rule (substring grounding), denominator {v}:")
    print(f"     hits {h1}  invented {i1}  echoed-auth {e1}  boilerplate {b1}"
          f"   -> precision {100.0*h1/v if v else 0:.1f}%")
    print(f"  B. strict rule (whole-word grounding), denominator {v}:")
    print(f"     hits {h2}  invented {i2}  echoed-auth {e2}  boilerplate {b2}"
          f"   -> precision {100.0*h2/v if v else 0:.1f}%")
    print()
    print(f"  answers harvest calls grounded that are NOT whole-word grounded: "
          f"{sum(1 for r in ans if r['harvest_grounded'] and not r['strict_grounded'])}")
    print(f"  answers that are a substring of the planning authority (harvest only "
          f"catches exact): {sum(1 for r in ans if r['is_auth_substr'] and not r['is_auth_exact'])}")
    print()
    print(f"  precision over ALL rows put to the model "
          f"(denominator {v + len(abst)}, abstentions included as non-answers): "
          f"{100.0*h2/(v+len(abst)) if (v+len(abst)) else 0:.1f}%")
    print(f"\n  {dt:.0f}s  ({dt/max(1,len(rows)):.2f}s/row)")

    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           "audit_rows.json"), "w", encoding="utf-8") as fh:
        json.dump(out, fh, indent=1, ensure_ascii=False)
    print("\n  every row written to audit_rows.json for verbatim checking")
    return 0


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

Verify Redboard

A Python module in the sessions folder of Claude that reads rb snapshot. It is built from the clean step (`clean`) and the flat step (`flat`).

ingestclaude / sessions/202609032310-coaching/verify_redboard.py · lines 1–57 of 57 · version 2026-09-03 23:10 · Not reached from any entry point (candidate for review) · pattern clean (shared by 37 files)

What it does
It loads rb snapshot. Defines clean, flat. Uses libraries json, os, random, re, subprocess. Side effects: reads or writes files; 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).
Inputs & outputs
In: JSON file rb-snapshot.json; command-line arguments.
What it achieves
Grade `logs/red-board.json` by re-fetching each cited job log and checking the quote.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609032310-coaching · Python module
Uses
json, os, random, re, subprocess, sys
Used by
none found
Produces
clean, flat
Defines here
clean, flat
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609032310-coaching/verify_redboard.py:1-57 · blob ab6d09c27e96cd0afd6ada405bd834d0408f5ff4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Grade logs/red-board.json by re-fetching each cited job log and checking the quote.

Does not trust triage.py's own grounding flag. For a sample of rows marked grounded, this
re-fetches the job log from the GitHub API and checks the quote is a whitespace-flattened
substring of the WHOLE log - and separately reports whether it appears only inside the
echoed `##[group]Run ...` script source rather than in real step output.
"""
import json, os, random, re, subprocess, sys

REPO = "C:/Users/vikra/OneDrive/Documents/GitHub/claude"
d = json.load(open("rb-snapshot.json", encoding="utf-8"))
rows = [r for r in d["rows"] if r.get("grounded") is True and r.get("quote")]
random.seed(11)
sample = random.sample(rows, min(int(sys.argv[1]) if len(sys.argv) > 1 else 6, len(rows)))

TS = re.compile(r"^\S*?\d{4}-\d\d-\d\dT[\d:.]+Z ", re.M)
ANSI = re.compile(r"\[[0-9;]*m|\[[0-9]{1,2};[0-9]{1,2}m|\[0m")

def clean(s):
    """strip the per-line timestamp and ANSI colour codes triage strips before matching"""
    s = TS.sub("", s)
    return ANSI.sub("", s)

def flat(s):
    return re.sub(r"\s+", " ", clean(s)).strip()

ok = bad = only_echo = 0
for r in sample:
    path = f"repos/{r['full_repo']}/actions/jobs/{r['job_id']}/logs"
    try:
        log = subprocess.run(["bash", os.path.join(REPO, "scripts", "gh-api.sh"), path, "--raw"],
                             capture_output=True, timeout=90).stdout.decode("utf-8", "replace")
    except Exception as e:
        print(f"  FETCH FAILED {r['repo']} {r['job_id']}: {e}")
        continue
    q = flat(r["quote"].strip('"'))
    present = q in flat(log)
    # lines that are echoed workflow source carry GitHub's 36;1m colour code
    real_out = [ln for ln in log.splitlines() if "36;1m" not in ln]
    in_real = q in flat("\n".join(real_out))
    tag = "OK " if present else "MISSING"
    if present:
        ok += 1
    else:
        bad += 1
    if present and not in_real:
        only_echo += 1
        tag = "ECHO-ONLY"
    print(f"  [{tag:9}] {r['repo']:<22} job {r['job_id']}  log {len(log):>7} chars")
    print(f"              quote: {q[:96]}")
    if not present:
        print(f"              first_error_line: {r.get('first_error_line','')[:90]}")

print(f"\n  sampled {len(sample)} rows marked grounded")
print(f"  quote verified verbatim in the log      {ok}")
print(f"  quote NOT found (triage overstated)     {bad}")
print(f"  quote present ONLY in echoed script src {only_echo}  <- real string, false role")

Verify Rows

A Python module in the sessions folder of Claude that reads audit rows, wider fleet and grid proximity.

ingestclaude / sessions/202609032310-coaching/verify_rows.py · lines 1–58 of 58 · version 2026-09-03 23:10 · Not reached from any entry point (candidate for review)

What it does
It loads audit rows, wider fleet and grid proximity. Uses libraries json, os, sys. Side effects: reads or writes files.
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).
Inputs & outputs
In: JSON file audit_rows.json; JSON file 202609030009-wider-fleet.json; JSON file 202608311610-grid-proximity.json.
What it achieves
Verify every audited row against the SOURCE FILE it claims to come from.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609032310-coaching · Python module
Uses
json, os, sys
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609032310-coaching/verify_rows.py:1-58 · blob 5ce83ee4c9a8f89c0836f28414681653cde796e4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Verify every audited row against the SOURCE FILE it claims to come from.

Not against a re-parse of my own loader - against the raw bytes of the release JSON.
A row is only confirmed if:
  - the project name occurs verbatim, as a JSON string, in the file named in `src`
  - the model's answer occurs verbatim inside that project name
"""
import json, os, sys

REL = ("C:/Users/vikra/OneDrive/Documents/GitHub/pipelinenews/"
       "releases/202609032159-pipelinenews/data/")
HERE = os.path.dirname(os.path.abspath(__file__))
rows = json.load(open(os.path.join(HERE, "audit_rows.json"), encoding="utf-8"))

raw = {}
for fn in ("202609030009-wider-fleet.json", "202608311610-grid-proximity.json"):
    with open(os.path.join(REL, fn), "rb") as fh:
        raw[fn] = fh.read()
    print(f"  {fn}: {len(raw[fn])} bytes read")

name_ok = name_bad = ans_ok = ans_bad = 0
answered = [r for r in rows if r.get("answer") is not None and not r.get("abstained")]
for r in answered:
    blob = raw[r["src"]]
    # the name must be present as a JSON string value in the raw bytes
    needle = json.dumps(r["name"], ensure_ascii=False).encode("utf-8")
    if needle in blob:
        name_ok += 1
    else:
        name_bad += 1
        print(f"  NAME NOT IN SOURCE: {r['name'][:70]!r}  ({r['src']})")
    if r["answer"].lower() in r["name"].lower():
        ans_ok += 1
    else:
        ans_bad += 1
        print(f"  ANSWER NOT IN NAME: {r['answer']!r} <- {r['name'][:70]!r}")

print(f"\n  answered rows checked          {len(answered)}")
print(f"  project name verbatim in source {name_ok} confirmed / {name_bad} absent")
print(f"  answer verbatim inside the name {ans_ok} confirmed / {ans_bad} absent")

print("\n  --- 10 sampled rows, verbatim ---")
for r in answered[:10]:
    print(f"    {r['answer']:<20} <- {r['name'][:62]}")
    print(f"       auth={r['auth']!r} strict={r['strict_grounded']} "
          f"auth_substr={r['is_auth_substr']} src={r['src']}")

sus = [r for r in answered if r["is_auth_substr"] and not r["is_auth_exact"]]
if sus:
    print("\n  --- answers that are a SUBSTRING of the planning authority ---")
    for r in sus:
        print(f"    answer={r['answer']!r} auth={r['auth']!r} name={r['name'][:60]!r}")
        print(f"       harvest scores this a HIT (it only compares exact equality)")

errs = [r for r in rows if r.get("answer") is None]
print(f"\n  --- {len(errs)} request failures harvest would have dropped silently ---")
for r in errs[:4]:
    print(f"    {r['error'][:100]}")

Ab

A Python command-line tool in the sessions folder of Claude that runs release (`run_release`). It is built from the scroll to table helper (`scroll_to_table`).

renderclaude / sessions/202609040030-ab-discovery/ab.py · lines 1–260 of 260 · version 2026-09-04 00:30 · Entry point

What it does
It loads data. Defines scroll_to_table, run_release, main. Uses libraries argparse, json, os, sys, time. Side effects: changes the web page (DOM); reads or writes files.
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).
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Drive two Pipeline News releases through the SAME reading and diff them. It accepts `--port`, `--a` and `--b`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609040030-ab-discovery · Python CLI
Uses
argparse, json, os, sys, time, clicker
Used by
none found
Produces
scroll_to_table, run_release, main
Defines here
scroll_to_table, run_release, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609040030-ab-discovery/ab.py:1-260 · blob f8147fbd5ec95348971ee097c146ae7a9792b0ab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""ab - drive two Pipeline News releases through the SAME reading and diff them.

Lane A is an instrument, not a shipper. This reuses familiars/clicker.py's Browser
verbatim - its own Chrome, its own port, its own profile, its arm() listeners
installed before the page's scripts run, and its refusal to measure a hidden tab.
What is added here is only the READING, and the fact that it is taken twice.

One Chrome per run, two navigations. Memory on this machine is the scarce
resource; two browsers where one will do is a cost with no evidence attached.

  python ab.py --port 9431 --a 202609020611 --b 202609032251
  python ab.py --port 9432 --a 202609031308 --b 202609032251 --mobile
"""

import argparse
import json
import os
import sys
import time

sys.path.insert(0, r'C:\Users\vikra\OneDrive\Documents\GitHub\claude\familiars')
from clicker import Browser, PROBE_VISIBLE  # noqa: E402

BASE = 'http://127.0.0.1:8971/releases/%s-pipelinenews/index.html'

# ── the reading ─────────────────────────────────────────────────────────────
#
# Every anchor below was read off the shipped index.html before it was used.
# clicker's own journey_summary asks for `#results tbody tr`; no Pipeline News
# release has ever had an element with id "results" - the table body is
# `#tbody`. That selector has been returning 0 for every generation it was
# pointed at, and 0 is indistinguishable from an empty table.

READ = r"""(() => {
  const t = e => e ? (e.textContent || '').replace(/\s+/g, ' ').trim() : null;
  const el = id => document.getElementById(id);
  const arc = id => { const c = el(id);
    if (!c || !c.toDataURL) return null;
    const d = c.toDataURL();
    let h = 0; for (let i = 0; i < d.length; i++) h = (h * 31 + d.charCodeAt(i)) | 0;
    return c.width + 'x' + c.height + '#' + (h >>> 0).toString(16); };
  const meta = el('resultsMeta');
  const rows = [...document.querySelectorAll('#tbody tr')];
  const wider = el('widerTechnology');
  return {
    hidden: document.hidden,
    viewport: innerWidth + 'x' + innerHeight,
    doc_height: document.documentElement.scrollHeight,
    screens_tall: +(document.documentElement.scrollHeight / innerHeight).toFixed(2),

    counter: t(meta),
    counter_dataset: meta ? JSON.parse(JSON.stringify(meta.dataset)) : null,

    v1: t(el('v1')), v2: t(el('v2')), v3: t(el('v3')),
    g1: arc('g1'), g2: arc('g2'), g3: arc('g3'),

    exportMeta: t(el('exportMeta')),
    export_dataset: el('exportMeta') ? JSON.parse(JSON.stringify(el('exportMeta').dataset)) : null,
    export_btn: (() => { const b = el('exportInline'); if (!b) return null;
      const r = b.getBoundingClientRect();
      return {text: t(b), disabled: !!b.disabled, w: Math.round(r.width), h: Math.round(r.height)}; })(),

    row_count: rows.length,
    first_rows: rows.slice(0, 2).map(tr =>
      [...tr.children].map(td => (td.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 26))),
    columns: [...document.querySelectorAll('#tbody')].length
      ? [...document.querySelectorAll('table thead th')].map(th => t(th)) : [],

    /* The ACTIONS cell reads "MAP ↗", not "MAP". clicker's journey_maplink
       tests /^MAP$/i against the trimmed text, so the arrow makes it match
       nothing and the journey reports zero MAP cells on a table full of them.
       Anchored equality against display text is the anchor that drifts. */
    map_hrefs: [...document.querySelectorAll('#tbody a')]
      .filter(a => /\bMAP\b/i.test(a.textContent || ''))
      .slice(0, 3).map(a => a.getAttribute('href')),
    map_cells_total: [...document.querySelectorAll('#tbody a,#tbody button')]
      .filter(e => /\bMAP\b/i.test(e.textContent || '')).length,
    map_cell_rect: (() => { const a = [...document.querySelectorAll('#tbody a')]
        .filter(x => /\bMAP\b/i.test(x.textContent || ''))[0];
      if (!a) return null; const r = a.getBoundingClientRect();
      return {w: Math.round(r.width), h: Math.round(r.height),
              left_px: Math.round(r.left), target: a.getAttribute('target')}; })(),
    /* how far sideways the MAP column is from the site name */
    table_scroll: (() => { const w = document.querySelector('.tablewrap');
      if (!w) return null;
      return {client: w.clientWidth, scroll: w.scrollWidth,
              overflow_px: w.scrollWidth - w.clientWidth,
              flicks: +((w.scrollWidth - w.clientWidth) / 417).toFixed(1)}; })(),
    pagination: (() => { const b = document.body.textContent || '';
      const m = b.match(/[\d,]+\s*[–-]\s*[\d,]+\s+of\s+[\d,]+/g);
      return m ? m.slice(0, 3) : []; })(),
    gauge_canvas: ['g1', 'g2', 'g3'].map(id => { const c = el(id); if (!c) return null;
      const r = c.getBoundingClientRect();
      return id + ' attr=' + c.width + 'x' + c.height
        + ' css=' + Math.round(r.width) + 'x' + Math.round(r.height); }),
    no_map_cells: (document.getElementById('tbody')
      ? (document.getElementById('tbody').textContent.match(/NO MAP/g) || []).length : 0),

    tech_buttons: [...document.querySelectorAll('#tech button')].map(b => {
      const r = b.getBoundingClientRect();
      return t(b) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height)
        + (b.getAttribute('aria-pressed') === 'true' ? ' *' : ''); }),
    wider_options: wider ? wider.options.length : 0,
    wider_selected: wider ? (wider.options[wider.selectedIndex] || {}).textContent : null,
    wider_rect: wider ? (r => Math.round(r.width) + 'x' + Math.round(r.height))(wider.getBoundingClientRect()) : null,
    widerFleetMeta: t(el('widerFleetMeta')),

    // how far a reader must travel before the product is on screen
    depth: (() => {
      const d = {};
      for (const [k, id] of [['technology_row', 'tech'], ['counter', 'resultsMeta'],
                             ['export', 'exportInline'], ['first_row', null]]) {
        const node = id ? el(id) : document.querySelector('#tbody tr');
        if (!node) { d[k] = null; continue; }
        const y = node.getBoundingClientRect().top + scrollY;
        d[k] = {px: Math.round(y), screens: +(y / innerHeight).toFixed(2)};
      }
      return d; })(),

    evidence: (() => { const e = globalThis.__PIPELINENEWS_FAST__;
      return e ? JSON.parse(JSON.stringify(e)) : null; })(),
    errs: (window.__errs || []).slice(0, 8),
    log: (window.__log || []).slice(0, 8)
  };
})()"""

# how much of the screen is product (the table) and how much is chrome,
# sampled at the first row so the question is asked where the answer lives
SHARE = r"""(() => {
  const W = innerWidth, H = innerHeight, cols = 30, rows = 60;
  const tb = document.getElementById('tbody');
  let product = 0, chrome = 0, none = 0; const owners = {};
  for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
    const e = document.elementFromPoint((i + 0.5) * W / cols, (j + 0.5) * H / rows);
    if (!e) { none++; continue; }
    if (tb && tb.contains(e)) { product++; continue; }
    chrome++;
    let n = e, name = '';
    while (n && n !== document.body) {
      if (n.id) { name = '#' + n.id; break; }
      if (n.className && typeof n.className === 'string' && n.className.trim()) {
        name = '.' + n.className.trim().split(/\s+/)[0]; break; }
      n = n.parentElement; }
    name = name || e.tagName.toLowerCase();
    owners[name] = (owners[name] || 0) + 1;
  }
  const total = cols * rows;
  return {table_percent: +(100 * product / total).toFixed(1),
          chrome_percent: +(100 * chrome / total).toFixed(1),
          nothing_percent: +(100 * none / total).toFixed(1),
          owners: Object.entries(owners).sort((a, b) => b[1] - a[1]).slice(0, 8)
            .map(([k, v]) => k + ' ' + (100 * v / total).toFixed(1) + '%')};
})()"""


def scroll_to_table(b):
    b.js("(()=>{const r=document.querySelector('#tbody tr');"
         "if(r)r.scrollIntoView({block:'start'});})()")
    time.sleep(0.6)


def run_release(b, gen, shots, tag):
    """Load one release and take the same reading four times: at rest, after a
    spine technology, after a wider-fleet technology, and at the table."""
    out = {'generation': gen, 'url': BASE % gen, 'shots': []}
    b.go(BASE % gen, settle=7.0)

    vis = b.js(PROBE_VISIBLE)
    if not isinstance(vis, dict) or vis.get('hidden') is not False:
        out['ABORT'] = 'document.hidden was not false on %s' % gen
        return out

    out['title'] = b.js('document.title')
    out['at_rest'] = b.js(READ)
    out['shots'].append(b.shot(os.path.join(shots, '%s-%s-01-rest.png' % (tag, gen))))

    scroll_to_table(b)
    out['share_at_table'] = b.js(SHARE)
    out['shots'].append(b.shot(os.path.join(shots, '%s-%s-02-table.png' % (tag, gen))))

    # spine technology: SOLAR is index 1 of #tech
    out['spine_pick'] = b.js(
        "(()=>{const bs=[...document.querySelectorAll('#tech button')];"
        "if(bs.length<2)return null;bs[1].click();"
        "return bs[1].textContent.trim();})()")
    time.sleep(1.5)
    out['after_spine'] = b.js(READ)
    out['shots'].append(b.shot(os.path.join(shots, '%s-%s-03-spine.png' % (tag, gen))))

    # wider fleet: the first real technology in the injected select
    out['wider_pick'] = b.js(
        "(()=>{const s=document.getElementById('widerTechnology');"
        "if(!s||s.options.length<2)return null;s.selectedIndex=1;"
        "s.dispatchEvent(new Event('change',{bubbles:true}));"
        "return s.options[1].textContent.trim();})()")
    time.sleep(1.8)
    out['after_wider'] = b.js(READ)
    out['shots'].append(b.shot(os.path.join(shots, '%s-%s-04-wider.png' % (tag, gen))))

    # THE EXPORT IS THE SURFACE THAT LEAVES THE BUILDING, so screen-reading
    # cannot cover it. On a release without the decline seam this click writes
    # a real 50-column CSV of somebody else's rows to disk, which is exactly
    # the defect under test -- so downloads are DENIED at the browser level
    # first (Browser.setDownloadBehavior), and the click is only ever made
    # while a non-spine cut owns the table, where the answer is interesting.
    out['export_click'] = {'state': 'after_wider'}
    b.js("document.getElementById('exportInline').click()")
    time.sleep(1.6)
    out['export_click']['after'] = b.js(
        "(()=>{const m=document.getElementById('exportMeta');if(!m)return null;"
        "return {text:(m.textContent||'').replace(/\\s+/g,' ').trim(),"
        "declined:m.classList.contains('is-declined'),"
        "missing:m.dataset.exportDeclinedColumns||null,"
        "counter:(document.getElementById('resultsMeta')||{}).textContent};})()")
    out['export_click']['errs'] = b.js('(window.__errs||[]).slice(0,6)')
    out['shots'].append(b.shot(os.path.join(shots, '%s-%s-05-export.png' % (tag, gen))))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--port', type=int, required=True)
    ap.add_argument('--a', required=True)
    ap.add_argument('--b', required=True)
    ap.add_argument('--mobile', action='store_true')
    ap.add_argument('--shots', required=True)
    ap.add_argument('--out', required=True)
    args = ap.parse_args()

    os.makedirs(args.shots, exist_ok=True)
    tag = 'm' if args.mobile else 'd'
    b = Browser(args.port, mobile=args.mobile, headless=True)
    result = {'viewport': '393x852' if args.mobile else '1400x900',
              'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}
    try:
        b.setup(); b.arm()
        # Deny every download before a single page loads. Lane A is read-only
        # over the products; a discovery run must not be able to write one of
        # the wrong-rows CSVs it exists to find.
        for m in ('Browser.setDownloadBehavior', 'Page.setDownloadBehavior'):
            try:
                b.send(m, behavior='deny')
            except Exception as exc:
                result.setdefault('download_guard', []).append('%s: %s' % (m, exc))
        result['A'] = run_release(b, args.a, args.shots, tag)
        # NO second arm(): addScriptToEvaluateOnNewDocument already fires on
        # every navigation, so __errs is reset per release on its own. Arming
        # twice would wrap console.warn/error twice and double every line.
        result['B'] = run_release(b, args.b, args.shots, tag)
    finally:
        b.close()

    with open(args.out, 'w', encoding='utf-8') as fh:
        json.dump(result, fh, indent=1)
    print(json.dumps(result, indent=1)[:200])
    print('WROTE', args.out)


if __name__ == '__main__':
    main()

Maphref

A Python command-line tool in the sessions folder of Claude. It is built from the sample step (`sample`).

renderclaude / sessions/202609040030-ab-discovery/maphref.py · lines 1–128 of 128 · version 2026-09-04 00:30 · Entry point · pattern sample (shared by 18 files)

What it does
It loads data. Defines sample, main. Uses libraries argparse, json, os, sys, time. Side effects: changes the web page (DOM); reads or writes files.
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).
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
What does MAP hand the Atlas, and does it match the row it sits in? It accepts `--port`, `--gen` and `--out`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609040030-ab-discovery · Python CLI
Uses
argparse, json, os, sys, time, collections, clicker
Used by
none found
Produces
sample, main
Defines here
sample, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609040030-ab-discovery/maphref.py:1-128 · blob 0df10a0fc2df6738ce372d2f3c398584015aa671 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""What does MAP hand the Atlas, and does it match the row it sits in?

The row for REPD 8795 reads "Landfill Gas" in the TECHNOLOGY column and its MAP
link carries `technology=biomass`. One of the two is what a reader will quote.
This walks every technology the product offers -- the five spine buttons and all
twenty wider-fleet options -- and for each one reports the row's own technology
text beside the technology the link would hand the Atlas.

It reads hrefs. It does not resolve them: a link's liveness cannot be asserted
from inside the page, and a string that describes liveness is not liveness.
"""

import argparse
import json
import os
import sys
import time
from collections import Counter

sys.path.insert(0, r'C:\Users\vikra\OneDrive\Documents\GitHub\claude\familiars')
from clicker import Browser, PROBE_VISIBLE  # noqa: E402

BASE = 'http://127.0.0.1:8971/releases/%s-pipelinenews/index.html'

# the row's own technology text beside the link's technology parameter
PAIRS = r"""(() => {
  const rows = [...document.querySelectorAll('#tbody tr')];
  const out = [];
  for (const tr of rows) {
    const cells = [...tr.children].map(td => (td.textContent || '').replace(/\s+/g, ' ').trim());
    const a = [...tr.querySelectorAll('a')].filter(x => /\bMAP\b/i.test(x.textContent || ''))[0];
    let param = null, ref = null, cap = null;
    if (a) {
      const u = new URL(a.getAttribute('href'), location.href);
      param = u.searchParams.get('technology');
      ref = u.searchParams.get('repd_ref');
      cap = u.searchParams.get('capacity_mw');
    }
    out.push({shown: cells[5] || null, link: param, ref: ref || cells[8] || null,
              cap_cell: cells[7] || null, cap_link: cap, has_link: !!a});
  }
  return out;
})()"""

PAGINATION = r"""(() => {
  const hits = [];
  for (const e of document.querySelectorAll('#projectWindowControls *, .pager, .pagination, [class*=page]')) {
    const t = (e.textContent || '').replace(/\s+/g, ' ').trim();
    if (/\bof\b/.test(t) && t.length < 60 && !e.querySelector('*')) hits.push(t);
  }
  return [...new Set(hits)].slice(0, 6);
})()"""


def sample(b, label):
    pairs = b.js(PAIRS)
    if not isinstance(pairs, list):
        return {'label': label, 'error': str(pairs)[:120]}
    mism = [p for p in pairs if p['has_link'] and p['shown'] and p['link']
            and p['shown'].lower().replace(' ', '_') != p['link'].lower()]
    return {
        'label': label,
        'rows': len(pairs),
        'with_link': sum(1 for p in pairs if p['has_link']),
        'mismatched': len(mism),
        'shown_vs_link': [k + ' -> ' + v for k, v in
                          Counter((p['shown'], p['link']) for p in pairs
                                  if p['has_link']).keys()],
        'cap_mismatch': sum(1 for p in pairs if p['has_link'] and p['cap_link']
                            and p['cap_cell']
                            and p['cap_cell'].replace(' MW', '').replace(',', '')
                            != p['cap_link']),
        'example': mism[0] if mism else None,
        'pagination': b.js(PAGINATION),
        'counter': b.js("(document.getElementById('resultsMeta')||{}).textContent"),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--port', type=int, required=True)
    ap.add_argument('--gen', required=True)
    ap.add_argument('--out', required=True)
    args = ap.parse_args()

    b = Browser(args.port, mobile=False, headless=True)
    res = {'generation': args.gen,
           'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'cuts': []}
    try:
        b.setup(); b.arm()
        for m in ('Browser.setDownloadBehavior', 'Page.setDownloadBehavior'):
            try:
                b.send(m, behavior='deny')
            except Exception:
                pass
        b.go(BASE % args.gen, settle=8.0)
        vis = b.js(PROBE_VISIBLE)
        if not isinstance(vis, dict) or vis.get('hidden') is not False:
            res['ABORT'] = 'document.hidden was not false'
            print(json.dumps(res)); return

        names = b.js("[...document.querySelectorAll('#tech button')]"
                     ".map(b=>b.textContent.trim())")
        for i, n in enumerate(names or []):
            b.js("document.querySelectorAll('#tech button')[%d].click()" % i)
            time.sleep(1.1)
            res['cuts'].append(sample(b, 'SPINE ' + n))

        n_opts = b.js("(document.getElementById('widerTechnology')||{options:[]})"
                      ".options.length")
        for i in range(1, int(n_opts or 0)):
            label = b.js(
                "(()=>{const s=document.getElementById('widerTechnology');"
                "s.selectedIndex=%d;s.dispatchEvent(new Event('change',{bubbles:true}));"
                "return s.options[%d].textContent.trim();})()" % (i, i))
            time.sleep(1.1)
            res['cuts'].append(sample(b, 'WIDER ' + str(label)))
        res['errs'] = b.js('(window.__errs||[]).slice(0,8)')
    finally:
        b.close()

    with open(args.out, 'w', encoding='utf-8') as fh:
        json.dump(res, fh, indent=1)
    print('WROTE', args.out, len(res['cuts']), 'cuts')


if __name__ == '__main__':
    main()