GLOBALGRID2050 / EXPLORE CODE

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

Triage and 2 more files

A Python command-line tool in the familiars folder of Claude that reads red board and triage estate. It builds prompt (`build_prompt`), parses answer (`parse_answer`) and fits excerpt (`fit_excerpt`).

700 lines of Python from claude, in 3 files. Topic: AI agents and coordination. Section 1601 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. Runners render · claude / familiars/runners.py lines 701–772
  2. Summon ingest · claude / familiars/summon.py lines 1–250
  3. Triage render · claude / familiars/triage.py lines 1–378

Runners

A Python command-line tool in the familiars folder of Claude that fetches runners estate and board, using SHA-256 from GitHub API and the GridAtlas repository.

renderclaude / familiars/runners.py · lines 701–772 of 772 (continued from section 1600) · Entry point · pattern write_atomic (shared by 2 files)

What it does
It fetches runners estate and board. Defines 17 functions or classes, including utc, _run, _git, _token, _api. Uses libraries argparse, hashlib, json, os, 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).
Inputs & outputs
In: data source: gridatlas data; data source: GitHub API; JSON file current.json; JSON file runners-estate.json; JSON file board.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 runs live (`run_live`), runs ci (`run_ci`) and runs estate (`run_estate`). A continuous pool that keeps this machine measuring while the model thinks. It accepts `--board`, `--once` and `--only`.
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
Summon (script call), Clicker (script call), GridAtlas — Atlas Page (estate URL), Atlas — World Page (estate URL), argparse, hashlib, json, os, subprocess, sys, time, traceback
Used by
none found
Produces
utc, run_live, run_ci, run_estate, run_proof, run_ceiling, run_clicker, call, diff_fingerprints, render_md, write_atomic, main
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 familiars/runners.py:701-772 · blob 7fc90609775323d656089b27b12521d2653808bf · 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
                # cp1252 here, and a UnicodeEncodeError in the logging line would
                # kill the daemon over a middot.
                line = '%s  %-8s %-5s %ss  %s' % (utc(), name, res['status'],
                                                  res.get('seconds'), (res.get('note') or '')[:150])
                print(line.encode('ascii', 'replace').decode('ascii'), flush=True)

            # 3. only the runners that just reported are diffed. A runner that did
            #    not run this pass has not moved, and claiming it did would be news
            #    about nothing.
            if new_fp:
                stamp = utc()
                changes += ['%s  %s' % (stamp, line)
                            for line in diff_fingerprints(prev_fp, new_fp)]
                prev_fp = {**prev_fp, **new_fp}

            # 4. a full sweep is every runner having reported since the last one
            sweep_closed = False
            if seen_since_sweep >= set(wanted):
                full_sweeps += 1
                seen_since_sweep = set()
                sweep_closed = True

            # 5. write the board whenever anything moved (and on a sweep close)
            if new_fp or sweep_closed:
                for name in state:
                    e = state[name]
                    e['age_seconds'] = (round(time.time() - last_started[name], 1)
                                        if e.get('measured_utc') else None)
                    e['next_due_utc'] = utc(last_started[name] + cadence[name]) if last_started[name] else None
                board = {
                    'board': 'familiars.runners.v1',
                    'written_utc': utc(),
                    'host': {'cores': cores, 'pool_workers': cap,
                             'cores_left_free': max(0, cores - cap),
                             'python': sys.version.split()[0],
                             'note': ('CPU only. The GPU is exercised only through the '
                                      'clicker fleet\'s WebGL; the NPU is not addressable '
                                      'from this process.')},
                    'daemon': {'started_utc': utc(started_wall),
                               'uptime': '%ds' % int(time.time() - started_wall),
                               'ticks': ticks, 'full_sweeps': full_sweeps,
                               'in_flight': sorted(inflight)},
                    'cadence_seconds': {n: cadence[n] for n in sorted(wanted)},
                    'changes_since': changes_since,
                    'changes': changes,
                    'runners': state,
                }
                write_atomic(board_path, json.dumps(board, indent=1, default=str))
                write_atomic(md_path, render_md(board))
                if sweep_closed:
                    # The sweep is the unit. Its news is published once, then the
                    # slate is clean and silence means silence.
                    changes = []
                    changes_since = '%s (sweep %d closed)' % (board['written_utc'], full_sweeps)

            if a.once and not inflight and all(
                    state[n]['status'] != 'never-run' for n in wanted):
                break
            time.sleep(a.tick if not a.once else 0.5)
    except KeyboardInterrupt:
        print('stopped by keyboard at %s' % utc())
    finally:
        try:
            pool.shutdown(wait=False, cancel_futures=True)
        except TypeError:
            pool.shutdown(wait=False)
    print('board: %s\nmd:    %s' % (board_path, md_path))
    return 0


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

Summon

A Python command-line tool in the familiars folder of Claude using data from GitHub API and the GridAtlas repository.

ingestclaude / familiars/summon.py · lines 1–250 of 250 · Entry point · pattern _token (shared by 2 files)

What it does
It fetches data. Defines 11 functions or classes, including _run, _token, _api, _get, fam_repo. Uses libraries json, os, subprocess, 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: data source: GitHub API; data source: gridatlas data; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 1 file: Runners (claude).
What it achieves
It is built from the fam repo helper (`fam_repo`), the fam ci helper (`fam_ci`) and the fam live helper (`fam_live`). Familiars - small local workers that do the donkey running on this machine.
Why it matters
Run by Runners.
Application
claude · familiars · Python CLI
Uses
Atlas — World Page (estate URL), GridAtlas — Atlas Page (estate URL), json, os, subprocess, sys, time, urllib.request, concurrent.futures
Used by
run by Runners (script call)
Produces
fam_repo, fam_ci, fam_live, fam_ceiling, fam_proof, main
Defines here
_run, _token, _api, _get, fam_repo, fam_ci, fam_live, fam_ceiling, fam_proof, _call, 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/summon.py:1-250 · blob e0fece159417ed0decd0eba451e948b8c67efcb5 · 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
"""Familiars - small local workers that do the donkey running on this machine.

WHY THIS EXISTS

An agent that checks CI, then the live site, then five repositories, then a ceiling,
spends its thinking on clerical work and arrives at the interesting question already
tired. Every one of those checks is a script. None of them needs judgement.

So they are summoned instead: named workers, run in PARALLEL across this machine's
twenty cores, each returning one small fact. The caller reads a single merged answer
and spends what it saved on the part that actually needs a mind.

    python familiars/summon.py                 # all of them
    python familiars/summon.py ci live         # only these
    python familiars/summon.py --json          # machine-readable

MEASURED, NOT ASSUMED

Every familiar returns what it actually observed, and says so when it could not look.
A familiar that cannot reach its subject returns an error string - never a cheerful
default, because a false green here would be worse than no familiar at all.

WINDOWS NOTE

multiprocessing on Windows re-imports this file in each worker, so the pool lives
behind a __main__ guard and every worker is a module-level function. Heredoc-piped
code crashes the pool here; this is a real file for that reason.
"""

import json
import os
import subprocess
import sys
import time
import urllib.request
from concurrent.futures import ProcessPoolExecutor, as_completed

GITHUB = r'C:\Users\vikra\OneDrive\Documents\GitHub'
REPOS = ['gridatlas', 'globalgrid2050', 'pipelinenews', 'claude', 'cvaa',
         'data-grid-gb', 'data-gridatlas']
CEILINGS = {'sld-sandbox': 368640, 'substation-intelligence': 400000}


def _run(cmd, cwd=None, timeout=90):
    try:
        p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True,
                           timeout=timeout, shell=False)
        return p.stdout.strip()
    except Exception as exc:
        return 'ERR ' + str(exc)[:80]


def _token():
    out = _run(['git', 'credential', 'fill'], cwd=GITHUB)
    for line in out.splitlines():
        if line.startswith('password='):
            return line[9:]
    return None


def _api(path, token, raw=False):
    req = urllib.request.Request('https://api.github.com/' + path)
    if token:
        req.add_header('Authorization', 'Bearer ' + token)
    req.add_header('Accept', 'application/vnd.github+json')
    with urllib.request.urlopen(req, timeout=60) as r:
        return r.read() if raw else json.load(r)


def _get(url, timeout=40):
    try:
        with urllib.request.urlopen(url, timeout=timeout) as r:
            return r.status, r.read()
    except Exception as exc:
        return 0, str(exc).encode()


# ── the familiars ────────────────────────────────────────────────────────────

def fam_repo():
    """Working-tree truth for every repo: dirty, ahead, behind."""
    out = {}
    for name in REPOS:
        path = os.path.join(GITHUB, name)
        if not os.path.isdir(os.path.join(path, '.git')):
            continue
        _run(['git', 'fetch', '-q', 'origin'], cwd=path, timeout=120)
        head = _run(['git', 'rev-parse', '--short', 'HEAD'], cwd=path)
        dirty = _run(['git', 'status', '--porcelain'], cwd=path)
        ahead = _run(['git', 'rev-list', '--count', 'origin/main..HEAD'], cwd=path)
        behind = _run(['git', 'rev-list', '--count', 'HEAD..origin/main'], cwd=path)
        out[name] = {
            'head': head,
            'dirty': len([l for l in dirty.splitlines() if l.strip()]),
            'ahead': ahead, 'behind': behind,
        }
    return out


def fam_ci():
    """Latest conclusion per repo on its own default branch."""
    token = _token()
    out = {}
    for name in REPOS:
        try:
            d = _api('repos/Ventusltd/%s/actions/runs?branch=main&per_page=4' % name, token)
            runs = d.get('workflow_runs', [])
            if not runs:
                out[name] = 'no runs'
                continue
            sha = runs[0]['head_sha'][:7]
            same = [r for r in runs if r['head_sha'].startswith(sha)]
            bad = [r['name'][:28] for r in same if r['conclusion'] == 'failure']
            out[name] = {'sha': sha,
                         'state': 'RED' if bad else 'green',
                         'failing': bad}
        except Exception as exc:
            out[name] = 'ERR ' + str(exc)[:60]
    return out


def fam_live():
    """What the public actually receives right now."""
    out = {}
    st, body = _get('https://ventusltd.github.io/gridatlas/atlas/current.json')
    if st == 200:
        try:
            j = json.loads(body)
            out['gridatlas_generation'] = j.get('generation')
        except Exception:
            out['gridatlas_generation'] = 'unparseable'
    else:
        out['gridatlas_generation'] = 'HTTP %s' % st
    for label, url in [
        ('world', 'https://ventusltd.github.io/gridatlas/atlas/world/'),
        ('atlas', 'https://ventusltd.github.io/gridatlas/atlas/'),
        ('pipelinenews', 'https://globalgrid2050.com/pipelinenews_intelligence/202609031308/'),
        ('homepage', 'https://globalgrid2050.com/'),
    ]:
        st, _ = _get(url)
        out[label] = st
    return out


def fam_ceiling():
    """Cartridge size against its ceiling, in CHARACTERS - bytes are a different number."""
    out = {}
    carts = os.path.join(GITHUB, 'gridatlas', 'atlas', 'cartridges')
    if not os.path.isdir(carts):
        return {'error': 'no cartridges directory'}
    newest = {}
    for fn in os.listdir(carts):
        if not fn.endswith('.js'):
            continue
        for key in CEILINGS:
            if key in fn:
                if key not in newest or fn > newest[key]:
                    newest[key] = fn
    for key, fn in newest.items():
        with open(os.path.join(carts, fn), encoding='utf-8') as fh:
            text = fh.read()
        out[key] = {'file': fn, 'chars': len(text), 'bytes': len(text.encode('utf-8')),
                    'ceiling': CEILINGS[key], 'headroom': CEILINGS[key] - len(text)}
    return out


def fam_proof():
    """The STEP the runner runs - not a proof chosen by hand."""
    ga = os.path.join(GITHUB, 'gridatlas')
    runner = os.path.join(ga, 'tools', 'proofs', 'run-current.mjs')
    if not os.path.isfile(runner):
        return {'error': 'run-current.mjs missing'}
    t0 = time.time()
    try:
        p = subprocess.run(['node', runner], cwd=ga, capture_output=True,
                           text=True, timeout=900)
    except Exception as exc:
        return {'error': str(exc)[:100]}
    tail = [l for l in p.stdout.splitlines() if 'checks passed' in l or '[FAIL]' in l]
    return {'rc': p.returncode, 'seconds': round(time.time() - t0, 1),
            'lines': tail[-6:]}


FAMILIARS = {
    'repo': fam_repo,
    'ci': fam_ci,
    'live': fam_live,
    'ceiling': fam_ceiling,
    'proof': fam_proof,
}


def _call(name):
    try:
        return name, FAMILIARS[name]()
    except Exception as exc:
        return name, {'error': str(exc)[:140]}


def main(argv):
    as_json = '--json' in argv
    wanted = [a for a in argv if a in FAMILIARS] or list(FAMILIARS)
    t0 = time.time()
    results = {}
    with ProcessPoolExecutor(max_workers=min(len(wanted), os.cpu_count() or 4)) as pool:
        futures = [pool.submit(_call, n) for n in wanted]
        for fut in as_completed(futures):
            name, value = fut.result()
            results[name] = value
    results['_summoned'] = {'familiars': len(wanted),
                            'seconds': round(time.time() - t0, 1),
                            'cores': os.cpu_count()}
    if as_json:
        print(json.dumps(results, indent=1))
        return 0

    s = results
    print('summoned %d familiars in %ss on %d cores'
          % (s['_summoned']['familiars'], s['_summoned']['seconds'], s['_summoned']['cores']))
    if 'live' in s:
        L = s['live']
        print('  live      gridatlas %s | world %s atlas %s pipelinenews %s homepage %s'
              % (L.get('gridatlas_generation'), L.get('world'), L.get('atlas'),
                 L.get('pipelinenews'), L.get('homepage')))
    if 'ci' in s:
        red = [k for k, v in s['ci'].items() if isinstance(v, dict) and v.get('state') == 'RED']
        print('  ci        %d red: %s' % (len(red), ', '.join(red) or 'none'))
        for k in red:
            print('              %s %s -> %s' % (k, s['ci'][k]['sha'],
                                                 '; '.join(s['ci'][k]['failing'])))
    if 'repo' in s:
        busy = ['%s(d%s a%s b%s)' % (k, v['dirty'], v['ahead'], v['behind'])
                for k, v in s['repo'].items()
                if isinstance(v, dict) and (v['dirty'] or v['ahead'] != '0' or v['behind'] != '0')]
        print('  repos     %s' % (', '.join(busy) or 'all clean and level'))
    if 'ceiling' in s:
        for k, v in s['ceiling'].items():
            if isinstance(v, dict):
                print('  ceiling   %-26s %d/%d chars, %d left'
                      % (k, v['chars'], v['ceiling'], v['headroom']))
    if 'proof' in s:
        P = s['proof']
        print('  proof     rc=%s in %ss' % (P.get('rc'), P.get('seconds')))
        for line in P.get('lines', []):
            print('              %s' % line.strip())
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Triage

A Python command-line tool in the familiars folder of Claude that reads red board and triage estate. It builds prompt (`build_prompt`), parses answer (`parse_answer`) and fits excerpt (`fit_excerpt`).

renderclaude / familiars/triage.py · lines 1–378 of 1174 · Entry point · pattern excerpt (shared by 3 files)

What it does
It loads red board and triage estate. Defines 36 functions or classes, including strip_noise, flatten, reds_from_estate, _row, cached_log. Uses libraries argparse, json, os, queue, re. Side effects: changes the web page (DOM); 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 red-board.json; JSON file triage-estate.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
Read every red run in the estate with the local models, and ground every answer. It accepts `--gpu`, `--igpu` and `--lines`.
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
Localai (import), Claude Audit Estate (script call), argparse, json, os, queue, re, statistics, subprocess, sys
Used by
none found
Produces
strip_noise, flatten, reds_from_estate, cached_log, excerpt, first_error_line, build_prompt, parse_answer, ground, device_context, fit_excerpt, generate_retrying
Defines here
strip_noise, flatten, reds_from_estate, _row, cached_log, excerpt, first_error_line, build_prompt, parse_answer, ground, device_context
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/triage.py:1-378 · blob f95d67fc3b920447c19f6c0c1b985ae713919577 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""triage.py - read every red run in the estate with the local models, and ground every answer.

WHY THIS EXISTS

The estate carries 40-odd red workflow runs at any moment, spread over 35 repositories, and
nobody reads them. audit_estate.py names WHICH runs are red and which job and step failed -
that is the API's own record and it is authoritative - but it cannot say WHY, because why is
in the log, and the logs are 50 kB each. Forty of those is two hours of human reading for a
question that gets asked every session.

The card was idle while that was true. Measured 2026-09-03 23:40: 10-20% GPU utilisation,
a 4B model resident in 3.95 GB of VRAM answering one question every few minutes. A model that
holds memory and answers nothing is worse than no model, because it costs the memory anyway.

So this is a work pump. It enumerates the reds, fetches every failing job's log, and fans them
across BOTH adapters with several requests in flight, so the cards are loaded rather than
idling between prompts. It writes logs/red-board.md: one line per red, grouped by cause, which
a human reads in thirty seconds.

THE THING THAT MAKES IT USABLE - GROUNDING

A model's paraphrase of a log is not evidence. Another lane measured this model at 98.3%
precision, and the one invention it made was a ONE-CHARACTER MUTATION of a real log line -
a sentence that reads exactly like the log and never appeared in it. No human reviewer catches
that, so it is prevented structurally rather than reviewed for:

  1. The model is never asked for facts we already hold. repo, workflow, run id, job name and
     FAILING STEP all come from the GitHub API through audit_estate.py. The model produces
     three things only: a class, a verbatim quote, and one sentence.
  2. The class must be one of seven strings. Anything else is coerced to `unknown` and counted.
  3. The quote must be a SUBSTRING of the excerpt the model was shown - character for
     character, after normalising whitespace and stripping ANSI and runner timestamps, which
     are layout, not content. Case is significant. A one-character mutation fails this test.
     A quote shorter than MIN_QUOTE characters fails it too, because "error" is in every log
     and grounds nothing.
  4. A row that fails the check is not repaired and not deleted. It is published as UNGROUNDED
     with the model's rejected claim shown as a claim, next to the log's own first error line,
     which is quoted deterministically by this file and not by any model.

An ungrounded row is a measurement, not a failure of the run.

DISCIPLINES CARRIED FROM CLAUDE.md

  - A missing input must FAIL, never skip. A log that will not fetch becomes a FETCH-FAILED row
    and the process exits non-zero; it never silently shrinks the denominator.
  - A red whose API record names no failing job (a startup_failure, usually) is its own row,
    NO-FAILING-JOB, and is never dropped just because there is nothing to read.
  - Report measurements, never grades. This file says "9 of 40 are missing-secret"; it never
    says the estate is healthy.
  - The tail of a runner log is post-job cleanup and a Node deprecation warning. Reading it as
    the cause was a measured mistake. The excerpt is built around the ##[error] lines instead,
    by localai.focus_errors.

USAGE

    python familiars/triage.py                       # full estate sweep -> logs/red-board.md
    python familiars/triage.py --limit 6             # a short sweep while developing
    python familiars/triage.py --calibrate-conc      # measure where concurrency stops paying
    python familiars/triage.py --calibrate-lines     # measure how much log the model needs
    python familiars/triage.py --loop 900            # run as a pump, one sweep every 15 min

Exit code is 0 only when every red the audit named produced a row and every input was read.
"""

import argparse
import json
import os
import queue
import re
import statistics
import subprocess
import sys
import threading
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import localai as L  # noqa: E402  - sibling module, same directory

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOGS = os.path.join(REPO_ROOT, 'logs')
CACHE = os.path.join(LOGS, 'triage-cache')
BOARD_MD = os.path.join(LOGS, 'red-board.md')
BOARD_JSON = os.path.join(LOGS, 'red-board.json')
ESTATE_JSON = os.path.join(LOGS, 'triage-estate.json')
OWNER = 'Ventusltd'

# The whole vocabulary. Seven strings, closed set. A model answer outside it is `unknown`,
# counted as a coercion, and never invented into a new category - a taxonomy that grows by
# one entry per run is not a taxonomy.
CLASSES = [
    'missing-secret',          # a credential, token or repository secret is absent or empty
    'contract-drift',          # a gate compared two things that were meant to be identical
    'nondeterministic-input',  # an upstream source moved: an API, a download, a live page
    'dead-route',              # a URL, path or artefact the job expected does not exist
    'timeout',                 # the job or a step ran out of time or was cancelled
    'by-design-refusal',       # a gate deliberately failed closed; the failure IS the product
    'unknown',                 # the log does not say
]
CLASS_HELP = {
    'missing-secret': 'a credential, token, or repository secret is absent, empty or unauthorised',
    'contract-drift': 'two things a gate required to be identical were not (bytes, digests, counts, pointers)',
    'nondeterministic-input': 'an upstream input moved under the job: an API response, a download, a live page',
    'dead-route': 'a URL, file path or artefact the job expected does not exist (404, No such file)',
    'timeout': 'the job or step exceeded its time limit, or was cancelled for running too long',
    'by-design-refusal': 'a gate refused on purpose and said so; the red is the gate working',
    'unknown': 'the log does not contain enough to say',
}

MIN_QUOTE = 24    # characters, normalised. Shorter than this grounds nothing.

# EXCERPT SIZE, MEASURED - `--calibrate-lines`, 6 real job logs (median 25,639 chars raw),
# qwen3:4b on the dGPU, 2026-09-04:
#
#     lines   prompt tokens   grounded   classes agreed with 160?
#        20             937        5/6   no  - one log read as by-design-refusal, not dead-route
#        40           1,586        6/6   YES - identical distribution
#        80           2,223        5/6   YES
#       160           3,766        6/6   YES
#       320           4,326        4/6   CUDA error: out of memory on a shared 8 GB card
#
# 40 lines is where the answers stop changing. Everything above it costs prefill on every
# request and buys no different answer; 320 costs the card itself. 20 is too few - the
# decisive line falls outside the window and the class flips. So the default is the smallest
# size that agreed, not the largest that fitted.
DEFAULT_LINES = 40

# CONCURRENCY, MEASURED - `--calibrate-conc`, 12 requests per rung, 2026-09-04:
#
#     dGPU   1 -> 63 tok/s aggregate | 2 -> 107 | 3 -> 107   (stops paying at 2)
#     iGPU   1 ->  5 tok/s aggregate | 2 ->  12 | 3 ->  12   (stops paying at 2)
#
# Both servers saturate at two requests in flight, which is Ollama's auto-chosen parallel
# slot count on this box (OLLAMA_NUM_PARALLEL is unset; OLLAMA_CONTEXT_LENGTH=8192 is not).
# Past two, requests queue in the HTTP server and aggregate throughput is flat while latency
# per answer grows. Raising OLLAMA_NUM_PARALLEL is the lever, and it belongs to whoever owns
# those servers, not to this file.
# THE MEASUREMENT ABOVE IS NOT THE POLICY. From 2026-09-04 the discrete card is committed to
# familiars/autopilot.py for an eight-hour overnight run, which is SERIAL by design, and
# localai.py now carries a governor that enforces one cross-process dGPU request at a time and
# refuses the iGPU outright. Two clients against one serial endpoint do not double throughput;
# they queue and double the resident pressure while queuing. So the shipped default is one
# request in flight and no iGPU, and the calibration above records what the hardware WOULD
# give if the card were free - which is the number to re-read when the autopilot ends.
DEFAULT_GPU_SLOTS = 1
DEFAULT_IGPU_SLOTS = 0

_ANSI = re.compile(r'\x1b\[[0-9;]*[A-Za-z]')
_TS = re.compile(r'^\s*\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z ?', re.M)
_WS = re.compile(r'\s+')


# --------------------------------------------------------------------------- normalising

def strip_noise(text):
    """Runner timestamps and ANSI colour are layout, not content. Removing them before the
    model sees the log saves roughly a fifth of the prompt tokens, and - more importantly -
    means the string the model can copy is the same string this file will search. The
    grounding check and the prompt must share one normalisation or the check is theatre."""
    return _TS.sub('', _ANSI.sub('', text.replace('\r', '')))


def flatten(text):
    """Whitespace-insensitive, character-sensitive. Used only for the substring test."""
    return _WS.sub(' ', text).strip()


# --------------------------------------------------------------------------- enumeration

def reds_from_estate(estate):
    """Every failing JOB in the estate, newest first. One row per job, not per run: a run with
    three failing jobs is three separate things broken and gets three lines.

    A red carrying no failing job is kept as a row with job_id None. That is a real state -
    a startup_failure, or a run cancelled before any job started - and dropping it would make
    the board disagree with audit_estate.py's own count."""
    rows = []
    for repo in estate.get('ci') or []:
        for red in repo.get('reds') or []:
            jobs = red.get('failed_jobs') or []
            if not jobs:
                rows.append(_row(repo, red, None))
                continue
            for j in jobs:
                rows.append(_row(repo, red, j))
    rows.sort(key=lambda r: r['at'] or '', reverse=True)
    return rows


def _row(repo, red, job):
    job_id = None
    if job and job.get('url'):
        m = re.search(r'/job/(\d+)', job['url'])
        if m:
            job_id = m.group(1)
    steps = (job or {}).get('steps') or []
    return {
        'repo': repo['repo'],
        'full_repo': '%s/%s' % (OWNER, repo['repo']),
        'workflow': red.get('workflow'),
        'run_id': red.get('run_id'),
        'sha': red.get('sha'),
        'at': red.get('at'),
        'at_head': bool(red.get('at_head')),
        'job': (job or {}).get('name') or (job or {}).get('job'),
        'job_id': job_id,
        # The failing step is the API's, never the model's. One less surface to invent on.
        'failing_step': '; '.join(steps) if steps else None,
    }


# --------------------------------------------------------------------------- log transport

def cached_log(row, refresh=False):
    """Fetch a job log, once. A completed job's log is immutable, so it is cached by job id and
    every later calibration pass is free. Raises rather than returning empty: a missing input
    must FAIL."""
    if not row['job_id']:
        raise L.LocalAIError('the API recorded no failing job for %s run %s'
                             % (row['repo'], row['run_id']))
    os.makedirs(CACHE, exist_ok=True)
    path = os.path.join(CACHE, '%s-%s.log' % (row['repo'], row['job_id']))
    if not refresh and os.path.exists(path) and os.path.getsize(path) > 0:
        with open(path, 'r', encoding='utf-8', errors='replace') as fh:
            return fh.read()
    text = L.fetch_job_log(row['full_repo'], row['job_id'])
    if not text.strip():
        raise L.LocalAIError('job %s log was empty' % row['job_id'])
    with open(path, 'w', encoding='utf-8', errors='replace', newline='') as fh:
        fh.write(text)
    return text


def excerpt(log, keep_lines=DEFAULT_LINES):
    """The lines around the failure, normalised. Never the tail: the tail of a runner log is
    'Post job cleanup' and a Node 20 deprecation warning, and a classifier fed the tail
    reported the warning as the cause. Measured, on gridatlas run 33800308935."""
    clean = strip_noise(log)
    focused = L.focus_errors(clean, keep_lines=keep_lines)
    used_focus = focused is not None
    body = focused if used_focus else clean
    lines = body.splitlines()
    if len(lines) > keep_lines:
        body = ('... [%d earlier lines omitted] ...\n' % (len(lines) - keep_lines)
                + '\n'.join(lines[-keep_lines:]))
    return body, used_focus


def first_error_line(log):
    """The log's own decisive line, quoted by this file and not by any model. Shown next to
    an UNGROUNDED row so a human still has one true thing to read."""
    for ln in strip_noise(log).splitlines():
        s = ln.strip()
        if s.startswith('##[error]'):
            return s[9:].strip()[:400]
    for ln in strip_noise(log).splitlines():
        s = ln.strip()
        if 'Process completed with exit code' in s:
            return s[:400]
    return None


# --------------------------------------------------------------------------- the model call

SYSTEM = ('You are a build engineer reading one failing CI job log. You answer only in the '
          'three labelled lines you are asked for. You never write markdown, headings, bold '
          'or bullets. You never guess: if the log does not say, the class is unknown.')


def build_prompt(row, body, strict=False):
    vocab = '\n'.join('  %-24s %s' % (c, CLASS_HELP[c]) for c in CLASSES)
    extra = ''
    if strict:
        extra = ('\nYOUR PREVIOUS ANSWER WAS REJECTED: the QUOTE you gave does not appear in '
                 'the log. Do not summarise, do not retype from memory, do not fix spelling. '
                 'Find one line in the log above and COPY IT CHARACTER FOR CHARACTER.\n')
    return (
        'Below is the log of a FAILING GitHub Actions job, reduced to the lines around its '
        'errors.\n\n'
        'Repository: %s\nWorkflow: %s\nFailing job: %s\nFailing step (from the API, already '
        'known - do not repeat it): %s\n\n'
        '--- LOG ---\n%s\n--- END LOG ---\n%s\n'
        'Reply with exactly three lines, in this order, and nothing else:\n\n'
        'CLASS: <one word from the list below, exactly as spelled>\n'
        'QUOTE: <one line copied VERBATIM from the log above, at least %d characters, the '
        'line that shows the failure>\n'
        'CAUSE: <one sentence, under 25 words, saying what that quoted line means>\n\n'
        'The class vocabulary, and nothing outside it:\n%s\n\n'
        'Rules. The QUOTE must be text that is actually present in the log above - it will be '
        'checked by exact string search and your answer is discarded if it is not found, so '
        'copy, never paraphrase. A deprecation warning is not a failure. "Process completed '
        'with exit code 1" is true of every red and explains nothing - quote the line that '
        'says WHY. Do not name the failing step; it is already known.\n\n'
        '--- ANSWER ---\nCLASS:'
        % (row['repo'], row['workflow'], row['job'], row['failing_step'] or 'not recorded',
           body, extra, MIN_QUOTE, vocab))


_FIELD = re.compile(r'^(CLASS|QUOTE|CAUSE)\s*:\s*(.*)$')


def parse_answer(text):
    """Three labelled lines out of whatever the model actually produced."""
    if not text.startswith('CLASS:'):
        text = 'CLASS:' + text
    out = {}
    current = None
    for ln in text.splitlines():
        m = _FIELD.match(ln.strip())
        if m:
            current = m.group(1)
            out[current] = m.group(2).strip()
        elif current == 'CAUSE' and ln.strip():
            out['CAUSE'] = (out.get('CAUSE', '') + ' ' + ln.strip()).strip()
    return out


def ground(quote, body):
    """The whole point of the file. Returns (ok, reason).

    Character-for-character containment after whitespace flattening. Not fuzzy, not
    case-insensitive, not token-overlap - every one of those readmits the one-character
    mutation this check exists to catch."""
    if not quote:
        return False, 'model produced no QUOTE line'
    q = quote.strip().strip('`"\u201c\u201d\'')
    q = flatten(strip_noise(q))
    if len(q) < MIN_QUOTE:
        return False, 'quote is %d chars, under the %d-char floor' % (len(q), MIN_QUOTE)
    if 'lines omitted' in q:
        return False, 'quote is this script\'s own elision marker, not log content'
    if q not in flatten(body):
        return False, 'quote is NOT a substring of the log excerpt'
    return True, 'verbatim substring of the excerpt'


ENDPOINT_RETRIES = [0]
_retry_lock = threading.Lock()

# --------------------------------------------------------------------- context budgeting
#
# Ollama's /api/generate does NOT error on an over-length prompt. It cuts it and answers
# from what is left, and the response looks exactly like a good one. That is the worst
# possible failure here, because the GROUNDING CHECK CANNOT SEE IT: the model quotes a line
# that really is in the part it was shown, the substring test passes, and the row is
# published as evidence-backed while the model never saw the half of the log that mattered.
#
# Measured 2026-09-04 on this box: the two endpoints do not have the same window.
#     11434  qwen3:4b   context_length 8192
#     11435  qwen3:0.6b context_length 4096
# and a 160-line excerpt builds a prompt of ~3,800 tokens median, 4,100 at the top of the
# range - which fits the dGPU and silently overflows the iGPU. The excerpt size that is
# right for one card is a truncation bug on the other.
#
# So the window is read from the server, per device, and the excerpt is fitted to it BEFORE
# the request goes out. Nothing is sent that does not fit. num_ctx is deliberately not
# overridden per request: localai.py records that doing so forces a full model reload and
# evicts the resident weights other lanes are using, so the excerpt bends and the server
# does not.

CHARS_PER_TOKEN = 2.9   # measured below the true ratio on purpose: it must never over-fit.
CTX_RESERVE = 192       # room for the system prompt and the chat scaffold Ollama adds.
_CTX = {}
_ctx_lock = threading.Lock()


def device_context(device):
    """The context window of the model actually loaded on that endpoint, from /api/ps.

    Not a constant in this file: the two servers are configured separately and one of them
    is restarted by other lanes. A hard-coded 8192 here would be a guess about somebody
    else's process."""
    with _ctx_lock:
        if device in _CTX:
            return _CTX[device]
    want = L.DEVICES[device]['model']
    for attempt in (0, 1):
        d = L._get(device, '/api/ps')
        for m in d.get('models') or []: