GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / familiars

Localai and 2 more files

A Python command-line tool in the familiars folder of Claude that fetches run log (`fetch_run_log`) and job log (`fetch_job_log`) and prints health (`print_health`) (units: kW).

700 lines of Python from claude, in 3 files. Topic: AI agents and coordination. Section 1598 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. Clicker interaction · claude / familiars/clicker.py lines 468–599
  2. Harvest ingest · claude / familiars/harvest.py lines 1–173
  3. Localai ingest · claude / familiars/localai.py lines 1–395

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 468–599 of 599 (continued from section 1597) · 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
journey_maplink, journey_arrival, 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 familiars/clicker.py:468-599 · 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

def journey_maplink(b, shots_dir):
    """Where does MAP actually go?

    Every Pipeline News generation builds every per-project Atlas link from one
    frozen constant, and ten invariants guard it - all of them shape checks. A
    pathname equality asserted that the route was /gridatlas/<release_id>/,
    which is exactly the form that has returned 404 since the Atlas moved to a
    composed shell. The check passed for four days while the button was dead.

    So this reads the HREF THE PRODUCT WOULD OPEN, off a rendered row, and
    reports it for a caller to resolve over the network. A link's liveness
    cannot be asserted from inside the page - CORS forbids the readback - and a
    string that describes liveness is not liveness."""
    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'
        return out

    time.sleep(2.0)
    out['title'] = b.js('document.title')
    out['module_threw'] = b.js(
        "(window.__errs||[]).filter(e=>/receiver|contract|Atlas/i.test(e)).slice(0,4)")
    out['links'] = b.js(
        "[...document.querySelectorAll('a')].map(a=>a.href)"
        ".filter(h=>/gridatlas/.test(h)).slice(0,6)")
    out['map_cells'] = b.js(
        "[...document.querySelectorAll('a,button')]"
        ".filter(e=>/^MAP$/i.test((e.textContent||'').trim()))"
        ".slice(0,3).map(e=>({tag:e.tagName, href:e.href||null,"
        " onclick:!!e.onclick}))")
    out['rows'] = b.js("document.querySelectorAll('#results tbody tr').length")
    out['console_errors'] = b.js('(window.__errs||[]).slice(0,6)')
    out['shots'].append(b.shot(os.path.join(shots_dir, 'maplink-01.png')))
    return out



def journey_arrival(b, shots_dir):
    """What does a reader actually GET when a deep link lands?

    Not how much screen the map has - what the product SAYS. Whether the
    identity resolved, whether any measurement was computed for it, and if
    not, whether the page says so or simply shows nothing. An absence that
    announces itself and an absence that is silent look identical in a
    screenshot and are completely different products."""
    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'
        return out

    time.sleep(7.0)                      # the register resolves before anything is read
    out['deep_link_state'] = b.js(
        "({state: document.body.dataset.gridatlasRepdDeepLink || null,"
        " ref: document.body.dataset.gridatlasRepdRef || null})")
    out['search_state'] = b.js(
        "(()=>{const s=window.__GRIDATLAS_PLACE_SEARCH__||window.__V9_PLACE_SEARCH__;"
        "if(!s)return null;const d=s.deep_link||{};"
        "return {status:d.status,resolved:d.resolved,mapped:d.mapped,name:d.name,"
        "technology:d.technology,capacity_mw:d.capacity_mw,message:d.message||null};})()")
    out['card_text'] = b.js(
        "(()=>{const c=document.querySelector('.maplibregl-popup-content,"
        ".gridatlas-sheet,.gridatlas-neon-block');"
        "return c?(c.textContent||'').replace(/\s+/g,' ').trim().slice(0,1400):null;})()")
    out['measurement_words'] = b.js(
        "(()=>{const t=(document.body.textContent||'').replace(/\s+/g,' ');"
        "const hits={};"
        "for (const w of ['Nearest','substation','km straight','corridor estimate',"
        "'400 kV','no measurement','not measured','No mapped feature']) "
        "  hits[w]=(t.match(new RegExp(w.replace(/[.*+?^${}()|[\\]\\\\]/g,'\\\\$&'),'gi'))||[]).length;"
        "return hits;})()")
    out['layers_lit'] = b.js(
        "(()=>{try{const m=window.map;if(!m||!m.getStyle)return null;"
        "const ls=m.getStyle().layers||[];"
        "const vis=ls.filter(l=>{try{return m.getLayoutProperty(l.id,'visibility')!=='none';}"
        "catch(_){return false;}});"
        "return {total:ls.length, visible:vis.length,"
        " named:vis.map(l=>l.id).filter(id=>/wind|solar|bess|repd|project/i.test(id)).slice(0,12)};"
        "}catch(e){return {error:String(e).slice(0,80)};}})()")
    out['camera'] = b.js(
        "(()=>{const L=window.__GRIDATLAS_NEON_LINKS__||{};"
        "const m=L.map||window.map||null;"
        "const cam=m&&m.getZoom?{zoom:+m.getZoom().toFixed(2),"
        " center:m.getCenter?[+m.getCenter().lng.toFixed(4),+m.getCenter().lat.toFixed(4)]:null,"
        " bearing:m.getBearing?+m.getBearing().toFixed(1):null,"
        " pitch:m.getPitch?+m.getPitch().toFixed(1):null}:null;"
        "return {camera:cam, requested_zoom:L.requested_zoom??null,"
        " zoom_applied:L.zoom_applied??null, has_map_handle:!!m};})()")
    out['console_errors'] = b.js('(window.__errs||[]).slice(0,8)')
    out['shots'].append(b.shot(os.path.join(shots_dir, 'arrival.png')))
    return out


