GLOBALGRID2050 / EXPLORE CODE

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

Localai and 1 more file

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).

549 lines of Python from claude, in 2 files. Topic: AI agents and coordination. Section 1599 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. Localai ingest · claude / familiars/localai.py lines 396–844
  2. Reap other · claude / familiars/reap.py lines 1–100

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 396–844 of 844 (continued from section 1598) · 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
failing_jobs, focus_errors, _tail, _head, job_classify_ci_failure, job_summarise_commit, job_triage_untracked, health, print_health, bench, sampler, print_bench, serve_igpu, 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/localai.py:396-844 · 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
        raise LocalAIError('gh-api.sh failed for %s: %s'
                           % (path, (out.stderr or b'')[:300].decode('utf-8', 'replace')))
    try:
        return json.loads(out.stdout.decode('utf-8', 'replace'))
    except ValueError as e:
        raise LocalAIError('gh-api.sh returned non-JSON for %s (%s)' % (path, e))


def failing_jobs(full_repo, run_id):
    """The API's own record of which job and which step failed - the cross-check the model's
    answer is measured against, so a confident wrong answer is visible rather than trusted."""
    d = gh_json('repos/%s/actions/runs/%s/jobs' % (full_repo, run_id))
    out = []
    for j in d.get('jobs') or []:
        if j.get('conclusion') in ('failure', 'timed_out'):
            out.append({'name': j.get('name'),
                        'steps': [s.get('name') for s in (j.get('steps') or [])
                                  if s.get('conclusion') in ('failure', 'timed_out')]})
    return out


def focus_errors(log, keep_lines=160):
    """Keep the lines that carry the failure. A runner log is mostly progress chatter; the
    decisive lines are marked ##[error] or report a non-zero exit."""
    lines = log.splitlines()
    hits = [i for i, ln in enumerate(lines)
            if '##[error]' in ln or 'Process completed with exit code' in ln
            or re.search(r'\b(FAIL|FAILED|Traceback|AssertionError)\b', ln)]
    if not hits:
        return None
    keep, span = set(), max(6, keep_lines // max(1, len(hits)))
    for i in hits:
        keep.update(range(max(0, i - span), min(len(lines), i + 6)))
    picked, last = [], -2
    for i in sorted(keep):
        if i != last + 1:
            picked.append('   ... [%d lines omitted] ...' % (i - last - 1))
        picked.append(lines[i])
        last = i
    return '\n'.join(picked)


def _tail(text, limit=MAX_CHARS):
    """Logs fail at the end; diffs matter at the top. Callers pick which end to keep."""
    if len(text) <= limit:
        return text
    return '...[%d chars elided]...\n' % (len(text) - limit) + text[-limit:]


def _head(text, limit=MAX_CHARS):
    if len(text) <= limit:
        return text
    return text[:limit] + '\n...[%d chars elided]...' % (len(text) - limit)


# --------------------------------------------------------------------------- jobs

SYS_TERSE = ('You are a terse build engineer. Answer in plain text only. '
             'No preamble, no markdown headings, no bullet characters unless asked. '
             'If the evidence does not support a conclusion, say so plainly.')


def job_classify_ci_failure(target):
    """Name the failing step and the one-line cause of a failing Actions run."""
    m = re.match(r'^([\w.-]+/[\w.-]+)#(\d+)$', str(target).strip())
    api_failing = []
    if m:
        log, api_failing = fetch_run_log(m.group(1), m.group(2))
        source = '%s run %s' % (m.group(1), m.group(2))
    else:
        if not os.path.isfile(target):
            raise LocalAIError(
                'no such log file: %r. Give a path, or owner/repo#run_id to fetch it. '
                '(Run ids come from `python scripts/audit_estate.py --json out.json`.)' % target)
        with open(target, 'r', encoding='utf-8', errors='replace') as fh:
            log = fh.read()
        source = os.path.abspath(target)
    if not log.strip():
        raise LocalAIError('log %r is empty; nothing to classify' % source)

    focused = focus_errors(log)
    excerpt = _tail(focused if focused else log)

    ask = ('Name the failure in this GitHub Actions log. A deprecation warning is NOT a '
           'failure. If the log does not show which step failed, write "STEP: unknown" - '
           'never invent a plausible step name.\n\n--- LOG ---\n%s')
    messages = [
        {'role': 'system', 'content':
            'You answer in exactly two lines, "STEP:" then "CAUSE:", and write nothing else. '
            'No markdown, no headings, no bold, no bullets, no preamble, no closing remark.'},
        {'role': 'user', 'content': ask % (
            '##[group]Run pytest -q\n'
            'FAILED tests/test_distance.py::test_ring - AssertionError: expected 12.4, got 18.9\n'
            '##[error]Process completed with exit code 1.')},
        {'role': 'assistant', 'content':
            'STEP: Run pytest -q\n'
            'CAUSE: test_ring failed its assertion, "expected 12.4, got 18.9", so pytest '
            'exited 1.'},
        {'role': 'user', 'content': ask % excerpt},
    ]
    r = chat(JOB_DEVICE['classify-ci-failure'], messages, num_predict=160,
             stop=['\n\n', '\n---'])
    r['source'] = source
    r['log_chars'] = len(log)
    r['focused'] = focused is not None
    r['api_failing_jobs'] = api_failing
    return r


def job_summarise_commit(sha, repo=None):
    """Two lines describing what a commit did, read from its own diff."""
    path = repo_path(repo or REPO_ROOT)
    sha = str(sha).strip()
    resolved = git(path, 'rev-parse', '--verify', '%s^{commit}' % sha).strip()
    subject = git(path, 'log', '-1', '--format=%s', resolved).strip()
    stat = git(path, 'show', '--stat', '--format=', resolved)
    diff = git(path, 'show', '--format=', '--unified=2', resolved)
    if not diff.strip() and not stat.strip():
        raise LocalAIError('commit %s in %s has no diff to read' % (resolved[:12], path))

    prompt = (
        'Below is a git commit from the repository %r.\n\n'
        'Write exactly two lines:\n'
        'Line 1: what changed, concretely, naming the files or functions.\n'
        'Line 2: why it matters, or "effect unclear from the diff" if the diff does not say.\n'
        'Do not restate the commit subject verbatim. Do not speculate beyond the diff.\n\n'
        '--- SUBJECT ---\n%s\n\n--- STAT ---\n%s\n\n--- DIFF ---\n%s'
        % (os.path.basename(path), subject, _head(stat, 2000), _head(diff, MAX_CHARS)))
    r = generate(JOB_DEVICE['summarise-commit'], prompt, system=SYS_TERSE, num_predict=180)
    r['repo'] = path
    r['sha'] = resolved
    r['subject'] = subject
    return r


def job_triage_untracked(repo, device=None):
    """Describe every untracked file, so uncommitted work is never deleted unread.

    Device is worth choosing deliberately. Measured 2026-09-03 on cvaa's two untracked files,
    qwen3:0.6b on the Intel iGPU called a markdown vaccine note "a deterministic, non-viable
    repository" - fluent and wrong. The 4B on the discrete card reads the same file correctly.
    The iGPU earns its place on bulk triage when the discrete card is contended by another
    lane, not on accuracy.
    """
    dev = device or JOB_DEVICE['triage-untracked']
    path = repo_path(repo)
    porcelain = git(path, 'status', '--porcelain', '--untracked-files=all')
    files = [ln[3:].strip().strip('"') for ln in porcelain.splitlines() if ln.startswith('??')]
    if not files:
        return {'repo': path, 'untracked': 0, 'files': [],
                'note': 'no untracked files in %s' % path}

    results = []
    for rel in files:
        full = os.path.join(path, rel)
        try:
            size = os.path.getsize(full)
        except OSError as e:
            results.append({'file': rel, 'error': 'unreadable: %s' % e})
            continue
        if os.path.isdir(full):
            results.append({'file': rel, 'error': 'directory, not a file'})
            continue
        try:
            with open(full, 'r', encoding='utf-8', errors='replace') as fh:
                head = fh.read(2000)
        except OSError as e:
            results.append({'file': rel, 'error': 'unreadable: %s' % e})
            continue
        if '\x00' in head:
            results.append({'file': rel, 'bytes': size, 'verdict': 'binary file, not read'})
            continue
        prompt = (
            'An untracked file was found in the git repository %r. Say in ONE sentence what '
            'it appears to be and whether it looks like work worth keeping. Judge only from '
            'the content shown. If the content is too thin to tell, say so.\n\n'
            'FILENAME: %s  (%d bytes)\n--- FIRST BYTES ---\n%s'
            % (os.path.basename(path), rel, size, head))
        try:
            g = generate(dev, prompt, system=SYS_TERSE, num_predict=160)
        except LocalAIError as e:
            # One file failing must not silently vanish from the listing, and must not abort
            # the other files either. It is recorded against its own name.
            results.append({'file': rel, 'bytes': size, 'error': str(e)})
            continue
        results.append({'file': rel, 'bytes': size, 'verdict': g['text'],
                        'tok_s': g['tok_s'], 'device': g['device']})
    # A per-file error must reach the exit code. Measured 2026-09-03: with the iGPU server
    # stopped, every one of cvaa's untracked files came back "endpoint DOWN" and the command
    # still exited 0 - a listing that described nothing, presented as a completed triage.
    # That is the estate's "green light that measured nothing", so the count is carried out
    # and main() fails on it.
    errors = sum(1 for f in results if f.get('error'))
    return {'repo': path, 'untracked': len(files), 'files': results, 'errors': errors}


# --------------------------------------------------------------------------- health

def health(devices=('gpu', 'igpu')):
    smi = nvidia_smi()
    report = {'measured_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
              'nvidia_smi': smi, 'devices': {}}
    failures = []
    for d in devices:
        try:
            ver = _get(d, '/api/version').get('version')
            rows = resident(d)
            probe = generate(d, 'Reply with the single word: ready.', num_predict=24)
            rows = resident(d) or rows
            report['devices'][d] = {
                'endpoint': DEVICES[d]['endpoint'],
                'adapter': DEVICES[d]['adapter'],
                'backend': DEVICES[d]['backend'],
                'ollama': ver,
                'model': DEVICES[d]['model'],
                'resident': rows,
                'tok_s': probe['tok_s'],
                'prefill_tok_s': probe['prefill_tok_s'],
                'load_s': probe['load_s'],
                'ok': True,
            }
        except LocalAIError as e:
            report['devices'][d] = {'endpoint': DEVICES[d]['endpoint'],
                                    'adapter': DEVICES[d]['adapter'],
                                    'ok': False, 'error': str(e)}
            failures.append(d)
    report['failed_devices'] = failures
    return report


def print_health(rep):
    smi = rep['nvidia_smi']
    print('measured %s' % rep['measured_utc'])
    if smi:
        print('nvidia-smi : %s  %d MiB total, %d used, %d free, util %d%%, driver %s'
              % (smi['name'], smi['total_mib'], smi['used_mib'], smi['free_mib'],
                 smi['util_pct'], smi['driver']))
    else:
        print('nvidia-smi : NOT AVAILABLE (no NVIDIA card, or driver not on PATH)')
    for d, v in rep['devices'].items():
        print('')
        print('[%s] %s via %s  -> %s' % (d, v['adapter'], v.get('backend', '?'), v['endpoint']))
        if not v['ok']:
            print('  STATUS   : DOWN')
            print('  ERROR    : %s' % v['error'])
            continue
        print('  ollama   : %s' % v['ollama'])
        print('  model    : %s' % v['model'])
        for m in v['resident']:
            print('  resident : %s  %.2f GB, %.2f GB in VRAM = %.1f%% offloaded, ctx %s, %s'
                  % (m['name'], m['size_gb'], m['vram_gb'], m['offload_pct'],
                     m['context'], m['quant']))
        if not v['resident']:
            print('  resident : nothing loaded right now')
        print('  measured : %s tok/s generate, %s tok/s prefill, %.3f s load'
              % (v['tok_s'], v['prefill_tok_s'], v['load_s']))


# --------------------------------------------------------------------------- bench

BENCH_PROMPT = ('Write a detailed technical explanation of how electricity transmission '
                'substations transform and switch high voltage power.')


def bench(devices=('gpu', 'igpu'), concurrency=2, num_predict=400):
    """Saturate the adapters and report what they actually sustained."""
    jobs = []
    for d in devices:
        _get(d, '/api/version')  # fail loudly before timing anything
        jobs.extend([d] * concurrency)

    samples = []
    stop = {'go': True}

    def sampler():
        while stop['go']:
            s = nvidia_smi()
            if s:
                samples.append((s['util_pct'], s['used_mib']))
            time.sleep(0.4)

    t0 = time.time()
    with ThreadPoolExecutor(max_workers=len(jobs) + 1) as ex:
        ex.submit(sampler)
        futs = [(d, ex.submit(generate, d, BENCH_PROMPT, None, num_predict)) for d in jobs]
        out = []
        for d, f in futs:
            out.append(f.result())
        stop['go'] = False
    wall = time.time() - t0

    per = {}
    for r in out:
        per.setdefault(r['device'], []).append(r)
    result = {'wall_s': round(wall, 2), 'concurrency_per_device': concurrency, 'devices': {}}
    total_tokens = 0
    for d, rs in per.items():
        toks = sum(r['eval_tokens'] for r in rs)
        total_tokens += toks
        result['devices'][d] = {
            'adapter': DEVICES[d]['adapter'],
            'model': DEVICES[d]['model'],
            'requests': len(rs),
            'tokens': toks,
            'per_request_tok_s': [r['tok_s'] for r in rs],
            'aggregate_tok_s': round(toks / wall, 1),
        }
    result['total_tokens'] = total_tokens
    result['aggregate_tok_s_all_devices'] = round(total_tokens / wall, 1)
    if samples:
        result['nvidia_util_pct_peak'] = max(s[0] for s in samples)
        result['nvidia_util_pct_mean'] = round(sum(s[0] for s in samples) / len(samples), 1)
        result['nvidia_used_mib_peak'] = max(s[1] for s in samples)
        result['nvidia_samples'] = len(samples)
    return result


def print_bench(b):
    print('bench: %d requests, %.2f s wall' % (
        sum(v['requests'] for v in b['devices'].values()), b['wall_s']))
    for d, v in b['devices'].items():
        print('  [%s] %-36s %d req, %d tok, per-request %s tok/s, aggregate %s tok/s'
              % (d, v['adapter'], v['requests'], v['tokens'],
                 v['per_request_tok_s'], v['aggregate_tok_s']))
    print('  TOTAL across adapters: %s tok/s (%d tokens in %.2f s)'
          % (b['aggregate_tok_s_all_devices'], b['total_tokens'], b['wall_s']))
    if 'nvidia_util_pct_peak' in b:
        print('  nvidia-smi during run: peak %d%% util, mean %s%%, peak %d MiB used, %d samples'
              % (b['nvidia_util_pct_peak'], b['nvidia_util_pct_mean'],
                 b['nvidia_used_mib_peak'], b['nvidia_samples']))


# --------------------------------------------------------------------------- serve

def serve_igpu():
    """Start an Ollama pinned to the Intel adapter. Ollama drops iGPUs unless told twice:
    OLLAMA_IGPU_ENABLE=1 admits it, GGML_VK_VISIBLE_DEVICES=1 hides the NVIDIA card from
    the Vulkan backend, and CUDA_VISIBLE_DEVICES=-1 stops it being picked up as CUDA."""
    if not os.path.exists(OLLAMA_EXE):
        raise LocalAIError('ollama.exe not found at %s' % OLLAMA_EXE)
    env = dict(os.environ)
    env.update({'OLLAMA_HOST': '127.0.0.1:11435', 'CUDA_VISIBLE_DEVICES': '-1',
                'GGML_VK_VISIBLE_DEVICES': '1', 'OLLAMA_IGPU_ENABLE': '1',
                'OLLAMA_KEEP_ALIVE': '30m'})
    subprocess.Popen([OLLAMA_EXE, 'serve'], env=env,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    for _ in range(15):
        time.sleep(2)
        try:
            v = _get('igpu', '/api/version', timeout=3)
            return 'igpu server up on %s, ollama %s' % (DEVICES['igpu']['endpoint'],
                                                        v.get('version'))
        except LocalAIError:
            continue
    raise LocalAIError('igpu server did not answer on %s within 30 s'
                       % DEVICES['igpu']['endpoint'])


# --------------------------------------------------------------------------- cli

def main():
    ap = argparse.ArgumentParser(
        description='Local inference on this machine, and the clerical jobs it does.')
    ap.add_argument('--health', action='store_true',
                    help='report model, backend, offload and measured tokens/s; '
                         'exits 2 if any endpoint is down')
    ap.add_argument('--bench', action='store_true', help='saturate the adapters, report throughput')
    ap.add_argument('--serve-igpu', action='store_true', help='start the Intel-pinned server')
    ap.add_argument('--job', choices=sorted(JOB_DEVICE), help='run one clerical job')
    ap.add_argument('--input', help='the job subject: log path or owner/repo#run_id, '
                                    'a commit sha, or a repo name')
    ap.add_argument('--repo', help='repo for summarise-commit (name under GitHub/ or a path)')
    ap.add_argument('--device', choices=sorted(DEVICES) + ['both'], default='both',
                    help='which adapter to use for --health/--bench')
    ap.add_argument('--concurrency', type=int, default=2, help='--bench requests per device')
    ap.add_argument('--json', action='store_true', help='machine-readable output')
    args = ap.parse_args()

    devices = tuple(DEVICES) if args.device == 'both' else (args.device,)

    if not (args.health or args.bench or args.serve_igpu or args.job):
        ap.error('nothing to do: pass --health, --bench, --serve-igpu or --job')

    try:
        if args.serve_igpu:
            print(serve_igpu())

        if args.health:
            rep = health(devices)
            print(json.dumps(rep, indent=2)) if args.json else print_health(rep)
            if rep['failed_devices']:
                sys.stderr.write('\nFAIL: endpoint down for: %s\n'
                                 % ', '.join(rep['failed_devices']))
                return 2

        if args.bench:
            b = bench(devices, concurrency=args.concurrency)
            print(json.dumps(b, indent=2)) if args.json else print_bench(b)

        if args.job:
            if not args.input:
                ap.error('--job %s needs --input' % args.job)
            if args.job == 'classify-ci-failure':
                r = job_classify_ci_failure(args.input)
            elif args.job == 'summarise-commit':
                r = job_summarise_commit(args.input, args.repo)
            else:
                # --device is an explicit override; without it the job keeps its routing.
                r = job_triage_untracked(
                    args.input, None if args.device == 'both' else args.device)
            if args.json:
                print(json.dumps(r, indent=2))
            elif args.job == 'triage-untracked':
                print('%s: %d untracked' % (r['repo'], r['untracked']))
                for f in r.get('files', []):
                    print('  %-52s %s' % (f['file'], f.get('verdict') or f.get('error')))
                if not r.get('files'):
                    print('  %s' % r.get('note', ''))
                if r.get('errors'):
                    sys.stderr.write('\nFAIL: %d of %d untracked files could not be described. '
                                     'This listing is INCOMPLETE.\n'
                                     % (r['errors'], r['untracked']))
                    return 2
            else:
                print(r['text'])
                for j in r.get('api_failing_jobs') or []:
                    print('\n[cross-check, GitHub jobs API] failing job %r, failing step(s): %s'
                          % (j['name'], ', '.join(repr(s) for s in j['steps']) or 'none recorded'))
                print('\n[%s on %s: %s tok/s, %d tokens%s]'
                      % (r['model'], DEVICES[r['device']]['adapter'],
                         r['tok_s'], r['eval_tokens'],
                         ', error-focused log' if r.get('focused') else ''))
    except LocalAIError as e:
        sys.stderr.write('FAIL: %s\n' % e)
        return 2
    return 0


if __name__ == '__main__':
    # The model may emit any Unicode it likes, emoji included. Windows stdout defaults
    # to cp1252 and raises UnicodeEncodeError on the first one, throwing away an answer
    # that was already computed correctly. Fail on the work, never on the printing.
    for _s in (sys.stdout, sys.stderr):
        try:
            _s.reconfigure(encoding='utf-8', errors='replace')
        except Exception:
            pass

    sys.exit(main())

Reap

A Python command-line tool in the familiars folder of Claude that works with ram free GB (`ram_free_gb`). It is built from the gpu step (`gpu`) and the runners step (`runners`).

otherclaude / familiars/reap.py · lines 1–100 of 100 · Entry point

What it does
Defines ps, gpu, ram_free_gb, runners, main. Uses libraries subprocess, sys, json. Side effects: 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
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Kill local-AI runners that hold memory with no task behind them.
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
subprocess, sys, json
Used by
none found
Produces
ps, gpu, ram_free_gb, runners, main
Defines here
ps, gpu, ram_free_gb, runners, 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/reap.py:1-100 · blob e934ae8c3d6ed1357d26f641033e6d9e523e8a83 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""reap.py - kill local-AI runners that hold memory with no task behind them.

WHY THIS EXISTS

Measured on 2026-09-03: the RTX 5070 reported 904 MiB free of 8151, and system RAM
reported 0.7 GB free of 15.5. The obvious reading was "this machine is maxed out".
It was not. Two llama-server.exe processes were holding 3.4 GB of VRAM and 3.2 GB of
RAM between them, and BOTH had a dead parent. The `ollama serve` that spawned each one
had exited without taking its runner with it. Nothing listened on 11434, so no request
could ever reach either runner again - but they still answered 200 on their own private
ports, so every liveness check that pinged the runner directly said "healthy".

That is the trap. A leaked runner looks alive from the outside. It holds a model in VRAM,
it responds to /health, and it will sit there until reboot. The only thing that
distinguishes it from a working runner is that its parent process is gone.

Reaping both took VRAM free from 904 MiB to 6762 MiB, and RAM free from 0.7 GB to 5.0 GB.
No task lost anything, because no task could reach them.

WHAT IT DOES NOT DO

It never kills a runner whose parent is alive - that one is serving somebody, possibly
another agent lane mid-call. Parentage is the whole test. --dry-run is the default;
you must pass --reap to actually kill anything.

Usage:
    python familiars/reap.py              # report only
    python familiars/reap.py --reap       # report, then kill the orphans
"""
import subprocess, sys, json

PS = ["powershell.exe", "-NoProfile", "-Command"]

def ps(cmd):
    r = subprocess.run(PS + [cmd], capture_output=True, text=True)
    return r.stdout.strip()

def gpu():
    r = subprocess.run(
        ["nvidia-smi", "--query-gpu=memory.used,memory.free", "--format=csv,noheader,nounits"],
        capture_output=True, text=True)
    if r.returncode != 0:
        return None
    used, free = [int(x) for x in r.stdout.strip().split(",")]
    return used, free

def ram_free_gb():
    out = ps("(Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory")
    return int(out) / 1048576 if out.isdigit() else None

def runners():
    """Every llama-server, with its parent and whether that parent still exists."""
    out = ps(
        "Get-CimInstance Win32_Process -Filter \"Name='llama-server.exe'\" | "
        "ForEach-Object { $p=$_; $alive = [bool](Get-CimInstance Win32_Process "
        "-Filter (\"ProcessId=\"+$p.ParentProcessId) -ErrorAction SilentlyContinue); "
        "[pscustomobject]@{pid=$p.ProcessId; ppid=$p.ParentProcessId; "
        "mb=[int]($p.WorkingSetSize/1MB); alive=$alive} } | ConvertTo-Json -Compress"
    )
    if not out:
        return []
    d = json.loads(out)
    return d if isinstance(d, list) else [d]

def main():
    do_reap = "--reap" in sys.argv
    g0, r0 = gpu(), ram_free_gb()

    rs = runners()
    if not rs:
        print("no llama-server processes running")
        return 0

    orphans = [r for r in rs if not r["alive"]]
    for r in rs:
        tag = "ORPHAN - no parent, unreachable" if not r["alive"] else "in use - parent alive"
        print(f"  pid {r['pid']:<7} ppid {r['ppid']:<7} {r['mb']:>5} MB   {tag}")

    if not orphans:
        print("\nnothing to reap; every runner has a live parent")
        return 0

    print(f"\n{len(orphans)} orphan(s) holding memory with no task behind them")
    if not do_reap:
        print("dry run - pass --reap to release them")
        return 0

    for r in orphans:
        ps(f"Stop-Process -Id {r['pid']} -Force -ErrorAction SilentlyContinue")
        print(f"  reaped pid {r['pid']}")

    g1, r1 = gpu(), ram_free_gb()
    if g0 and g1:
        print(f"\nVRAM free  {g0[1]} -> {g1[1]} MiB  (+{g1[1]-g0[1]})")
    if r0 and r1:
        print(f"RAM  free  {r0:.1f} -> {r1:.1f} GB  (+{r1-r0:.1f})")
    return 0

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