GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / logs/tools

Verify Memory Store and 1 more file

A Python command-line tool in the tools folder of Claude that projects slug (`project_slug`) and loads audits (`load_audits`), using SHA-256.

661 lines of Python from claude, in 2 files. Topic: AI agents and coordination. Section 1606 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. Verify Memory Store storage · claude / logs/tools/verify_memory_store.py lines 1–404
  2. Claude Audit Estate storage · claude / scripts/audit_estate.py lines 1–257

Verify Memory Store

A Python command-line tool in the tools folder of Claude that projects slug (`project_slug`) and loads audits (`load_audits`), using SHA-256.

storageclaude / logs/tools/verify_memory_store.py · lines 1–404 of 404 · Entry point · pattern sha256_of (shared by 2 files)

What it does
It loads data. Defines 7 functions or classes, including sha256_of, project_slug, load_audits, measure, reconcile. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
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). README: "The live figure is always `logs/reports/memory-manifest.json`, which `verify_memory_store.py` regenerates."
Inputs & outputs
In: JSON file memory-manifest.json; DuckDB queries; command-line arguments.
Downstream impact
Used directly by 1 file: Claude Verify Memory Store Workflow (claude).
What it achieves
It is built from the sha256 of helper (`sha256_of`), the measure step (`measure`) and the reconcile step (`reconcile`). Verify that the session memory store contains what it claims to contain. It accepts `--check` and `--transcripts`.
Why it matters
Run by Claude Verify Memory Store Workflow.
Application
claude · logs/tools · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, os, re, sys
Used by
run by Claude Verify Memory Store Workflow (workflow run)
Produces
sha256_of, project_slug, load_audits, measure, reconcile, iso, main
Defines here
sha256_of, project_slug, load_audits, measure, reconcile, iso, 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 logs/tools/verify_memory_store.py:1-404 · blob 61d559d41addb3d5bc2f5fad1b1f7f4654f238e7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python
"""Verify that the session memory store contains what it claims to contain.

The failure this exists to catch is not a crash. It is a store that answers every
query while holding less than it should: a session that was never converted, or a
conversion that dropped lines quietly. Both leave a store that looks healthy,
because the rows that are missing are exactly the rows nothing asks about.

So nothing here is inferred from prose or from a file count. Every number is
measured out of the parquet itself with DuckDB and reconciled against the audit
record jsonl_to_parquet.py wrote beside it:

  rows                == the audit's parquet_rows
  distinct source_line== the audit's jsonl_lines        (the completeness claim)
  source_line 1..N    contiguous, no gaps               (the silent-hole check)
  file size on disk   == the audit's parquet_bytes
  exactly one session_id per file

It then regenerates logs/reports/memory-manifest.json, which is the artefact the
cvaa vaccine `memory-store-complete` reads. Under --check it validates the
committed manifest instead of rewriting it, so CI fails on a stale one.

Exits non-zero on any mismatch.

  python logs/tools/verify_memory_store.py            # verify and write manifest
  python logs/tools/verify_memory_store.py --check    # verify, write nothing (CI)
  python logs/tools/verify_memory_store.py --transcripts DIR
        additionally report transcripts in DIR that never reached the store.
        Local only: CI cannot see ~/.claude/projects, and this script does not
        pretend otherwise.

Depends only on duckdb (see requirements.txt). Deliberately no pandas/numpy: the
machine this was written on has duckdb without numpy, so .df() is not available
and fetchall() is used throughout.
"""

from __future__ import annotations

import argparse
import datetime as _dt
import hashlib
import json
import os
import re
import sys
from pathlib import Path

try:
    import duckdb
except ImportError:  # pragma: no cover - the message matters more than the trace
    sys.exit("duckdb is not installed. pip install -r requirements.txt")

REPO = Path(__file__).resolve().parents[2]
PARQUET_DIR = REPO / "logs" / "parquet"
REPORT_DIR = REPO / "logs" / "reports"
MANIFEST = REPORT_DIR / "memory-manifest.json"


def sha256_of(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def project_slug(cwd: str | None) -> str:
    """The project key Claude Code uses: every path separator becomes one dash.

    'C:\\Users\\vikra' -> 'C--Users-vikra'
    """
    if not cwd:
        return "unknown"
    return re.sub(r"[:\\/]", "-", cwd)


def load_audits() -> dict[str, dict]:
    """Audit records keyed by the parquet filename they claim to describe."""
    audits: dict[str, dict] = {}
    for path in sorted(REPORT_DIR.glob("*.json")):
        if path.name == MANIFEST.name:
            continue
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            audits[f"!unreadable:{path.name}"] = {"_error": str(exc), "_file": path.name}
            continue
        if not isinstance(data, dict) or "output_parquet" not in data:
            continue
        audits[str(data["output_parquet"])] = data | {"_file": path.name}
    return audits


def measure(con, path: Path) -> dict:
    """Everything we know about a parquet file, read out of the file."""
    rel = path.as_posix()
    # epoch_us, not min(ts)/max(ts). Handing a TIMESTAMP WITH TIME ZONE back to Python
    # makes DuckDB import pytz, which is not a declared dependency of anything here - it
    # was merely installed on the machine this was written on, so the verifier passed
    # locally and died on a clean runner with ModuleNotFoundError. Microseconds since the
    # epoch are a plain integer: no pytz, no ICU, and no dependence on the session
    # timezone, which would otherwise render the same instant differently on a BST laptop
    # and a UTC runner and show up as a spurious manifest mismatch.
    row = con.execute(
        "select count(*), count(distinct source_line), min(source_line), "
        "max(source_line), epoch_us(min(ts)), epoch_us(max(ts)), count(distinct session_id), "
        "any_value(session_id), any_value(cwd) from read_parquet(?)",
        [rel],
    ).fetchone()
    keys = ("rows", "distinct_source_lines", "min_source_line", "max_source_line",
            "first_ts", "last_ts", "n_sessions", "session_id", "cwd")
    m = dict(zip(keys, row))
    m["parquet_bytes"] = path.stat().st_size
    m["parquet_sha256"] = sha256_of(path)
    m["parquet_file"] = path.relative_to(REPO).as_posix()
    return m


def reconcile(m: dict, audit: dict | None) -> list[str]:
    """Every way this file can disagree with what was claimed about it."""
    name = m["parquet_file"]
    problems: list[str] = []

    if m["rows"] == 0:
        problems.append(f"{name}: 0 rows; the file exists and the session is not in it")
        return problems

    # NOT rows == source_lines. That invariant is false and measuring it proved so:
    # one JSONL line carrying three images and a caption becomes four rows, one per
    # content block, which is what block_no is for. session_9556e57d is 2360 rows
    # over 2356 complete source lines and is not missing anything. A rule asserting
    # rows == source_lines would fire forever on a healthy store, and the only way to
    # satisfy it would be to make the converter throw content blocks away.
    #
    # The completeness claim is about LINES: every line of the transcript must be
    # represented by at least one row. Rows may exceed lines; they may never be
    # fewer, and no line may be skipped.
    if m["rows"] < m["distinct_source_lines"]:
        problems.append(
            f"{name}: {m['rows']} rows over {m['distinct_source_lines']} source lines; "
            "a line cannot produce fewer than one row"
        )
    expected_span = (m["max_source_line"] or 0) - (m["min_source_line"] or 0) + 1
    if expected_span != m["distinct_source_lines"]:
        missing = expected_span - m["distinct_source_lines"]
        problems.append(
            f"{name}: source lines run {m['min_source_line']}..{m['max_source_line']} "
            f"but only {m['distinct_source_lines']} are present; {missing} line(s) are gaps"
        )

    if audit is None:
        problems.append(
            f"{name}: no audit record in logs/reports/ names this file, so its "
            "row count was never reconciled against a source transcript"
        )
        return problems

    claimed_rows = audit.get("parquet_rows")
    claimed_lines = audit.get("jsonl_lines")
    claimed_bytes = audit.get("parquet_bytes")
    src = audit.get("source_jsonl", "?")

    claimed_distinct = audit.get("distinct_source_lines", claimed_lines)

    if claimed_rows != m["rows"]:
        problems.append(
            f"{name}: audit {audit['_file']} claims {claimed_rows} rows, file holds {m['rows']}"
        )
    if claimed_distinct != m["distinct_source_lines"]:
        problems.append(
            f"{name}: audit claims {claimed_distinct} distinct source lines, "
            f"file holds {m['distinct_source_lines']}"
        )
    if claimed_lines != m["distinct_source_lines"]:
        problems.append(
            f"{name}: {src} has {claimed_lines} lines, store holds "
            f"{m['distinct_source_lines']}; "
            f"{abs((claimed_lines or 0) - m['distinct_source_lines'])} never arrived"
        )
    if claimed_bytes != m["parquet_bytes"]:
        problems.append(
            f"{name}: audit claims {claimed_bytes} bytes, file is {m['parquet_bytes']}; "
            "the audit describes a different build than the one committed"
        )
    unparseable = audit.get("unparseable_lines") or []
    if unparseable:
        problems.append(
            f"{name}: conversion could not parse {len(unparseable)} source line(s): "
            f"{unparseable[:5]}"
        )
    if audit.get("lines_reconciled") is False:
        problems.append(f"{name}: audit {audit['_file']} records lines_reconciled: false")
    return problems


EPOCH = _dt.datetime(1970, 1, 1, tzinfo=_dt.timezone.utc)


def iso(micros) -> str | None:
    """Microseconds since the epoch to an ISO-8601 UTC string, identically everywhere."""
    if micros is None:
        return None
    return (EPOCH + _dt.timedelta(microseconds=int(micros))).isoformat()


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--check", action="store_true",
                    help="validate the committed manifest; write nothing")
    ap.add_argument("--transcripts", metavar="DIR",
                    help="also report .jsonl transcripts in DIR with no parquet")
    args = ap.parse_args()

    problems: list[str] = []
    audits = load_audits()
    for key, audit in audits.items():
        if key.startswith("!unreadable:"):
            problems.append(f"{audit['_file']}: not readable as JSON: {audit['_error']}")

    parquets = sorted(PARQUET_DIR.glob("*.parquet")) if PARQUET_DIR.is_dir() else []

    real_audits = {k: v for k, v in audits.items() if not k.startswith("!")}
    if not parquets:
        if real_audits:
            print("FAIL: logs/reports/ describes "
                  f"{len(real_audits)} conversion(s) and logs/parquet/ holds no parquet files")
            return 1
        print("logs/parquet/ is empty and no audit record claims otherwise; "
              "nothing to verify")
        return 0

    con = duckdb.connect()
    con.execute("set enable_progress_bar = false")

    rows_out = []
    sessions = []
    for path in parquets:
        m = measure(con, path)
        audit = real_audits.get(path.name)
        problems.extend(reconcile(m, audit))
        claimed = (audit or {}).get("jsonl_lines")
        rows_out.append((
            m["parquet_file"],
            str(m["session_id"] or "?")[:8],
            str(claimed if claimed is not None else "-"),
            str(m["rows"]),
            str(m["distinct_source_lines"]),
            f"{m['parquet_bytes']:,}",
            "OK" if claimed == m["distinct_source_lines"] and m["rows"] >= m["distinct_source_lines"]
            else "MISMATCH",
        ))
        # The audit record is the canonical namer of a session: jsonl_to_parquet.py
        # keys sessions as <project>__<uuid>, because a bare uuid is not unique across
        # projects. Fall back to what the file itself carries when no audit says.
        sessions.append({
            "session_id": (audit or {}).get("session_id") or m["session_id"],
            "project": (audit or {}).get("project") or project_slug(m["cwd"]),
            "source_lines": claimed if claimed is not None else m["distinct_source_lines"],
            # The field the completeness check rests on. rows may legitimately exceed
            # source_lines (one line, many content blocks); this may not.
            "distinct_source_lines": m["distinct_source_lines"],
            "rows": m["rows"],
            "parquet_file": m["parquet_file"],
            "parquet_bytes": m["parquet_bytes"],
            "parquet_sha256": m["parquet_sha256"],
            "first_ts": iso(m["first_ts"]),
            "last_ts": iso(m["last_ts"]),
        })

    # An audit record naming a parquet that is not there is a session that was
    # converted and then lost - the same hole from the other direction.
    for name, audit in real_audits.items():
        if not (PARQUET_DIR / name).exists():
            problems.append(
                f"{audit['_file']} names {name}, which is not in logs/parquet/"
            )

    header = ("parquet", "session", "src_lines", "rows", "distinct", "bytes", "state")
    widths = [max(len(header[i]), max((len(r[i]) for r in rows_out), default=0))
              for i in range(len(header))]
    line = "  ".join("-" * w for w in widths)
    print("Memory store reconciliation")
    print(line)
    print("  ".join(h.ljust(w) for h, w in zip(header, widths)))
    print(line)
    for r in rows_out:
        print("  ".join(c.ljust(w) for c, w in zip(r, widths)))
    print(line)
    total_rows = sum(s["rows"] for s in sessions)
    total_src = sum(s["source_lines"] or 0 for s in sessions)
    print(f"{len(sessions)} session(s); {total_rows:,} rows from {total_src:,} source lines")

    if args.transcripts:
        tdir = Path(args.transcripts)
        # A session is keyed <project>__<uuid> in the store and named <uuid>.jsonl on
        # disk. Compare on the uuid, or every transcript reads as unconverted and the
        # check becomes a rule that always fires - which is no more useful than one
        # that never does.
        uuid_of = lambda s: str(s).rsplit("__", 1)[-1]
        known = {uuid_of(s["session_id"]) for s in sessions}
        missing = [p.stem for p in tdir.rglob("*.jsonl") if uuid_of(p.stem) not in known]
        # A subagent's sidechain transcript is not a session. 23 of them sit beside the
        # 11 sessions here, and counting them as holes would make this fire on a store
        # that is complete - a rule that always fires is worth no more than one that
        # never does. They are reported, and they are not failures.
        sidechains = sorted(s for s in missing if s.startswith("agent-"))
        unconverted = sorted(s for s in missing if not s.startswith("agent-"))
        if sidechains:
            print(f"\n{len(sidechains)} subagent sidechain transcript(s) in {tdir} are "
                  "outside the store's scope, which is whole sessions")
        if unconverted:
            print(f"\n{len(unconverted)} session transcript(s) in {tdir} never reached the store:")
            for stem in unconverted:
                print(f"  - {stem}")
            problems.append(
                f"{len(unconverted)} session transcript(s) under {tdir} have no parquet "
                "in the store"
            )
        else:
            print(f"\nevery session transcript under {tdir} is in the store")

        # Presence is not coverage. A session is converted ONCE, on request, and then
        # keeps running - so a store can hold a parquet for every transcript and still
        # be missing hours. On 3 September the store held session 5b94bee7 and stopped
        # at 18:34:11Z; the session ran to 21:40:57Z, and 797 lines existed nowhere but
        # the live JSONL. Every check above passed on it, because they all reconcile
        # the store against ITSELF. This one reconciles it against the source.
        live = {uuid_of(p.stem): p for p in tdir.rglob("*.jsonl")
                if not p.stem.startswith("agent-")}
        behind = []
        for s in sessions:
            path = live.get(uuid_of(s["session_id"]))
            if path is None:
                continue  # converted from a transcript this machine no longer holds
            try:
                with open(path, "rb") as fh:
                    now_lines = sum(1 for ln in fh if ln.strip())
            except OSError as exc:
                problems.append(f"{path} could not be read to check for staleness: {exc}")
                continue
            stored = s["source_lines"] or 0
            if now_lines > stored:
                behind.append((str(s["session_id"])[:8], stored, now_lines, path))
        if behind:
            print(f"\n{len(behind)} session(s) in the store are BEHIND the live transcript:")
            for sid, stored, now_lines, path in behind:
                print(f"  - {sid}: store holds {stored:,} lines, "
                      f"{path.name} now has {now_lines:,} (+{now_lines - stored:,})")
            problems.append(
                f"{len(behind)} session(s) are behind their live transcript; "
                "re-run jsonl_to_parquet.py and render_session_markdown.py for each"
            )
        elif sessions:
            print("no session in the store is behind its live transcript")

    generation = _dt.datetime.now(_dt.timezone.utc).strftime("%Y%m%d%H%M")
    manifest = {"generation": generation,
                "sessions": sorted(sessions, key=lambda s: str(s["session_id"]))}

    if args.check:
        if not MANIFEST.exists():
            problems.append(f"{MANIFEST.relative_to(REPO).as_posix()} does not exist; "
                            "run this script without --check to write it")
        else:
            try:
                committed = json.loads(MANIFEST.read_text(encoding="utf-8"))
            except json.JSONDecodeError as exc:
                committed = None
                problems.append(f"memory-manifest.json is not valid JSON: {exc}")
            if committed is not None:
                if not re.fullmatch(r"\d{12}", str(committed.get("generation", ""))):
                    problems.append(
                        f"manifest generation {committed.get('generation')!r} "
                        "is not a 12-digit UTC stamp"
                    )
                # Generation moves every minute; the sessions are the claim.
                if committed.get("sessions") != manifest["sessions"]:
                    problems.append(
                        "committed memory-manifest.json does not match the store as "
                        "measured; regenerate it with "
                        "python logs/tools/verify_memory_store.py"
                    )
    else:
        REPORT_DIR.mkdir(parents=True, exist_ok=True)
        # newline="" so Python does not translate \n to \r\n on Windows. .gitattributes
        # here mandates eol=lf in the WORKING COPY as well as the blob, precisely so the
        # file on disk is the file that ships; writing CRLF puts this one file out of
        # step with the rule the repository sets for itself.
        with MANIFEST.open("w", encoding="utf-8", newline="") as fh:
            fh.write(json.dumps(manifest, indent=2) + "\n")
        print(f"\nwrote {MANIFEST.relative_to(REPO).as_posix()} (generation {generation})")

    if problems:
        print(f"\n{len(problems)} problem(s):")
        for p in problems:
            print(f"  - {p}")
        return 1
    print("\nthe store holds every line every audit record claims for it")
    return 0


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

Claude Audit Estate

A Python command-line tool in the scripts folder using data from GitHub API. It is built from the token step (`token`), the API step (`api`) and the git step (`git`).

storageclaude / scripts/audit_estate.py · lines 1–257 of 257 · Entry point · pattern token (shared by 3 files)

What it does
It fetches data. Defines 7 functions or classes, including token, api, git, repos, ci_for. Uses libraries argparse, json, os, subprocess, sys. 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; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: Localai (claude); Triage (claude); Claude CI History Mine (claude). Reached from 1 other entry point, including Claude CI History Mine Workflow (claude).
What it achieves
One pass over every repository the account owns: CI, then git. It accepts `--json` and `--only`.
Why it matters
Run by Localai, Triage and Claude CI History Mine.
Application
claude · scripts · Python CLI
Uses
argparse, json, os, subprocess, sys, time, urllib.error, urllib.request
Used by
run by Localai (script call), run by Triage (script call), run by Claude CI History Mine (script call)
Produces
token, api, git, repos, ci_for, git_for, main
Defines here
token, api, git, repos, ci_for, git_for, 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 scripts/audit_estate.py:1-257 · blob 3ee20b50e3e9c5005b06aa4b03e995e9a75bf901 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""audit_estate.py - one pass over every repository the account owns: CI, then git.

WHY THIS EXISTS

The two questions asked at the start of a session - "what is red?" and "what is
uncommitted?" - were answered by hand, repo by repo, and answered differently each time.
Each hand answer cost six tool calls and got one thing wrong: a feature branch counted as
a red, a working tree counted as a state, a repo missing from the sweep because the sweep
enumerated disk instead of the account.

So it is one script.

    python scripts/audit_estate.py                 # human report
    python scripts/audit_estate.py --json out.json # machine-readable too

THE DISCIPLINES IT CARRIES, so they are not remembered

- Repos come from the GitHub API, never from disk. One session scanned 15 when the
  account had 30.
- CI is filtered to each repo's DEFAULT BRANCH. A feature branch fails on its first run
  and that is not a defect.
- A red names the failing JOB and STEP, read off the runner's own jobs API - not guessed
  from a workflow file, and not reproduced locally first.
- A dirty tree is UNMEASURABLE, never red and never green. It is reported as its own
  third state, with the paths that make it dirty, so another lane's work in progress is
  never filed as a defect.
- git-clean is not byte-clean: the CRLF count is reported separately, because digests
  taken from a working tree lie.
- The token is read once, held in one variable, never printed and never written down.
"""

import argparse
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor

GITHUB_DIR = r'C:\Users\vikra\OneDrive\Documents\GitHub'
API = 'https://api.github.com/'


def token():
    p = subprocess.run(['git', 'credential', 'fill'], input='protocol=https\nhost=github.com\n\n',
                       capture_output=True, text=True, cwd=GITHUB_DIR)
    for line in p.stdout.splitlines():
        if line.startswith('password='):
            return line[9:]
    return None


TOKEN = token()


def api(path, retries=2):
    req = urllib.request.Request(API + path, headers={
        'Accept': 'application/vnd.github+json',
        'User-Agent': 'ventus-estate-audit',
        **({'Authorization': 'Bearer ' + TOKEN} if TOKEN else {}),
    })
    for attempt in range(retries + 1):
        try:
            with urllib.request.urlopen(req, timeout=45) as r:
                return json.load(r)
        except Exception as exc:
            if attempt == retries:
                return {'_error': str(exc)[:120]}
            time.sleep(1.5)


def git(repo, *args, timeout=60):
    try:
        p = subprocess.run(['git', '-C', repo, *args], capture_output=True, text=True,
                           timeout=timeout)
        # rstrip only: a leading space is DATA in `status --porcelain` (' M path'),
        # and stripping it shifted every first-line path by one character.
        return p.stdout.rstrip() if p.returncode == 0 else ''
    except Exception:
        return ''


def repos():
    """Every repo the account can see, newest push first. From the API, never from disk."""
    out, page = [], 1
    while True:
        got = api('user/repos?per_page=100&affiliation=owner,organization_member'
                  '&sort=pushed&page=%d' % page)
        if not isinstance(got, list) or not got:
            break
        out += [{'name': r['name'], 'full': r['full_name'], 'default': r['default_branch'],
                 'pushed': r['pushed_at'], 'private': r['private']} for r in got]
        if len(got) < 100:
            break
        page += 1
    return out


def ci_for(repo):
    """Latest run per workflow ON THE DEFAULT BRANCH. Reds carry their failing steps."""
    name, branch = repo['name'], repo['default']
    runs = api('repos/%s/actions/runs?branch=%s&per_page=60' % (repo['full'], branch))
    if isinstance(runs, dict) and runs.get('_error'):
        return {'repo': name, 'state': 'unreachable', 'detail': runs['_error']}
    items = runs.get('workflow_runs', []) if isinstance(runs, dict) else []
    items = [r for r in items if r.get('head_branch') == branch]
    if not items:
        return {'repo': name, 'state': 'no-runs', 'workflows': [], 'reds': []}

    latest = {}
    for r in items:                      # API returns newest first
        latest.setdefault(r['name'], r)

    reds, waiting, green = [], [], []
    for wf, r in latest.items():
        row = {'workflow': wf, 'conclusion': r.get('conclusion'), 'status': r.get('status'),
               'sha': (r.get('head_sha') or '')[:7], 'run_id': r.get('id'),
               'at': r.get('updated_at')}
        if r.get('status') != 'completed':
            waiting.append(row)
        elif r.get('conclusion') == 'success':
            green.append(row)
        elif r.get('conclusion') in ('failure', 'timed_out', 'startup_failure'):
            jobs = api('repos/%s/actions/runs/%s/jobs' % (repo['full'], r['id']))
            failed = []
            for j in (jobs.get('jobs', []) if isinstance(jobs, dict) else []):
                if j.get('conclusion') in ('failure', 'timed_out'):
                    steps = [s['name'] for s in j.get('steps', [])
                             if s.get('conclusion') == 'failure']
                    failed.append({'job': j.get('name'), 'steps': steps,
                                   'url': j.get('html_url')})
            row['failed_jobs'] = failed
            reds.append(row)
        # cancelled / skipped / neutral are neither, and are not counted as either

    head = items[0]
    head_sha = head.get('head_sha') or ''
    for r in reds:
        r['at_head'] = head_sha.startswith(r['sha'])
    at_head = [r for r in reds if r['at_head']]
    stale = [r for r in reds if not r['at_head']]
    # A workflow whose LAST run failed weeks ago, on a commit that is no longer the head,
    # does not make today's head red. Counting the two together is a wrong denominator,
    # and a wrong denominator gets quoted rather than checked.
    return {'repo': name,
            'state': 'red' if at_head else ('stale-red' if stale else ('green' if green else 'none')),
            'reds_at_head': len(at_head), 'reds_stale': len(stale),
            'branch': branch, 'head_sha': (head.get('head_sha') or '')[:7],
            'workflows': len(latest), 'green': len(green), 'waiting': len(waiting),
            'reds': reds}


def git_for(repo):
    """Local clone state. A dirty tree is UNMEASURABLE, not a defect and not a state."""
    path = os.path.join(GITHUB_DIR, repo['name'])
    if not os.path.isdir(path):
        return {'repo': repo['name'], 'present': False}
    git(path, 'fetch', '--quiet', 'origin', timeout=120)
    branch = git(path, 'rev-parse', '--abbrev-ref', 'HEAD')
    upstream = git(path, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}')
    default = repo['default']
    counts = git(path, 'rev-list', '--left-right', '--count', 'origin/%s...HEAD' % default)
    behind, ahead = (counts.split() + ['?', '?'])[:2]
    porcelain = [l for l in git(path, 'status', '--porcelain').splitlines() if l]
    modified = [l for l in porcelain if not l.startswith('??')]
    untracked = [l for l in porcelain if l.startswith('??')]
    eol = git(path, 'ls-files', '--eol')
    crlf = sum(1 for l in eol.splitlines() if 'w/crlf' in l)
    worktrees = max(0, git(path, 'worktree', 'list').count('\n'))
    return {'repo': repo['name'], 'present': True, 'branch': branch,
            'upstream': upstream or None, 'default': default,
            'ahead': ahead, 'behind': behind,
            'modified': len(modified), 'untracked': len(untracked),
            'modified_paths': [l[3:] for l in modified][:12],
            'untracked_paths': [l[3:] for l in untracked][:12],
            'crlf_files': crlf, 'worktrees': worktrees,
            'local_head': git(path, 'rev-parse', 'HEAD')[:7],
            'remote_head': git(path, 'rev-parse', 'origin/%s' % default)[:7],
            'measurable': not modified}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--json', help='also write the full result here')
    ap.add_argument('--only', nargs='*', help='limit to these repo names')
    args = ap.parse_args()

    t0 = time.time()
    all_repos = repos()
    if args.only:
        all_repos = [r for r in all_repos if r['name'] in args.only]
    print('%d repositories from the API (auth: %s)' % (all_repos and len(all_repos) or 0,
                                                       'yes' if TOKEN else 'NO - 60/hr'))

    with ThreadPoolExecutor(max_workers=12) as pool:
        ci = list(pool.map(ci_for, all_repos))
    local = [r for r in all_repos if os.path.isdir(os.path.join(GITHUB_DIR, r['name']))]
    with ThreadPoolExecutor(max_workers=8) as pool:
        gits = list(pool.map(git_for, local))

    print('\n== CI on default branches ==')
    reds = [c for c in ci if c.get('state') == 'red']
    order = {'red': 0, 'stale-red': 1, 'green': 2}
    for c in sorted(ci, key=lambda x: (order.get(x.get('state'), 3), x['repo'])):
        st = c.get('state')
        if st in ('red', 'stale-red'):
            print('  %-9s %-28s %s  (%d workflows, %d green, %d red at head, %d stale red)' %
                  ('RED@HEAD' if st == 'red' else 'stale-red', c['repo'], c.get('head_sha', ''),
                   c.get('workflows', 0), c.get('green', 0),
                   c.get('reds_at_head', 0), c.get('reds_stale', 0)))
            for r in sorted(c['reds'], key=lambda x: not x['at_head']):
                print('          %-6s %-42s %s  %s' %
                      ('AT HEAD' if r['at_head'] else 'stale', r['workflow'][:42], r['sha'],
                       (r.get('at') or '')[:16]))
                for fj in r.get('failed_jobs', []):
                    print('            job %-28s step: %s' %
                          (str(fj['job'])[:28], '; '.join(fj['steps'][:3]) or '(none named)'))
        elif st == 'green':
            print('  green %-28s %d workflows, %d waiting' %
                  (c['repo'], c.get('workflows', 0), c.get('waiting', 0)))
        else:
            print('  %-5s %-28s %s' % (st, c['repo'], c.get('detail', '')))

    print('\n== git ==')
    for g in sorted(gits, key=lambda x: x['repo']):
        flags = []
        if g['branch'] != g['default']:
            flags.append('ON BRANCH %s' % g['branch'])
        if g['ahead'] not in ('0', '?'):
            flags.append('%s ahead' % g['ahead'])
        if g['behind'] not in ('0', '?'):
            flags.append('%s behind' % g['behind'])
        if g['modified']:
            flags.append('UNMEASURABLE: %d modified' % g['modified'])
        if g['untracked']:
            flags.append('%d untracked' % g['untracked'])
        print('  %-28s %s  crlf %-5d wt %-3d %s' %
              (g['repo'], g['local_head'], g['crlf_files'], g['worktrees'],
               ' | '.join(flags) or 'clean, at origin'))
        for p in g['modified_paths']:
            print('        M  %s' % p)

    print('\n%d red, %d clean-and-measurable of %d local clones, %.1fs'
          % (len(reds), sum(1 for g in gits if g['measurable'] and g['ahead'] == '0'),
             len(gits), time.time() - t0))

    if args.json:
        with open(args.json, 'w', encoding='utf-8') as fh:
            json.dump({'measured_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
                       'ci': ci, 'git': gits}, fh, indent=1)
        print('wrote %s' % args.json)


if __name__ == '__main__':
    main()