JOURNEYS = {'world': journey_world, 'summary': journey_summary,
            'atlas-rest': journey_atlas_rest, 'maplink': journey_maplink,
            'arrival': journey_arrival}


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--port', type=int, required=True)
    ap.add_argument('--url', required=True)
    ap.add_argument('--journey', default='world', choices=sorted(JOURNEYS))
    ap.add_argument('--mobile', action='store_true')
    ap.add_argument('--shots', default=None)
    ap.add_argument('--headed', action='store_true')
    a = ap.parse_args(argv)

    shots = a.shots or tempfile.mkdtemp(prefix='clicker-shots-')
    os.makedirs(shots, exist_ok=True)

    b = Browser(a.port, mobile=a.mobile, headless=not a.headed)
    try:
        b.setup()
        b.arm()
        b.go(a.url)
        result = JOURNEYS[a.journey](b, shots)
    finally:
        b.close()

    result['_clicker'] = {'port': a.port, 'mobile': a.mobile, 'url': a.url,
                          'shots_dir': shots}
    print(json.dumps(result, indent=1))
    return 0 if not result.get('ABORT') else 2


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

Harvest

A Python command-line tool in the familiars folder of Claude that fetches wider fleet, grid proximity, wind and solar.

ingestclaude / familiars/harvest.py · lines 1–173 of 173 · Entry point

What it does
It fetches wider fleet, grid proximity, wind and solar. Defines ask, load, main. 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). Domain terms in the code: wind, solar.
Inputs & outputs
In: JSON file 202609030009-wider-fleet.json; JSON file 202608311610-grid-proximity.json; command-line arguments.
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`) and the load step (`load`). Measure whether the local model is worth harvesting, on a real estate defect.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · familiars · Python CLI
Uses
json, os, re, sys, time, urllib.request, collections
Used by
none found
Produces
ask, load, main
Defines here
ask, load, 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 familiars/harvest.py:1-173 · blob 1c56f7fc7a1976ae69a614dc8ac8409769e1b75c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""harvest.py - measure whether the local model is worth harvesting, on a real estate defect.

WHY THIS EXISTS

The estate carries a known defect: the spine field called `town` is the PLANNING AUTHORITY,
not the settlement. "Aberdeenshire" is not where a project is; it is who decides it. Any card
that prints that field as a location is telling the reader something false.

The settlement is usually present, but only as free text inside the project name:

    "The Kintore Hydrogen Project, Kintore - Hydrogen Plant"   -> Kintore
    "Ewe Hill Wind Farm Extension II"                          -> (none; no settlement stated)

That is fuzzy extraction over messy human strings, which is the one shape of work a small
local model can plausibly do better than a regex - and the one shape where it is easy to
fool yourself into believing it did. So this does not ask the model to do the job. It asks
whether the model CAN do the job, and prints a number.

THE SCORING RULE

A model answer is only counted correct if it survives three checks that need no gazetteer:

  1. GROUNDED  - the answer appears verbatim in the source name. A locality the model
                 invented is the failure mode that matters, and it is invisible unless
                 tested for explicitly.
  2. NOT THE AUTHORITY - the answer is not just the planning authority echoed back. That is
                 the defect we are trying to fix; reproducing it is not a fix.
  3. NOT BOILERPLATE - the answer is not a technology or project word ("Solar Farm",
                 "Hydrogen Plant", "Extension"). A model that returns the tech word scores
                 well on grounding while being useless.

ABSTENTION IS CORRECT. Many names contain no settlement at all. A model that says NONE on
those is right, and a model that invents something is worse than useless - it would write a
false locality into a shipping product. So abstention is scored separately from accuracy,
and a high invention rate fails the harvest regardless of how good the hits look.

WHAT THE NUMBER MEANS

Precision here is: of the answers the model volunteered, how many were real, grounded,
non-authority localities. Ship the model into the pipeline only if precision is high AND
invention is near zero. A model that is right 70% of the time is not usable for a field a
reader will trust - it is a machine for generating plausible wrong towns.

Usage:
    python familiars/harvest.py            # 40 rows
    python familiars/harvest.py 120        # more
"""
import json, os, re, sys, time, urllib.request, collections

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/")
REL = os.environ.get("PN_DATA", REL.replace("/c/", "C:/"))

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):
    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):
            continue
        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))
        for r in rs:
            if r.get(namekey):
                rows.append((r[namekey], str(r.get(authkey) or ""), fn.split("-")[-1][:-5]))
    # deterministic spread across both files rather than the first N of one
    step = max(1, len(rows) // n)
    return rows[::step][:n]


def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 40
    rows = load(n)
    print(f"harvest test: {len(rows)} project names, model {MODEL}\n")

    volunteered = hit = invented = echoed = boiler = 0
    abstained = 0
    examples, misses = [], []
    t0 = time.time()

    for name, auth, src in rows:
        try:
            a = ask(name)
        except Exception as e:
            print("  request failed:", e)
            continue
        low = a.lower()
        if low in ("none", "n/a", "unknown", "") or low.startswith("none"):
            abstained += 1
            continue
        volunteered += 1
        grounded = low in name.lower()
        is_auth = auth and low == auth.lower()
        is_boiler = bool(BOILER.match(a)) or low in ("uk", "england", "scotland", "wales")
        if not grounded:
            invented += 1
            misses.append((name, a, "INVENTED - not in the name"))
        elif is_auth:
            echoed += 1
            misses.append((name, a, "echoed the planning authority"))
        elif is_boiler:
            boiler += 1
            misses.append((name, a, "boilerplate/tech word"))
        else:
            hit += 1
            if len(examples) < 6:
                examples.append((name, a))

    dt = time.time() - t0
    print(f"  answered      {volunteered:>4}   abstained (said NONE) {abstained}")
    print(f"  usable hits   {hit:>4}")
    print(f"  INVENTED      {invented:>4}   <- not present in the source name")
    print(f"  echoed auth   {echoed:>4}")
    print(f"  boilerplate   {boiler:>4}")
    prec = 100.0 * hit / volunteered if volunteered else 0.0
    invrate = 100.0 * invented / volunteered if volunteered else 0.0
    print(f"\n  precision  {prec:5.1f}%   invention {invrate:5.1f}%   {dt:.0f}s "
          f"({dt/max(1,len(rows)):.2f}s/row)")

    if examples:
        print("\n  hits:")
        for nm, a in examples:
            print(f"    {a:<22} <- {nm[:70]}")
    if misses:
        print("\n  failures:")
        for nm, a, why in misses[:6]:
            print(f"    {a:<22} <- {nm[:56]}  [{why}]")

    print()
    if volunteered == 0:
        print("  VERDICT: model abstained on everything. Nothing to harvest.")
    elif prec >= 90 and invrate <= 2:
        print("  VERDICT: HARVEST. Precision high and invention near zero.")
    elif invrate > 10:
        print(f"  VERDICT: DISCARD. {invrate:.0f}% invention would write false localities "
              "into a shipping field.")
    else:
        print(f"  VERDICT: NOT YET. {prec:.0f}% precision is not good enough for a field a "
              "reader trusts. Usable only behind human review.")
    return 0


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

Localai

A Python command-line tool in the familiars folder of Claude that fetches run log (`fetch_run_log`) and job log (`fetch_job_log`) and prints health (`print_health`) (units: kW).

ingestclaude / familiars/localai.py · lines 1–395 of 844 · Entry point · pattern generate (shared by 2 files)

What it does
It fetches data. Defines 29 functions or classes, including LocalAIError, _url, _get, _post, generate. Uses libraries argparse, io, json, os, re. 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: command-line arguments.
Downstream impact
Used directly by 1 file: Triage (claude).
What it achieves
It serves igpu (`serve_igpu`) and is built from the local ai error class (`LocalAIError`) and the generate step (`generate`). The clerical mind that runs on this machine's own silicon. It accepts `--health`, `--bench` and `--serve-igpu`.
Why it matters
Imported by Triage.
Application
claude · familiars · Python CLI
Uses
Claude Audit Estate (script call), Claude Gh API (script call), argparse, io, json, os, re, shutil, subprocess, sys
Used by
imported by Triage (import)
Produces
LocalAIError, generate, chat, nvidia_smi, resident, repo_path, git, git_bash, fetch_run_log, fetch_job_log, gh_json, failing_jobs
Defines here
LocalAIError, _url, _get, _post, generate, chat, nvidia_smi, resident, repo_path, git, git_bash, fetch_run_log, fetch_job_log, _slug, gh_json
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/localai.py:1-395 · blob f7268dde3331a5f5b63f8b901ff7c255ae99df27 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""localai.py - the clerical mind that runs on this machine's own silicon.

WHY THIS EXISTS

A large model's attention is the scarce resource in this estate. Reading a 4,000-line
CI log to find which step died, describing what an untracked file appears to be, turning
a diff into two lines - none of that needs a frontier model. It needs a competent reader
that is already resident in VRAM and answers in under a second.

So it runs here. Two adapters on this laptop, both working:

    gpu   RTX 5070 Laptop, CUDA 13.1, sm_120   qwen3:4b-instruct-2507-q4_K_M   :11434
    igpu  Intel(R) Graphics, Vulkan            qwen3:0.6b                      :11435

The discrete card carries the model that needs to be right. The integrated GPU - which
Ollama drops by default, and which cost nothing because it is soldered to the CPU - carries
the short classifications. Measured together they do more work than either alone.

    python familiars/localai.py --health
    python familiars/localai.py --bench
    python familiars/localai.py --job classify-ci-failure --input <log path>
    python familiars/localai.py --job classify-ci-failure --input Ventusltd/cvaa#33715076001
    python familiars/localai.py --job summarise-commit    --input <sha> [--repo gridatlas]
    python familiars/localai.py --job triage-untracked    --input gridatlas
    python familiars/localai.py --serve-igpu     # start the Intel-pinned server

MEASURED, NOT ASSUMED

The failure mode this file is written against is a model that silently ran on the CPU, or
an endpoint that was never up, while the caller got a fluent answer and believed it. So:

  - --health FAILS with a non-zero exit when the endpoint is down. It never falls back to a
    cheerful default, and it never substitutes one device for another silently.
  - Offload is read from /api/ps as size_vram / size. Anything below 100% is reported as the
    number, not as a pass. A model half on the CPU is a measurement, not an error - but it is
    never described as "on the GPU".
  - Every job that cannot find its subject RAISES. A missing log, an unknown sha, a repo that
    is not there: these exit non-zero. A skip is not a pass.
  - Throughput is read from Ollama's own eval_count / eval_duration, which counts generated
    tokens against the generation clock only. Load time is reported separately, because
    folding a cold start into tokens/s is how a fast model gets reported as a slow one.

WINDOWS NOTES

python3 is a broken Store stub here; this file is run with `python`. Requests are stdlib
urllib - no dependency is added to requirements.txt for this. Per-request num_ctx is
deliberately NOT sent: it differs from the server's loaded context and forces a full model
reload, which was measured costing ~5 s and evicting the resident weights. Context is set
once on the server via OLLAMA_CONTEXT_LENGTH.
"""

import argparse
import io
import json
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
import zipfile
from concurrent.futures import ThreadPoolExecutor

GITHUB = r'C:\Users\vikra\OneDrive\Documents\GitHub'
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OLLAMA_EXE = os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Ollama', 'ollama.exe')

DEVICES = {
    'gpu': {
        'endpoint': 'http://127.0.0.1:11434',
        'model': 'qwen3:4b-instruct-2507-q4_K_M',
        'adapter': 'NVIDIA GeForce RTX 5070 Laptop GPU',
        'backend': 'CUDA',
        # The -instruct-2507 line has no thinking mode; sending think=false is a 400 here.
        'thinking': False,
    },
    'igpu': {
        'endpoint': 'http://127.0.0.1:11435',
        'model': 'qwen3:0.6b',
        'adapter': 'Intel(R) Graphics',
        'backend': 'Vulkan',
        # Plain qwen3:0.6b IS a thinking model, and that is a trap for short clerical jobs:
        # measured on 2026-09-03 it spent all 90 permitted tokens inside <think> and returned
        # response="" with done_reason="length" - 392 thinking characters, nothing to show the
        # caller. Thinking is switched off explicitly rather than paid for in a budget this
        # small. See the empty-completion guard in generate().
        'thinking': True,
    },
}

# Jobs are routed to the device that suits them. The 0.6B on the iGPU is competent at
# "name this file" and is not trusted with a diff.
JOB_DEVICE = {
    'classify-ci-failure': 'gpu',
    'summarise-commit': 'gpu',
    'triage-untracked': 'igpu',
}

MAX_CHARS = 12000  # ~3k tokens, comfortably inside the 8192 context with room to answer


class LocalAIError(RuntimeError):
    """Raised when the local stack cannot be measured. Never caught to produce a default."""


# --------------------------------------------------------------------------- transport

def _url(device, path):
    return DEVICES[device]['endpoint'] + path


def _get(device, path, timeout=10):
    try:
        with urllib.request.urlopen(_url(device, path), timeout=timeout) as r:
            return json.load(r)
    except urllib.error.URLError as e:
        raise LocalAIError(
            'endpoint DOWN for device %r at %s%s (%s). '
            'Start it: `ollama serve` for gpu, or `python familiars/localai.py --serve-igpu` '
            'for the Intel adapter. Not falling back to another device.'
            % (device, DEVICES[device]['endpoint'], path, e))
    except OSError as e:
        raise LocalAIError('endpoint unreadable for device %r: %s' % (device, e))


def _post(device, path, payload, timeout=600):
    body = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(_url(device, path), data=body,
                                 headers={'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        raise LocalAIError('device %r returned HTTP %s: %s'
                           % (device, e.code, e.read()[:400].decode('utf-8', 'replace')))
    except urllib.error.URLError as e:
        raise LocalAIError(
            'endpoint DOWN for device %r at %s (%s). Not falling back.'
            % (device, DEVICES[device]['endpoint'], e))


def generate(device, prompt, system=None, num_predict=320, temperature=0.0, stop=None):
    """One completion. Returns the text and the metrics Ollama measured for it.

    `stop` matters more than it looks. Asking a 4B for "exactly two lines, no markdown" was
    measured failing twice: it answered with headings, bold and an emoji regardless. Ending
    the prompt mid-sentence so the model can only continue it, plus a stop sequence, is what
    actually holds the shape - an instruction is a request, a stop token is a constraint.
    """
    if device not in DEVICES:
        raise LocalAIError('unknown device %r; known: %s' % (device, ', '.join(DEVICES)))
    opts = {'temperature': temperature, 'num_predict': num_predict}
    if stop:
        opts['stop'] = list(stop)
    payload = {
        'model': DEVICES[device]['model'],
        'prompt': prompt,
        'stream': False,
        'keep_alive': '30m',
        'options': opts,
    }
    if system:
        payload['system'] = system
    if DEVICES[device].get('thinking'):
        payload['think'] = False
    t0 = time.time()
    r = _post(device, '/api/generate', payload)
    wall = time.time() - t0
    ev, ed = r.get('eval_count') or 0, r.get('eval_duration') or 0
    pe, pd = r.get('prompt_eval_count') or 0, r.get('prompt_eval_duration') or 0
    text = (r.get('response') or '').strip()
    # An empty completion is a failure, not a blank cell. Left unguarded it prints as None in
    # a results table and reads as "nothing to report" - the cheerful default this file exists
    # to prevent. Say what was actually spent, so the cause is in the message.
    if not text:
        raise LocalAIError(
            'device %r returned an EMPTY completion (done_reason=%r, %d tokens generated, '
            '%d thinking chars). The token budget was spent without producing an answer; '
            'raise num_predict or disable thinking for this model.'
            % (device, r.get('done_reason'), ev, len(r.get('thinking') or '')))
    return {
        'device': device,
        'model': DEVICES[device]['model'],
        'text': text,
        'eval_tokens': ev,
        'eval_s': round(ed / 1e9, 3) if ed else 0.0,
        'tok_s': round(ev / (ed / 1e9), 1) if ed else None,
        'prompt_tokens': pe,
        'prefill_tok_s': round(pe / (pd / 1e9), 1) if pd else None,
        'load_s': round((r.get('load_duration') or 0) / 1e9, 3),
        'wall_s': round(wall, 2),
    }


def chat(device, messages, num_predict=320, temperature=0.0, stop=None):
    """Same as generate(), but multi-turn - which is what actually constrains output shape.

    Measured 2026-09-03 on classify-ci-failure: three escalating instructions and then a
    worked example inside a single prompt all failed to stop this 4B answering in markdown
    prose. Putting the example in as a real assistant TURN worked first time. The model
    imitates the conversation it is in far more reliably than it obeys a description of one.
    """
    if device not in DEVICES:
        raise LocalAIError('unknown device %r; known: %s' % (device, ', '.join(DEVICES)))
    opts = {'temperature': temperature, 'num_predict': num_predict}
    if stop:
        opts['stop'] = list(stop)
    payload = {'model': DEVICES[device]['model'], 'messages': messages, 'stream': False,
               'keep_alive': '30m', 'options': opts}
    if DEVICES[device].get('thinking'):
        payload['think'] = False
    t0 = time.time()
    r = _post(device, '/api/chat', payload)
    wall = time.time() - t0
    ev, ed = r.get('eval_count') or 0, r.get('eval_duration') or 0
    pe, pd = r.get('prompt_eval_count') or 0, r.get('prompt_eval_duration') or 0
    text = ((r.get('message') or {}).get('content') or '').strip()
    if not text:
        raise LocalAIError(
            'device %r returned an EMPTY chat completion (done_reason=%r, %d tokens). '
            'The budget was spent without an answer.' % (device, r.get('done_reason'), ev))
    return {'device': device, 'model': DEVICES[device]['model'], 'text': text,
            'eval_tokens': ev, 'eval_s': round(ed / 1e9, 3) if ed else 0.0,
            'tok_s': round(ev / (ed / 1e9), 1) if ed else None,
            'prompt_tokens': pe,
            'prefill_tok_s': round(pe / (pd / 1e9), 1) if pd else None,
            'load_s': round((r.get('load_duration') or 0) / 1e9, 3),
            'wall_s': round(wall, 2)}


# --------------------------------------------------------------------------- hardware

def nvidia_smi():
    """Free/used VRAM and utilisation straight from nvidia-smi. None if there is no card."""
    try:
        out = subprocess.run(
            ['nvidia-smi', '--query-gpu=name,memory.total,memory.used,memory.free,'
             'utilization.gpu,driver_version', '--format=csv,noheader,nounits'],
            capture_output=True, text=True, timeout=20)
    except (OSError, subprocess.SubprocessError):
        return None
    if out.returncode != 0 or not out.stdout.strip():
        return None
    f = [p.strip() for p in out.stdout.strip().splitlines()[0].split(',')]
    if len(f) < 6:
        return None
    return {'name': f[0], 'total_mib': int(f[1]), 'used_mib': int(f[2]),
            'free_mib': int(f[3]), 'util_pct': int(f[4]), 'driver': f[5]}


def resident(device):
    """What /api/ps says is loaded, including how much of it actually sits in VRAM."""
    ps = _get(device, '/api/ps')
    rows = []
    for m in ps.get('models') or []:
        size, vram = m.get('size') or 0, m.get('size_vram') or 0
        rows.append({
            'name': m.get('name'),
            'size_gb': round(size / 1e9, 2),
            'vram_gb': round(vram / 1e9, 2),
            'offload_pct': round(100.0 * vram / size, 1) if size else 0.0,
            'context': m.get('context_length'),
            'quant': (m.get('details') or {}).get('quantization_level'),
        })
    return rows


# --------------------------------------------------------------------------- git / gh

def repo_path(name_or_path):
    """Resolve a repo name to its canonical checkout. Raises if it is not a git repo."""
    if os.path.isdir(os.path.join(name_or_path, '.git')) or os.path.isfile(
            os.path.join(name_or_path, '.git')):
        return os.path.abspath(name_or_path)
    cand = os.path.join(GITHUB, name_or_path)
    if os.path.exists(os.path.join(cand, '.git')):
        return cand
    raise LocalAIError('no git repo at %r (tried %r and %r)'
                       % (name_or_path, os.path.abspath(name_or_path), cand))


def git(cwd, *args, **kw):
    out = subprocess.run(['git'] + list(args), cwd=cwd, capture_output=True,
                         text=True, errors='replace', timeout=kw.get('timeout', 120))
    if out.returncode != 0 and not kw.get('allow_fail'):
        raise LocalAIError('git %s failed in %s: %s'
                           % (' '.join(args), cwd, (out.stderr or '').strip()[:400]))
    return out.stdout


def git_bash():
    """Locate Git Bash, never the WSL stub.

    `bash` on this machine's PATH resolves to C:\\Users\\...\\AppData\\Local\\Microsoft\\
    WindowsApps\\bash.exe - the Windows Store WSL launcher, the same trap as the python3 stub
    CLAUDE.md records. It is worse than python3's, because it does not error: it HANGS.
    Measured 2026-09-03, gh-api.sh through it timed out at 180 s and again at 25 s with
    stdin=DEVNULL, while the identical command in Git Bash returned 30,442 bytes in 1.345 s.
    A hang reads as a slow network, so this resolves the real shell explicitly and says so.
    """
    for cand in (r'C:\Program Files\Git\bin\bash.exe',
                 r'C:\Program Files\Git\usr\bin\bash.exe',
                 r'C:\Program Files (x86)\Git\bin\bash.exe'):
        if os.path.exists(cand):
            return cand
    git_exe = shutil.which('git')
    if git_exe:  # ...\Git\cmd\git.exe -> ...\Git\bin\bash.exe
        cand = os.path.join(os.path.dirname(os.path.dirname(git_exe)), 'bin', 'bash.exe')
        if os.path.exists(cand):
            return cand
    found = shutil.which('bash')
    if found and 'WindowsApps' not in found:
        return found
    raise LocalAIError(
        'Git Bash not found. The only bash on PATH is %r, which is the WSL Store stub and '
        'hangs instead of running the script. Install Git for Windows or set the path here.'
        % found)


def fetch_run_log(full_repo, run_id):
    """Pull a failing run's logs through scripts/gh-api.sh, which holds the credential."""
    if not os.path.exists(os.path.join(REPO_ROOT, 'scripts', 'gh-api.sh')):
        raise LocalAIError('scripts/gh-api.sh not found under %s' % REPO_ROOT)
    # Git Bash mangles a Windows path handed to it as an argument: C:\Users\...\gh-api.sh
    # arrived as "C:UsersvikraOneDrive..." with every backslash eaten, and bash reported
    # "No such file or directory". The script is invoked by a RELATIVE posix path with
    # cwd set instead, which needs no conversion and no MSYS_NO_PATHCONV.
    path = 'repos/%s/actions/runs/%s/logs' % (full_repo, run_id)
    out = subprocess.run([git_bash(), 'scripts/gh-api.sh', path, '--raw'], cwd=REPO_ROOT,
                         capture_output=True, timeout=180, stdin=subprocess.DEVNULL)
    if out.returncode != 0 or not out.stdout:
        raise LocalAIError('gh-api.sh could not fetch %s: %s'
                           % (path, (out.stderr or b'')[:300].decode('utf-8', 'replace')))
    try:
        zf = zipfile.ZipFile(io.BytesIO(out.stdout))
    except zipfile.BadZipFile:
        raise LocalAIError('run %s logs were not a zip; API said: %s'
                           % (run_id, out.stdout[:300].decode('utf-8', 'replace')))
    names = [n for n in zf.namelist() if n.endswith('.txt')]
    if not names:
        raise LocalAIError('run %s logs contained no .txt entries' % run_id)

    # Concatenating every job's log and reading the tail was measured picking up the wrong
    # thing: on gridatlas run 33800308935 the tail was a Node 20 deprecation WARNING from a
    # passing job, and the classifier dutifully reported it as the failure. A warning at the
    # end of the file is not the cause of the run being red. So the failing job is identified
    # from the API first, and only its log is read.
    failing = failing_jobs(full_repo, run_id)
    wanted = names
    if failing:
        picked = [n for n in names
                  if any(_slug(j['name']) in _slug(n) for j in failing)]
        if picked:
            wanted = picked
    chunks = ['===== %s =====\n%s' % (n, zf.read(n).decode('utf-8', 'replace'))
              for n in wanted]
    return '\n'.join(chunks), failing


def fetch_job_log(full_repo, job_id):
    """One JOB's log as plain text. The run-level endpoint above returns a zip of every job
    and costs a redirect plus an unzip; the job-level one returns the single log that matters.

    Measured 2026-09-03 on globalgrid2050 job 100839327538: 1.3s, 57 kB, HTTP 200, no zip.
    That is the difference between a 44-job estate sweep costing a minute and costing ten,
    which is why triage.py uses this one and not fetch_run_log.

    The job id is in audit_estate.py's JSON already, on each failed job's `url`.
    """
    if not os.path.exists(os.path.join(REPO_ROOT, 'scripts', 'gh-api.sh')):
        raise LocalAIError('scripts/gh-api.sh not found under %s' % REPO_ROOT)
    path = 'repos/%s/actions/jobs/%s/logs' % (full_repo, job_id)
    out = subprocess.run([git_bash(), 'scripts/gh-api.sh', path, '--raw'], cwd=REPO_ROOT,
                         capture_output=True, timeout=180, stdin=subprocess.DEVNULL)
    if out.returncode != 0 or not out.stdout:
        raise LocalAIError('gh-api.sh could not fetch %s: %s'
                           % (path, (out.stderr or b'')[:300].decode('utf-8', 'replace')))
    text = out.stdout.decode('utf-8', 'replace').lstrip('')
    # A 404/410 comes back as JSON with HTTP 200 semantics through curl -sSL; it is not a log.
    if text.lstrip().startswith('{') and '"message"' in text[:400]:
        raise LocalAIError('job %s log unavailable: %s' % (job_id, text[:200]))
    return text


def _slug(s):
    return re.sub(r'[^a-z0-9]+', '', str(s).lower())


def gh_json(path):
    """One authenticated GitHub API call through gh-api.sh."""
    out = subprocess.run([git_bash(), 'scripts/gh-api.sh', path], cwd=REPO_ROOT,
                         capture_output=True, timeout=120, stdin=subprocess.DEVNULL)
    if out.returncode != 0: