#!/usr/bin/env python3
"""swarm.py: read the shared state of this repository and place marks in it.

Standard library only (Python 3.8+). Nothing here is required: every mark this tool
makes can be made with git and a text editor, and AGENTS.md says how. The tool makes
the common moves atomic and the state legible. It holds no state of its own.

    brief     what a participant needs before acting (fetches first: a checkpoint)
    status    write STATUS.md, the generated page (never edited by hand, never committed)
    claim     take a hold on a line: atomic, via a compare-and-swap push
    renew     extend your hold
    release   give the hold back
    sync      checkpoint, integrate the medium, push your commits
    anchors   which places in the texts have a line, and which are unmined
    census    who has been here, by kind of participant
    check     the few hard invariants (exit 1 if one is broken)
    identity  set this clone's git identity to the repository's convention
"""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import os
import random
import re
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
ARTICLE = ROOT / "texts" / "automate-asocial" / "translation.md"
STATUSES = ("seed", "open", "resting", "closed")
PASS_KINDS = ("pass", "reading", "correction", "note", "handoff")
HOLDABLE_EXTRAS = ("tools", "protocol", "texts")
SOURCE_STATUSES = ("named", "located", "read", "checked")
SOURCE_HOLD_PREFIX = "source--"
DEFAULT_LIMITS = {"swarm_size": 0, "max_live_holds": 6, "hold_hours": 3, "min_open": 3, "max_open": 18, "max_per_day": 40}
PENCILS_DOWN = ("QUIET since {t}: pencils down. Do not finish: hand off. Under 'Passes' add a mark "
                "`### <date> | <your kind> | handoff` saying what you established (with its sources), what you "
                "were in the middle of, and what remains; put what remains under 'Threads'; write your journal "
                "entry; sync; release; stop. Take nothing new. The next participant resumes from your handoff.")
HEADING = re.compile(r"^\s{0,3}#{2,4}\s*(\d{4}-\d{2}-\d{2})\s*[|·]\s*([\w.+-]+)\s*[|·]\s*([a-z]+)\b", re.I)
ATTRIBUTION = re.compile(r"^\s*co-authored-by:|^\s*claude-session:|claude\.ai/code|generated (with|by) \[?"
                         r"(claude|chatgpt|codex|copilot|gemini|cursor|antigravity|an? (ai|llm)\b)", re.I | re.M)
AGENT_EMAIL = re.compile(r"noreply@anthropic\.com|@openai\.com|\[bot\]|copilot|cursoragent|gemini-cli|antigravity", re.I)
AGENT_NAMES = {"claude", "claude code", "codex", "chatgpt", "gemini", "antigravity", "cursor agent", "copilot"}
RULE_FILES = ("AGENTS.md", "CLAUDE.md", "GEMINI.md", "limits.conf", "tools/swarm.py")
SECTIONS = ("Question", "Where it stands", "Threads", "Passes")


# ---------------------------------------------------------------- small helpers

def sh(*args: str, cwd: Path = ROOT) -> tuple[int, str, str]:
    try:
        p = subprocess.run(list(args), cwd=cwd, capture_output=True, text=True)
        return p.returncode, p.stdout.strip(), p.stderr.strip()
    except OSError as exc:
        return 127, "", str(exc)


def git(*args: str) -> tuple[int, str, str]:
    return sh("git", *args)


def now() -> dt.datetime:
    return dt.datetime.now(dt.timezone.utc).replace(second=0, microsecond=0)


def stamp(t: dt.datetime) -> str:
    return t.strftime("%Y-%m-%dT%H:%MZ")


def unstamp(s: str) -> dt.datetime | None:
    text = (s or "").strip().replace(" UTC", "Z")
    for form in ("%Y-%m-%dT%H:%MZ", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%MZ", "%Y-%m-%d %H:%M"):
        try:
            return dt.datetime.strptime(text, form).replace(tzinfo=dt.timezone.utc)
        except ValueError:
            continue
    return None


def read(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8-sig", errors="replace")
    except OSError:
        return ""


def blob_id(path: Path) -> str:
    try:
        data = path.read_bytes()
    except OSError:
        return ""
    return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()


def items(value: str) -> list[str]:
    return [v for v in re.split(r"[,\s]+", value or "") if v]


def parse_fields(text: str, comments: bool = True) -> tuple[dict[str, str], list[str]]:
    """'key: value' lines. Tolerant: a bad line is reported, never fatal."""
    meta: dict[str, str] = {}
    problems: list[str] = []
    if "\ufffd" in text:
        problems.append("has bytes that are not UTF-8 (shown as \ufffd): save the file again as UTF-8")
    for raw in text.splitlines():
        line = raw.strip()
        if comments and not line.startswith("#"):
            line = line.split(" #", 1)[0].rstrip()
        if not line or line.startswith("#"):
            continue
        m = re.match(r"^([A-Za-z_][\w-]*)\s*:\s*(.*)$", line)
        if not m:
            problems.append(f"unreadable line: {raw.strip()[:60]!r}")
            continue
        key, value = m.group(1).lower(), m.group(2).strip()
        if key in meta and meta[key] != value:
            problems.append(f"'{key}' given twice (a merge kept both sides?); using the last")
        meta[key] = value
    return meta, problems


def parse_marked(text: str) -> tuple[dict[str, str], str, list[str]]:
    """A Markdown file with a '---' fenced block of fields at the top."""
    text = text.lstrip()
    if not text.startswith("---"):
        return {}, text, ["no '---' block of fields at the top"]
    parts = text.split("\n---", 1)
    if len(parts) < 2:
        return {}, text, ["the '---' block of fields is not closed"]
    meta, problems = parse_fields(parts[0][3:], comments=False)
    if "\ufffd" in parts[1]:
        problems.append("has bytes that are not UTF-8 (shown as \ufffd): save the file again as UTF-8")
    if re.search(r"^(<{7}|>{7})( |$)", text, re.M):
        problems.append("merge conflict markers (<<<<<<< / >>>>>>>) were left in the file")
    body = parts[1].split("\n", 1)[1] if "\n" in parts[1] else ""
    return meta, body, problems


def memory_path() -> Path:
    rc, out, _ = git("rev-parse", "--git-dir")
    base = Path(out) if rc == 0 and out else ROOT / ".git"
    return (base if base.is_absolute() else ROOT / base) / "swarm-holds"


def remembered() -> dict[str, str]:
    """The holds this clone acquired: id -> session. Local, private, safe to lose."""
    out: dict[str, str] = {}
    for row in read(memory_path()).splitlines():
        cells = row.split()
        if len(cells) == 2:
            out[cells[0]] = cells[1]
    return out


def remember(hold_id: str, session: str | None) -> None:
    mine = remembered()
    if session is None:
        mine.pop(hold_id, None)
    else:
        mine[hold_id] = session
    try:
        memory_path().write_text("".join(f"{k} {v}\n" for k, v in mine.items()), encoding="utf-8")
    except OSError:
        pass


def today_count(journal: list[dict]) -> int:
    return sum(1 for e in journal if e["date"] == now().strftime("%Y-%m-%d"))


# ---------------------------------------------------------------- the state

def load_limits() -> dict:
    """Lenient to read ('key: 3', 'key = 3', 'key: 3 until Monday'). The stop switch fails
    closed: if max_live_holds cannot be read, it is 0."""
    limits: dict = dict(DEFAULT_LIMITS)
    seen = set()
    for raw in read(ROOT / "limits.conf").splitlines():
        m = re.match(r"^\s*([A-Za-z_]+)\s*[:=]\s*(-?\d+)", raw)
        if m:
            key, value = m.group(1).lower(), int(m.group(2))
            if key != "quiet_at":
                limits[key] = min(value, limits[key]) if key in seen else value  # given twice: the lower holds
                seen.add(key)
        q = re.match(r"^\s*quiet_at\s*[:=]\s*(\S.*?)\s*$", raw)
        if q:
            when = unstamp(q.group(1))
            earlier = limits.get("quiet_at")
            limits["quiet_unreadable"] = limits.get("quiet_unreadable", False) or when is None
            limits["quiet_at"] = min(when, earlier) if when and earlier else (when or earlier)  # given twice: the earlier
    limits["missing"] = [k for k in DEFAULT_LIMITS if k not in seen]
    limits["unreadable"] = "max_live_holds" in limits["missing"] or "max_per_day" in limits["missing"]
    if limits["unreadable"]:
        limits["max_live_holds"] = 0
    return limits


def tempo(limits: dict) -> tuple[str, str]:
    """open, closing (a quiet time is set and still ahead) or quiet (it has passed).
    The stop switch fails closed here too: a quiet time that cannot be read is quiet."""
    if limits.get("quiet_unreadable"):
        return "quiet", ("limits.conf has a quiet_at that cannot be read, so the swarm is quiet. "
                         "Write it as 2026-11-28T15:05Z, or remove the line.")
    q = limits.get("quiet_at")
    if q is None:
        return "open", ""
    left = int((q - now()).total_seconds() // 60)
    if left <= 0:
        return "quiet", PENCILS_DOWN.format(t=stamp(q))
    return "closing", (f"The swarm goes quiet at {stamp(q)}, in {left} minute(s). Land your contribution before "
                       "then. If it will not fit, stop where you are and hand it off (AGENTS.md, 'Going quiet').")


def article_anchors() -> list[str]:
    text = read(ARTICLE)
    pages = sorted({int(n) for n in re.findall(r'id="p(\d+)"', text)})
    notes = sorted({int(n) for n in re.findall(r'id="fn-(\d+)"', text)})
    return [f"p{n}" for n in pages] + [f"fn-{n}" for n in notes]


def prompt_paragraphs() -> dict[str, str]:
    """Anchor -> first words, for every paragraph of every verbatim prompt."""
    out: dict[str, str] = {}
    for path in sorted((ROOT / "prompts").glob("*.md")):
        if path.name == "README.md":
            continue
        name = re.sub(r"^\d{4}-\d{2}-\d{2}-", "", path.stem)
        blocks = [b for b in re.split(r"\n\s*\n", read(path)) if b.strip()]
        for i, block in enumerate(blocks, 1):
            if block.strip().strip("-") == "":
                continue  # a bare separator: numbered, but nothing to mine
            out[f"{name}#{i}"] = " ".join(block.split())[:70]
    return out


def expand_anchor(token: str) -> list[str]:
    m = re.match(r"^(.*?)(\d+)\.\.(?:\1)?(\d+)$", token)
    if not m:
        return [token]
    lo, hi = int(m.group(2)), int(m.group(3))
    if hi < lo or hi - lo > 200:
        return [token]
    return [f"{m.group(1)}{n}" for n in range(lo, hi + 1)]


def open_threads(body: str) -> list[str]:
    section = re.search(r"^## Threads[ \t]*\n(.*?)(?=^## |\Z)", body, re.M | re.S)
    return re.findall(r"^[ \t]*[-*] \[ \][ \t]+(.+?)[ \t]*$", section[1], re.M) if section else []


def thread_signature(threads: list[str]) -> str:
    return hashlib.sha256("\n".join(sorted(threads)).encode("utf-8")).hexdigest()[:12]


def load_lines(known_anchors: set[str]) -> dict[str, dict]:
    lines: dict[str, dict] = {}
    for path in sorted((ROOT / "lines").glob("*.md")):
        if path.name == "README.md":
            continue
        meta, body, problems = parse_marked(read(path))
        status = meta.get("status", "")
        if status not in STATUSES:
            problems.append(f"status {status!r} is not one of {', '.join(STATUSES)}")
        if path.stem.startswith(SOURCE_HOLD_PREFIX):
            problems.append("the source-- prefix is reserved for source discovery holds")
        if not re.match(r"^[a-z0-9][a-z0-9-]*$", path.stem):
            problems.append("its file name cannot be held: rename it to lower-case letters, digits and hyphens")
        ticks = re.findall(r"^\s*[-*] \[[ xX]\] (.+?)\s*$", body, re.M)
        for tick in sorted({t for t in ticks if ticks.count(t) > 1}):
            problems.append(f"a thread appears {ticks.count(tick)} times (a merge kept both sides?): keep one: {tick[:40]!r}")
        passes = []
        under_passes = bare = False
        for raw in body.splitlines():
            h = HEADING.match(raw)
            if h and h.group(3).lower() in PASS_KINDS:
                passes.append((h.group(1), h.group(2), h.group(3).lower()))
                bare = False
            elif re.match(r"^##\s+Passes\b", raw):
                under_passes = bare = True
            elif re.match(r"^\s{0,3}#{1,3}(\s|\d)", raw) and (under_passes or re.match(r"^\s{0,3}#+\s*\d", raw)):
                problems.append(f"heading not in the form '### date | who | kind', so what is under it is not seen: {raw[:60]!r}")
                bare = False
            elif bare and raw.strip():
                problems.append(f"writing under '## Passes' with no '### date | who | kind' heading above it: {raw[:40]!r}")
                bare = False
        anchors: list[str] = []
        for token in items(meta.get("anchors", "")):
            for a in expand_anchor(token):
                if a in known_anchors:
                    anchors.append(a)
                else:
                    problems.append(f"anchor {a!r} is not a place in the texts")
        for section in SECTIONS:
            n = len(re.findall(rf"^## {re.escape(section)}\s*$", body, re.M))
            if n != 1:
                problems.append(f"'## {section}' appears {n} times (a merge kept both sides, or it was removed): tidy by hand")
        try:
            priority = int(meta.get("priority", "3") or 3)
        except ValueError:
            priority = 3
            problems.append("priority is not a number")
        lines[path.stem] = {
            "id": path.stem,
            "path": path.relative_to(ROOT).as_posix(),
            "title": meta.get("title", path.stem),
            "status": status,
            "priority": priority,
            "needs": items(meta.get("needs", "")),
            "needs_owner": meta.get("needs_owner", "").strip(),
            "anchors": anchors,
            "passes": passes,
            "threads": len(open_threads(body)),
            "thread_signature": thread_signature(open_threads(body)),
            "sources": sorted(set(re.findall(r"sources/([\w.-]+?)\.md", body))),
            "problems": problems,
        }
    return lines


def load_holds(cross: bool = True) -> dict[str, dict]:
    holds: dict[str, dict] = {}
    hours = load_limits()["hold_hours"]
    for path in sorted((ROOT / "holds").glob("*")):
        if path.name == "README.md" or path.name.startswith("."):
            continue
        if path.is_file():
            meta, problems = parse_fields(read(path))
        else:
            meta, problems = {}, ["is a folder; a hold is one plain file named after the line (holds/README.md)"]
        until = unstamp(meta.get("until", ""))
        readable = until is not None
        if not readable:
            ts = git("log", "-1", "--format=%ct", "--", f"holds/{path.name}")[1]
            until = (dt.datetime.fromtimestamp(int(ts), dt.timezone.utc) if ts.isdigit() else now()) + dt.timedelta(hours=hours)
            problems.append(f"no readable 'until' (write it as 2026-11-28T17:05Z): it stands for {hours}h from its "
                            f"last commit, to {stamp(until)}, and can be taken over after that")
        elif until > now() + dt.timedelta(hours=max(24, 4 * hours)):
            problems.append(f"'until' is {meta['until']}, more than a day away: a slip in the date?")
        holds[path.name] = {
            "id": path.name,
            "by": meta.get("by", "unknown"),
            "session": meta.get("session", ""),
            "since": meta.get("since", ""),
            "until": meta.get("until", "") if readable else stamp(until),
            "live": until > now(),
            "readable": readable,
            "problems": problems,
        }
    return across_branches(holds) if cross else holds


BRANCHES_READ: list[str] = []
FULL_FETCH: list[bool] = []  # empty: no fetch this run; [False]: the fetch of every branch failed


def across_branches(holds: dict[str, dict]) -> dict[str, dict]:
    """Read the holds on every branch origin has, not only the medium's (lines/medium-and-authority).
    A harness that confines a session to its own branch makes each branch a medium of its own, and a
    hold there is invisible to `brief` elsewhere until it is merged. Each hold file was last written by
    some commit C. A copy of it is superseded when some branch contains C but no longer carries that
    session's hold there (it was released, or taken over, after C). What is left, live and not ours,
    is held elsewhere: it counts as live here, and two sessions left on one line are a contest."""
    refs = [r for r in git("for-each-ref", "--format=%(refname:short)", "refs/remotes/origin")[1].split()
            if r not in ("origin", "origin/HEAD")]
    BRANCHES_READ[:] = refs
    trees: dict[str, dict[str, dict]] = {"HEAD": {k: h for k, h in holds.items() if h["session"]}}
    for r in refs:
        found: dict[str, dict] = {}
        for row in git("ls-tree", f"{r}:holds")[1].splitlines():
            parts = row.split(None, 3)
            if len(parts) == 4 and parts[1] == "blob" and parts[3] != "README.md":
                meta, _ = parse_fields(git("cat-file", "-p", parts[2])[1])
                found[parts[3]] = meta
        trees[r] = found
    writer: dict[tuple[str, str], str] = {}
    contains: dict[str, set[str]] = {}

    def wrote(ref: str, hold_id: str) -> str:
        return writer.setdefault((ref, hold_id), git("log", "-1", "--format=%H", ref, "--", f"holds/{hold_id}")[1])

    def superseded(hold_id: str, ref: str, session: str) -> str:
        c = wrote(ref, hold_id)
        if not c:
            return ""
        if c not in contains:
            inside = set(git("branch", "-r", "--format=%(refname:short)", "--contains", c)[1].split())
            if git("merge-base", "--is-ancestor", c, "HEAD")[0] == 0:
                inside.add("HEAD")
            contains[c] = inside
        for other in contains[c]:
            there = trees.get(other, {}).get(hold_id)
            if other in trees and (there is None or there.get("session") != session):
                return other
        return ""

    for hold_id, h in holds.items():
        if h["live"] and h["session"]:
            gone = superseded(hold_id, "HEAD", h["session"])
            if gone:
                h["live"], h["released_on"] = False, gone.replace("origin/", "")
    t = now()
    for r in refs:
        for hold_id, meta in trees[r].items():
            session, until = meta.get("session", ""), unstamp(meta.get("until", ""))
            mine = holds.get(hold_id)
            if not session or until is None or until <= t:
                continue
            if mine and mine["session"] == session:  # the same hold: a renewal elsewhere counts
                if not mine.get("released_on") and until > (unstamp(mine["until"]) or t):
                    mine["until"], mine["live"] = meta["until"], True
                continue
            if superseded(hold_id, r, session):
                continue
            on = r.replace("origin/", "")
            if mine and mine["live"]:
                if mine.get("on") != on and session not in [x["session"] for x in mine.setdefault("rivals", [])]:
                    rival = {"session": session, "by": meta.get("by", "unknown"), "on": on,
                             "key": precedence(wrote(r, hold_id), session)}
                    mine["rivals"].append(rival)
                    mine["key"] = precedence(wrote(f"origin/{mine['on']}" if mine.get("on") else "HEAD", hold_id),
                                             mine["session"])
                    keeper = "this one" if mine["key"] < rival["key"] else f"session {session}"
                    mine["problems"].append(
                        f"CONTESTED: also held by {rival['by']} (session {session}) on {on}, "
                        f"{meta.get('since', '?')} to {meta.get('until')}. The hold written first keeps the "
                        f"line (ties by the lower session): {keeper} keeps it, the other releases at once")
                continue
            holds[hold_id] = {"id": hold_id, "by": meta.get("by", "unknown"), "session": session,
                              "since": meta.get("since", ""), "until": meta.get("until", ""), "live": True,
                              "readable": True, "problems": [], "on": on}
    return holds


def precedence(commit: str, session: str) -> tuple[int, str]:
    """Which of two holders on one line keeps it: the hold whose file was written first, by author time
    (a rebase keeps it, where it renews the commit time), and on a tie the lower session token. Both
    holders read the same two commits, so both reach the same verdict without speaking."""
    t = git("log", "-1", "--format=%at", commit)[1] if commit else ""
    return (int(t) if t.isdigit() else 2 ** 62, session)


def yields_to(hold: dict) -> dict | None:
    """The rival this hold must give way to, if any."""
    beaten = [r for r in hold.get("rivals", []) if r["key"] < hold.get("key", (0, ""))]
    return min(beaten, key=lambda r: r["key"]) if beaten else None


def load_sources() -> dict[str, dict]:
    sources: dict[str, dict] = {}
    for path in sorted((ROOT / "sources").glob("*.md")):
        if path.name == "README.md":
            continue
        meta, body, problems = parse_marked(read(path))
        if meta.get("status", "") not in SOURCE_STATUSES:
            problems.append(f"status is not one of {', '.join(SOURCE_STATUSES)}")
        sources[path.stem] = {"status": meta.get("status", ""), "cite": meta.get("cite", ""), "problems": problems,
                              "searches": len(SEARCH_RECORD.findall(body))}
    return sources


def source_key(hold_id: str) -> str:
    return hold_id[len(SOURCE_HOLD_PREFIX):] if hold_id.startswith(SOURCE_HOLD_PREFIX) else ""


# A recorded unsuccessful search: a bold run naming a search and its result, e.g.
# "**Bounded search, 28 November 2026 (claude-code): not located.**" (sources/README.md).
SEARCH_RECORD = re.compile(r"\*\*[^*\n]*\b(?:search|query)\b[^*\n]*\bnot (?:located|found)\b[^*\n]*\*\*", re.I)


def available_source_keys(state: dict, searched: bool = False) -> list[str]:
    """Standalone discovery candidates, excluding already held or located sources. A named source
    whose file records an unsuccessful search is set apart (searched=True lists those instead):
    its next step is the one the file names, not another draw (sources/README.md)."""
    return [key for key, src in state["sources"].items()
            if src["status"] == "named" and re.fullmatch(r"[a-z0-9][a-z0-9-]*", key)
            and bool(src.get("searches")) == searched
            and not state["holds"].get(SOURCE_HOLD_PREFIX + key, {}).get("live")]


def located_on_branch(key: str) -> str:
    """Check fetched tips before starting discovery; source status only moves forward."""
    for ref in BRANCHES_READ:
        rc, content, _ = git("show", f"{ref}:sources/{key}.md")
        if rc == 0:
            meta, _, problems = parse_marked(content)
            if not problems and meta.get("status") in SOURCE_STATUSES[1:]:
                return ref.removeprefix("origin/")
    return ""


def journal_field(body: str, key: str) -> str:
    """Read one unambiguous, single-line assessment field; never infer a missing value."""
    found = re.findall(r"^\*\*" + re.escape(key) + r":\*\*[ \t]*(.+)$", body, re.M)
    return found[0].strip() if len(found) == 1 else ""


def utility_feedback(state: dict) -> tuple[dict, dict]:
    """Self-assessments are evidence, not quality grades. Explicit flags carry work."""
    lines = state["lines"]
    scores: dict[str, list[dict]] = {}
    flags: dict[str, list[dict]] = {}
    addressed = {(e["line"], name) for e in state["journal"]
                 for name in e.get("addresses", [])}
    for e in state["journal"]:
        target = e["line"]
        if (target in lines or target in HOLDABLE_EXTRAS or target.startswith(SOURCE_HOLD_PREFIX)) and e.get("utility") is not None:
            scores.setdefault(target, []).append(e)
        flag = e.get("flag")
        if not flag:
            continue
        target, action, reason = flag
        if target in lines and lines[target]["status"] != "closed" and (target, e["name"]) not in addressed:
            flags.setdefault(target, []).append({"name": e["name"], "action": action, "reason": reason})
    return scores, flags


def growth_state(state: dict) -> tuple[int, int, bool]:
    """Measure outstanding active obligations, not cumulative historical text."""
    active = [ln for ln in state["lines"].values() if ln["status"] == "open"]
    threads = sum(ln["threads"] for ln in active)
    target = max(1, state["limits"].get("max_open_threads", 120))
    return threads, target, threads > target or len(active) > state["limits"]["max_open"]


def utility_overview(state: dict) -> list[str]:
    scores, flags = utility_feedback(state)
    reports = [e for group in scores.values() for e in group]
    threads, target, over = growth_state(state)
    out = [f"Outstanding open threads: {threads} (pressure target {target}); "
           + ("consolidation pressure is elevated." if over else "growth and consolidation can coexist."),
           "Utility (self-assessed marginal contribution, not a grade): "
           + (", ".join(f"{i}: {sum(e['utility'] == i for e in reports)}" for i in range(4))
              if reports else "no reports yet")
           + f"; {len(reports)} reports across {len(scores)} lines; {len(flags)} lines with unresolved flags."]
    originals = {e["name"]: e for e in reports}
    comparisons = []
    for e in state["journal"]:
        if e.get("calibration"):
            name, value, reason = e["calibration"]
            prior = originals.get(name)
            if prior and name != e["name"] and prior["line"] == e["line"]:
                comparisons.append((prior["utility"], value, reason, e["name"]))
    if comparisons:
        out.append(f"Independent utility comparisons: {len(comparisons)}; "
                   f"{sum(old == new for old, new, _, _ in comparisons)} agree. "
                   "Comparisons are assessments, not ground truth.")
        differences = [(old, new, reason, name) for old, new, reason, name in comparisons if old != new]
        if differences:
            old, new, reason, name = differences[-1]
            out.append(f"Calibration example: {old} → {new}/3 — {reason[:110]} [journal/{name}]")
    for label, group in (("Higher reported utility", [e for e in reports if e["utility"] == 3]),
                         ("Lower reported utility", [e for e in reports if e["utility"] <= 1])):
        for e in sorted(group, key=lambda x: x["name"], reverse=True)[:2]:
            out.append(f"{label}: {e['line']} ({e['utility']}/3) — {e['utility_reason'][:110]} "
                       f"[journal/{e['name']}]")
    return out


def load_journal() -> list[dict]:
    entries = []
    for path in sorted((ROOT / "journal").glob("*.md")):
        if path.name == "README.md":
            continue
        text = read(path)
        meta, body, problems = parse_marked(text)
        first = next((ln.strip() for ln in body.splitlines() if ln.strip()), "")
        rating = re.fullmatch(r"([0-3])\s*\|\s*(\S.*)", journal_field(body, "Utility"))
        flag = re.fullmatch(r"([a-z0-9][a-z0-9-]*)\s*\|\s*(rest|merge|focus)\s*\|\s*(\S.*)",
                            journal_field(body, "Flag"))
        addresses = [x.strip() for x in journal_field(body, "Addresses").split(",")
                     if re.fullmatch(r"[a-zA-Z0-9_.-]+\.md", x.strip())]
        retain = re.fullmatch(r"([a-f0-9]{12})\s*\|\s*(\S.*)", journal_field(body, "Retain obligations"))
        calibration = re.fullmatch(r"([a-zA-Z0-9_.-]+\.md)\s*\|\s*([0-3])\s*\|\s*(\S.*)",
                                   journal_field(body, "Calibration"))
        entries.append({
            "retain": retain[1] if retain else None,
            "calibration": (calibration[1], int(calibration[2]), calibration[3]) if calibration else None,
            "utility": int(rating[1]) if rating else None,
            "utility_reason": rating[2] if rating else "",
            "flag": flag.groups() if flag else None, "addresses": addresses,
            "name": path.name, "date": path.name[:10], "by": meta.get("by", "unknown"),
            "line": meta.get("line", ""), "first": first[:110], "length": len(text.splitlines()),
            "problems": problems,
        })
    return entries


def load_incidents() -> list[dict]:
    """Immutable observations and separate review receipts; reporting needs no hold."""
    root = ROOT / "incidents"
    entries = []
    for path in sorted(root.glob("*.md")):
        if path.name == "README.md" or path.name.startswith("review-"):
            continue
        meta, body, problems = parse_marked(read(path))
        kind = meta.get("kind", "").strip()
        if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,79}", kind):
            problems.append("missing or invalid kind (use a short lowercase hyphenated class)")
            kind = "unclassified"
        operation = meta.get("operation", "").strip()
        if not operation or not body.strip():
            problems.append("missing operation or incident evidence")
        receipt = root / f"review-{path.name}"
        reviewed = False
        if receipt.is_file():
            review, explanation, errors = parse_marked(read(receipt))
            reviewed = (not errors and review.get("report") == path.name
                        and review.get("disposition") in ("transient", "duplicate", "tracked", "resolved")
                        and bool(explanation.strip()))
            if reviewed:
                problems = []  # reports are immutable: a valid receipt is the only way their format problems can clear
            else:
                problems.append(f"invalid review receipt {receipt.name}; observation remains unreviewed")
        entries.append({"name": path.name, "kind": kind, "operation": operation,
                        "reviewed": reviewed, "problems": problems})
    return entries


def strays() -> list[tuple[str, str]]:
    out: list[tuple[str, str]] = []
    for path in sorted((ROOT / "lines").glob("*")):
        if path.name.startswith("."):
            continue
        if path.is_file() and path.suffix != ".md":
            out.append((f"lines/{path.name}", "is not read as a line: a line is lines/<id>.md"))
        elif path.is_dir() and not (ROOT / "lines" / f"{path.name}.md").is_file():
            out.append((f"lines/{path.name}/", f"is a folder with no line beside it (lines/{path.name}.md)"))
    for path in sorted((ROOT / "journal").glob("*")):
        if path.name != "README.md" and not re.match(r"^\d{4}-\d{2}-\d{2}.*\.md$", path.name):
            out.append((f"journal/{path.name}", "is not named YYYY-MM-DDTHHMMZ-<line>.md: it is unread, or sorts out of order"))
    for path in sorted((ROOT / "incidents").glob("*")):
        if path.name == "README.md" or path.name.startswith("."):
            continue
        if path.suffix != ".md":
            out.append((f"incidents/{path.name}", "is not read as an incident report: a report is incidents/<name>.md"))
        elif path.name.startswith("review-") and not (ROOT / "incidents" / path.name[len("review-"):]).is_file():
            out.append((f"incidents/{path.name}", f"is read as a review receipt, but {path.name[len('review-'):]} does not "
                        "exist: a report may not be named review-*, and a receipt names its report exactly"))
    names = [re.sub(r"^\d{4}-\d{2}-\d{2}-", "", q.stem) for q in (ROOT / "prompts").glob("*.md") if q.name != "README.md"]
    for name in sorted({n for n in names if names.count(n) > 1}):
        out.append((f"prompts/*-{name}.md", f"{names.count(name)} prompts share the name '{name}', so their anchors "
                    f"{name}#N collide: give the later one another name"))
    if git("ls-files", "--", "STATUS.md")[1]:
        out.append(("STATUS.md", "is committed, and it is generated: git rm --cached STATUS.md, commit, sync"))
    # the journal is append-only on the medium too: an entry changed there is answered by a later entry that names it
    said = "\n".join(read(q) for q in (ROOT / "journal").glob("*.md") if q.name != "README.md")
    for name in sorted(set(git("log", "--diff-filter=MD", "--name-only", "--format=", "--", "journal/")[1].splitlines())):
        base = name.rsplit("/", 1)[-1]
        if base and base != "README.md" and base not in said:
            out.append((name, f"was changed or deleted after it was written: add an entry that names {base} and says what changed"))
    return out


def load_state() -> dict:
    prompts = prompt_paragraphs()
    article = article_anchors()
    known = set(article) | set(prompts)
    return {
        "limits": load_limits(),
        "article_anchors": article,
        "prompt_anchors": prompts,
        "lines": load_lines(known),
        "holds": load_holds(),
        "sources": load_sources(),
        "journal": load_journal(),
        "incidents": load_incidents(),
        "strays": strays(),
    }


# ---------------------------------------------------------------- sensing
#
# A sensor reads the state and reports a pressure: a condition that some work would
# relieve. Pressures are not assignments and not permissions. To make a class of
# failure visible to every later participant, add or sharpen a sensor here (AGENTS.md,
# "Three orders of edit"), then relieve the instance like any other work.

def sense(state: dict) -> list[dict]:
    lines, holds, sources = state["lines"], state["holds"], state["sources"]
    live = {k for k, h in holds.items() if h["live"]}
    out: list[dict] = []

    def add(kind: str, subject: str, why: str, take: bool = False, priority: int = 3) -> None:
        out.append({"kind": kind, "subject": subject, "why": why, "take": take, "priority": priority})

    scores, flags = utility_feedback(state)
    threads, target, over = growth_state(state)
    retained = {(e["line"], e["retain"]) for e in state["journal"] if e.get("retain")}
    active_count = sum(ln["status"] == "open" for ln in lines.values())
    if over:
        add("sprawl", "active obligations", f"{threads} open threads (target {target}), "
            f"{active_count} open lines (ceiling {state['limits']['max_open']}); "
            "reduce or consolidate obligations before expanding the frontier. No automatic deletion.")
    # Observations are evidence, not tasks. Group by class so repeated failures are visible.
    incidents: dict[str, list[dict]] = {}
    for incident in state.get("incidents", []):
        for problem in incident["problems"]:
            add("illegible", f"incidents/{incident['name']}", problem)
        if not incident["reviewed"]:
            incidents.setdefault(incident["kind"], []).append(incident)
    for kind, reports in incidents.items():
        names = ", ".join(r["name"] for r in reports[:3])
        if len(reports) > 3:
            names += ", ..."
        add("incident", kind, f"{len(reports)} unreviewed operational report(s): {names}. "
            "Read the evidence; account for it under the ordinary hold and leave review receipts "
            "(incidents/README.md). Not an assignment.")
    for ln in lines.values():
        if ln["needs_owner"]:
            add("owner", ln["id"], ln["needs_owner"])
    for h in holds.values():
        if not h["live"] and not h.get("released_on"):
            key = source_key(h["id"])
            if key in sources:
                if sources[key]["status"] != "named":
                    add("stranded", h["id"], "source already located; remove the lapsed discovery hold")
                continue
            ln = lines.get(h["id"])
            blocked = bool(ln) and (bool(ln["needs_owner"]) or ln["status"] == "closed")
            if blocked or not ln:
                add("stranded", h["id"], f"hold by {h['by']} lapsed at {h['until']}, and it cannot be taken "
                    f"over with claim: delete holds/{h['id']} by hand")
            else:
                add("stranded", h["id"], f"hold by {h['by']} lapsed at {h['until']}: take it over, "
                    "starting from what its holder pushed", take=True, priority=ln["priority"])
    if len(live) > state["limits"]["max_live_holds"] > 0:
        add("crowded", "holds/", f"{len(live)} live holds, and limits.conf allows {state['limits']['max_live_holds']}")
    for ln in lines.values():
        if ln["id"] in live or ln["needs_owner"] or ln["status"] == "closed":
            continue
        marked = flags.get(ln["id"], [])
        signature = ln.get("thread_signature")
        burden = ln["status"] == "open" and (ln["threads"] >= max(1, state["limits"].get("threads_per_line", 8))
                                             or (over and ln["threads"] >= 3)
                                             or active_count > state["limits"]["max_open"])
        if signature and (ln["id"], signature) in retained:
            burden = False
        if marked or burden:
            why = f"{ln['threads']} open thread(s); assess significance, consolidate or rest where justified"
            if marked:
                why += "; " + "; ".join(f"{x['action']}: {x['reason'][:100]} (journal/{x['name']})"
                                         for x in marked[:2])
            if signature:
                why += f"; obligation fingerprint {signature}"
            add("consolidate", ln["id"], why + ". Keep evidence; answer flags explicitly.", take=True,
                priority=ln["priority"])
        if ln["status"] != "open":
            continue
        kinds = [k for _, _, k in ln["passes"]]
        at = len(kinds) - 1 - kinds[::-1].index("pass") if "pass" in kinds else -1
        last = ln["passes"][at] if at >= 0 and "reading" not in kinds[at:] else None
        if kinds and kinds[-1] == "handoff":
            put = ln["passes"][-1]
            add("resume", ln["id"], f"put down mid-work on {put[0]} by {put[1]}: pick it up from the handoff, "
                "not from the beginning", take=True, priority=ln["priority"])
        elif last:
            add("reading", ln["id"], f"the pass of {last[0]} by {last[1]} has had no cold reading "
                "(by a different session, from the sources, not from the pass)", take=True,
                priority=ln["priority"])
        elif ln["status"] == "open" and (not ln["passes"] or ln["threads"]):
            what = "no pass yet" if not ln["passes"] else f"{ln['threads']} open thread(s)"
            add("open", ln["id"], f"{what}: {ln['title']}", take=True, priority=ln["priority"])
        elif ln["status"] == "open":
            add("settle", ln["id"], "read, and no open threads: mark it resting if sufficient", take=True,
                priority=ln["priority"])
    named = available_source_keys(state)
    named_set = set(named)
    searched = available_source_keys(state, searched=True)
    for ln in lines.values():
        for key in ln["sources"]:
            if key not in sources:
                add("unsourced", ln["id"], f"cites sources/{key}.md, which does not exist")
            elif key in named_set:
                add("unsourced", ln["id"], f"leans on sources/{key}.md, which nobody has yet located or read")
            elif key in searched:
                add("unsourced", ln["id"], f"leans on sources/{key}.md, searched for and not found: "
                    "say in the line what rests on it alone")
    if searched:
        add("unsourced", f"{len(searched)} source(s)", "searched, not found: " + ", ".join(
            f"{k} ({sources[k]['searches']}x)" for k in searched[:10]) + (" ..." if len(searched) > 10 else "")
            + ". Not drawn: read the file's last search and take only the next step it names, under the source "
            "hold; do not repeat a search already recorded")
    if named:
        add("unsourced", f"{len(named)} source(s)", "only named, not yet located: " + ", ".join(named[:10])
            + (" ..." if len(named) > 10 else "") + ". Claim source--<key> before standalone discovery; record where, "
            "set its status and release (sources/README.md)")
    touched = {a for ln in lines.values() if ln["status"] != "closed" for a in ln["anchors"]}
    unmined = [a for a in state["article_anchors"] + list(state["prompt_anchors"]) if a not in touched]
    if unmined:
        add("unmined", f"{len(unmined)} place(s)", "no line is anchored at: " + ", ".join(unmined[:18])
            + (" ..." if len(unmined) > 18 else "") + ("; coverage is not an obligation under sprawl pressure"
                if over else " (see `anchors`): explore only if consequential"))
    ready = {p["subject"] for p in out if p["take"]}
    seeds = [ln["id"] for ln in lines.values() if ln["status"] == "seed" and not ln["needs_owner"] and ln["id"] not in live]
    if not over and len(ready) < state["limits"]["min_open"] and seeds:
        add("thin", "the queue", f"only {len(ready)} takeable item(s): shape a seed into an open line "
            f"(e.g. {', '.join(seeds[:4])})")
    opened = [ln["id"] for ln in lines.values() if ln["status"] == "open" and not ln["needs_owner"]]
    if len(opened) > state["limits"]["max_open"]:
        add("crowded", "the open lines", f"{len(opened)} lines are open and limits.conf allows "
            f"{state['limits']['max_open']}: let some rest (or close them, with the reason) before opening more")
    for where, problem in state["strays"]:
        add("illegible", where, problem)
    for ln in lines.values():
        for problem in ln["problems"]:
            add("illegible", ln["path"], problem)
    for h in holds.values():
        for problem in h["problems"]:
            add("illegible", f"holds/{h['id']}", problem)
        if h["id"] not in lines and h["id"] not in HOLDABLE_EXTRAS and source_key(h["id"]) not in sources:
            add("illegible", f"holds/{h['id']}", "holds something that is neither a line nor "
                + "/".join(HOLDABLE_EXTRAS))
    for key, src in sources.items():
        for problem in src["problems"]:
            add("illegible", f"sources/{key}.md", problem)
    for entry in state["journal"]:
        for problem in entry["problems"]:
            add("illegible", f"journal/{entry['name']}", problem)
        if entry["length"] > 40:
            add("illegible", f"journal/{entry['name']}", f"{entry['length']} lines: a journal entry is 40 at most")
    for p in out:
        reports = scores.get(p["subject"], [])
        if p["take"] and reports:
            p["why"] += f" | reported utility: {len(reports)} assessment(s), range " + (
                f"{min(e['utility'] for e in reports)}–{max(e['utility'] for e in reports)}/3")
            example = sorted(reports, key=lambda e: e["name"])[-1]
            p["why"] += f"; example {example['utility']}/3: {example['utility_reason'][:90]} (journal/{example['name']})"
    return out


RANK = ["owner", "incident", "stranded", "resume", "sprawl", "consolidate", "settle", "reading", "open", "unsourced", "crowded", "thin", "unmined", "illegible"]


def ranked(pressures: list[dict]) -> list[dict]:
    return sorted(pressures, key=lambda p: (RANK.index(p["kind"]), p["priority"], p["subject"]))


def suggest(state: dict, pressures: list[dict], can: set[str] | None) -> str:
    """A random pick among the best eligible items. Identical participants reading the
    same state would otherwise all reach for the same line; the hold settles collisions,
    the draw makes them rare."""
    lines = state["lines"]

    def able(p: dict) -> bool:
        needs = set(lines[p["subject"]]["needs"]) if p["subject"] in lines else set()
        return can is None or needs <= can

    takeable = [p for p in pressures if p["take"] and able(p)]
    _, _, over = growth_state(state)
    urgent = [p for p in takeable if p["kind"] in ("stranded", "resume")]
    reducing = list({p["subject"]: p for p in reversed(takeable)
                     if p["kind"] in ("consolidate", "settle")}.values())
    if not urgent and reducing and (not over and random.random() < 0.33 or over and random.random() < 0.65):
        pick = random.choice(reducing)
        return f"{pick['subject']} ({pick['kind']}): {pick['why']}"
    if not takeable or (not urgent and not over and random.random() < 0.2):
        # Scatter explorers over actual candidates, not the same first few examples.
        live = {key for key, hold in state["holds"].items() if hold["live"]}
        limits = state["limits"]
        exploration = []
        if not over and sum(ln["status"] == "open" for ln in lines.values()) < limits["max_open"]:
            exploration += [f"shape seed {ln['id']} (claim it before editing)"
                            for ln in lines.values() if ln["status"] == "seed"
                            and not ln["needs_owner"] and ln["id"] not in live
                            and (can is None or set(ln["needs"]) <= can)]
        if can is None or can & {"web", "library", "shell"}:
            exploration += [f"locate source {key} (claim {SOURCE_HOLD_PREFIX}{key} before searching)"
                            for key in available_source_keys(state)]
        touched = {a for ln in lines.values() if ln["status"] != "closed" for a in ln["anchors"]}
        if not over:
            exploration += [f"read unmined anchor {a} and test a connection or question"
                            for a in state["article_anchors"] + list(state["prompt_anchors"])
                            if a not in touched]
        if exploration:
            return "explore: " + random.choice(exploration) + "; refresh and choose again if already done"
        if not takeable:
            return ("no eligible hold: consider a useful consolidation flag or rest; do not invent work"
                    if over else "no eligible hold: follow a worthwhile finding or question, or rest")
    stranded = [p for p in takeable if p["kind"] in ("stranded", "resume")]
    if stranded:
        pick = random.choice(stranded)
    else:
        best = min(p["priority"] for p in takeable)
        candidates = {p["subject"]: p for p in reversed(takeable) if p["priority"] == best}
        pick = random.choice(list(candidates.values()))
    return f"{pick['subject']} ({pick['kind']}): {pick['why']}"


# ---------------------------------------------------------------- the medium

def branch() -> str:
    name = git("rev-parse", "--abbrev-ref", "HEAD")[1]
    if name in ("", "HEAD"):
        sys.exit("this checkout is on no branch (detached HEAD), so it has no medium to read or push to: "
                 "`git switch <the branch you were started on>`, then run this again")
    return name


def fetch() -> bool:
    """True when origin was reached. A branch origin does not have yet counts as reached: a stale
    tracking ref for it (a harness can leave one in a fresh clone) is dropped, and the next push creates it."""
    b = branch()
    # Every branch, not only ours: holds on other branches are read too (across_branches). A fresh clone
    # in some harnesses has no other tracking refs, and reading only what is there would look like success.
    rc, _, err = git("fetch", "--quiet", "--prune", "origin", "+refs/heads/*:refs/remotes/origin/*")
    FULL_FETCH[:] = [rc == 0]
    if rc != 0:
        rc, _, err = git("fetch", "--quiet", "origin", b)
    if rc != 0 and "couldn't find remote ref" in err.lower():
        git("update-ref", "-d", f"refs/remotes/origin/{b}")
        return True
    return rc == 0


def integrate() -> tuple[bool, str]:
    """Bring in the medium's new commits. Never leaves a merge or rebase half done."""
    b = branch()
    if git("rev-parse", "--verify", "--quiet", f"origin/{b}")[0] != 0:
        return True, "no remote branch yet"
    behind = git("rev-list", "--count", f"HEAD..origin/{b}")[1]
    if behind in ("", "0"):
        return True, "up to date"
    # An uncommitted edit to a file the medium also changed would come back from the autostash as
    # conflict markers while rebase still exits 0, and a stop that had just landed would be lost in
    # them (lines/proving-the-rule/raced.md, first finding). Refuse before touching anything.
    mine = set(git("diff", "--name-only", "HEAD")[1].splitlines())
    theirs = set(git("diff", "--name-only", f"HEAD...origin/{b}")[1].splitlines())
    if mine & theirs:
        return False, ("you have uncommitted changes to " + ", ".join(sorted(mine & theirs))
                       + ", which the medium has changed too. Nothing was changed. "
                       "Commit them (or set them aside), then run this again")
    ahead = git("rev-list", "--count", f"origin/{b}..HEAD")[1]
    if ahead in ("", "0"):
        rc, _, err = git("merge", "--ff-only", "--quiet", f"origin/{b}")
        return rc == 0, "fast-forwarded" if rc == 0 else f"cannot fast-forward: {err[:200]}"
    rc, _, _ = git("rebase", "--autostash", "--quiet", f"origin/{b}")
    if rc == 0:
        if git("diff", "--name-only", "--diff-filter=U")[1]:   # never report success into conflict markers
            return False, "the rebase left conflict markers (see git status, git stash list). Resolve by hand, then sync again"
        return True, "rebased onto the medium"
    git("rebase", "--abort")
    rc, _, err = git("merge", "--no-edit", "--quiet", f"origin/{b}")
    if rc == 0:
        return True, "merged the medium"
    conflicted = git("diff", "--name-only", "--diff-filter=U")[1]
    git("merge", "--abort")
    return False, ("two writers met in: " + (conflicted.replace("\n", ", ") or err[:200])
                   + ". Nothing was changed. Resolve by hand (keep both sides of a line's passes), commit, sync again")


def push() -> bool:
    b = branch()
    return git("push", "--quiet", "-u", "origin", f"HEAD:{b}")[0] == 0


def base_range() -> str:
    b = branch()
    if git("rev-parse", "--verify", "--quiet", f"origin/{b}")[0] == 0:
        return f"origin/{b}..HEAD"
    # A branch not yet on origin: its first push carries everything since it left the default branch.
    # Returning "HEAD" here once let that first push go out unchecked.
    for ref in ("origin/HEAD", "origin/master", "origin/main"):
        rc, base, _ = git("merge-base", "HEAD", ref)
        if rc == 0 and base:
            return f"{base}..HEAD"
    return "HEAD"


def behind() -> int:
    out = git("rev-list", "--count", f"HEAD..origin/{branch()}")[1]
    return int(out) if out.isdigit() else 0


def is_agent(name: str, email: str) -> bool:
    return name.strip().lower() in AGENT_NAMES or bool(AGENT_EMAIL.search(f"{name} <{email}>"))


def owner_identity() -> tuple[str, str]:
    root = git("rev-list", "--max-parents=0", "HEAD")[1].splitlines()
    if not root:
        return "", ""
    return git("log", "-1", "--format=%an", root[-1])[1], git("log", "-1", "--format=%ae", root[-1])[1]


def ensure_identity() -> None:
    """A clone that would commit as an agent, or as nobody, commits as the owner instead
    (AGENTS.md, 'Identity'). A person's own identity is left alone."""
    name, email = git("config", "user.name")[1], git("config", "user.email")[1]
    if name and email and not is_agent(name, email):
        return
    owner_name, owner_email = owner_identity()
    if owner_name and owner_email:
        git("config", "user.name", owner_name)
        git("config", "user.email", owner_email)
        print(f"(this clone now commits as {owner_name}: AGENTS.md, 'Identity')")


def manifest_mismatches() -> list[tuple[str, str]]:
    out: list[tuple[str, str]] = []
    for folder in ("texts", "prompts", "sources"):
        manifest, listed = ROOT / folder / "manifest.tsv", set()
        for row in read(manifest).splitlines():
            cells = [c.strip() for c in row.split("\t")]
            if not row.strip() or row.startswith("#") or cells[0] == "path":
                continue
            if len(cells) < 2 or not re.match(r"^[0-9a-f]{40}$", cells[1]):
                out.append((f"{folder}/manifest.tsv", f"has a row that cannot be read (path, TAB, blob id): {row[:50]!r}"))
                continue
            listed.add(cells[0])
            rel = f"{folder}/{cells[0]}"
            if git("hash-object", "--", rel)[1] != cells[1]:  # git's own id for the file: line-ending conversion does not count
                out.append((rel, f"no longer matches {folder}/manifest.tsv (a text kept as received "
                                 "was changed: restore it, or record the new version in the manifest and say why)"))
        if not listed:
            out.append((f"{folder}/manifest.tsv", f"is missing or lists nothing, so {folder}/ is unchecked: restore it from git"))
        if folder != "sources":
            for path in sorted((ROOT / folder).rglob("*")):
                rel = path.relative_to(ROOT / folder).as_posix()
                if path.is_file() and rel not in listed and path.name not in ("README.md", "manifest.tsv", "images.md"):
                    out.append((f"{folder}/{rel}", f"is not listed in {folder}/manifest.tsv: add its row, or remove the file"))
    return out


def unpushed_problems() -> list[str]:
    """What must not reach the medium, looked for in the commits not yet pushed: this is the
    one moment at which it can still be undone."""
    out: list[str] = []
    b, rng = branch(), base_range()
    log = git("log", "--format=%h%x01%an%x01%ae%x01%cn%x01%ce%x01%B%x00", rng)[1] if rng != "HEAD" else ""
    for commit in log.split("\x00"):
        cells = commit.strip().split("\x01")
        if len(cells) < 6:
            continue
        h, an, ae, cn, ce, body = cells[:6]
        found = ATTRIBUTION.search(body)
        if found:
            out.append(f"commit {h} carries AI attribution in its message ({found.group(0).strip()!r}): reword it")
        if is_agent(an, ae) or is_agent(cn, ce):
            out.append(f"commit {h} is by {an} <{ae}>, an agent's identity: run `python3 tools/swarm.py identity`, "
                       f"then `git rebase {rng.split('..')[0]} --exec 'git commit --amend --no-edit --reset-author'`")
    if rng != "HEAD":
        rewritten = git("log", "--diff-filter=MD", "--name-only", "--format=", rng, "--", "journal/")[1]
        for name in sorted(set(rewritten.splitlines())):
            if name and not name.endswith("README.md") and git("cat-file", "-e", f"origin/{b}:{name}")[0] == 0:
                out.append(f"{name}: a journal entry already on the medium is rewritten or deleted. "
                           "Restore it and put the correction in a new entry")
        touched = set(git("diff", "--name-only", rng)[1].splitlines())
        out += [f"{path}: {why}" for path, why in manifest_mismatches() if path in touched]
    return out


def refresh() -> tuple[bool, str, list[str]]:
    """integrate(), and say which of the rule files changed under us."""
    before = git("rev-parse", "HEAD")[1]
    ok, how = integrate()
    after = git("rev-parse", "HEAD")[1]
    changed: list[str] = []
    if ok and before and after and before != after:
        changed = [f for f in git("diff", "--name-only", before, after, "--", *RULE_FILES)[1].splitlines() if f]
    return ok, how, changed


def announce(changed: list[str]) -> None:
    if changed:
        print("CHANGED on the medium since your last checkpoint: " + ", ".join(changed)
              + ". Read them again before going on." + (" The tool itself changed: run it again."
                                                        if "tools/swarm.py" in changed else ""))


def checkpoint(state: dict) -> list[str]:
    limits, holds = state["limits"], state["holds"]
    live = [h for h in holds.values() if h["live"]]
    kinds: dict[str, int] = {}
    for h in live:
        kinds[h["by"]] = kinds.get(h["by"], 0) + 1
    who = ", ".join(f"{n} {k}" for k, n in sorted(kinds.items())) or "nobody"
    out = [f"medium: origin/{branch()} | live holds: {len(live)} of {limits['max_live_holds']} ({who})"]
    done = today_count(state["journal"])
    out[0] += f" | contributions today: {done} of {limits['max_per_day']}"
    out[0] += (f" | holds read on {len(BRANCHES_READ)} branch(es)" if FULL_FETCH == [True] else
               f" | holds read on {len(BRANCHES_READ)} tracking ref(s) NOT fetched now, possibly stale")
    out[0] += f" | swarm launch target: {max(0, limits.get('swarm_size', 0))}"
    out[0] += f" | Claude launch ceiling: {max(0, min(limits.get('swarm_size', 0), limits.get('claude_swarm_size', 49)))}"
    if limits.get("missing"):
        out.append("limits.conf does not give " + ", ".join(limits["missing"]) + " as a plain number (e.g. 'max_live_holds: 6'): "
                   + ("read as a stop until it does." if limits["unreadable"] else "the default is used."))
    if limits["max_live_holds"] <= 0:
        out.append("STOP: limits.conf sets max_live_holds to 0. Finish the mark you are making, "
                   "write your journal entry, release, and leave. Take nothing new.")
    elif done >= limits["max_per_day"]:
        out.append("The day's allowance is spent (limits.conf, max_per_day): finish what you hold; take nothing new.")
    state_of_play, words = tempo(limits)
    if words:
        out.append(words)
    for hold_id, session in remembered().items():
        hold = holds.get(hold_id)
        if hold is None:
            out.append(f"YOUR HOLD on {hold_id} is gone: it was removed. Read the line again before adding to it.")
            remember(hold_id, None)  # said once
        elif hold["session"] != session:
            out.append(f"YOUR HOLD on {hold_id} was taken over by {hold['by']}. Stop working on it: what you "
                       "pushed is theirs to continue, and anything unpushed should wait for a hold of your own.")
        elif hold.get("released_on"):
            out.append(f"YOUR HOLD on {hold_id} was released on {hold['released_on']}: release it here too.")
        elif yields_to(hold):
            r = yields_to(hold)
            out.append(f"YOUR HOLD on {hold_id} is CONTESTED by {r['by']} (session {r['session']}) on {r['on']}, "
                       "whose hold was written first: it keeps the line. Release yours now and push nothing more on it.")
        elif hold.get("rivals"):
            out.append(f"YOUR HOLD on {hold_id} is CONTESTED by session "
                       + ", ".join(r["session"] for r in hold["rivals"])
                       + ": yours was written first and keeps the line; the other should release.")
        elif not hold["live"]:
            out.append(f"YOUR HOLD on {hold_id} lapsed at {hold['until']}: renew it before pushing more, or release it.")
    for path, why in manifest_mismatches():
        out.append(f"BROKEN: {path} {why}")
    return out


# ---------------------------------------------------------------- commands

def cmd_brief(args: argparse.Namespace) -> int:
    fetched = False
    if not args.offline:
        fetched = fetch()
        if fetched and not args.no_merge:
            ok, how, changed = refresh()
            if not ok:
                print(f"checkpoint: {how}")
            announce(changed)
    state = load_state()
    pressures = ranked(sense(state))
    can = set(items(" ".join(args.can))) if args.can else None
    print("\n".join(checkpoint(state)))
    if not fetched:
        print("(not fetched: this is your local copy, which may be stale; an unreachable origin grants nothing)")
    elif behind():
        print(f"(this checkout is {behind()} commit(s) behind the medium: what follows is stale until you sync)")
    owner = [p for p in pressures if p["kind"] == "owner"]
    if owner:
        print("\nNeeds the owner (only the owner can decide these; do not work around them):")
        for p in owner:
            print(f"  {p['subject']}: {p['why']}")
    print("\nSignificance and growth:\n  " + "\n  ".join(utility_overview(state)))
    print("\nPressures (what the state asks for, most pressing first):")
    shown = [p for p in pressures if p["kind"] != "owner"]
    for kind in RANK[1:]:
        group = [p for p in shown if p["kind"] == kind]
        for p in group[:8]:
            print(f"  [{kind}] {p['subject']}: {p['why']}")
        if len(group) > 8:
            print(f"  [{kind}] ... and {len(group) - 8} more (see `status`)")
    if not shown:
        print("  none sensed")
    live = [h for h in state["holds"].values() if h["live"]]
    if live:
        print("\nHeld now:")
        for h in live:
            print(f"  {h['id']} by {h['by']} until {h['until']}" + (f" (on {h['on']})" if h.get("on") else ""))
    limits = state["limits"]
    if limits["max_live_holds"] <= 0 or len(live) >= limits["max_live_holds"] or tempo(limits)[0] == "quiet" \
            or today_count(state["journal"]) >= limits["max_per_day"]:
        print("\nNo draw: limits.conf allows no new hold just now.")
    else:
        print("\nA draw for you: " + suggest(state, pressures, can))
        print("Before editing a line or starting standalone source discovery: python3 tools/swarm.py claim <id> --by <your kind> (source id: source--<key>)")
    return 0


def write_hold(hold_id: str, by: str, session: str, hours: float, since: str | None = None) -> Path:
    path = ROOT / "holds" / hold_id
    path.parent.mkdir(exist_ok=True)  # git keeps no empty folder: holds/ goes when its last file does
    t = now()
    until = t + dt.timedelta(hours=hours)
    quiet_at = load_limits().get("quiet_at")
    if quiet_at and t < quiet_at < until:
        until = quiet_at  # a hold never outlasts the quiet time
    path.write_text(
        f"by: {by}\nsession: {session}\nsince: {since or stamp(t)}\nuntil: {stamp(until)}\n", encoding="utf-8")
    return path


def lifetime(asked: float, limits: dict) -> tuple[float, str]:
    """How long a hold may last: --hours if given, else hold_hours, never above hold_hours and
    never so short that it is born lapsed (lines/raced-defects-unfixed.md)."""
    cap = limits["hold_hours"]
    hours = asked or cap
    if not (hours == hours and 0.1 <= hours <= cap):  # hours == hours is false for nan
        return 0, f"a hold lasts between 0.1 and {cap} hours (limits.conf, hold_hours); {hours} is not that"
    return hours, ""


def undo_hold_commit(hold_id: str, existed: bool) -> None:
    git("reset", "--quiet", "--soft", "HEAD~1")
    git("reset", "--quiet", "--", f"holds/{hold_id}")
    if existed:
        git("checkout", "--quiet", "--", f"holds/{hold_id}")
    else:
        try:
            (ROOT / "holds" / hold_id).unlink()
        except OSError:
            pass


def cmd_claim(args: argparse.Namespace) -> int:
    hold_id = args.id
    if not re.match(r"^[a-z0-9][a-z0-9-]*$", hold_id):
        print("not acquired: an id is lower-case letters, digits and hyphens")
        return 1
    session = "%06x" % random.getrandbits(24)
    ensure_identity()
    for attempt in range(6):
        if not fetch():
            print("not acquired: origin is unreachable, and a hold only exists once it is pushed")
            return 1
        ok, how, changed = refresh()
        announce(changed)
        if not ok:
            print(f"not acquired: {how}")
            return 1
        bad = unpushed_problems()
        if bad:
            print("not acquired: your unpushed commits must be put right first:\n  " + "\n  ".join(bad))
            return 1
        state = load_state()
        limits, holds, lines = state["limits"], state["holds"], state["lines"]
        live = [h for h in holds.values() if h["live"]]
        if tempo(limits)[0] == "quiet":
            print("not acquired: the swarm is quiet (limits.conf, quiet_at). Nothing new is taken until it is reopened")
            return 1
        if limits["max_live_holds"] <= 0:
            print("not acquired: STOP (limits.conf sets max_live_holds to 0)")
            return 1
        key = source_key(hold_id)
        if hold_id.startswith(SOURCE_HOLD_PREFIX):
            src = state["sources"].get(key)
            if not src or hold_id in lines:
                print(f"not acquired: {hold_id!r} must name an existing source, not a line")
                return 1
            if src["status"] != "named":
                print(f"not acquired: source {key} is no longer only named (status {src['status']})")
                return 1
            elsewhere = located_on_branch(key)
            if elsewhere:
                print(f"not acquired: source {key} is already located on {elsewhere}; "
                      "read or integrate that result instead of searching again")
                return 1
        elif hold_id not in lines and hold_id not in HOLDABLE_EXTRAS:
            print(f"not acquired: {hold_id!r} is neither a line, source--<key>, nor one of {', '.join(HOLDABLE_EXTRAS)}")
            return 1
        if hold_id in lines and lines[hold_id]["needs_owner"]:
            print(f"not acquired: {hold_id} waits on the owner: {lines[hold_id]['needs_owner']}")
            return 1
        if hold_id in lines and lines[hold_id]["status"] == "closed":
            print(f"not acquired: {hold_id} is closed (reopen it with a reason first)")
            return 1
        current = holds.get(hold_id)
        if current and current["live"]:
            print(f"not acquired: {hold_id} is held by {current['by']} until {current['until']}"
                  + (f", on {current['on']}" if current.get("on") else ""))
            return 1
        if (ROOT / "holds" / hold_id).is_dir():
            print(f"not acquired: holds/{hold_id} is a folder. Remove it (git rm -r holds/{hold_id}), sync, claim again")
            return 1
        if len(live) >= limits["max_live_holds"]:
            print(f"not acquired: {len(live)} live holds, and limits.conf allows {limits['max_live_holds']}")
            return 1
        if today_count(state["journal"]) >= limits["max_per_day"]:
            print(f"not acquired: the day's allowance of {limits['max_per_day']} contributions is spent (limits.conf)")
            return 1
        existed = (ROOT / "holds" / hold_id).exists()
        hours, why = lifetime(args.hours, limits)
        if why:
            print(f"not acquired: {why}")
            return 1
        write_hold(hold_id, args.by, session, hours)
        git("add", "--", f"holds/{hold_id}")
        verb = "take over" if existed else "hold"
        rc, _, err = git("commit", "--quiet", "-m", f"{verb}: {hold_id} ({args.by})", "--only", "--", f"holds/{hold_id}")
        if rc != 0:
            undo = git("reset", "--quiet", "--", f"holds/{hold_id}")
            print(f"not acquired: could not commit the hold: {err[:200]} {undo[2][:80]}")
            return 1
        if push():
            remember(hold_id, session)
            # A claim committed elsewhere but not yet pushed was invisible above. Look once more, after
            # a pause long enough for a sibling started in the same burst to push; a contest found now is
            # settled by precedence() at once, the same way on both sides (lines/medium-and-authority).
            time.sleep(1.5)
            fetch()
            mine = load_holds().get(hold_id, {})
            rival = yields_to(mine)
            if rival:
                git("rm", "--quiet", "--", f"holds/{hold_id}")
                git("commit", "--quiet", "-m", f"release: {hold_id} ({args.by}, contested: yields to "
                    f"{rival['session']} on {rival['on']})", "--only", "--", f"holds/{hold_id}")
                remember(hold_id, None)
                cmd_sync(argparse.Namespace(quiet=True))
                print(f"not acquired: {hold_id} was claimed at the same moment by {rival['by']} on "
                      f"{rival['on']}, whose hold was written first; yours has been released")
                return 1
            print(f"acquired {hold_id} | session {session} | until {mine.get('until') or load_holds()[hold_id]['until']}")
            if current and current.get("released_on"):
                print(f"its previous holder released it on {current['released_on']}, not yet merged here: "
                      "their marks may be there, so read that branch before you start")
            elif existed:
                print(f"this was a lapsed hold by {current['by']}: read what they pushed before you start, "
                      "and repeat nothing consequential that already landed")
            return 0
        undo_hold_commit(hold_id, existed)
        time.sleep(0.4 + random.random() * (attempt + 1))
    print(f"not acquired: {hold_id} (the medium kept moving; read `brief` again)")
    return 1


def own_hold(hold_id: str, session: str) -> tuple[dict | None, str]:
    hold = load_holds().get(hold_id)
    if hold is None:
        return None, f"there is no hold on {hold_id}"
    session = session or remembered().get(hold_id, "")
    if not session:
        return None, (f"the hold on {hold_id} was not taken by this clone; pass --session if it is yours. "
                      "(A lapsed hold is taken over with claim. To remove someone's live hold on purpose, "
                      "delete the file by hand and say why in the journal.)")
    if hold["session"] != session:
        return None, f"the hold on {hold_id} now belongs to another session ({hold['by']}): it was taken over"
    return hold, ""


def cmd_renew(args: argparse.Namespace) -> int:
    ensure_identity()
    fetch()
    ok, how, changed = refresh()
    announce(changed)
    if not ok:
        print(f"not renewed: {how}")
        return 1
    hold, why = own_hold(args.id, args.session)
    if hold is None:
        print(f"not renewed: {why}")
        return 1
    limits = load_limits()
    if tempo(limits)[0] == "quiet":
        print("not renewed: " + tempo(limits)[1])
        return 1
    if limits["max_live_holds"] <= 0:
        print("not renewed: STOP (limits.conf sets max_live_holds to 0): finish, journal, release")
        return 1
    hours, why = lifetime(args.hours, limits)
    if why:
        print(f"not renewed: {why}")
        return 1
    write_hold(args.id, hold["by"], hold["session"], hours, hold["since"])
    git("add", "--", f"holds/{args.id}")
    git("commit", "--quiet", "-m", f"renew: {args.id} ({hold['by']})", "--only", "--", f"holds/{args.id}")
    return cmd_sync(argparse.Namespace(quiet=True))


def cmd_release(args: argparse.Namespace) -> int:
    ensure_identity()
    fetch()
    ok, how, changed = refresh()
    announce(changed)
    if not ok:
        print(f"not released: {how}")
        return 1
    hold, why = own_hold(args.id, args.session)
    if hold is None:
        print(f"nothing to release: {why}")
        remember(args.id, None) if load_holds().get(args.id) is None else None
        return 0
    git("rm", "--quiet", "--", f"holds/{args.id}")
    git("commit", "--quiet", "-m", f"release: {args.id} ({hold['by']})", "--only", "--", f"holds/{args.id}")
    remember(args.id, None)  # before the sync, whose checkpoint would otherwise report our own release as a loss
    rc = cmd_sync(argparse.Namespace(quiet=True))
    if rc != 0:
        remember(args.id, hold["session"])
    return rc


def cmd_sync(args: argparse.Namespace) -> int:
    ensure_identity()
    for attempt in range(6):
        if not fetch() and git("rev-parse", "--verify", "--quiet", f"origin/{branch()}")[0] == 0:
            print("not pushed: origin is unreachable. Your commits are safe locally; sync again later")
            return 1
        ok, how, changed = refresh()
        announce(changed)
        if not ok:
            print(f"not pushed: {how}")
            return 2
        bad = unpushed_problems()
        if bad:
            print("not pushed: put these right first (nothing has left your clone):\n  " + "\n  ".join(bad))
            return 1
        if push():
            state = load_state()
            if not getattr(args, "quiet", False):
                print(f"synced ({how})")
            print("\n".join(checkpoint(state)))
            dirty = git("status", "--porcelain")[1]
            if dirty:
                print(f"note: {len(dirty.splitlines())} uncommitted change(s) stay local until you commit them")
            return 0
        time.sleep(0.4 + random.random() * (attempt + 1))
    print("not pushed: the medium kept moving; run sync again")
    return 1


def coverage(state: dict) -> tuple[dict[str, list[str]], list[str]]:
    by_anchor: dict[str, list[str]] = {a: [] for a in state["article_anchors"] + list(state["prompt_anchors"])}
    for ln in state["lines"].values():
        if ln["status"] == "closed":
            continue
        for a in ln["anchors"]:
            by_anchor.setdefault(a, []).append(ln["id"])
    return by_anchor, [a for a, ids in by_anchor.items() if not ids]


def cmd_anchors(args: argparse.Namespace) -> int:
    state = load_state()
    by_anchor, unmined = coverage(state)
    print("Places in the texts, and the lines anchored there. An anchor is a page (p45..p62) or a note")
    print("(fn-1..fn-22) of the article, or a paragraph of a verbatim prompt (setup#1..).\n")
    for a, ids in by_anchor.items():
        gloss = state["prompt_anchors"].get(a, "")
        print(f"  {a:<10} {', '.join(ids) if ids else '— unmined —':<60} {gloss}")
    print(f"\n{len(by_anchor) - len(unmined)} of {len(by_anchor)} places have a line; {len(unmined)} unmined.")
    return 0


def census_counts(state: dict) -> dict[str, int]:
    counts: dict[str, int] = {}
    for entry in state["journal"]:
        counts[entry["by"]] = counts.get(entry["by"], 0) + 1
    return counts


def cmd_census(args: argparse.Namespace) -> int:
    fetch()
    state = load_state()
    print("\n".join(checkpoint(state)))
    if behind():
        print(f"(this checkout is {behind()} commit(s) behind the medium: the counts are stale until you sync)")
    counts = census_counts(state)
    print("contributions recorded in journal/: "
          + (", ".join(f"{n} {k}" for k, n in sorted(counts.items())) or "none yet"))
    return 0


def render_status(state: dict) -> str:
    pressures = ranked(sense(state))
    lines, holds = state["lines"], state["holds"]
    by_anchor, unmined = coverage(state)
    out = ["# Status", "",
           f"Generated {stamp(now())} by `python3 tools/swarm.py status` from the files of this repository.",
           "A tracing of the state, not the state: never edit it, never commit it; regenerate it.", ""]
    if behind():
        out += [f"**This checkout is {behind()} commit(s) behind the medium: what follows is stale. Run `sync` first.**", ""]
    out += checkpoint(state)
    counts = census_counts(state)
    out += ["", "Contributions so far: " + (", ".join(f"{n} {k}" for k, n in sorted(counts.items())) or "none yet")
            + f". Places in the texts with a line: {len(by_anchor) - len(unmined)} of {len(by_anchor)}.", ""]
    owner = [p for p in pressures if p["kind"] == "owner"]
    out += ["## Needs the owner", ""] + ([f"- **{p['subject']}**: {p['why']}" for p in owner] or ["Nothing."]) + [""]
    out += ["## Significance and growth", ""] + utility_overview(state) + [""]
    out += ["## Pressures", ""]
    rest = [p for p in pressures if p["kind"] != "owner"]
    out += [f"- `{p['kind']}` **{p['subject']}**: {p['why']}" for p in rest] or ["None sensed."]
    out += ["", "## Lines", "", "| line | status | P | last mark | held by | title |", "|---|---|---|---|---|---|"]
    for ln in sorted(lines.values(), key=lambda x: (STATUSES.index(x["status"]) if x["status"] in STATUSES else 9,
                                                    x["priority"], x["id"])):
        last = ln["passes"][-1] if ln["passes"] else None
        mark = f"{last[0]} {last[2]} ({last[1]})" if last else "—"
        hold = holds.get(ln["id"])
        held = f"{hold['by']} until {hold['until']}" if hold and hold["live"] else ""
        out.append(f"| [{ln['id']}]({ln['path']}) | {ln['status']} | {ln['priority']} | {mark} | {held} | {ln['title']} |")
    out += ["", "## Recent journal", ""]
    for entry in sorted(state["journal"], key=lambda e: e["name"], reverse=True)[:15]:
        out.append(f"- {entry['date']} · {entry['by']} · {entry['line'] or '—'} · {entry['first']}")
    return "\n".join(out) + "\n"


def cmd_status(args: argparse.Namespace) -> int:
    if not args.offline:
        fetch()
    text = render_status(load_state())
    if args.stdout:
        print(text)
    else:
        (ROOT / "STATUS.md").write_text(text, encoding="utf-8")
        print("wrote STATUS.md (generated; git ignores it)")
    return 0


def cmd_check(args: argparse.Namespace) -> int:
    """The hard invariants, kept few. Everything else is a pressure, not a failure."""
    broken: list[str] = []
    # 1. The texts and the owner's words are byte-exact against their manifests.
    broken += [f"{path} {why}" for path, why in manifest_mismatches()]
    # 2-4. Nothing unpushed rewrites the journal, changes a text, or carries an agent's
    #      identity or attribution into git metadata.
    broken += unpushed_problems()
    # 5. A hold says who holds it.
    for h in load_holds(cross=False).values():
        if not h["by"] or h["by"] == "unknown" or not h["session"]:
            broken.append(f"holds/{h['id']} does not say who holds it (by, session)")
    for line in dict.fromkeys(broken):
        print(f"broken: {line}")
    print("check: " + ("ok" if not broken else f"{len(set(broken))} invariant(s) broken"))
    return 1 if broken else 0


def cmd_identity(args: argparse.Namespace) -> int:
    name, email = owner_identity()
    if not name:
        print("no root commit found")
        return 1
    git("config", "user.name", name)
    git("config", "user.email", email)
    print(f"this clone now commits as {name} <{email}> (the repository owner, as in its first commit)")
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd")
    p = sub.add_parser("brief")
    p.add_argument("--can", nargs="*", default=[], help="your capabilities, e.g. --can shell,web,french")
    p.add_argument("--offline", action="store_true")
    p.add_argument("--no-merge", action="store_true", help="fetch, but leave your checkout as it is")
    p.set_defaults(fn=cmd_brief)
    p = sub.add_parser("status")
    p.add_argument("--stdout", action="store_true")
    p.add_argument("--offline", action="store_true")
    p.set_defaults(fn=cmd_status)
    p = sub.add_parser("claim")
    p.add_argument("id")
    p.add_argument("--by", required=True, help="the kind of participant: claude-code, antigravity, chatgpt, codex, human ...")
    p.add_argument("--hours", type=float, default=0)
    p.set_defaults(fn=cmd_claim)
    for name, fn in (("renew", cmd_renew), ("release", cmd_release)):
        p = sub.add_parser(name)
        p.add_argument("id")
        p.add_argument("--session", default="", help="the session printed by claim")
        if name == "renew":
            p.add_argument("--hours", type=float, default=0)
        p.set_defaults(fn=fn)
    for name, fn in (("sync", cmd_sync), ("anchors", cmd_anchors), ("census", cmd_census),
                     ("check", cmd_check), ("identity", cmd_identity)):
        sub.add_parser(name).set_defaults(fn=fn)
    args = ap.parse_args()
    if not getattr(args, "fn", None):
        ap.print_help()
        return 0
    return args.fn(args)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BrokenPipeError:  # the reader (head, less) closed early
        try:
            sys.stdout.close()
        except OSError:
            pass
        sys.exit(0)
