#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""rocq-live: live Rocq proof sessions for any project, no per-project setup.

  rocq-live goto  FILE[:LINE] [--full]  proof state just before LINE (default:
                                      end of file). Starts a session if none
                                      runs; afterwards re-checks only from the
                                      first changed character: edit, goto,
                                      repeat. With a LINE, a finished Qed proof
                                      before it that was not edited is taken as
                                      Admitted (statement checked, tactics not);
                                      --full, or no LINE, checks every proof
  rocq-live run   FILE[:LINE] 'TAC.'  run sentences on the current state (or on
                                      the state before LINE), print the goals
                                      or the error (error: no change)
  rocq-live query FILE 'CMD.'         run, print, undo (Search, Check, Print, About)
  rocq-live try   FILE 'T1.' 'T2.' ..  run each tactic alone on the current state:
                                      which work, goals left; state unchanged
  rocq-live audit FILE [NAME..] [--allow AX,..]  Admitted/admit/axioms and
                                      Print Assumptions vs the allowed axioms
  rocq-live check FILE [--allow-stale] [--rebuild] [--all-errors]  coqc's verdict on the whole
                                      file (errors in coqc's format, exit 0 OK, 1
                                      error, 2 not checked), from the live session:
                                      re-checks only what an edit can affect (a
                                      Qed proof's tactics: that proof; a statement,
                                      definition or instance: the proofs that can
                                      see it). Refuses
                                      (exit 2) if a dependency's .vo is out of date.
                                      --all-errors: every failing proof, not just
                                      the first error
  rocq-live compile FILE [--deps-only] write .vo files with the project's build
                                      step: out-of-date dependencies, then FILE
  rocq-live impact FILE               what an edit to FILE breaks elsewhere: compile
                                      FILE and every file that requires it, in order
                                      and in parallel (ROCQ_LIVE_JOBS); a failure
                                      skips what depends on it
  rocq-live back  FILE [N]            undo the last N runs (default 1)
  rocq-live goals FILE                print the current goals
  rocq-live start FILE [LINE]         like goto, but always a fresh session
  rocq-live stop  FILE | --all        stop the session(s) at once
  rocq-live list                      running sessions: memory, idle time, limits
  rocq-live gc                        apply the limits now (also automatic)
  rocq-live stats [FILE] [--since 7d] what rocq-live did and saved (local log only)
  rocq-live info  FILE                project root, toolchain and load path found
  rocq-live mcp                       serve the same commands as MCP tools (stdio)

Each session is a background process holding one `coqtop -emacs` for one file,
so a step costs only that step: no prefix replays.

Project detection (from FILE's directory upwards, nearest marker wins):
  .rocq-live     optional config, `key value` lines (see below)
  dune-project   load path from `dune coq top` (also builds what FILE imports)
  _CoqProject    load path from its -Q/-R/-I/-arg lines (build it yourself)
Toolchain: the config's `switch`, else $ROCQ_LIVE_SWITCH, else the current opam
switch if it has coqtop, else coqtop on PATH.

.rocq-live keys (all optional; relative paths are from its directory):
  switch   rocq-9.0               opam switch (`path`: use coqtop on PATH)
  flags    -Q theories My         load path flags, verbatim
  loadpath scripts/loadpath.sh {file}   command printing the flags; may build
  build    make -j8 vos           command run before each start/goto
  compile  make {vo}              how `compile` builds one file ({file}: the .v,
                                  {vo}: its .vo relative to the root); default:
                                  coqc with the load path, or dune build
  axioms   classic functional_extensionality_dep   axioms `audit` accepts

Limits (machine-wide; environment, else ~/.config/rocq-live/config with the
same `key value` lines; read at each use, so changes apply to running sessions):
  max_mb       ROCQ_LIVE_MAX_MB       all sessions together (default: half the RAM)
  session_mb   ROCQ_LIVE_SESSION_MB   one session (default: max_mb)
  max_sessions ROCQ_LIVE_MAX_SESSIONS (default 16)
  grace        ROCQ_LIVE_GRACE        a session used this recently (seconds) is
                                      not stopped for max_sessions (default 600)
  idle         ROCQ_LIVE_IDLE         seconds before an idle session exits (1200;
                                      its recipe restores it on next use)
Over max_mb, or over max_sessions (sparing sessions used within `grace`), the
least recently used idle sessions are stopped (GC: when a session starts, after
each request, and every second while a step runs). A step that takes a session over session_mb, or the total over
max_mb with nothing idle left to stop, is interrupted, and that session's
coqtop is restarted to give the memory back. A busy session is never stopped.
Environment: ROCQ_LIVE_FLAGS (load path override), ROCQ_LIVE_SWITCH,
ROCQ_LIVE_TIMEOUT (seconds per step; default 600 for goto/start, 120 others),
ROCQ_LIVE_TRY_TIMEOUT (seconds per tactic in `try`; default 30),
ROCQ_LIVE_FAST=0 (goto checks every proof, as --full),
ROCQ_LIVE_REUSE=0 (after an edit inside a proof, re-run every proof after it),
ROCQ_LIVE_COMPACT=0 (run/try show every hypothesis, not only the changed ones),
ROCQ_LIVE_STATS=0 (record nothing in ~/.cache/rocq-live/stats.jsonl),
ROCQ_LIVE_DAEMON=0 (no background process: each call starts coqtop, rebuilds
the state from the recipe and exits; slower per call, nothing left running).

Recipes: each session saves its last goto line and the runs on top of it in
~/.cache/rocq-live/recipes (kept 7 days). A session stopped by gc, the idle
timeout or a reboot is restored from it on its next use (fast replay), and
says so; `stop` forgets it.

A running session watches the .vo/.vos files of the project modules it has
loaded; when one is rebuilt, the session restarts coqtop and replays the file
to the last goto line and the runs on top, and says so. `goto` also rebuilds
FILE's imports first (dune, or the `build`/`loadpath` command), so: edit an
imported file, then goto, and the new version is used.
"""
import hashlib
import json
import os
import re
import select
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time

VERSION = "0.4.0"        # the release workflow writes the tag's version here
SELF = os.path.abspath(__file__)
SESSION_DIR = "/tmp/rocq-live-%d" % os.getuid()   # short: AF_UNIX paths <= 104
TIMEOUT_GOTO = 600          # replaying a long prefix can be slow
TIMEOUT_STEP = 120          # a run/query longer than this is a hang to fix
USER_CONFIG = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"),
                           "rocq-live", "config")
LOG_KEEP = 86400            # the log of a dead session is kept this long (debugging)
RECIPE_DIR = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"),
                          "rocq-live", "recipes")
RECIPE_KEEP = 7 * 86400     # a session's recipe (line + runs) is kept this long
STATS_MAX = 20 << 20        # the stats log is rotated (one old copy kept) past this size
VIA = "cli"                 # "mcp" in the MCP server: recorded with each request
MAX_ERRORS = 50             # check --all-errors reports at most this many
WATCH_EVERY = 1.0           # seconds between memory checks while a step runs
GRACE_MEMORY = 5            # after an interrupt for memory, wait this long, then kill coqtop
GRACE_TIMEOUT = 20          # same, after an interrupt for time
ECHO_ENV = "ROCQ_LIVE_ECHO_ARGV"
ECHO_TAG = "ROCQ_LIVE_ARGV "


class Fail(Exception):
    """A user-facing error: the message is the whole report."""


# ---------------------------------------------------------------- limits

def phys_mb():
    try:
        return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / (1 << 20)
    except (ValueError, OSError, AttributeError):
        return 16384.0


def limits():
    """Machine-wide session limits, read at each use so a change applies to
    running sessions: environment, else ~/.config/rocq-live/config (`key
    value` lines), else defaults."""
    cfg = {}
    try:
        with open(USER_CONFIG, encoding="utf-8") as f:
            for raw in f:
                key, _, val = raw.split("#")[0].strip().partition(" ")
                if key:
                    cfg[key] = val.strip()
    except OSError:
        pass

    def get(env, key, default):
        val = os.environ.get(env) or cfg.get(key)
        try:
            return float(val) if val else default
        except ValueError:
            return default
    total = get("ROCQ_LIVE_MAX_MB", "max_mb", phys_mb() / 2)
    return {"max_mb": total,
            "session_mb": min(get("ROCQ_LIVE_SESSION_MB", "session_mb", total), total),
            "max_sessions": max(1, int(get("ROCQ_LIVE_MAX_SESSIONS", "max_sessions", 16))),
            "grace": get("ROCQ_LIVE_GRACE", "grace", 600),
            "idle": get("ROCQ_LIVE_IDLE", "idle", 1200)}


def fmt_mb(mb):
    return "%.1f GB" % (mb / 1024) if mb >= 1024 else "%d MB" % mb


def group_mb():
    """Resident memory (MB) of every process group, from one `ps` call. A
    session is a process group (its daemon and coqtop)."""
    r = subprocess.run(["ps", "-A", "-o", "pgid=,rss="], capture_output=True, text=True)
    out = {}
    for line in r.stdout.splitlines():
        parts = line.split()
        if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
            g = int(parts[0])
            out[g] = out.get(g, 0) + int(parts[1]) / 1024
    return out


# ---------------------------------------------------------------- sentences

def next_sentence_end(text, start):
    """End offset (just past the terminator) of the sentence starting at
    `start`, or None if there is no complete sentence there. A sentence ends
    at a `.` followed by white space or the end of text, outside comments
    (nested) and strings, and not part of `..`; a `{` or `}` that starts a
    sentence is a sentence of its own (focusing braces)."""
    i, n, depth, started = start, len(text), 0, False
    while i < n:
        c = text[i]
        if text.startswith("(*", i):
            depth += 1; i += 2; continue
        if depth:
            if text.startswith("*)", i):
                depth -= 1; i += 2
            else:
                i += 1
            continue
        if c == '"':                      # string; "" is an escaped quote
            i += 1
            while i < n and not (text[i] == '"' and not text.startswith('""', i)):
                i += 2 if text.startswith('""', i) else 1
            i += 1; started = True; continue
        if not started and c in "{}":
            return i + 1
        if c == "." and (i + 1 == n or text[i + 1].isspace()) and not (i > 0 and text[i - 1] == "."):
            return i + 1
        if not c.isspace():
            started = True
        i += 1
    return None


def strip_comments(text):
    out, depth, i = [], 0, 0
    while i < len(text):
        if text.startswith("(*", i):
            depth += 1; i += 2
        elif depth and text.startswith("*)", i):
            depth -= 1; i += 2
        else:
            if not depth:
                out.append(text[i])
            i += 1
    return "".join(out)


def only_blank(text):
    """True if `text` holds no sentence (only white space and comments)."""
    return re.sub(r"\s", "", strip_comments(text)) == ""


def complete(text):
    """True if `text` is a non-empty sequence of complete sentences."""
    off, n = 0, 0
    while True:
        end = next_sentence_end(text, off)
        if end is None:
            return n > 0 and only_blank(text[off:])
        off, n = end, n + 1


def line_offset(text, line):
    """Offset of the start of 1-based `line` (len(text) past the end)."""
    off = 0
    for _ in range(line - 1):
        nl = text.find("\n", off)
        if nl < 0:
            return len(text)
        off = nl + 1
    return off


# ------------------------------------------------------------ project setup

def find_up(start, names):
    """Nearest directory at or above `start` holding one of `names`; returns
    (dir, set of the names present there) or (None, set())."""
    d = start
    while True:
        here = {n for n in names if os.path.exists(os.path.join(d, n))}
        if here:
            return d, here
        parent = os.path.dirname(d)
        if parent == d:
            return None, set()
        d = parent


CONFIG_KEYS = ("switch", "flags", "loadpath", "build", "compile", "axioms")


def read_config(path):
    cfg = {}
    with open(path, encoding="utf-8") as f:
        for raw in f:
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            key, _, val = line.partition(" ")
            if key not in CONFIG_KEYS:
                raise Fail("rocq-live: %s: unknown key %r (%s)" % (path, key, ", ".join(CONFIG_KEYS)))
            cfg[key] = val.strip()
    return cfg


def parse_coqproject(path):
    """The load-path flags of a _CoqProject, with absolute directories."""
    base = os.path.dirname(path)
    with open(path, encoding="utf-8") as f:
        toks = shlex.split(f.read(), comments=True)
    flags, i = [], 0
    while i < len(toks):
        t = toks[i]
        if t in ("-Q", "-R") and i + 2 < len(toks):
            flags += [t, os.path.join(base, toks[i + 1]), toks[i + 2]]; i += 3
        elif t == "-I" and i + 1 < len(toks):
            flags += [t, os.path.join(base, toks[i + 1])]; i += 2
        elif t == "-arg" and i + 1 < len(toks):
            flags += shlex.split(toks[i + 1]); i += 2
        else:
            i += 1                        # file names and makefile options
    return flags


_env_cache = {}


def toolchain_env(switch, root):
    """(environment, description) for running coqtop. `switch` is an opam
    switch name, "path", or None (pick: current opam switch with coqtop, else
    PATH)."""
    key = (switch, root)
    if key in _env_cache:
        return _env_cache[key]
    env, desc = dict(os.environ), "coqtop on PATH"
    env.pop(ECHO_ENV, None)
    if switch != "path" and shutil.which("opam"):
        sw = switch
        if not sw:
            r = subprocess.run(["opam", "switch", "show"], cwd=root, capture_output=True, text=True)
            sw = r.stdout.strip() if r.returncode == 0 else None
        if sw:
            r = subprocess.run(["opam", "exec", "--switch=" + sw, "--", "env", "-0"],
                               cwd=root, capture_output=True)
            if r.returncode == 0:
                oenv = dict(kv.split("=", 1) for kv in r.stdout.decode().split("\0") if "=" in kv)
                if shutil.which("coqtop", path=oenv.get("PATH")) or switch:
                    env, desc = oenv, "opam switch " + sw
            elif switch:
                raise Fail("rocq-live: cannot select opam switch %s:\n%s" % (sw, r.stderr.decode()))
    elif switch and switch != "path":
        raise Fail("rocq-live: config asks for opam switch %s but opam is not installed" % switch)
    env.pop(ECHO_ENV, None)
    _env_cache[key] = (env, desc)
    return env, desc


def toplevel_cmd(env):
    if shutil.which("coqtop", path=env.get("PATH")):
        return ["coqtop"]
    if shutil.which("rocq", path=env.get("PATH")):
        return ["rocq", "repl"]
    raise Fail("rocq-live: no coqtop (or rocq) found; set `switch` in .rocq-live or ROCQ_LIVE_SWITCH")


def run_tool(cmd, cwd, env, what, shell=False):
    """Run a setup command; its stdout on success, Fail with its output else."""
    r = subprocess.run(cmd, cwd=cwd, env=env, shell=shell, capture_output=True, text=True)
    if r.returncode != 0:
        raise Fail("rocq-live: %s failed (exit %d); FILE's imports do not build:\n%s%s"
                   % (what, r.returncode, r.stdout[-6000:], r.stderr[-6000:]))
    return r.stdout


def toplevel_shim():
    """An executable that runs this script, for dune's --toplevel (dune needs
    a program; this file may not be executable, e.g. when installed from a
    wheel). Written once per Python and script location."""
    d = os.path.join(os.path.dirname(RECIPE_DIR), "bin")
    shim = os.path.join(d, "toplevel-" + hashlib.sha1((sys.executable + SELF).encode()).hexdigest()[:12])
    body = "#!/bin/sh\nexec %s -I %s \"$@\"\n" % (shlex.quote(sys.executable), shlex.quote(SELF))
    try:
        with open(shim) as f:
            if f.read() == body:
                return shim
    except OSError:
        pass
    os.makedirs(d, exist_ok=True)
    tmp = shim + ".tmp%d" % os.getpid()
    with open(tmp, "w") as f:
        f.write(body)
    os.chmod(tmp, 0o755)
    os.replace(tmp, shim)
    return shim


def dune_flags(path, env, proj_dir):
    """`dune rocq top` / `dune coq top` builds FILE's imports, then runs the
    toplevel with the right flags. The toplevel is this script, which only
    prints its argv as JSON (paths may contain spaces, so `--toplevel=echo`
    is not enough). Projects on `(using rocq ...)` need `dune rocq top`, those
    on `(using coq ...)` need `dune coq top` (removed in newer dune): try the
    one the project names first, then the other."""
    e = dict(env); e[ECHO_ENV] = "1"
    try:
        with open(os.path.join(proj_dir, "dune-project"), encoding="utf-8") as f:
            rocq_first = re.search(r"\(using\s+rocq\b", f.read()) is not None
    except OSError:
        rocq_first = False
    errors = []
    for sub in (["rocq", "coq"] if rocq_first else ["coq", "rocq"]):
        r = subprocess.run(["dune", sub, "top", "--display=quiet", "--toplevel=" + toplevel_shim(),
                            os.path.basename(path)], cwd=os.path.dirname(path), env=e,
                           capture_output=True, text=True)
        for line in r.stdout.splitlines():
            if line.startswith(ECHO_TAG):
                return json.loads(line[len(ECHO_TAG):])
        errors.append("$ dune %s top ... (exit %d)\n%s%s"
                      % (sub, r.returncode, r.stdout[-4000:], r.stderr[-4000:]))
        if "unknown command" not in r.stderr:
            break                     # a real error (a build failure): report it
    raise Fail("rocq-live: dune could not build FILE's imports or give its load path "
               "(is %s in a coq.theory/rocq.theory?):\n%s" % (path, "\n".join(errors)))


def resolve(path, build=True):
    """Project of `path`: {root, kind, flags, env, desc, cmd}. With `build`,
    first run whatever brings FILE's imports up to date."""
    start_dir = os.path.dirname(path)
    cfg_dir, _ = find_up(start_dir, [".rocq-live"])
    proj_dir, here = find_up(start_dir, ["dune-project", "dune-workspace", "_CoqProject"])
    root = cfg_dir or proj_dir or find_up(start_dir, [".git"])[0] or start_dir
    cfg = read_config(os.path.join(cfg_dir, ".rocq-live")) if cfg_dir else {}
    switch = cfg.get("switch") or os.environ.get("ROCQ_LIVE_SWITCH") or None
    env, desc = toolchain_env(switch, root)
    qfile = shlex.quote(path)
    if build and cfg.get("build"):
        run_tool(cfg["build"].replace("{file}", qfile), root, env, "build command", shell=True)
    if os.environ.get("ROCQ_LIVE_FLAGS"):
        kind, flags = "ROCQ_LIVE_FLAGS", shlex.split(os.environ["ROCQ_LIVE_FLAGS"])
    elif cfg.get("flags"):
        kind, flags = ".rocq-live flags", shlex.split(cfg["flags"])
    elif cfg.get("loadpath"):
        cmd = cfg["loadpath"].replace("{file}", qfile)
        kind, flags = ".rocq-live loadpath", shlex.split(run_tool(cmd, root, env, "loadpath command", shell=True))
    elif "dune-project" in here or "dune-workspace" in here:
        kind, flags = "dune", dune_flags(path, env, proj_dir)
    elif "_CoqProject" in here:
        kind, flags = "_CoqProject", parse_coqproject(os.path.join(proj_dir, "_CoqProject"))
    else:
        kind, flags = "none (no .rocq-live, dune-project or _CoqProject found)", []
    # relative directories in flags are relative to the root
    out, i = [], 0
    while i < len(flags):
        if flags[i] in ("-Q", "-R") and i + 2 < len(flags):
            out += [flags[i], os.path.join(root, flags[i + 1]), flags[i + 2]]; i += 3
        elif flags[i] == "-I" and i + 1 < len(flags):
            out += [flags[i], os.path.join(root, flags[i + 1])]; i += 2
        else:
            out.append(flags[i]); i += 1
    return {"root": root, "kind": kind, "flags": out, "env": env, "desc": desc,
            "cmd": toplevel_cmd(env), "axioms": cfg.get("axioms", "").split(),
            "compile": cfg.get("compile")}


# ------------------------------------------------------------ coqtop driver

PROMPT = re.compile(r"<prompt>[^\n]*? < (\d+) \|[^\n]*?</prompt>")
ERROR = re.compile(r"^Error:", re.M)


class StepTimeout(Exception):
    pass


class Coqtop:
    """One coqtop -emacs process. `send(text)` runs complete sentences and
    returns (output, error?); `state` is the state id after them."""

    def __init__(self, cmd, flags, cwd, env):
        self.p = subprocess.Popen(cmd + ["-q", "-emacs"] + flags, cwd=cwd, env=env,
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT)
        self.marks, self.timeout, self.buf = 0, TIMEOUT_GOTO, b""
        self.watch, self.why = None, None   # watch(): reason to interrupt, or None
        out, _ = self._read_until(lambda s: PROMPT.search(s), TIMEOUT_GOTO)
        self.state = int(PROMPT.findall(out)[-1])

    def _read_until(self, done, timeout):
        """Read until done(output); after `timeout` seconds interrupt the
        running command (SIGINT) and keep reading. (output, interrupted?)"""
        deadline, interrupted = time.time() + timeout, False
        next_watch = time.time() + WATCH_EVERY
        while True:
            s = self.buf.decode("utf-8", "replace")
            if done(s):
                self.buf = b""
                return s, interrupted
            if self.watch and not interrupted and time.time() >= next_watch:
                next_watch = time.time() + WATCH_EVERY
                why = self.watch()
                if why:                   # over a memory limit: stop the step now
                    self.why = why
                    os.kill(self.p.pid, signal.SIGINT)
                    interrupted, deadline = True, time.time() + GRACE_MEMORY
                    continue
            left = deadline - time.time()
            if left <= 0:
                if interrupted:
                    # SIGINT did not stop it (some Rocq versions do not poll
                    # for it in the VM): kill coqtop; the session restarts it
                    self.p.kill()
                    self.p.wait()
                    raise StepTimeout("coqtop did not respond to an interrupt; killed it")
                os.kill(self.p.pid, signal.SIGINT)
                interrupted, deadline = True, time.time() + GRACE_TIMEOUT
                continue
            r, _, _ = select.select([self.p.stdout], [], [], min(left, 1.0))
            if r:
                chunk = os.read(self.p.stdout.fileno(), 1 << 16)
                if not chunk:
                    raise StepTimeout("coqtop exited:\n" + s[-4000:])
                self.buf += chunk

    def send(self, text):
        """Run `text`, then a marker command whose message (a unique name)
        followed by a prompt means all is done."""
        self.marks += 1
        mark = "rocq_live_mark_%d" % self.marks
        self.p.stdin.write((text + "\nFail Check %s.\n" % mark).encode())
        self.p.stdin.flush()

        def done(s):
            k = s.find(mark + " was not found")
            return k >= 0 and PROMPT.search(s, k)
        out, interrupted = self._read_until(done, self.timeout)
        k = out.find(mark + " was not found")
        body = out[:out.rfind("The command has indeed failed", 0, k)]
        self.state = int(PROMPT.findall(out[k:])[-1])
        error = bool(ERROR.search(body)) or interrupted
        if interrupted and self.why:
            body += "\nrocq-live: step interrupted: %s" % self.why
        elif interrupted:
            body += "\nrocq-live: step interrupted after %d s (ROCQ_LIVE_TIMEOUT)" % self.timeout
        return clean(body), error

    def back_to(self, state):
        self.send("BackTo %d." % state)

    def close(self):
        try:
            self.p.stdin.close()
            self.p.wait(10)
        except Exception:
            self.p.kill()


def clean(out):
    """coqtop -emacs output without prompts and markup."""
    out = PROMPT.sub("", out)
    out = re.sub(r"</?infomsg>|</?warning>", "", out)
    return re.sub(r"\n{3,}", "\n\n", out).strip("\n")


# ------------------------------------------------- watching loaded modules

LOADED = re.compile(r"^\s+([A-Za-z0-9_'.]+)\s*$", re.M)
_hashes = {}


def bindings(flags, root):
    """(logical prefix, directory) of each -Q/-R inside the project: only
    project modules are watched (installed libraries do not change)."""
    out, i = [], 0
    while i < len(flags):
        if flags[i] in ("-Q", "-R") and i + 2 < len(flags):
            d = os.path.realpath(flags[i + 1])
            if d == root or d.startswith(root + os.sep):
                out.append((flags[i + 2], d))
            i += 3
        else:
            i += 1
    return out


def products(libraries_output, binds):
    """Build products coqtop may have loaded for the project modules listed
    by `Print Libraries`: the .vo and the .vos of each binding that fits."""
    paths = []
    for lib in LOADED.findall(libraries_output):
        for prefix, d in binds:
            if lib.startswith(prefix + "."):
                rel = lib[len(prefix) + 1:].replace(".", os.sep)
                paths += [os.path.join(d, rel + ".vo"), os.path.join(d, rel + ".vos")]
    return paths


def fingerprint(path):
    """Content hash (None if missing), recomputed only when mtime/size change:
    a product restored with the same content is not a change."""
    try:
        st = os.stat(path)
    except OSError:
        return None
    key = (st.st_mtime_ns, st.st_size)
    hit = _hashes.get(path)
    if hit is None or hit[0] != key:
        with open(path, "rb") as f:
            hit = (key, hashlib.sha1(f.read()).hexdigest())
        _hashes[path] = hit
    return hit[1]


# ------------------------------------------------- try / audit helpers

def error_text(out, limit=240):
    """The message of the first error in `out`, on one line."""
    k = out.find("Error:")
    if k < 0:
        lines = out.strip().splitlines()
        return lines[-1] if lines else "error"
    msg = " ".join(out[k + len("Error:"):].split())
    msg = msg.split(" rocq-live:")[0]
    return "Error: " + (msg[:limit] + " ..." if len(msg) > limit else msg)


def goal_count(out):
    """Goals left in a tactic's output: 0 when it closed them."""
    if re.search(r"No more (sub)?goals|This subproof is complete|All the remaining goals are on the shelf", out):
        return 0
    m = re.search(r"^(\d+) (?:focused )?goals?\b", out, re.M)
    return int(m.group(1)) if m else 1


def goals_word(n):
    return "no goals left" if n == 0 else "%d goal%s left" % (n, "" if n == 1 else "s")


def first_lines(text, n):
    lines = text.strip("\n").splitlines()
    return "\n".join(lines[:n] + (["... (%d more lines)" % (len(lines) - n)] if len(lines) > n else []))


def indent(text):
    return "\n".join("    " + l for l in text.splitlines())


def short_list(names, n=5):
    return ", ".join(names[:n]) + (" and %d more" % (len(names) - n) if len(names) > n else "")


_OPEN_OR_QUOTE = re.compile(r'\(\*|"')
_OPEN_OR_CLOSE = re.compile(r"\(\*|\*\)")
_NOT_NEWLINE = re.compile(r"[^\n]")


def blank_comments(text):
    """`text` with comments and strings replaced by spaces (newlines kept), so
    offsets and line numbers still match the file. Comments nest; inside a
    string, "" is an escaped quote."""
    out, pos, depth, n = [], 0, 0, len(text)
    while pos < n:
        if not depth:
            m = _OPEN_OR_QUOTE.search(text, pos)
            if not m:
                out.append(text[pos:])
                break
            out.append(text[pos:m.start()])
            if m.group() == "(*":
                out.append("  ")
                depth, pos = 1, m.end()
                continue
            j = m.end()                      # a string: find its closing quote
            while True:
                k = text.find('"', j)
                if k < 0:
                    k = n
                    break
                if text.startswith('""', k):
                    j = k + 2
                    continue
                break
            out.append(_NOT_NEWLINE.sub(" ", text[m.start():k + 1]))
            pos = k + 1
        else:
            m = _OPEN_OR_CLOSE.search(text, pos)
            if not m:
                out.append(_NOT_NEWLINE.sub(" ", text[pos:]))
                break
            out.append(_NOT_NEWLINE.sub(" ", text[pos:m.start()]) + "  ")
            depth += 1 if m.group() == "(*" else -1
            pos = m.end()
    return "".join(out)


ADMITS = re.compile(r"\b(Admitted\s*\.|admit\b|give_up\b|Admit\s+Obligations\b)")
AXIOM_DECL = re.compile(r"(?m)^\s*(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Polymorphic|Monomorphic)\s+)*"
                        r"(Axioms?|Conjectures?|Parameters?)\s+([A-Za-z_][\w']*)")
DECL = re.compile(r"^(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Program|Polymorphic|Monomorphic|Equations)\s+)*"
                  r"(Theorem|Lemma|Corollary|Proposition|Fact|Remark|Example|Property|Definition|"
                  r"Fixpoint|CoFixpoint|Instance)\s+([A-Za-z_][\w']*)")


def scan_admits(text):
    """(line, what) of each admit and axiom declaration in `text` (comments
    already blanked)."""
    found = []
    for m in ADMITS.finditer(text):
        found.append((text.count("\n", 0, m.start()) + 1, m.group(1).split()[0].rstrip(".")))
    for m in AXIOM_DECL.finditer(text):
        found.append((text.count("\n", 0, m.start(1)) + 1, "%s %s" % (m.group(1), m.group(2))))
    return sorted(found)


def declarations(text):
    """Qualified names of the file's declarations (modules tracked; nothing
    inside a Module Type, whose contents are not constants)."""
    names, stack, off = [], [], 0
    while True:
        end = next_sentence_end(text, off)
        if end is None:
            break
        sent = " ".join(text[off:end].split())
        off = end
        m = re.match(r"^(?:Module|Declare Module)\s+Type\s+([\w']+)", sent)
        if m:
            if ":=" not in sent:
                stack.append(("T", m.group(1)))
            continue
        m = re.match(r"^Module\s+(?:(?:Import|Export)\s+)?([\w']+)", sent)
        if m:
            if ":=" not in sent:
                stack.append(("M", m.group(1)))
            continue
        m = re.match(r"^Section\s+([\w']+)", sent)
        if m:
            stack.append(("S", m.group(1)))
            continue
        m = re.match(r"^End\s+([\w']+)\s*\.$", sent)
        if m:
            for k in range(len(stack) - 1, -1, -1):
                if stack[k][1] == m.group(1):
                    del stack[k:]
                    break
            continue
        m = DECL.match(sent)
        if m and not any(k == "T" for k, _ in stack):
            names.append(".".join([n for k, n in stack if k == "M"] + [m.group(2)]))
    return names


def axioms_of(out):
    """Axiom names in `Print Assumptions` output ([] when closed)."""
    axs, section = [], None
    for line in out.splitlines():
        if re.match(r"^[A-Z][A-Za-z ]+:$", line):
            section = line[:-1]
        elif section == "Axioms" and re.match(r"^\S+ :", line):
            axs.append(line.split(" :")[0])
    return axs


def axiom_allowed(ax, allowed):
    """`Print Assumptions` prints the shortest unambiguous name: match either
    way round on a qualified suffix."""
    return any(ax == a or ax.endswith("." + a) or a.endswith("." + ax) for a in allowed)


# ------------------------------------------------- fast replay

# A sentence that opens a proof: a theorem-like statement without `:=`.
STMT = re.compile(r"^(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Polymorphic|Monomorphic|Program)\s+)*"
                  r"(Theorem|Lemma|Corollary|Proposition|Fact|Remark|Example|Property|Goal|"
                  r"Definition|Fixpoint|CoFixpoint|Instance)\b")


def norm_sentence(blank, a, b):
    return " ".join(blank[a:b].split())


def fast_enabled():
    return os.environ.get("ROCQ_LIVE_FAST", "1") != "0"


def section_depths(blank):
    """{sentence start offset: number of open Sections there}."""
    depths, stack, off = {}, [], 0
    while True:
        end = next_sentence_end(blank, off)
        if end is None:
            return depths
        t = norm_sentence(blank, off, end)
        depths[off] = sum(1 for k in stack if k == "S")
        m = re.match(r"^(Section|Module(?:\s+Type)?)\s+(?:(?:Import|Export)\s+)?([\w']+)", t)
        if m and ":=" not in t:
            stack.append("S" if m.group(1) == "Section" else "M")
        elif re.match(r"^End\s+[\w']+\s*\.$", t) and stack:
            stack.pop()
        off = end


def proof_extent(text, blank, off, end):
    """If the sentence text[off:end] opens an opaque proof (a theorem-like
    statement without `:=`, closed by Qed or Admitted, not Program, not
    `Proof term.`, no nested proof), its parts: {"using": offsets of a `Proof
    using` sentence or None, "body": where the tactics start, "sents":
    offsets of the tactic sentences, "last": start of the Qed/Admitted
    sentence, "stop": its end, "section_ok": True unless Admitted would
    generalize it differently over Section variables}, else None."""
    t = norm_sentence(blank, off, end)
    m = STMT.match(t)
    if not m or ":=" in t or re.search(r"\bProgram\b", t.split(m.group(1))[0]):
        return None
    using, body, sents, p, first = None, end, [], end, True
    while True:
        e2 = next_sentence_end(text, p)
        if e2 is None:
            return None
        u = norm_sentence(blank, p, e2)
        if not u:
            p = e2
            continue
        if first and u.startswith("Proof"):
            if re.match(r"^Proof\s+using\b", u):
                using = (p, e2)
            elif not re.match(r"^Proof\s*(with\b.*)?\.$", u):
                return None              # `Proof term.` ends the proof by itself
            body = e2
        elif re.match(r"^(Qed|Admitted)\s*\.$", u):
            return {"using": using, "body": body, "sents": sents, "last": p, "stop": e2,
                    "using_in_stmt": "using" in t.split(m.group(1))[0]}
        elif re.match(r"^(Defined|Abort|Save)\b", u) or (STMT.match(u) and ":=" not in u):
            return None                  # transparent, aborted, or a nested proof
        else:
            sents.append((p, e2))
        first = False
        p = e2


def skippable(new, blank, off, end, target, edit, depths):
    """If the sentence new[off:end] opens a finished opaque proof that ends
    before `target`, does not overlap the edited region `edit` and can be
    replaced by Admitted without changing what follows, return (offsets of a
    `Proof using` sentence or None, end of the proof's Qed/Admitted)."""
    ext = proof_extent(new, blank, off, end)
    if not ext:
        return None
    stop = ext["stop"]
    if stop > target or (off < edit[1] and stop > edit[0]):
        return None
    if depths.get(off, 0) and not (ext["using"] or ext["using_in_stmt"]):
        return None    # in a Section, Admitted would generalize differently without `Proof using`
    return ext["using"], stop


def cosmetic_pairs(old, new, start, old_end, new_end):
    """If `old` and `new` hold the same sentences from the boundary `start`
    on, differing only in the comments and white space before them, and the
    texts agree again from old_end/new_end, {old sentence end: new sentence
    end} for the sentences up to there; else None."""
    delta = len(new) - len(old)
    po = pn = start
    pairs = {}
    while not (po >= old_end and pn >= new_end and pn - po == delta):
        eo, en = next_sentence_end(old, po), next_sentence_end(new, pn)
        if eo is None or en is None:
            if eo is None and en is None and only_blank(old[po:]) and only_blank(new[pn:]):
                return pairs
            return None
        if sentence_core(old[po:eo]) != sentence_core(new[pn:en]):
            return None
        pairs[eo] = en
        po, pn = eo, en
    return pairs


def statement_before(blank, bounds):
    """(start, end) of the nearest theorem-like statement before the
    boundary bounds[-1], walking back over the sentences between `bounds`;
    None if a sentence that closes a proof or opens/closes a block comes
    first. (A caller checks that the boundary is inside that proof.)"""
    for i in range(len(bounds) - 1, max(0, len(bounds) - 5000), -1):
        a, b = bounds[i - 1], bounds[i]
        u = norm_sentence(blank, a, b)
        if STMT.match(u) and ":=" not in u:
            return a, b
        if re.match(r"^(Qed|Admitted|Defined|Abort|Save|End|Section|Module)\b", u):
            return None
    return None


def parse_item(text, blank, off):
    """The top-level item starting at the boundary `off`: a proof (from its
    statement to its Qed/Admitted/Defined/Abort/Save) or a single sentence.
    {"end", "head": the first sentence normalized, "proof": bool, "closer",
    "sents": tactic sentences of a proof, "ext": proof_extent or None};
    None if the text ends inside it."""
    e = next_sentence_end(text, off)
    if e is None:
        return None
    u = norm_sentence(blank, off, e)
    if not (STMT.match(u) and ":=" not in u):
        return {"start": off, "end": e, "head": u, "proof": False}
    p, sents = e, []
    while True:
        e2 = next_sentence_end(text, p)
        if e2 is None:
            return None
        w = norm_sentence(blank, p, e2)
        m = re.match(r"^(Qed|Admitted|Defined|Abort|Save)\b", w)
        if m:
            return {"start": off, "end": e2, "head": u, "proof": True, "closer": m.group(1),
                    "sents": sents, "ext": proof_extent(text, blank, off, e)}
        if STMT.match(w) and ":=" not in w:
            return None                                  # a nested proof
        if w and not (not sents and re.match(r"^Proof\b", w)):
            sents.append((p, e2))
        p = e2


def instance_class(head):
    """C in `Instance name binders : C args ...`, or None."""
    m = re.match(r"^(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Polymorphic|Monomorphic)\s+)*"
                 r"Instance\s+[^\W\d][\w']*", head)
    if not m:
        return None
    depth, i = 0, m.end()
    while i < len(head):
        c = head[i]
        if c in "([{":
            depth += 1
        elif c in ")]}":
            depth -= 1
        elif depth == 0 and head.startswith(":=", i):
            return None
        elif depth == 0 and c == ":":
            t = IDENT.search(head, i + 1)
            return t.group() if t else None
        i += 1
    return None


CLASS_DECL = re.compile(r"^(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Polymorphic|Monomorphic|Cumulative|"
                        r"NonCumulative)\s+)*(Class|Existing\s+Class)\s+([^\W\d][\w']*)")


def class_members(head):
    """Names a Class sentence declares besides the class: its methods and
    constructor (a single-method class `Class C := m : T.` too)."""
    out = set(re.findall(r"(?:\{|;)\s*([^\W\d][\w']*)\s*(?::>|::|:)", head))
    out |= set(re.findall(r":=\s*([^\W\d][\w']*)\s*(?::(?!=)|\{)", head))
    return out


def edit_effect(old, new, d, k, bounds):
    """What the change [d, len - k) means for the proofs after it. Returns
    (start, old end, new end, names, walk start) of the edited top-level
    items, or
    None if anything after the change may be affected:
    - an edit to the tactics of one self-contained opaque proof: no names
      (what follows a Qed sees only its statement);
    - otherwise the names the edited items declare (old and new): proofs
      (statement changed, transparent, or in a Section without `Proof
      using`), definitions, Fixpoints, Ltacs. Queries declare nothing.
    - an Instance: also its class and the class's methods, provided the class
      is declared in this file; the walk then starts at the class, since
      code before the edit (generic in the class) can reach the instance
      through typeclass search.
    Anything else (Inductive, Notation, Hint, Section, Module, Program, ...)
    gives None. `bounds`: sentence boundaries up to d (from 0)."""
    bo, bn = blank_comments(old), blank_comments(new)
    bounds = list(bounds)
    p = bounds[-1]
    while True:                      # the rest of the boundaries up to d
        e = next_sentence_end(old, p)
        if e is None or e > d:
            break
        bounds.append(e)
        p = e
    start = bounds[-1]               # the item holding d: a sentence, or a proof around it
    st = statement_before(bo, bounds)
    if st:
        it = parse_item(old, bo, st[0])
        if it and it["proof"] and it["end"] > start:
            start = st[0]
    delta, oe, ne = len(new) - len(old), len(old) - k, len(new) - k
    olds, news, po, pn = [], [], start, start
    while po < oe or pn < ne or pn - po != delta:
        if po < oe or pn - po > delta:
            it = parse_item(old, bo, po)
            if it is None:
                if only_blank(old[po:]) and po < len(old):
                    po = len(old)
                    continue
                return None
            olds.append(it)
            po = it["end"]
        else:
            it = parse_item(new, bn, pn)
            if it is None:
                if only_blank(new[pn:]) and pn < len(new):
                    pn = len(new)
                    continue
                return None
            news.append(it)
            pn = it["end"]
    # items that did not change at the end (an insertion before them)
    while olds and news and news[-1]["start"] - olds[-1]["start"] == delta and \
            sentence_core(old[olds[-1]["start"]:olds[-1]["end"]]) == \
            sentence_core(new[news[-1]["start"]:news[-1]["end"]]):
        po, pn = olds[-1]["start"], news[-1]["start"]
        olds.pop()
        news.pop()
    if len(olds) == 1 and len(news) == 1 and olds[0]["proof"] and news[0]["proof"]:
        xo, xn = olds[0]["ext"], news[0]["ext"]
        if xo and xn and self_contained(bo, xo["sents"]) and self_contained(bn, xn["sents"]) \
                and old[start:xo["body"]] == new[start:xn["body"]] \
                and (xo["using"] or xo["using_in_stmt"] or not section_depths(bo).get(start, 0)):
            return start, po, pn, set(), pn              # tactics only
    names, walk = set(), pn
    for it, text, blank in [(i, old, bo) for i in olds] + [(i, new, bn) for i in news]:
        head = it["head"]
        if it["proof"]:
            if not self_contained(blank, it["sents"]) or it["closer"] == "Save":
                return None
            if it["closer"] == "Abort":
                continue
        else:
            v = head
            while WRAPPER.match(v):
                v = WRAPPER.sub("", v, count=1)
            if QUERY.match(v):
                continue
            head = v
        kind, name = declared(head)
        if kind == "Goal":
            continue
        if not name or not kind or (it["proof"] is False and kind not in (
                "Definition", "Fixpoint", "CoFixpoint", "Let", "Example", "Ltac", "Instance") and
                ":=" not in head):
            return None
        if kind in ("Fixpoint", "CoFixpoint"):
            names |= set(re.findall(r"\bwith\s+([^\W\d][\w']*)", head))   # mutual ones
        elif re.search(r"\bwith\b", head) and it["proof"]:
            return None
        names.add(name)
        if kind == "Instance":
            cls = instance_class(head)
            decl = None
            for i in range(1, len(bounds)):
                if bounds[i] > start:
                    break
                m = CLASS_DECL.match(norm_sentence(bo, bounds[i - 1], bounds[i]))
                if m and m.group(2) == cls:
                    decl = (bounds[i - 1], bounds[i], norm_sentence(bo, bounds[i - 1], bounds[i]))
            if decl is None:
                return None                              # a class from elsewhere
            names |= {cls} | class_members(decl[2])
            walk = min(walk, decl[1])
    return start, po, pn, names, walk


NAMED = re.compile(r"^(?:#\[[^\]]*\]\s*)?(?:(?:Local|Global|Polymorphic|Monomorphic|Cumulative|"
                   r"NonCumulative)\s+)*(Theorem|Lemma|Corollary|Proposition|Fact|Remark|Example|"
                   r"Property|Definition|Fixpoint|CoFixpoint|Let|Instance|Ltac|Goal)\b\s*([^\W\d][\w']*)?")
IDENT = re.compile(r"[^\W\d][\w']*")
# a sentence that changes nothing later proofs could see
QUERY = re.compile(r"^(Check|Print|About|Locate|Search\w*|Compute|Eval|Fail|Succeed|Show|Test|Pwd)\b")
WRAPPER = re.compile(r"^(?:Time|Timeout\s+\d+|Redirect\s+\S+|Instructions|Profile)\s+")
# tactics that search the whole environment for lemmas, so they can use one
# without naming it (CoqHammer, Tactician)
SEARCHING_TACTICS = {"hammer", "hhammer", "predict", "synth", "suggest"}


def declared(head):
    """(keyword, name) of a sentence that declares a name, or (None, None)."""
    m = NAMED.match(head)
    if not m:
        return None, None
    return m.group(1), (None if m.group(1) == "Goal" else m.group(2))


def affected_proofs(text, blank, start, names, skip=None):
    """After a change to what `names` denote, walk the rest of `text` from
    `start` without running it: the (start, end) of each proof that may
    check differently, or None if the change reaches something later proofs
    can use without naming it (a Hint, an Instance, a Notation, Arguments, a
    module command, ...). A proof that mentions an affected name is
    affected; a definition, a transparent proof, a proof statement, an Ltac
    or (in a Section without `Proof using`) any proof that mentions one
    adds its own name. An Instance of a class among `names` adds its name
    too: typeclass search for that class is already accounted for. `skip`:
    (start, end) of text not to walk (the edited items)."""
    names, affected, depths, off = set(names), set(), section_depths(blank), start

    def mentions(a, b):
        return any(t in names for t in IDENT.findall(blank[a:b]))
    while True:
        if skip and skip[0] <= off < skip[1]:
            off = skip[1]
        end = next_sentence_end(text, off)
        if end is None:
            return affected
        u = norm_sentence(blank, off, end)
        if not u:
            off = end
            continue
        if STMT.match(u) and ":=" not in u:               # a proof: find where it ends
            p, closer = end, None
            while True:
                e2 = next_sentence_end(text, p)
                if e2 is None:
                    return affected                       # unfinished: nothing after it
                w = norm_sentence(blank, p, e2)
                if re.match(r"^(Qed|Admitted|Defined|Abort|Save)\b", w):
                    closer = w.split()[0].rstrip(".")
                    break
                if STMT.match(w) and ":=" not in w:
                    return None                           # a nested proof: give up
                p = e2
            stop = e2
            tokens = set(IDENT.findall(blank[off:stop]))
            if tokens & names or tokens & SEARCHING_TACTICS:
                affected.add((off, stop))
                ext = proof_extent(text, blank, off, end)
                if ext and not self_contained(blank, ext["sents"]):
                    return None
                if closer == "Save" or re.search(r"\bwith\b", u):
                    return None
                auto_vars = depths.get(off, 0) and not (ext and (ext["using"] or ext["using_in_stmt"]))
                if closer != "Abort" and (mentions(off, end) or not ext or auto_vars):
                    kind, name = declared(u)
                    if (kind == "Instance" and instance_class(u) not in names) or (kind != "Goal" and not name):
                        return None
                    if name:
                        names.add(name)
            off = stop
            continue
        if mentions(off, end):                            # any other sentence
            v = u
            while WRAPPER.match(v):
                v = WRAPPER.sub("", v, count=1)
            kind, name = declared(v)
            if QUERY.match(v):
                pass
            elif name and kind != "Goal" and not re.search(r"\bwith\b", v) and (
                    kind != "Instance" or instance_class(v) in names):
                names.add(name)
            else:
                return None
        off = end


# Commands that may appear inside a proof without changing anything after it.
# Any other capitalized sentence in a proof (Set, Hint, Ltac, Opaque, ...)
# could, so a proof containing one is not treated as self-contained.
HARMLESS_IN_PROOF = re.compile(
    r"^(Show|Check|Search\w*|About|Print|Locate|Compute|Eval|Fail|Succeed|Time|Timeout|Info|"
    r"Guarded|Focus|Unfocus|Unshelve|Optimize|Undo|Restart)\b")


def self_contained(blank, sents):
    """True if a proof's tactic sentences cannot affect anything after its
    Qed: no vernacular command that changes global state, and no `abstract`
    (it declares constants that later sentences could name)."""
    for a, b in sents:
        u = norm_sentence(blank, a, b)
        if re.search(r"\b(abstract|transparent_abstract)\b", u):
            return False
        if re.match(r"^[A-Z#]", u) and not HARMLESS_IN_PROOF.match(u):
            return False
    return True


def sentence_core(chunk):
    """A sentence as sent (leading blanks and comments included) without its
    leading blanks and comments."""
    blank = blank_comments(chunk)
    return chunk[len(blank) - len(blank.lstrip()):]


# ------------------------------------------------- check (coqc's verdict)

def count_sentences(text):
    n, off = 0, 0
    while True:
        end = next_sentence_end(text, off)
        if end is None:
            return n
        if not only_blank(text[off:end]):
            n += 1
        off = end


def block_kinds(blank):
    """{name: "section" | "module" | "module type"} of the blocks opened in
    the file (comments blanked), for coqc's message about unclosed ones."""
    kinds, off = {}, 0
    while True:
        end = next_sentence_end(blank, off)
        if end is None:
            return kinds
        t = norm_sentence(blank, off, end)
        m = re.match(r"^(Section|Module\s+Type|Module)\s+(?:(?:Import|Export)\s+)?([\w']+)", t)
        if m and ":=" not in t:
            kinds[m.group(2)] = ("section" if m.group(1) == "Section" else
                                 "module" if m.group(1) == "Module" else "module type")
        off = end


LOCATION = re.compile(r"Toplevel input, characters (\d+)-(\d+):")


def coqc_diag(text, error, name):
    """The error of a failed sentence as coqc prints it: `File "NAME", line
    L, characters A-B:` then the message. coqtop reports byte offsets into the
    sentence as it was sent (one sentence per send); coqc counts bytes from
    the start of the line where the error starts. An error without a location
    gets the sentence's own, as in coqc."""
    start, sent, out = error
    k = ERROR.search(out)
    msg = out[k.start():].rstrip() if k else out.strip()
    locs = list(LOCATION.finditer(out, 0, k.start() if k else len(out)))
    if locs:
        a, b = int(locs[-1].group(1)), int(locs[-1].group(2))
    else:
        blank = blank_comments(sent)
        lead = len(blank) - len(blank.lstrip())
        a, b = len(sent[:lead].encode()), len(sent.encode())
    data = text.encode()
    base = len(text[:start].encode())
    A, B = min(base + a, len(data)), min(base + b, len(data))
    bol = data.rfind(b"\n", 0, A) + 1
    return 'File "%s", line %d, characters %d-%d:\n%s' % (
        name, data.count(b"\n", 0, A) + 1, A - bol, B - bol, msg)


def coqc_name(file):
    """The file name as coqc prints it: as given, with ./ before a relative
    path that does not start with ./ or ../ (OCaml's Filename.is_implicit)."""
    explicit = os.path.isabs(file) or file.startswith(("./", "../"))
    return file if explicit else "./" + file


# ------------------------------------------------- out-of-date dependencies

DEP_DIR = os.path.join(os.path.dirname(RECIPE_DIR), "deps")
REQUIRES = re.compile(r"\b(?:From|Require|Load|Declare)\b[\s\S]*?\.(?=\s|$)")


def dep_tool(env):
    if shutil.which("coqdep", path=env.get("PATH")):
        return ["coqdep"]
    if shutil.which("rocq", path=env.get("PATH")):
        return ["rocq", "dep"]
    return None


def project_sources(proj):
    """The .v files under the project's own -Q/-R directories."""
    seen, out = set(), []
    for _, d in bindings(proj["flags"], os.path.realpath(proj["root"])):
        for dp, dns, fns in os.walk(d):
            dns[:] = sorted(n for n in dns if not n.startswith(".") and n != "_build")
            for fn in sorted(fns):
                if fn.endswith(".v"):
                    p = os.path.realpath(os.path.join(dp, fn))
                    if p not in seen:
                        seen.add(p)
                        out.append(p)
    return out


def dep_graph(proj, path):
    """{.v: [.v it requires]} over the project's own files, from coqdep.
    Cached on disk; coqdep re-runs only for files whose Require lines
    changed, or for all when files were added or removed (that can change
    how names resolve). None if there is no coqdep."""
    tool = dep_tool(proj["env"])
    if not tool:
        return None
    files = project_sources(proj)
    if path not in files:
        files.append(path)
    lp, i, fl = [], 0, proj["flags"]
    while i < len(fl):
        if fl[i] in ("-Q", "-R") and i + 2 < len(fl):
            lp += fl[i:i + 3]; i += 3
        elif fl[i] == "-I" and i + 1 < len(fl):
            lp += fl[i:i + 2]; i += 2
        else:
            i += 1
    key = hashlib.sha1(json.dumps([proj["root"], lp, tool]).encode()).hexdigest()[:12]
    cache_file = os.path.join(DEP_DIR, key + ".json")
    try:
        with open(cache_file) as f:
            cache = json.load(f)
    except (OSError, ValueError):
        cache = {}
    new, todo = {}, []
    for f in files:
        st = os.stat(f)
        stamp = [st.st_mtime_ns, st.st_size]
        old = cache.get(f)
        if old and old[:2] == stamp:
            new[f] = old
            continue
        with open(f, encoding="utf-8", errors="replace") as h:
            req = hashlib.sha1("\n".join(REQUIRES.findall(h.read())).encode()).hexdigest()
        if old and old[2] == req:
            new[f] = stamp + [req, old[3]]
        else:
            new[f] = stamp + [req, None]
            todo.append(f)
    if set(cache) != set(files):
        todo = files                  # a file came or went: names may resolve differently
    found = {}
    for k in range(0, len(todo), 400):
        r = subprocess.run(tool + lp + todo[k:k + 400], cwd=proj["root"], env=proj["env"],
                           capture_output=True, text=True)
        for line in r.stdout.splitlines():
            lhs, sep, rhs = line.partition(": ")
            toks = rhs.split()
            if not sep or ".required_vo" not in lhs or not toks:
                continue
            src = os.path.realpath(os.path.join(proj["root"], toks[0]))
            found[src] = [os.path.realpath(os.path.join(proj["root"], t))[:-1]
                          for t in toks[1:] if t.endswith(".vo")]
    known = set(files)
    for f in todo:
        new[f][3] = [d for d in found.get(f, []) if d in known]
    if new != cache:
        try:
            os.makedirs(DEP_DIR, exist_ok=True)
            tmp = cache_file + ".tmp%d" % os.getpid()
            with open(tmp, "w") as h:
                json.dump(new, h)
            os.replace(tmp, cache_file)
        except OSError:
            pass
    return {f: v[3] or [] for f, v in new.items()}


def built_ns(v):
    """When the .v's library was last built (its .vo, or a non-empty .vos
    from a `make vos` build, whichever is newer), or None."""
    t = None
    for ext in (".vo", ".vos"):
        try:
            st = os.stat(v[:-2] + ext)
        except OSError:
            continue
        if ext == ".vo" or st.st_size:
            t = max(t or 0, st.st_mtime_ns)
    return t


def build_order(graph, roots):
    """`roots` and the files they require (transitively, through `graph`),
    each after what it requires."""
    order, seen = [], set()
    stack = [(r, False) for r in reversed(list(roots))]
    while stack:                       # post-order: dependencies first
        v, expanded = stack.pop()
        if expanded:
            order.append(v)
            continue
        if v in seen:
            continue
        seen.add(v)
        stack.append((v, True))
        stack.extend((d, False) for d in reversed(graph.get(v, [])) if d not in seen)
    return order


def outdated(graph, order, root):
    """{.v: why} of the files in `order` (dependencies first) that make would
    rebuild: no .vo, a .vo older than its .v, or older than a .vo it
    requires (or requiring one that is itself out of date)."""
    why = {}
    for v in order:
        rel, t = os.path.relpath(v, root), built_ns(v)
        if t is None:
            why[v] = "%s has no .vo" % rel
        elif os.stat(v).st_mtime_ns > t:
            why[v] = "%s is newer than its .vo" % rel
        else:
            for d in graph.get(v, []):
                if why.get(d):
                    why[v] = "%s requires %s, which is out of date" % (rel, os.path.relpath(d, root))
                    break
                td = built_ns(d)
                if td and td > t:
                    why[v] = "%s's .vo is older than %s's, which it requires" % (rel, os.path.relpath(d, root))
                    break
    return why


def stale_deps(path, proj):
    """[(.v, why)] of the libraries FILE requires (transitively) that make
    would rebuild, in build order. [] for dune projects (resolve just built
    them) or when it cannot be told (no coqdep)."""
    if proj["kind"] == "dune":
        return []
    try:
        graph = dep_graph(proj, path)
    except (OSError, ValueError, subprocess.SubprocessError):
        return []
    if not graph:
        return []
    order = [v for v in build_order(graph, [path]) if v != path]
    why = outdated(graph, order, proj["root"])
    return [(v, why[v]) for v in order if why.get(v)]


def stale_list(stale, n=8):
    return "\n".join(["  " + w for _, w in stale[:n]] +
                     (["  ... and %d more" % (len(stale) - n)] if len(stale) > n else []))


def stale_note(path, proj):
    """A warning for goto: the session loads .vo files older than their
    sources, so edits in those files are not seen."""
    try:
        stale = stale_deps(path, proj)
    except Exception:              # a warning must never break goto
        return ""
    if not stale:
        return ""
    return ("rocq-live: warning: %d of this file's dependencies %s out of date, so the session uses "
            "their old .vo:\n%s\nrocq-live: rebuild with `rocq-live compile FILE --deps-only` (MCP: "
            "rocq_compile, deps_only) to use your edits; the session then reloads them"
            % (len(stale), "is" if len(stale) == 1 else "are", stale_list(stale)))


def compile_cmd(proj, v):
    """(command, shell?, cwd) that builds v's .vo as the project does."""
    root = proj["root"]
    if proj.get("compile"):
        vo = os.path.relpath(v[:-2] + ".vo", root)
        return (proj["compile"].replace("{file}", shlex.quote(v)).replace("{vo}", shlex.quote(vo)),
                True, root)
    if proj["kind"] == "dune":
        return (["dune", "build", "--display=quiet", os.path.basename(v)[:-2] + ".vo"],
                False, os.path.dirname(v))
    if proj["kind"] == ".rocq-live loadpath":
        raise Fail("rocq-live: the load path comes from a `loadpath` command, so where .vo files go "
                   "is up to your build; set `compile` in .rocq-live (e.g. `compile make {vo}`)")
    env = proj["env"]
    tool = (["coqc"] if shutil.which("coqc", path=env.get("PATH")) else
            ["rocq", "compile"] if shutil.which("rocq", path=env.get("PATH")) else None)
    if not tool:
        raise Fail("rocq-live: no coqc (or rocq) found to compile with")
    return tool + proj["flags"] + [os.path.relpath(v, root)], False, root


def build(path, proj, deps_only):
    """Compile FILE's out-of-date dependencies in order, then FILE unless
    deps_only. (text, error?)"""
    root, done, t0 = proj["root"], [], time.time()
    todo = [] if proj["kind"] == "dune" else [v for v, _ in stale_deps(path, proj)]
    if not deps_only:
        todo.append(path)
    for v in todo:
        cmd, shell, cwd = compile_cmd(proj, v)
        r = subprocess.run(cmd, shell=shell, cwd=cwd, env=proj["env"], capture_output=True, text=True)
        if r.returncode:
            return ("%s%s\nrocq-live: compiling %s failed (exit %d)%s"
                    % (r.stdout, r.stderr, os.path.relpath(v, root), r.returncode,
                       "; compiled before it: " + ", ".join(done) if done else "")), True
        done.append(os.path.relpath(v, root))
    if not done:
        return ("rocq-live: dependencies up to date (dune builds them)" if proj["kind"] == "dune"
                else "rocq-live: dependencies up to date"), False
    return "rocq-live: compiled %s (%.1f s)" % (", ".join(done), time.time() - t0), False


def source_flags(proj):
    """The load path with dune's build copies (_build/default/...) mapped
    back to the source directories, so coqdep reads the files you edit."""
    root = os.path.realpath(proj["root"])
    b = os.path.join(root, "_build", "default")
    out, i, fl = [], 0, proj["flags"]
    while i < len(fl):
        if fl[i] in ("-Q", "-R") and i + 2 < len(fl):
            d = os.path.realpath(fl[i + 1])
            if d == b or d.startswith(b + os.sep):
                src = root + d[len(b):]
                d = src if os.path.isdir(src) else d
            out += [fl[i], d, fl[i + 2]]
            i += 3
        else:
            out.append(fl[i])
            i += 1
    return out


def compile_one(proj, v):
    """("ok", seconds) or ("failed", output) for building v's .vo."""
    t0 = time.time()
    cmd, shell, cwd = compile_cmd(proj, v)
    r = subprocess.run(cmd, shell=shell, cwd=cwd, env=proj["env"], capture_output=True, text=True)
    if r.returncode:
        return "failed", (r.stdout + r.stderr).strip()
    return "ok", time.time() - t0


def compile_jobs():
    try:
        return max(1, int(os.environ.get("ROCQ_LIVE_JOBS", "")))
    except ValueError:
        return max(1, min(4, (os.cpu_count() or 2) // 2))


def impact(file):
    """Compile FILE, then every project file that requires it (directly or
    not), in dependency order and in parallel, rebuilding on the way any
    out-of-date file they need: what an edit to FILE breaks elsewhere. A
    failure skips what depends on it; other branches go on. dune projects:
    one `dune build` of those targets."""
    import concurrent.futures as cf
    path = norm(file)
    proj = resolve(path)
    root, t0 = proj["root"], time.time()
    dune = proj["kind"] == "dune" and not proj.get("compile")
    sproj = dict(proj, flags=source_flags(proj)) if proj["kind"] == "dune" else proj
    graph = dep_graph(sproj, path)
    if graph is None:
        raise Fail("rocq-live: impact needs coqdep (or rocq dep) to find the files that require FILE")
    users = {}
    for v, ds in graph.items():
        for d in ds:
            users.setdefault(d, []).append(v)
    cone, stack = set(), [path]
    while stack:
        for w in users.get(stack.pop(), []):
            if w not in cone and w != path:
                cone.add(w)
                stack.append(w)
    rel = os.path.relpath(path, root)
    head = "rocq-live impact %s: %d file(s) require it" % (rel, len(cone))
    targets = [v for v in build_order(graph, [path] + sorted(cone)) if v in cone or v == path]
    if dune:
        vos = [os.path.relpath(v[:-2] + ".vo", root) for v in targets]
        r = subprocess.run(["dune", "build", "--display=quiet"] + vos, cwd=root, env=proj["env"],
                           capture_output=True, text=True)
        listed = "\n".join("  " + os.path.relpath(v, root) for v in targets)
        out = (r.stdout + r.stderr).strip()
        verdict = "all built" if r.returncode == 0 else "dune build failed (exit %d)" % r.returncode
        record({"cmd": "impact", "file": path, "s": round(time.time() - t0, 3), "via": VIA,
                "compiled": len(targets) if r.returncode == 0 else 0, "err": r.returncode != 0})
        return ("%s\n%s%s\nrocq-live: %s [%.1f s]" % (head, listed, "\n" + out if out else "", verdict,
                                                     time.time() - t0)), r.returncode != 0
    # what to build: FILE, the files that require it, and anything out of
    # date that they require
    needed = set(targets)
    order = build_order(graph, needed)
    why = outdated(graph, order, root)
    needed |= {v for v in order if why.get(v)}
    order = [v for v in build_order(graph, sorted(needed)) if v in needed]
    results, running, pending, jobs = {}, {}, list(order), compile_jobs()
    with cf.ThreadPoolExecutor(jobs) as ex:
        while pending or running:
            for v in list(pending):
                deps = [d for d in graph.get(v, []) if d in needed]
                blocked = [d for d in deps if results.get(d, ("",))[0] in ("failed", "skipped")]
                if blocked:
                    results[v] = ("skipped", blocked[0])
                    pending.remove(v)
                elif len(running) < jobs and all(results.get(d, ("",))[0] == "ok" for d in deps):
                    running[ex.submit(compile_one, proj, v)] = v
                    pending.remove(v)
            if running:
                done, _ = cf.wait(list(running), return_when=cf.FIRST_COMPLETED)
                for fut in done:
                    results[running.pop(fut)] = fut.result()
            elif pending:                           # not in a DAG; never spin
                for v in pending:
                    results[v] = ("skipped", None)
                pending = []
    lines, counts = [head], {"ok": 0, "failed": 0, "skipped": 0}
    for v in order:
        state, info = results[v]
        counts[state] += 1
        r_ = os.path.relpath(v, root)
        extra = "" if v == path or v in cone else "  (out of date, needed)"
        if state == "ok":
            lines.append("ok       %s (%.1f s)%s" % (r_, info, extra))
        elif state == "failed":
            lines.append("FAILED   %s%s\n%s" % (r_, extra, info))
        else:
            lines.append("skipped  %s (requires %s, which %s)" % (
                r_, os.path.relpath(info, root) if info else "?",
                "failed" if results.get(info, ("",))[0] == "failed" else "was skipped"))
    lines.append("rocq-live: %d compiled, %d failed, %d not checked [%.1f s, %d job(s)]"
                 % (counts["ok"], counts["failed"], counts["skipped"], time.time() - t0, jobs))
    record({"cmd": "impact", "file": path, "s": round(time.time() - t0, 3), "via": VIA,
            "compiled": counts["ok"], "failed": counts["failed"], "skipped": counts["skipped"],
            "err": bool(counts["failed"] or counts["skipped"])})
    return "\n".join(lines), bool(counts["failed"] or counts["skipped"])


# ------------------------------------------------- usage statistics

def stats_file():
    return os.environ.get("ROCQ_LIVE_STATS_FILE") or os.path.join(os.path.dirname(RECIPE_DIR), "stats.jsonl")


def stats_target():
    """Where this process logs: the stats file, or None (ROCQ_LIVE_STATS=0).
    Sent with each request, so a session logs where its client says."""
    return None if os.environ.get("ROCQ_LIVE_STATS", "1") == "0" else stats_file()


def record(event, path=""):
    """Append one event to the local stats log (one JSON line). Nothing is
    sent anywhere; ROCQ_LIVE_STATS=0 turns it off. `path`: the client's
    stats_target() (None: do not log). Never fails a request."""
    path = stats_target() if path == "" else path
    if not path:
        return
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        if os.path.exists(path) and os.path.getsize(path) > STATS_MAX:
            os.replace(path, path + ".old")
        event = dict(event, t=round(time.time(), 1))
        with open(path, "a") as f:
            f.write(json.dumps(event, separators=(",", ":")) + "\n")
    except (OSError, TypeError, ValueError):
        pass


# ------------------------------------------------- recipes

def recipe_path(path):
    return os.path.join(RECIPE_DIR, hashlib.sha1(path.encode()).hexdigest()[:12] + ".json")


def save_recipe(path, line, runs):
    try:
        os.makedirs(RECIPE_DIR, exist_ok=True)
        tmp = recipe_path(path) + ".tmp"
        with open(tmp, "w") as f:
            json.dump({"file": path, "line": line, "runs": runs, "saved": time.time()}, f)
        os.replace(tmp, recipe_path(path))
    except OSError:
        pass


def load_recipe(path):
    try:
        with open(recipe_path(path)) as f:
            r = json.load(f)
        if r.get("file") == path and time.time() - r.get("saved", 0) < RECIPE_KEEP:
            return r
    except (OSError, ValueError):
        pass
    return None


def drop_recipe(path):
    try:
        os.unlink(recipe_path(path))
    except OSError:
        pass


# ------------------------------------------------- suggestions and compact goals

MISSING = re.compile(r"The\s+(?:reference|variable)\s+(\S+?)\s+was\s+not\s+found\s+in\s+the\s+current\s+environment")
SUGGEST_BUDGET = 8          # seconds of Search per error, looking for similar names


def parse_search(out):
    """[(name, type on one line)] from `Search` output."""
    entries = []
    for line in out.splitlines():
        m = re.match(r"^([^\s:][^\s]*?):(?:\s(.*))?$", line)
        if m:
            entries.append([m.group(1), (m.group(2) or "").strip()])
        elif entries and line.strip():
            entries[-1][1] = (entries[-1][1] + " " + line.strip()).strip()
    return entries


def name_parts(name):
    return [t for t in re.split(r"[_'.]+", name.split(".")[-1].lower()) if t]


def name_score(name, cand):
    """How alike two names are: their parts matched up fuzzily (so a typo or
    parts in another order still score high), then the last components as
    strings, then a shared qualifier."""
    import difflib
    ratio = lambda a, b: difflib.SequenceMatcher(None, a, b).ratio()
    ps, qs = name_parts(name), name_parts(cand)
    if not ps or not qs:
        return 0.0
    parts = sum(max(ratio(p, q) for q in qs) for p in ps) / len(ps)
    parts *= min(len(ps), len(qs)) / max(len(ps), len(qs))
    whole = ratio(name.split(".")[-1].lower(), cand.split(".")[-1].lower())
    qual = name.rsplit(".", 1)[0] if "." in name else None
    if qual:          # Nat.add_com: Nat.add_comm, not and_comm
        same = "." in cand and (cand.rsplit(".", 1)[0] + ".").endswith("." + qual + ".") or \
            cand.rsplit(".", 1)[0] == qual
        return max(parts, whole) + (0.05 if same else -0.15)
    return max(parts, whole)


CLOSE_NAME = 0.8           # a suggested name must score at least this
NEAR_EXACT = 0.95          # a loaded name this close needs no look into unloaded libraries


def rank_names(name, found, n=5):
    """The names in `found` most like `name`."""
    scored = sorted(((name_score(name, c), c) for c in found if c != name), key=lambda x: (-x[0], len(x[1])))
    return [c for sc, c in scored if sc >= CLOSE_NAME][:n]


_where = {}


def library_dirs(proj):
    """Directories with the .glob files of what could be Required: the
    toolchain's libraries (`-where`: theories, user-contrib) and the
    project's load path."""
    key = tuple(proj["cmd"])
    if key not in _where:
        try:
            r = subprocess.run(proj["cmd"] + ["-where"], env=proj["env"], capture_output=True,
                               text=True, timeout=10)
            w = r.stdout.strip().splitlines()[-1] if r.returncode == 0 and r.stdout.strip() else None
        except (OSError, subprocess.SubprocessError):
            w = None
        _where[key] = [os.path.join(w, d) for d in ("theories", "user-contrib")] if w else []
    dirs = list(_where[key])
    fl, i = proj["flags"], 0
    while i < len(fl):
        if fl[i] in ("-Q", "-R") and i + 2 < len(fl):
            dirs.append(fl[i + 1])
            i += 3
        else:
            i += 1
    return [d for d in dict.fromkeys(dirs) if os.path.isdir(d)]


def unloaded_names(name, dirs):
    """[(score, qualified name, library)] for names like `name` in the
    .glob files under `dirs`, best first. Both definitions and references
    record where a name lives (references also cover names a functor puts
    into a module). Names containing `name`'s last component are
    considered, so a missing letter at the end is found too."""
    base = name.split(".")[-1]
    if len(base) < 5:
        return []
    heads, seen, visited = {}, {}, set()
    matches = []                  # (path, line) of .glob lines that contain base
    for top in dirs:              # walked in Python: links followed (Homebrew), any grep
        for dp, dns, fns in os.walk(top, followlinks=True):
            real = os.path.realpath(dp)
            if real in visited:
                dns[:] = []
                continue
            visited.add(real)
            for fn in fns:
                if not fn.endswith(".glob"):
                    continue
                path = os.path.join(dp, fn)
                try:
                    with open(path, encoding="utf-8", errors="replace") as f:
                        data = f.read()
                except OSError:
                    continue
                if base not in data:
                    continue
                for line in data.splitlines():
                    if line.startswith("F") and path not in heads:
                        heads[path] = line[1:].strip()
                    if base in line:
                        matches.append((path, line))
    for path, line in matches:
        t = line.split()
        if len(t) >= 4 and t[0].startswith("R") and base in t[3]:          # a reference
            lib, sec, nm = t[1], t[2], t[3]
        elif len(t) == 4 and base in t[3] and re.match(r"^[a-z]+$", t[0]):  # a definition
            lib, sec, nm = heads.get(path), t[2], t[3]
        else:
            continue
        if not lib or nm.startswith("_"):
            continue
        full = ((sec + ".") if sec != "<>" else "") + nm
        if (full, lib) not in seen:
            seen[(full, lib)] = [name_score(name, full), 0]
        seen[(full, lib)][1] += 1
    ranked = sorted(seen.items(), key=lambda kv: (-kv[1][0], -kv[1][1], len(kv[0][1])))
    return [(sc, full, lib) for (full, lib), (sc, _) in ranked if sc >= CLOSE_NAME]


GOAL_HEAD = re.compile(r"^\d+ (?:focused )?goals?\b")
GOAL_RULE = re.compile(r"^\s*={4,}\s*$")


def parse_goal(text):
    """(lines up to the first goal's header, its hypotheses, lines from the
    ==== rule on) of a goals display, or None. A hypothesis starts at a line
    indented by two spaces; deeper lines continue it."""
    lines = text.split("\n")
    head = next((i for i, l in enumerate(lines) if GOAL_HEAD.match(l)), None)
    if head is None:
        return None
    rule = next((i for i in range(head + 1, len(lines)) if GOAL_RULE.match(lines[i])), None)
    if rule is None:
        return None
    hyps = []
    for line in lines[head + 1:rule]:
        if re.match(r"^  \S", line):
            hyps.append([line])
        elif hyps and line.strip():
            hyps[-1].append(line)
    return lines[:head + 1], ["\n".join(h) for h in hyps], lines[rule:]


def compact_enabled():
    return os.environ.get("ROCQ_LIVE_COMPACT", "1") != "0"


def hyp_name(entry):
    return entry[2:].split(" :")[0].strip()


def compact_goals(shown, text):
    """`text` (a goals display) with the first goal's hypotheses that are
    unchanged from `shown` (the hypotheses last displayed) replaced by one
    line naming them; `text` itself if that saves little."""
    if not shown:
        return text
    parsed = parse_goal(text)
    if not parsed:
        return text
    head, hyps, rest = parsed
    before = set(shown)
    same = [h for h in hyps if h in before]
    if len(same) < 3:
        return text
    names = [n.strip() for h in same for n in hyp_name(h).split(",")]
    listed = ", ".join(names[:25]) + (", ..." if len(names) > 25 else "")
    now = {n.strip() for h in hyps for n in hyp_name(h).split(",")}
    gone = [n.strip() for h in shown for n in hyp_name(h).split(",") if n.strip() not in now]
    out = head + ["  (%d unchanged hypotheses not shown: %s)" % (len(names), listed)]
    out += [h for h in hyps if h not in before]
    if gone:
        out.append("  (no longer in context: %s)" % ", ".join(gone[:25]))
    return "\n".join(out + rest)


# --------------------------------------------------------------- session

class Session:
    """The file's checked prefix: `done` lists (end offset, coqtop state) of
    each sentence checked, `text` the file as last read (the offsets refer to
    it), `runs` stacks (state before, text) of each run, `line` the last goto
    target, `loaded` the fingerprint of each watched product when it was
    loaded. `checked` holds (statement start, proof end) of each opaque proof
    known to check in `text` with the same imports: it outlives a coqtop
    restart, and such a proof is not re-run unless something it can depend
    on changes. `skipped` lists (statement end, proof end, checked?) of the
    proofs the current coqtop holds as Admitted."""

    def __init__(self, path, proj):
        self.path, self.name = path, os.path.relpath(path, proj["root"])
        self.line, self.loaded, self.text = 0, {}, ""
        self.watch = None          # memory watchdog, given to every coqtop started
        self.configure(proj)

    def configure(self, proj):
        self.proj = proj
        self.binds = bindings(proj["flags"], os.path.realpath(proj["root"]))
        self.checked = set()       # another load path: nothing is known to check
        self.start_coqtop()

    def start_coqtop(self):
        p = self.proj
        self.coq = Coqtop(p["cmd"], p["flags"], p["root"], p["env"])
        self.coq.watch = self.watch
        self.done, self.runs, self.skipped = [(0, self.coq.state)], [], []
        self.shown = None          # hypotheses of the goal last displayed (compact goals)
        self.metrics = {}          # what the current request did, for the stats log
        self.compact = compact_enabled()

    def note_loaded(self):
        out, _ = self.coq.send("Print Libraries.")
        for p in products(out, self.binds):
            if p not in self.loaded:
                fp = fingerprint(p)
                if fp is not None:
                    self.loaded[p] = fp

    def changed(self):
        root = self.proj["root"]
        return sorted(os.path.relpath(p, root) for p, fp in self.loaded.items()
                      if fingerprint(p) != fp)

    def restart(self, note, cmd):
        """Restart coqtop; unless the request is itself a goto, replay the
        file to the last goto line and the runs on top."""
        record({"cmd": "restart", "file": self.path, "why": note.replace("rocq-live: ", "")[:100]})
        runs = [text for _, text in self.runs]
        self.coq.close()
        self.loaded = {}
        self.start_coqtop()
        if cmd == "goto":
            return note
        out, failed = self.goto(self.line)
        if failed:
            return note + "; replaying %s stopped at an error:\n%s" % (self.name, out)
        for text in runs:
            out, err = self.run(text)
            if err:
                return note + "; replayed to line %s, but this run now fails: %s\n%s" % (
                    self.line or "EOF", text, out)
        return note + "; replayed to line %s%s" % (
            self.line or "EOF", " and %d run(s)" % len(runs) if runs else "")

    def before(self, cmd, proj):
        """Before a request: pick up a new load path or rebuilt imports."""
        if proj and any(proj[k] != self.proj[k] for k in ("flags", "cmd", "desc")):
            self.coq.close()
            self.loaded = {}
            self.configure(proj)
            return "rocq-live: the load path changed; restarted coqtop"
        changed = self.changed()
        if not changed:
            return ""
        shown = ", ".join(changed[:4]) + (" ..." if len(changed) > 4 else "")
        self.checked = set()           # proofs may now check differently
        return self.restart("rocq-live: %s changed since it was loaded; restarted coqtop" % shown, cmd)

    def line_of(self, off):
        return self.text.count("\n", 0, off) + 1

    def goto(self, line, full=False, strict=False, all_errors=False):
        """State just before `line` (0: end of file). Re-checks from the first
        changed character, except what the change cannot affect:
        - an edit to comments or white space between sentences re-runs nothing;
        - a proof already checked (see `checked`) is taken as Admitted, its
          statement re-checked: an edit inside one self-contained Qed proof
          keeps the proofs after it checked, since what follows a Qed sees
          only the statement.
        Unless `full`, a finished Qed proof before the target that was not
        edited is taken as Admitted as well (statement checked, tactics not),
        as `coqc -vos` does. `strict` (audit) runs every proof for real.
        With `all_errors`, an error inside an opaque proof is recorded in
        `errors` and the proof is closed with Admitted, so checking goes on
        (up to MAX_ERRORS); an error anywhere else still stops."""
        with open(self.path, encoding="utf-8") as f:
            new = f.read()
        target = line_offset(new, line) if line else len(new)
        self.line = line
        full = full or strict or not line          # the whole file: check every proof
        old = self.text
        d, m = 0, min(len(old), len(new))       # first changed character
        while d < m and old[d] == new[d]:
            d += 1
        if d == m and len(old) == len(new):
            d = len(new) + 1
        # the edited region of the new text: [d, len(new) - common suffix)
        if not old or d > len(new):
            edit = (len(new) + 1, len(new) + 1)
        else:
            k = 0
            while k < m - d and old[len(old) - 1 - k] == new[len(new) - 1 - k]:
                k += 1
            edit = (d, max(len(new) - k, d + 1))
            if self.carry_over(old, new, d, k):     # comments/white space only
                d, edit = len(new) + 1, (len(new) + 1, len(new) + 1)
        if full:          # re-check proofs taken as Admitted before the target
            for body, stop, known in self.skipped:
                if body < target and (strict or not known):
                    d = min(d, body)
                    break
        keep = [e for e in self.done if e[0] == 0 or (e[0] < d and e[0] <= target)]
        if keep != self.done or self.runs:
            self.coq.back_to(keep[-1][1])
        self.done, self.runs, self.text = keep, [], new
        self.skipped = [x for x in self.skipped if x[1] <= keep[-1][0]]
        fast = not full and fast_enabled()
        reuse = not strict and bool(self.checked) and os.environ.get("ROCQ_LIVE_REUSE", "1") != "0"
        blank = depths = None
        msgs, failed, off, skipped_now = [], False, self.done[-1][0], 0
        self.error, self.sent, self.reused = None, 0, 0   # error: (start offset, text sent, output)
        self.errors = []                  # with all_errors: errors in proofs closed with Admitted
        opening = None                    # (statement start, proof end, statement end) of the proof being run
        if off and off < target:          # resuming inside a proof? it counts once its Qed runs
            blank = blank_comments(new)
            depths = section_depths(blank) if fast or reuse else {}
            st = statement_before(blank, [e for e, _ in self.done])
            ext = proof_extent(new, blank, *st) if st else None
            if ext and st[1] <= off < ext["stop"]:
                opening = (st[0], ext["stop"], st[1])
        while True:
            end = next_sentence_end(new, off)
            if end is None or end > target:
                break
            if only_blank(new[off:end]):
                off = end; continue
            if blank is None:
                blank = blank_comments(new)
                depths = section_depths(blank) if fast or reuse else {}
            blk, known = None, False
            if fast or reuse:
                blk = skippable(new, blank, off, end, target, edit, depths)
                known = bool(blk) and reuse and (off, blk[1]) in self.checked
                if blk and not (fast or known):
                    blk = None
            if blk:
                using, stop = blk
                parts = [(new[off:end], off, end)]
                if using:
                    parts.append((new[using[0]:using[1]], using[0], using[1]))
                parts.append(("Admitted.", stop, stop))
                bad = None
                for text, at_start, at_end in parts:
                    out, err = self.coq.send(text)
                    self.sent += 1
                    if err:
                        bad = (at_start, text, out)
                        break
                    self.done.append((at_end, self.coq.state))
                if bad is None:
                    self.skipped.append((end, stop, known))
                    if known:
                        self.reused += 1
                    else:
                        skipped_now += 1
                    off = stop
                    continue
                # the statement itself fails: report it like any error
                while self.done[-1][0] > off:
                    self.done.pop()
                self.error, out, err = bad, bad[2], True
            else:
                out, err = self.coq.send(new[off:end])
                self.sent += 1
                if err:
                    self.error = (off, new[off:end], out)
                elif opening is None:
                    ext = proof_extent(new, blank, off, end)
                    if ext:
                        opening = (off, ext["stop"], end)
            if err and all_errors and opening and len(self.errors) < MAX_ERRORS \
                    and "rocq-live: step interrupted" not in out:
                # inside a proof: note the error, close the proof with Admitted, go on
                self.coq.back_to(self.done[-1][1])
                _, bad = self.coq.send("Admitted.")
                if not bad:
                    self.errors.append(self.error)
                    self.done.append((opening[1], self.coq.state))
                    self.skipped.append((opening[2], opening[1], False))
                    off, opening = opening[1], None
                    continue
            if err:
                at = self.line_of(off + len(new[off:end]) - len(new[off:end].lstrip()))
                self.coq.back_to(self.done[-1][1])
                failed = True
                msgs.append("rocq-live: error in the sentence at %s line %d; stopped before it\n%s"
                            % (self.name, at, out))
                break
            self.done.append((end, self.coq.state))
            if opening and end == opening[1]:
                self.checked.add(opening[:2])    # its Qed/Admitted went through
                opening = None
            off = end
        self.note_loaded()
        m = self.metrics
        m["sent"], m["kept"], m["fast"] = m.get("sent", 0) + self.sent, m.get("kept", 0) + self.reused, \
            m.get("fast", 0) + skipped_now
        if not line:                      # the whole file: what a full run would have done
            total = count_sentences(new)
            m["total"] = total
            m["full"] = self.sent >= total and not self.reused and not self.skipped
        stop = self.line_of(self.done[-1][0]) if self.done[-1][0] else 0
        msgs.append(self.goals())
        msgs.append("rocq-live: checked up to %s line %d (asked for line %s)"
                    % (self.name, stop, line or "EOF"))
        n = sum(1 for x in self.skipped if not x[2])
        if n:
            msgs.append("rocq-live: %d finished proof(s) before it taken as Admitted%s (statements "
                        "checked, tactics not; goto --full checks them)"
                        % (n, " (%d just now)" % skipped_now if skipped_now != n else ""))
        if self.reused:
            msgs.append("rocq-live: %d proof(s) checked before were not re-run (nothing they depend "
                        "on changed; statements re-checked)" % self.reused)
        return "\n".join(msgs), failed

    def carry_over(self, old, new, d, k):
        """The file changed from `old` to `new` in [d, len - k). If only
        comments or white space between sentences changed, move the
        session's offsets to the new text and return True. Otherwise keep as
        checked the proofs before the change, and those after it if the change
        is one edit_effect understands: all of them after a change to the
        tactics of a Qed proof, else those that cannot see the names it
        changed (see edit_effect, affected_proofs)."""
        delta = len(new) - len(old)
        s0 = [e for e, _ in self.done if e <= d][-1]      # a sentence boundary before d
        if not (any(e > d for e, _ in self.done) or any(b > d for _, b in self.checked)):
            return False                                  # nothing after the change to keep
        pairs = cosmetic_pairs(old, new, s0, len(old) - k, len(new) - k)
        if pairs is not None:
            def moved(x):
                return x if x <= s0 else pairs.get(x, x + delta)
            self.done = [(moved(e), st) for e, st in self.done]
            self.skipped = [(moved(b), moved(e), kn) for b, e, kn in self.skipped]
            self.checked = {(moved(a), moved(b)) for a, b in self.checked}
            self.text = new
            return True
        edit = edit_effect(old, new, d, k, [e for e, _ in self.done if e <= d])
        kept = {(a, b) for a, b in self.checked if b <= d}
        if edit:
            first, old_stop, new_stop, names, walk = edit
            later = {(a + delta, b + delta) for a, b in self.checked if a >= old_stop}
            if names:                 # names changed: keep what cannot see them
                affected = affected_proofs(new, blank_comments(new), walk, names,
                                           skip=(first, new_stop) if walk < first else None)
                later = set() if affected is None else later - affected
            kept |= later
        self.checked = kept
        return False

    def handle(self, cmd, arg, via=None, log=""):
        """One request: (output, error?), recorded in the stats log with what
        it cost and saved. goto/run/back also save the session's recipe (line
        + runs) so it can be restored later."""
        self.metrics, t0 = {}, time.time()
        res = self._handle(cmd, arg)
        record(dict(self.metrics, cmd=cmd, file=self.path, s=round(time.time() - t0, 3),
                    err=bool(res[1]), via=via or VIA), log)
        return res

    def _handle(self, cmd, arg):
        if cmd == "goto":
            a = arg if isinstance(arg, dict) else {"line": arg or 0}
            res = self.goto(a.get("line") or 0, bool(a.get("full")))
        elif cmd == "run":
            res = self.run(arg)
        elif cmd == "query":
            res = self.query(arg)
        elif cmd == "back":
            res = self.back(arg)
        elif cmd == "goals":
            res = self.goals(), False
        elif cmd == "try":
            res = self.try_(arg["tactics"], arg["each_timeout"])
        elif cmd == "audit":
            res = self.audit(arg.get("names") or [], arg.get("allow") or self.proj.get("axioms") or [])
        elif cmd == "check":
            res = self.check(arg.get("name") or self.name, bool(arg.get("all_errors")))
        else:
            return "rocq-live: unknown command " + cmd, True
        if cmd in ("goto", "run", "back", "audit", "check"):
            save_recipe(self.path, self.line, [t for _, t in self.runs])
        if res[1] and cmd in ("goto", "run", "query", "try", "check") and MISSING.search(res[0]):
            hints = self.suggest(res[0])
            if hints:
                res = (res[0] + "\n" + "\n".join(hints), res[1])
        return res

    def run(self, text):
        if not complete(text):
            return "rocq-live: give complete sentences ending with '.'", True
        before = self.coq.state
        out, err = self.coq.send(text)
        if err:
            self.coq.back_to(before)
            return out + "\nrocq-live: error; state unchanged", True
        self.runs.append((before, text))
        self.note_loaded()
        if not out:
            out, _ = self.coq.send("Show.")
        return self.display(out, compact=True), False

    def query(self, text):
        before = self.coq.state
        out, err = self.coq.send(text)
        self.coq.back_to(before)
        return out, err

    def back(self, n):
        if n < 1 or n > len(self.runs):
            return "rocq-live: %d run(s) to undo, asked %d" % (len(self.runs), n), True
        state = self.runs[-n][0]
        del self.runs[-n:]
        self.coq.back_to(state)
        return self.goals(), False

    def goals(self):
        out, err = self.coq.send("Show.")
        return self.display("(no open proof)" if err or not out else out)

    def display(self, text, compact=False):
        """A goals display for the client: compacted against the goals last
        shown if `compact` (see compact_goals); remembers its hypotheses."""
        out = compact_goals(self.shown, text) if compact and self.compact else text
        if len(out) < len(text):
            self.metrics["goal_chars_saved"] = self.metrics.get("goal_chars_saved", 0) + len(text) - len(out)
        parsed = parse_goal(text)
        self.shown = parsed[1] if parsed else None
        return out

    def suggest(self, text):
        """Hints for names an error says do not exist: similar names that do
        (with their types), found by Search in the current state."""
        names = []
        for m in MISSING.finditer(text):
            n = m.group(1).rstrip(".")
            if n not in names:
                names.append(n)
        lines, timeout = [], self.coq.timeout
        deadline = time.time() + SUGGEST_BUDGET
        for name in names[:3]:
            base = name.split(".")[-1]
            if len(base) < 4:
                continue
            found = {}
            parts = [t for t in re.split(r"[_']+", base) if len(t) >= 3]
            queries = ['Search "%s".' % base]                  # a longer name, another module
            if len(parts) >= 2:                                 # the same parts, another order
                queries.append("Search %s." % " ".join('"%s"' % t for t in parts))
            queries += ['Search "%s".' % t for t in parts]      # a typo in one part
            try:
                for q in queries:
                    left = deadline - time.time()
                    if left < 0.5 or len(rank_names(name, found)) >= 3:
                        break
                    self.coq.timeout = left
                    out, err = self.query(q)
                    if not err:
                        for n_, t in parse_search(out):
                            found.setdefault(n_, t)
            finally:
                self.coq.timeout = timeout
            best = rank_names(name, found)
            # unless a loaded name is (almost) it: is it in a library that is
            # not loaded? Check that requiring it works (undone right after)
            hit = None
            if not best or name_score(name, best[0]) < NEAR_EXACT:
                try:
                    for sc, full, lib in unloaded_names(name, library_dirs(self.proj))[:3]:
                        left = deadline - time.time()
                        if left < 0.5:
                            break
                        if best and sc <= name_score(name, best[0]):
                            break                       # a loaded name is as good
                        self.coq.timeout = left
                        out, err = self.query("Require Import %s.\nCheck %s." % (lib, full))
                        if not err:
                            hit = (full, lib, " ".join(out.split()))
                            break
                finally:
                    self.coq.timeout = timeout
            kind = "library" if hit else "loaded" if best else "none"
            self.metrics["hints_" + kind] = self.metrics.get("hints_" + kind, 0) + 1
            if hit:
                full, lib, typ = hit
                short = lib.split(".")
                req = ("From %s Require Import %s." % (short[0], short[-1]) if len(short) > 1
                       else "Require Import %s." % lib)
                said = "" if full == name else "%s does not exist here; " % name
                lines.append("rocq-live hint: %s%s is in %s, which is not loaded; add `%s`"
                             % (said, full, lib, req))
                lines.append("  " + typ[:200] + (" ..." if len(typ) > 200 else ""))
            elif best:
                lines.append("rocq-live hint: %s does not exist here; similar names:" % name)
                lines += ["  %s : %s" % (c, found[c][:160] + (" ..." if len(found[c]) > 160 else ""))
                          for c in best]
            else:
                lines.append("rocq-live hint: no name like %s is loaded, and no installed library on "
                             "the load path has one (Search only sees loaded libraries)" % name)
        return lines

    def try_(self, tactics, each_timeout):
        """Run each tactic alone on the current state, then undo it: which
        ones work, and what they leave. The state is unchanged."""
        before, timeout, rows = self.coq.state, self.coq.timeout, []
        for i, tac in enumerate(tactics, 1):
            text = tac if complete(tac) else tac.rstrip() + "."
            if not complete(text):
                rows.append((i, tac, None, "not a complete sentence"))
                continue
            self.coq.timeout = min(each_timeout, timeout)
            try:
                out, err = self.coq.send(text)
            finally:
                self.coq.timeout = timeout
            if not err and not out:
                out, _ = self.coq.send("Show.")
            if not err and self.compact:
                full = out
                out = compact_goals(self.shown, out)
                if len(out) < len(full):
                    self.metrics["goal_chars_saved"] = (self.metrics.get("goal_chars_saved", 0)
                                                        + len(full) - len(out))
            self.coq.back_to(before)
            rows.append((i, tac, None if err else goal_count(out), out))
        ok = [r for r in rows if r[2] is not None]
        ok.sort(key=lambda r: r[2])
        head = "rocq-live: %d of %d tactics work; state unchanged" % (len(ok), len(rows))
        if ok:
            head += "; best: [%d] %s (%s)" % (ok[0][0], ok[0][1], goals_word(ok[0][2]))
        lines = [head]
        for i, tac, n, out in rows:
            if n is None:
                lines.append("[%d] %s -> FAILS: %s" % (i, tac, error_text(out)))
            else:
                lines.append("[%d] %s -> works (%s)" % (i, tac, goals_word(n)))
                if n and len(tactics) > 1:
                    lines.append(indent(first_lines(out, 12)))
                elif n:
                    lines.append(indent(out))
        return "\n".join(lines), not ok

    def audit(self, names, allowed):
        """Admitted/admit/axioms in the file, and `Print Assumptions` of its
        declarations (or of `names`) against the allowed axioms. Checks the
        whole file first; afterwards the session is back where it was."""
        line, runs = self.line, [text for _, text in self.runs]
        out, failed = self.goto(0, strict=True)     # Print Assumptions needs real proofs
        if failed:
            return ("rocq-live audit %s: FAIL (the file does not check)\n%s" % (self.name, out)), True
        text = blank_comments(self.text)
        static = scan_admits(text)
        decls = names or declarations(text)
        uses, unchecked = {}, []
        for name in decls:
            res, err = self.query("Print Assumptions %s." % name)
            if err:
                unchecked.append((name, error_text(res)))
            else:
                uses[name] = axioms_of(res)
        bad, ok_used = {}, {}
        for name, axs in uses.items():
            for ax in axs:
                (ok_used if axiom_allowed(ax, allowed) else bad).setdefault(ax, []).append(name)
        # an axiom declared here is fine if allowed; an admit fails the audit
        # unless only some NAMES were asked for (then their Print Assumptions
        # decides: it lists every admitted lemma they depend on)
        failing = [(ln, w) for ln, w in static
                   if not (w.split()[0].rstrip("s") in ("Axiom", "Parameter", "Conjecture")
                           and axiom_allowed(w.split()[1], allowed))]
        if names:
            failing = []
        verdict = "FAIL" if (failing or bad or unchecked) else "PASS"
        rep_ = ["rocq-live audit %s: %s" % (self.name, verdict)]
        for ln, what in static:
            tag = "" if (ln, what) in failing else (
                "  (elsewhere in the file)" if names else "  (allowed)")
            rep_.append("  line %d: %s%s" % (ln, what, tag))
        for ax, who in sorted(bad.items()):
            rep_.append("  axiom not allowed: %s  (used by %s)" % (ax, short_list(who)))
        for ax, who in sorted(ok_used.items()):
            rep_.append("  allowed axiom: %s  (used by %s)" % (ax, short_list(who)))
        for name, e in unchecked:
            rep_.append("  could not check %s: %s" % (name, e))
        closed = sum(1 for axs in uses.values() if not axs)
        rep_.append("  %d declaration(s) checked with Print Assumptions, %d closed; allowed axioms: %s"
                    % (len(uses), closed, " ".join(allowed) or "(none: set `axioms` in .rocq-live)"))
        # back to where the session was
        back_out, back_failed = self.goto(line)
        for t in runs:
            o, e = self.run(t)
            if e:
                rep_.append("rocq-live: note: after the audit, this run no longer applies: %s" % t)
                break
        return "\n".join(rep_), verdict == "FAIL"

    def check(self, name, all_errors=False):
        """coqc's verdict on the whole file: every proof checked (nothing taken
        as Admitted), the first error in coqc's format, and coqc's end-of-file
        rules (no open proof, Section or Module). Only what changed since the
        last goto/check can affect is re-run. The session stays at the end of
        the file, or before the error, so the next check after a fix starts
        there. With `all_errors`, every proof that fails is reported (each
        closed with Admitted to go on); an error outside a proof still stops.
        Error code 1: the file does not check; 2: not checked."""
        t0 = time.time()
        out, failed = self.goto(0, full=True, all_errors=all_errors)
        total = count_sentences(self.text)
        if failed and self.error is None:
            return out + "\nrocq-live: %s NOT CHECKED" % name, 2
        if failed and "rocq-live: step interrupted" in self.error[2]:
            return ("%s\nrocq-live: %s NOT CHECKED: the check was interrupted (see above)"
                    % (self.error[2], name)), 2
        diags = [coqc_diag(self.text, e, name) for e in self.errors]
        last = coqc_diag(self.text, self.error, name) if failed else self.eof_error(name)
        if last:
            diags.append(last)
        stats = "[%s%s, %.1f s]" % ("all %d sentences run" % total if self.sent >= total else
                                    "%d of %d sentences re-run" % (self.sent, total),
                                    ", %d proof(s) checked before kept" % self.reused if self.reused else "",
                                    time.time() - t0)
        self.metrics["errors"] = len(diags)
        self.metrics["all_errors"] = all_errors
        if not diags:
            return "rocq-live: %s OK %s" % (name, stats), False
        note = ""
        if all_errors:
            note = " %d error(s)" % len(diags)
            if self.errors:
                note += "; %d failing proof(s) closed with Admitted to go on" % len(self.errors)
            if len(self.errors) >= MAX_ERRORS:
                note += "; stopped after %d" % MAX_ERRORS
            elif failed:
                note += "; stopped at an error outside a proof"
        return "%s\nrocq-live: %s FAILED%s %s" % ("\n".join(diags), name, note, stats), 1

    def eof_error(self, name):
        """coqc's error at the end of a file that leaves a proof, Section or
        Module open (asked of Rocq itself), else ""."""
        out, err = self.query("Show Conjectures.")
        pending = out.split() if not err else []
        if pending:
            return "Error: There are pending proofs in file %s: %s." % (name, ", ".join(pending))
        kinds, blocks, before = block_kinds(blank_comments(self.text)), [], self.coq.state
        try:
            for _ in range(1000):
                # ending a block that does not exist names the innermost one
                out, err = self.coq.send("End rocq_live_no_such_block.")
                m = re.search(r"Last block to end has name (\S+?)\.?\s*$", out, re.M)
                if not m:
                    break
                blocks.append("%s %s" % (kinds.get(m.group(1), "section"), m.group(1)))
                out, err = self.coq.send("End %s." % m.group(1))
                if err:
                    break
        finally:
            self.coq.back_to(before)
        if not blocks:
            return ""
        listed = blocks[0] if len(blocks) == 1 else ", ".join(blocks[:-1]) + " and " + blocks[-1]
        return "Error: The %s %s to be closed." % (listed, "needs" if len(blocks) == 1 else "need")


# ---------------------------------------------------------- daemon

def sock_path(path):
    return os.path.join(SESSION_DIR, hashlib.sha1(path.encode()).hexdigest()[:12] + ".sock")


def write_line(conn, obj):
    conn.sendall((json.dumps(obj) + "\n").encode())


_code = None


def code_id():
    """Hash of this script: a session started by another version is restarted."""
    global _code
    if _code is None:
        with open(SELF, "rb") as f:
            _code = hashlib.sha1(f.read()).hexdigest()[:12]
    return _code


def touch(path):
    with open(path, "a"):
        os.utime(path)


def serve(path, sock, projfile):
    """Daemon body: one request at a time, each a JSON line, answered with a
    JSON line {out, err}. While a request runs, `.busy` exists (GC never stops
    a busy session); `.used` is touched at each request (least recently used
    sessions are stopped first)."""
    with open(projfile) as f:
        proj = json.load(f)
    os.unlink(projfile)
    srv = socket.socket(socket.AF_UNIX)
    srv.bind(sock)
    srv.listen(16)
    for ext, val in ((".file", path), (".pid", str(os.getpid())), (".code", code_id())):
        with open(sock + ext, "w") as f:
            f.write(val)
    touch(sock + ".used")
    pgid = os.getpgid(0)
    notes = []
    floor = [0.0]     # memory just after the last restart: limits below it cannot be met
    base = [0.0]      # memory when the current request began

    def session_limit(lim):
        return max(lim["session_mb"], floor[0] * 1.25)

    def watch():
        """While a step runs: over the per-session limit, interrupt it; over
        the total, stop idle sessions (GC) and interrupt only if that is not
        enough."""
        lim, mem = limits(), group_mb()
        own = mem.get(pgid, 0)
        if own > session_limit(lim):
            return ("this session uses %s, over the per-session limit %s (session_mb)"
                    % (fmt_mb(own), fmt_mb(session_limit(lim))))
        total = sum(m for g, m in mem.items() if g in session_groups())
        if total > lim["max_mb"]:
            notes.extend(gc(keep=sock))
            mem = group_mb()
            total = sum(m for g, m in mem.items() if g in session_groups())
            # interrupt only a step that is itself growing: stopping a quiet
            # one would not bring the total down
            if total > lim["max_mb"] and own > base[0] + 64:
                return ("the sessions use %s together, over the limit %s (max_mb), and no idle "
                        "session is left to stop" % (fmt_mb(total), fmt_mb(lim["max_mb"])))
        return None

    session = None
    try:
        try:
            session = Session(path, proj)     # requests wait in the backlog
            session.watch = session.coq.watch = watch
        except (StepTimeout, OSError, IndexError) as e:
            boot_error = "rocq-live: coqtop did not start: %s" % e
        else:
            boot_error = None
        while True:
            r, _, _ = select.select([srv], [], [], limits()["idle"])
            if not r:
                break                          # idle too long
            conn, _ = srv.accept()
            with conn:
                line = conn.makefile().readline()
                if not line:
                    continue                   # a liveness probe
                if boot_error:
                    write_line(conn, {"out": boot_error, "err": True})
                    break
                req = json.loads(line)
                cmd, arg = req["cmd"], req.get("arg")
                if cmd == "stop":
                    write_line(conn, {"out": "rocq-live: session stopped", "err": False})
                    break
                touch(sock + ".busy"); touch(sock + ".used")
                del notes[:]
                base[0] = group_mb().get(pgid, 0)
                try:
                    session.coq.timeout, session.coq.why = TIMEOUT_GOTO, None
                    note = session.before(cmd, req.get("proj"))
                    session.coq.timeout = req.get("timeout", TIMEOUT_GOTO)
                    session.compact = req.get("compact", True)
                    out, err = session.handle(cmd, arg, req.get("via"), req.get("log", ""))
                    # memory: a step that was stopped for memory, or a coqtop
                    # still over the per-session limit, keeps its heap: restart
                    # coqtop to give it back (the file is replayed)
                    lim = limits()
                    own = group_mb().get(pgid, 0)
                    if session.coq.why or own > session_limit(lim):
                        session.coq.why = None
                        notes.append(session.restart(
                            "rocq-live: this session used %s (per-session limit %s); restarted "
                            "coqtop to free it" % (fmt_mb(own), fmt_mb(session_limit(lim))), "replay"))
                        floor[0] = group_mb().get(pgid, 0)
                        if floor[0] > lim["session_mb"]:
                            notes.append("rocq-live: even freshly started, this file needs %s, more "
                                         "than session_mb %s; using %s as its limit (raise session_mb)"
                                         % (fmt_mb(floor[0]), fmt_mb(lim["session_mb"]),
                                            fmt_mb(session_limit(lim))))
                    notes.extend(gc(keep=sock))
                except StepTimeout as e:
                    if session.coq.p.poll() is None:      # coqtop hangs: give up
                        write_line(conn, {"out": "rocq-live: session lost: %s" % e, "err": True})
                        break
                    # coqtop died during the step (a crash in Rocq): start it
                    # again where the session was; the step is not applied
                    try:
                        session.coq.timeout = TIMEOUT_GOTO
                        what = ("did not stop when interrupted (%s); killed it" % (session.coq.why or "too slow")
                                if "did not respond" in str(e) else
                                "died during this step (exit %s)" % session.coq.p.returncode)
                        session.coq.why = None
                        note2 = session.restart("rocq-live: coqtop %s; restarted it" % what, "replay")
                    except StepTimeout as e2:
                        write_line(conn, {"out": "rocq-live: session lost: %s\n%s" % (e, e2), "err": True})
                        break
                    out, err = ("%s\nrocq-live: the step was not applied" % note2 if "did not respond" in str(e)
                                else "%s\n%s\nrocq-live: the step was not applied" % (str(e)[:4000], note2)), True
                    note = ""
                finally:
                    try:
                        os.unlink(sock + ".busy")
                    except OSError:
                        pass
                    touch(sock + ".used")
                if note:
                    out = note + "\n" + out
                if notes:
                    out = out + "\n" + "\n".join(notes)
                write_line(conn, {"out": out, "err": err})
    finally:
        if session:
            session.coq.close()
        srv.close()
        for ext in SUFFIXES:
            try:
                os.unlink(sock + ext)
            except OSError:
                pass


# ---------------------------------------------------------- client API
# Each returns (text, error?). Used by the CLI and by the MCP server.

def norm(file):
    path = os.path.realpath(os.path.abspath(os.path.expanduser(file)))
    if not path.endswith(".v") or not os.path.isfile(path):
        raise Fail("rocq-live: no such .v file: " + file)
    return path


def alive(sock):
    try:
        c = socket.socket(socket.AF_UNIX)
        c.connect(sock)
        c.close()
        return True
    except OSError:
        return False


SUFFIXES = ("", ".file", ".pid", ".busy", ".used", ".proj", ".code")


def kill_session(sock):
    """Kill the daemon's process group (daemon and coqtop) at once: a stop
    request would wait behind a step that is still running."""
    try:
        os.killpg(int(open(sock + ".pid").read()), signal.SIGKILL)
    except (OSError, ValueError):
        pass
    for ext in SUFFIXES:
        try:
            os.unlink(sock + ext)
        except OSError:
            pass


def mtime(path, default=0.0):
    try:
        return os.path.getmtime(path)
    except OSError:
        return default


def sweep():
    """Live sessions, least recently used first, as dicts {sock, file, pid,
    busy, used, mb}; on the way, remove what dead sessions left behind (a
    file younger than a minute may belong to a session still starting)."""
    if not os.path.isdir(SESSION_DIR):
        return []
    now, live = time.time(), []
    socks = {os.path.join(SESSION_DIR, n[:n.index(".sock") + 5])
             for n in os.listdir(SESSION_DIR) if ".sock" in n}
    mem = None
    for sock in sorted(socks):
        if alive(sock):
            if mem is None:
                mem = group_mb()
            try:
                pid = int(open(sock + ".pid").read())
                name = open(sock + ".file").read()
            except (OSError, ValueError):
                continue
            live.append({"sock": sock, "file": name, "pid": pid, "busy": os.path.exists(sock + ".busy"),
                         "used": mtime(sock + ".used", mtime(sock + ".file")), "mb": mem.get(pid, 0)})
            continue
        for ext in SUFFIXES:
            if now - mtime(sock + ext, now) > 60:
                try:
                    os.unlink(sock + ext)
                except OSError:
                    pass
        if now - mtime(sock + ".log", now) > LOG_KEEP:
            try:
                os.unlink(sock + ".log")
            except OSError:
                pass
    if os.path.isdir(RECIPE_DIR):
        for n in os.listdir(RECIPE_DIR):
            if now - mtime(os.path.join(RECIPE_DIR, n), now) > RECIPE_KEEP:
                try:
                    os.unlink(os.path.join(RECIPE_DIR, n))
                except OSError:
                    pass
    live.sort(key=lambda x: x["used"])
    return live


def session_groups():
    """Process groups of the live sessions (their daemons' pids)."""
    out = set()
    if os.path.isdir(SESSION_DIR):
        for n in os.listdir(SESSION_DIR):
            if n.endswith(".sock.pid"):
                try:
                    out.add(int(open(os.path.join(SESSION_DIR, n)).read()))
                except (OSError, ValueError):
                    pass
    return out


def gc(keep=None, adding=0):
    """Enforce the limits: stop least recently used idle sessions while they
    use more than max_mb together, or while there are more than max_sessions
    (counting `adding` sessions about to start). For the count only, a session
    used in the last `grace` seconds is spared: an agent between two tool
    calls looks idle but will be back, and stopping it costs a full re-check,
    while an extra idle coqtop costs only memory (which max_mb bounds). Never
    stops `keep` or a busy session. Returns a note per stopped session."""
    lim, live, notes, now = limits(), sweep(), [], time.time()
    count, total = len(live) + adding, sum(x["mb"] for x in live)
    for x in live:                       # least recently used first
        if x["sock"] == keep or x["busy"]:
            continue
        if total > lim["max_mb"]:
            why = "sessions used %s together, limit %s (max_mb)" % (fmt_mb(total), fmt_mb(lim["max_mb"]))
        elif count > lim["max_sessions"]:
            if now - x["used"] < lim["grace"]:
                continue                 # used recently: its agent is likely coming back
            why = "more than %d sessions (max_sessions)" % lim["max_sessions"]
        else:
            break
        kill_session(x["sock"])
        record({"cmd": "gc", "file": x["file"], "why": why[:80], "mb": round(x["mb"])})
        count, total = count - 1, total - x["mb"]
        notes.append("rocq-live: gc stopped the least recently used session %s (%s): %s"
                     % (x["file"], fmt_mb(x["mb"]), why))
    return notes


def upgraded(sock):
    """True if the session runs another version of this script."""
    try:
        return open(sock + ".code").read() != code_id()
    except OSError:
        return True


def request(sock, cmd, arg=None, proj=None):
    default = TIMEOUT_GOTO if cmd in ("goto", "check") else TIMEOUT_STEP
    timeout = float(os.environ.get("ROCQ_LIVE_TIMEOUT", default))
    c = socket.socket(socket.AF_UNIX)
    c.connect(sock)
    msg = {"cmd": cmd, "arg": arg, "timeout": timeout, "compact": compact_enabled(), "via": VIA,
           "log": stats_target()}
    if proj:
        msg["proj"] = proj
    c.sendall((json.dumps(msg) + "\n").encode())
    line = c.makefile().readline()
    c.close()
    if not line:
        return "rocq-live: the session ended; its log: %s.log" % sock, True
    resp = json.loads(line)
    return resp["out"], resp["err"]


def describe(path, proj):
    return "rocq-live: %s: %s, load path from %s (root %s)" % (
        os.path.basename(path), proj["desc"], proj["kind"], proj["root"])


def daemon_enabled():
    """ROCQ_LIVE_DAEMON=0: no background process; each call rebuilds the
    state from the file's recipe (fast replay) and exits."""
    return os.environ.get("ROCQ_LIVE_DAEMON", "1") != "0"


def start(file, line=0, full=False, proj=None, first=None):
    """A fresh session for FILE; its first request is a goto to LINE, or
    `first` = (cmd, arg)."""
    path = norm(file)
    if not daemon_enabled():
        return local("goto", path, {"line": line, "full": full}, proj=proj)
    proj = proj or resolve(path)
    sock = sock_path(path)
    kill_session(sock)
    os.makedirs(SESSION_DIR, exist_ok=True)
    notes = gc(adding=1)
    projfile = sock + ".proj"
    with open(projfile, "w") as f:
        json.dump(proj, f)
    log = open(sock + ".log", "w")
    subprocess.Popen([sys.executable, "-I", SELF, "_serve", path, sock, projfile],
                     stdin=subprocess.DEVNULL, stdout=log, stderr=log,
                     start_new_session=True, cwd=proj["root"])
    for _ in range(200):
        if alive(sock):
            break
        time.sleep(0.05)
    else:
        return "rocq-live: session did not start; see %s.log" % sock, True
    out, err = request(sock, *(first or ("goto", {"line": line, "full": full})))
    return "\n".join(notes + [describe(path, proj), out]), err


def goto(file, line=0, full=False):
    path = norm(file)
    proj = resolve(path)              # rebuild imports; maybe a new load path
    note = stale_note(path, proj)
    sock = sock_path(path)
    if not daemon_enabled():
        out, err = local("goto", path, {"line": line, "full": full}, proj=proj)
    elif not alive(sock) or upgraded(sock):
        out, err = start(file, line, full, proj)
    else:
        out, err = request(sock, "goto", {"line": line, "full": full}, proj)
    return (note + "\n" + out if note else out), err


def check(file, allow_stale=False, rebuild=False, all_errors=False):
    """coqc's verdict on FILE from its live session (see Session.check).
    Error code 1: FILE does not check; 2: it was not checked (a dependency
    is out of date or does not build, or no session)."""
    path = norm(file)
    name = coqc_name(file)
    try:
        proj = resolve(path)
    except Fail as e:
        return "%s\nrocq-live: %s NOT CHECKED" % (e, name), 2
    notes = []
    if rebuild:
        out, err = build(path, proj, deps_only=True)
        if err:
            return "%s\nrocq-live: %s NOT CHECKED: a dependency does not compile" % (out, name), 2
        if "compiled" in out:
            notes.append(out)
    stale = stale_deps(path, proj)
    if stale and not allow_stale:
        return ("rocq-live: %s NOT CHECKED: %d of its dependencies %s out of date (make would rebuild "
                "%s):\n%s\nrocq-live: rebuild with `rocq-live compile %s --deps-only` (MCP: rocq_compile, "
                "deps_only), or `check --rebuild`; or check against the old .vo with --allow-stale"
                % (name, len(stale), "is" if len(stale) == 1 else "are",
                   "it" if len(stale) == 1 else "them", stale_list(stale), file)), 2
    if stale:
        notes.append("rocq-live: warning: checking against out-of-date dependencies (--allow-stale):\n"
                     + stale_list(stale))
    arg = {"name": name, "all_errors": all_errors}
    if not daemon_enabled():
        out, err = local("check", path, arg, proj=proj)
    else:
        sock = sock_path(path)
        if not alive(sock) or upgraded(sock):
            out, err = start(file, proj=proj, first=("check", arg))
            if not alive(sock):
                return "%s\nrocq-live: %s NOT CHECKED" % (out, name), 2
        else:
            out, err = request(sock, "check", arg, proj)
    return "\n".join(notes + [out]), err


def compile_(file, deps_only=False):
    path = norm(file)
    t0 = time.time()
    out, err = build(path, resolve(path), deps_only)
    record({"cmd": "compile", "file": path, "s": round(time.time() - t0, 3), "via": VIA, "err": bool(err)})
    return out, err


_notes = []          # notes for the next reply (a restored session)


def restore(file, path, sock, why):
    """Start a session again from its recipe: the last goto line (fast
    replay) and the runs made on top of it."""
    rec = load_recipe(path)
    if rec is None:
        raise Fail("rocq-live: no session for %s; start one with: rocq-live goto %s LINE"
                   % (file, file))
    t0 = time.time()
    out, err = start(file, rec["line"])
    if not alive(sock):
        raise Fail(out)
    lost = None
    for i, text in enumerate(rec["runs"]):
        o, e = request(sock, "run", text)
        if e:
            lost = (len(rec["runs"]) - i, text)
            break
    msg = ("rocq-live: %s; restored the session from its recipe in %.1f s: line %s and %d run(s)"
           % (why, time.time() - t0, rec["line"] or "EOF", len(rec["runs"]) - (lost[0] if lost else 0)))
    if lost:
        msg += "; the run `%s` no longer applies, so it and %d later one(s) were dropped" % (lost[1], lost[0] - 1)
    if err:
        msg += "\n" + out
    _notes.append(msg)


def _live(file):
    """The socket of FILE's session; restores a stopped or outdated one from
    its recipe."""
    path = norm(file)
    sock = sock_path(path)
    if not alive(sock):
        restore(file, path, sock, "the session had been stopped (gc, idle timeout or reboot)")
    elif upgraded(sock):
        restore(file, path, sock, "rocq-live was updated")
    return sock


def at_line(file, line):
    """With an explicit LINE, run/query/try first go to the state before it."""
    if line is None:
        return None
    out, err = goto(file, line)
    if err:
        raise Fail(out)
    return None


def run(file, text, line=None):
    if not daemon_enabled():
        return local("run", norm(file), text, line)
    at_line(file, line)
    return request(_live(file), "run", text)


def query(file, text, line=None):
    if not daemon_enabled():
        return local("query", norm(file), text, line)
    at_line(file, line)
    return request(_live(file), "query", text)


def back(file, n=1):
    if not daemon_enabled():
        return local("back", norm(file), int(n))
    return request(_live(file), "back", int(n))


def goals(file):
    if not daemon_enabled():
        return local("goals", norm(file))
    return request(_live(file), "goals")


def try_(file, tactics, line=None):
    if not tactics:
        raise Fail("rocq-live: give at least one tactic to try")
    each = float(os.environ.get("ROCQ_LIVE_TRY_TIMEOUT", "30"))
    arg = {"tactics": list(tactics), "each_timeout": each}
    if not daemon_enabled():
        return local("try", norm(file), arg, line)
    at_line(file, line)
    return request(_live(file), "try", arg)


def audit(file, names=None, allow=None):
    path = norm(file)
    arg = {"names": names or [], "allow": allow or []}
    if not daemon_enabled():
        return local("audit", path, arg)
    sock = sock_path(path)
    if not alive(sock) or upgraded(sock):
        out, err = start(file, 0)
        if not alive(sock):
            return out, True
    return request(sock, "audit", arg, resolve(path))


def local(cmd, path, arg=None, line=None, proj=None):
    """No-daemon mode: a coqtop for this call only. The state comes from the
    recipe (the last goto line, fast replay, and the runs on top), or from
    LINE when given; goto/run/back save the recipe again."""
    proj = proj or resolve(path)
    s = Session(path, proj)
    try:
        default = TIMEOUT_GOTO if cmd in ("goto", "audit", "check") else TIMEOUT_STEP
        timeout = float(os.environ.get("ROCQ_LIVE_TIMEOUT", default))
        if cmd in ("goto", "audit", "check"):
            s.coq.timeout = timeout
            return s.handle(cmd, arg)
        rec = load_recipe(path) if line is None else None
        s.coq.timeout = TIMEOUT_GOTO
        out, failed = s.goto(line if line is not None else (rec["line"] if rec else 0))
        if failed:
            return out, True
        notes = []
        for text in (rec["runs"] if rec else []):
            o, e = s.run(text)
            if e:
                notes.append("rocq-live: the saved run `%s` no longer applies; dropped it and later ones" % text)
                break
        s.coq.timeout = timeout
        res, err = s.handle(cmd, arg)       # run/back save the recipe again
        return "\n".join(notes + [res]), err
    finally:
        s.coq.close()


def stop(file):
    if file in ("--all", "all"):
        live = sweep()
        for x in live:
            kill_session(x["sock"])
            drop_recipe(x["file"])
        return "rocq-live: stopped %d session(s)" % len(live), False
    # no existence check: the file of a session may have been deleted
    path = os.path.realpath(os.path.abspath(os.path.expanduser(file)))
    kill_session(sock_path(path))
    drop_recipe(path)                     # an explicit stop: forget the state too
    return "rocq-live: session stopped", False


def sessions():
    """Live sessions with their memory and idle time, and the limits."""
    live, lim, now = sweep(), limits(), time.time()
    rows = []
    for x in reversed(live):              # most recently used first
        idle = now - x["used"]
        rows.append("%-8s %-8s %s%s" % (fmt_mb(x["mb"]),
                    "busy" if x["busy"] else "%dm idle" % (idle // 60) if idle >= 60 else "%ds idle" % idle,
                    x["file"], ""))
    total = sum(x["mb"] for x in live)
    rows.append("%d session(s), %s; limits: %d sessions (sparing those used in the last %dm), "
                "%s total, %s per session, %dm idle"
                % (len(live), fmt_mb(total), lim["max_sessions"], lim["grace"] // 60,
                   fmt_mb(lim["max_mb"]), fmt_mb(lim["session_mb"]), lim["idle"] // 60))
    return "\n".join(rows), False


def parse_since(text):
    """`7d`, `12h`, `30m` or `all` -> the earliest time to count (0: all)."""
    m = re.match(r"^(\d+(?:\.\d+)?)\s*([dhm])$", (text or "all").strip())
    if not m:
        if (text or "all").strip() != "all":
            raise Fail("rocq-live: --since takes e.g. 7d, 12h, 30m or all")
        return 0
    return time.time() - float(m.group(1)) * {"d": 86400, "h": 3600, "m": 60}[m.group(2)]


def fmt_s(sec):
    return "%.1f s" % sec if sec < 90 else "%.1f min" % (sec / 60) if sec < 5400 else "%.1f h" % (sec / 3600)


def stats(since="all", file=None):
    """What rocq-live did and saved, from the local stats log."""
    cutoff = parse_since(since)
    want = os.path.realpath(os.path.expanduser(file)) if file else None
    events = []
    for path in (stats_file() + ".old", stats_file()):
        try:
            with open(path) as f:
                for line in f:
                    try:
                        e = json.loads(line)
                    except ValueError:
                        continue
                    if e.get("t", 0) >= cutoff and (not want or e.get("file") == want):
                        events.append(e)
        except OSError:
            pass
    if not events:
        return ("rocq-live stats: nothing recorded%s (log: %s%s)"
                % (" for this period/file" if (cutoff or want) else "", stats_file(),
                   "; ROCQ_LIVE_STATS=0 is set" if os.environ.get("ROCQ_LIVE_STATS") == "0" else "")), False
    events.sort(key=lambda e: e.get("t", 0))
    calls = [e for e in events if e.get("cmd") not in ("restart", "gc")]
    span = events[-1]["t"] - events[0]["t"]
    lines = ["rocq-live stats: %d request(s) on %d file(s)%s" % (
        len(calls), len({e.get("file") for e in calls}),
        "" if not cutoff else " since %s" % time.strftime("%Y-%m-%d %H:%M", time.localtime(cutoff)))]
    # time: whole-file checks against what a full run of that file costs
    last_full, spent, estimate, unknown, n = {}, 0.0, 0.0, 0, 0
    for e in calls:
        if e.get("cmd") not in ("goto", "check", "audit") or not e.get("total"):
            continue
        f = e.get("file")
        if e.get("full"):
            last_full[f] = (e["s"], e["total"])
            continue
        n += 1
        if f in last_full:
            fs, ft = last_full[f]
            spent += e["s"]
            estimate += fs * e["total"] / max(ft, 1)
        else:
            unknown += 1
    if n:
        if n - unknown:
            lines.append("  time    %d whole-file check(s) took %s; full re-checks would have taken about %s"
                         " (from each file's last full run) -> ~%s saved%s"
                         % (n - unknown, fmt_s(spent), fmt_s(estimate), fmt_s(max(0.0, estimate - spent)),
                            "; %d more with no full run to compare" % unknown if unknown else ""))
        else:
            lines.append("  time    %d whole-file check(s); no full run of those files recorded to compare with"
                         % n)
    sent = sum(e.get("sent", 0) for e in calls)
    total = sum(e.get("total", 0) for e in calls if e.get("total"))
    sent_whole = sum(e.get("sent", 0) for e in calls if e.get("total"))
    kept, fast = sum(e.get("kept", 0) for e in calls), sum(e.get("fast", 0) for e in calls)
    if sent or kept or fast:
        lines.append("  work    %s sentence(s) run%s; %d checked proof(s) kept instead of re-run; "
                     "%d proof(s) skipped by fast replay"
                     % ("{:,}".format(sent), " (whole-file checks: %s of %s, %.0f%%)" % (
                         "{:,}".format(sent_whole), "{:,}".format(total), 100.0 * sent_whole / total)
                         if total else "", kept, fast))
    ae = [e for e in calls if e.get("cmd") == "check" and e.get("all_errors")]
    if ae:
        errs = sum(e.get("errors", 0) for e in ae)
        lines.append("  errors  check --all-errors: %d call(s) found %d error(s), %d more than one per call"
                     % (len(ae), errs, sum(max(0, e.get("errors", 0) - 1) for e in ae)))
    saved = sum(e.get("goal_chars_saved", 0) for e in calls)
    if saved:
        lines.append("  tokens  compact goals left out %s characters of unchanged hypotheses (~%s tokens)"
                     % ("{:,}".format(saved), "{:,}".format(saved // 4)))
    h = {k: sum(e.get("hints_" + k, 0) for e in calls) for k in ("loaded", "library", "none")}
    if any(h.values()):
        lines.append("  hints   %d name hint(s): %d similar loaded name(s), %d in a library to Require, "
                     "%d with nothing similar" % (sum(h.values()), h["loaded"], h["library"], h["none"]))
    imp = [e for e in calls if e.get("cmd") == "impact"]
    if imp:
        lines.append("  impact  %d run(s): %d file(s) compiled, %d failed, %d skipped"
                     % (len(imp), sum(e.get("compiled", 0) for e in imp), sum(e.get("failed", 0) for e in imp),
                        sum(e.get("skipped", 0) for e in imp)))
    restarts = [e for e in events if e.get("cmd") == "restart"]
    gcs = [e for e in events if e.get("cmd") == "gc"]
    if restarts or gcs:
        lines.append("  upkeep  %d coqtop restart(s), %d session(s) stopped by gc" % (len(restarts), len(gcs)))
    by = {}
    for e in calls:
        by.setdefault(e.get("cmd"), []).append(e)
    parts = []
    for cmd, es in sorted(by.items(), key=lambda kv: -len(kv[1])):
        times = sorted(e.get("s", 0) for e in es)
        errs = sum(1 for e in es if e.get("err"))
        parts.append("%s %d (median %s%s)" % (cmd, len(es), fmt_s(times[len(times) // 2]),
                                              ", %d error" % errs + ("s" if errs != 1 else "") if errs else ""))
    lines.append("  calls   " + ", ".join(parts))
    via = {}
    for e in calls:
        via[e.get("via", "cli")] = via.get(e.get("via", "cli"), 0) + 1
    lines.append("          via %s; over %s; log: %s"
                 % (", ".join("%s %d" % kv for kv in sorted(via.items())), fmt_s(span), stats_file()))
    return "\n".join(lines), False


def collect():
    notes = gc()
    return "\n".join(notes) or "rocq-live: gc: nothing to stop (within the limits)", False


def info(file):
    path = norm(file)
    proj = resolve(path, build=False)
    v = subprocess.run(proj["cmd"] + ["--version"], env=proj["env"], capture_output=True, text=True)
    flags = " ".join(shlex.quote(f) for f in proj["flags"])
    return ("root:      %s\nload path: %s\ntoolchain: %s (%s: %s)\nflags:     %s\nsession:   %s"
            % (proj["root"], proj["kind"], proj["desc"], " ".join(proj["cmd"]),
               (v.stdout.strip().splitlines() or ["?"])[0], flags or "(none)",
               "running" if alive(sock_path(path)) else "none")), False


HINTS = [
    (r"Cannot\s+find\s+a\s+physical\s+path\s+bound\s+to\s+logical\s+path\s+(\S+?)(?:\s+with\s+prefix\s+(\S+?))?\.?\s*$",
     lambda m: "no load-path binding covers %s. `rocq-live info FILE` shows the flags in use; add a "
     "-Q/-R for it (_CoqProject, the dune theory's `theories`, or `flags` in .rocq-live)"
     % ((m.group(2) + "." if m.group(2) else "") + m.group(1))),
    (r"Unable\s+to\s+locate\s+library\s+(\S+?)\.?\s*$",
     lambda m: "%s is not on the load path or not built yet. `rocq-live info FILE` shows the flags; "
     "build the library (or set `build` in .rocq-live)" % m.group(1)),
    (r"bad\s+version\s+number|compiled\s+with\s+another\s+version|incompatible\s+version",
     lambda m: "a .vo was built by a different Rocq than the coqtop in use. `rocq-live info FILE` "
     "shows the toolchain; use the one that built it (`switch` in .rocq-live, ROCQ_LIVE_SWITCH) or rebuild"),
    (r"Compiled\s+library\s+(\S+)\s+\(in\s+file[^)]*\)\s+makes\s+inconsistent\s+assumptions\s+over\s+library\s+(\S+)",
     lambda m: ("a .vo was built by a different Rocq/stdlib than the coqtop in use; check the toolchain "
                "(`rocq-live info FILE`) or rebuild"
                if re.match(r"(Corelib|Coq|Stdlib)\.", m.group(2)) else
                "%s is stale: it was compiled against an older %s. Rebuild %s (and what depends on it)"
                % (m.group(1), m.group(2), m.group(1)))),
    (r"step interrupted after \d+ s",
     lambda m: "the step ran too long (a diverging or very slow tactic). Try a cheaper tactic, or "
     "raise ROCQ_LIVE_TIMEOUT if it is really needed"),
    (r"over the per-session limit|over the limit \S+ \S+ \(max_mb\)",
     lambda m: "the step used too much memory; tactics that split goals repeatedly (destruct in a "
     "repeat, case analysis) can build huge goal trees: close branches as they appear"),
    (r"This command requires an open proof|No focused proof",
     lambda m: "no proof is open at this point: `goto` a line inside a proof first"),
]


def explain(out):
    """Plain-language hints for errors whose fix is not in the message."""
    hints = []
    for pat, msg in HINTS:
        m = re.search(pat, out, re.M)
        if m:
            h = "rocq-live hint: " + msg(m)
            if h not in hints:
                hints.append(h)
    return hints


def safe(fn, *args):
    try:
        out, err = fn(*args)
    except Fail as e:
        out, err = str(e), True
    except (OSError, subprocess.SubprocessError, ValueError) as e:
        out, err = "rocq-live: %s: %s" % (type(e).__name__, e), True
    if _notes:
        out = "\n".join(_notes + [out])
        del _notes[:]
    if err:
        out = "\n".join([out] + explain(out))
    return out, err


# ---------------------------------------------------------- MCP server

LINE_DOC = ("1-based line: the state just before this line (put it on the first "
            "line of a tactic, not inside one). Omit or 0 for the end of the file.")
FILE_DOC = "Path to the .v file (absolute, or relative to the server's directory)."

TOOLS = [
    ("rocq_goto", "Show the Rocq proof state just before LINE of FILE, in a live coqtop "
     "session (started on first use; the project's root, load path and toolchain are found "
     "automatically, and FILE's imports are rebuilt). Later calls re-check only from the "
     "first character changed in FILE, so the loop is: edit the file, rocq_goto, repeat. "
     "Reports the first error before LINE, if any.",
     {"file": ("string", FILE_DOC), "line": ("integer", LINE_DOC),
      "full": ("boolean", "Also re-check finished proofs before LINE (by default a finished "
               "Qed proof you did not edit is taken as Admitted: its statement is checked, its "
               "tactics are not)."),
      "fresh": ("boolean", "Kill any running session for FILE and start a new one.")},
     ["file"]),
    ("rocq_run", "Run tactics/commands (complete sentences ending in '.') on top of the "
     "session's current state and return the new goals or the error. An error leaves the "
     "state unchanged. Use to try tactics without editing the file; rocq_back undoes. "
     "Hypotheses unchanged since the goals last shown are summarized in one line naming "
     "them (rocq_goals shows everything). An error about a name that does not exist comes "
     "with similar names that do, and their types.",
     {"file": ("string", FILE_DOC), "text": ("string", "Sentences, e.g. 'intros x. simpl.'"),
      "line": ("integer", "Optional: first go to the state before this line (as rocq_goto).")},
     ["file", "text"]),
    ("rocq_query", "Run a command, return its output, then undo it: Search, Check, Print, "
     "About, Locate, Print Assumptions, Compute ...",
     {"file": ("string", FILE_DOC), "text": ("string", "e.g. 'Search (_ + 0 = _).'"),
      "line": ("integer", "Optional: first go to the state before this line (as rocq_goto).")},
     ["file", "text"]),
    ("rocq_try", "Try several tactics, each alone, on the session's current state and report "
     "which work and how many goals each leaves (best first); the state is unchanged. Use it "
     "instead of guessing one tactic at a time; then rocq_run the winner.",
     {"file": ("string", FILE_DOC),
      "tactics": ("array", "Tactics, e.g. [\"lia\", \"auto\", \"reflexivity\"] (a final '.' is added if missing)"),
      "line": ("integer", "Optional: first go to the state before this line (as rocq_goto).")},
     ["file", "tactics"]),
    ("rocq_audit", "Check FILE for unfinished or assumed proofs: Admitted/admit/give_up, "
     "Axiom/Parameter declarations, and `Print Assumptions` of every declaration (or of NAMES) "
     "against the allowed axioms (`axioms` in .rocq-live, or ALLOW). PASS/FAIL with lines and names. "
     "Checks the whole file; the session returns to where it was.",
     {"file": ("string", FILE_DOC),
      "names": ("array", "Only these declarations (qualified if inside a Module)."),
      "allow": ("array", "Allowed axiom names, overriding the project's `axioms`.")},
     ["file"]),
    ("rocq_check", "Check the whole FILE as coqc would, much faster: the live session re-runs "
     "only what changed since the last rocq_check/rocq_goto can affect (after an edit to a Qed "
     "proof's tactics, just that proof; to a statement, definition or instance, the proofs that "
     "can see it; comments "
     "and white space, nothing), so the verdict after an edit usually takes a fraction of a "
     "second instead of a full compile. Every proof is checked (nothing is taken "
     "as Admitted) and a file that leaves a proof, Section or Module open fails, as with coqc. "
     "Gives OK, or the first error in coqc's format (File \"...\", line N, characters A-B). "
     "Refuses, without checking, when a dependency's .vo is out of date (its .v was edited "
     "since): then rocq_compile with deps_only, or allow_stale. Writes no .vo (rocq_compile does).",
     {"file": ("string", FILE_DOC),
      "allow_stale": ("boolean", "Check against out-of-date dependencies anyway (their old .vo)."),
      "all_errors": ("boolean", "Report every proof that fails, not just the first error (each "
                     "failing proof is closed with Admitted to go on; an error outside a proof still "
                     "stops). Use it after a change that may break several proofs.")},
     ["file"]),
    ("rocq_compile", "Build .vo files with the project's own build step (coqc with the load "
     "path, dune, or `compile` in .rocq-live): first FILE's out-of-date dependencies in "
     "dependency order, then FILE itself unless deps_only. Use it when rocq_check refuses "
     "because a dependency is out of date, or when other files need FILE's new .vo. Running "
     "sessions that loaded a rebuilt .vo reload it by themselves.",
     {"file": ("string", FILE_DOC),
      "deps_only": ("boolean", "Only rebuild FILE's out-of-date dependencies, not FILE.")},
     ["file"]),
    ("rocq_impact", "Find what an edit to FILE breaks in other files: compile FILE, then every "
     "project file that requires it (directly or not), in dependency order and in parallel, "
     "rebuilding any out-of-date file they need. Reports each file as ok, FAILED (with coqc's "
     "errors) or skipped (it requires one that failed). Use it after changing a statement or "
     "definition other files use. Writes .vo files, as a build does.",
     {"file": ("string", FILE_DOC)}, ["file"]),
    ("rocq_back", "Undo the last N rocq_run calls (default 1) and show the goals.",
     {"file": ("string", FILE_DOC), "n": ("integer", "How many runs to undo.")}, ["file"]),
    ("rocq_goals", "Show the current goals of FILE's session.",
     {"file": ("string", FILE_DOC)}, ["file"]),
    ("rocq_stop", "Stop FILE's session (kills coqtop at once), or every session with all=true.",
     {"file": ("string", FILE_DOC), "all": ("boolean", "Stop every session.")}, []),
    ("rocq_stats", "What rocq-live has done and saved, from its local log: time of whole-file "
     "checks against full re-checks, sentences and proofs not re-run, errors found per "
     "--all-errors check, goal text left out by compact goals, name hints, calls and latency.",
     {"since": ("string", "Only events since: 7d, 12h, 30m, or all (default)."),
      "file": ("string", "Only this file.")}, []),
    ("rocq_sessions", "List the running sessions with their memory and idle time, and the "
     "limits (sessions beyond them are stopped automatically, least recently used first).", {}, []),
    ("rocq_info", "Show how FILE's project is set up: root, toolchain, load path flags.",
     {"file": ("string", FILE_DOC)}, ["file"]),
]


def tool_list():
    out = []
    for name, desc, props, req in TOOLS:
        # hints for clients' approval rules: no tool edits source files (a
        # goto may build the project's imports, as a build would); only
        # rocq_compile and rocq_impact exist to write files (.vo)
        out.append({"name": name, "description": desc,
                    "annotations": {"readOnlyHint": name not in ("rocq_compile", "rocq_impact"),
                                    "destructiveHint": False,
                                    "idempotentHint": name in ("rocq_goals", "rocq_sessions", "rocq_info", "rocq_try",
                                                               "rocq_stats"),
                                    "openWorldHint": False},
                    "inputSchema": {
            "type": "object", "required": req,
            "properties": {k: dict({"type": t, "description": d},
                                   **({"items": {"type": "string"}} if t == "array" else {}))
                           for k, (t, d) in props.items()}}})
    return out


def call_tool(name, a):
    f = a.get("file", "")
    if name == "rocq_goto":
        return safe(start if a.get("fresh") else goto, f, int(a.get("line") or 0), bool(a.get("full")))
    at = int(a["line"]) if a.get("line") else None
    if name == "rocq_run":
        return safe(run, f, a.get("text", ""), at)
    if name == "rocq_query":
        return safe(query, f, a.get("text", ""), at)
    if name == "rocq_try":
        tacs = a.get("tactics") or []
        return safe(try_, f, [tacs] if isinstance(tacs, str) else tacs, at)
    if name == "rocq_audit":
        return safe(audit, f, a.get("names") or [], a.get("allow") or [])
    if name == "rocq_check":
        return safe(check, f, bool(a.get("allow_stale")), False, bool(a.get("all_errors")))
    if name == "rocq_compile":
        return safe(compile_, f, bool(a.get("deps_only")))
    if name == "rocq_impact":
        return safe(impact, f)
    if name == "rocq_back":
        return safe(back, f, int(a.get("n") or 1))
    if name == "rocq_goals":
        return safe(goals, f)
    if name == "rocq_stop":
        return safe(stop, "--all" if a.get("all") else f)
    if name == "rocq_sessions":
        return safe(sessions)
    if name == "rocq_stats":
        return safe(stats, a.get("since") or "all", a.get("file") or None)
    if name == "rocq_info":
        return safe(info, f)
    return "unknown tool " + name, True


def mcp():
    """MCP over stdio: newline-delimited JSON-RPC 2.0. Calls run in threads
    (a session serialises its own requests), so one slow goto does not block
    work on another file."""
    global VIA
    VIA = "mcp"
    lock = threading.Lock()

    def send(obj):
        with lock:
            sys.stdout.write(json.dumps(obj) + "\n")
            sys.stdout.flush()

    def handle(msg):
        mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {}
        if mid is None:
            return                                # a notification
        if method == "initialize":
            result = {"protocolVersion": params.get("protocolVersion", "2025-06-18"),
                      "capabilities": {"tools": {}},
                      "serverInfo": {"name": "rocq-live", "version": VERSION},
                      "instructions": "Live Rocq proof sessions. Use rocq_goto to see the "
                      "goal at a line (edit the file, then rocq_goto again: only the change "
                      "is re-checked), rocq_run/rocq_back to try tactics, rocq_query for "
                      "Search/Check/Print. To know whether a whole file compiles, use "
                      "rocq_check (coqc's verdict, re-checking only what changed) instead of "
                      "running coqc; rocq_compile writes the .vo when other files need it."}
        elif method == "tools/list":
            result = {"tools": tool_list()}
        elif method == "tools/call":
            text, err = call_tool(params.get("name"), params.get("arguments") or {})
            result = {"content": [{"type": "text", "text": text}], "isError": bool(err)}
        elif method == "ping":
            result = {}
        else:
            send({"jsonrpc": "2.0", "id": mid,
                  "error": {"code": -32601, "message": "method not found: %s" % method}})
            return
        send({"jsonrpc": "2.0", "id": mid, "result": result})

    last = {}

    def ordered(msg, prev, done):
        for ev in prev:
            ev.wait()
        try:
            handle(msg)
        finally:
            done.set()

    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            msg = json.loads(line)
        except ValueError:
            send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
            continue
        # calls on one file run in arrival order (each waits for the previous
        # one on that file); calls on other files run in parallel
        f = ((msg.get("params") or {}).get("arguments") or {}).get("file")
        key = os.path.realpath(os.path.expanduser(f)) if isinstance(f, str) and f else None
        # a call without a file (sessions, stop all) waits for every earlier call
        done = threading.Event()
        prev = [last[key]] if key in last else []
        if key is None:
            prev = list(last.values())
        if key and "*" in last:
            prev.append(last["*"])
        last[key or "*"] = done
        threading.Thread(target=ordered, args=(msg, prev, done), daemon=True).start()
    for ev in list(last.values()):        # stdin closed: answer what is in flight
        ev.wait()
    return 0


# ---------------------------------------------------------- CLI

def split_file_line(args):
    """FILE:LINE or FILE [LINE]."""
    f, rest = args[0], args[1:]
    m = re.match(r"^(.*\.v):(\d+)$", f)
    if m:
        return m.group(1), int(m.group(2)), rest
    if rest and rest[0].isdigit():
        return f, int(rest[0]), rest[1:]
    return f, 0, rest


def main(argv):
    if os.environ.get(ECHO_ENV):                  # we are dune's --toplevel
        print(ECHO_TAG + json.dumps(argv))
        return 0
    if argv[:1] == ["_serve"] and len(argv) == 4:
        serve(argv[1], argv[2], argv[3]); return 0
    usage = __doc__.split("\n\n")[1]
    if not argv or argv[0] in ("-h", "--help", "help"):
        print(__doc__); return 0
    cmd, args = argv[0], argv[1:]
    if cmd == "mcp":
        return mcp()
    if cmd in ("list", "sessions"):
        out, err = safe(sessions)
    elif cmd == "gc":
        out, err = safe(collect)
    elif cmd == "stats":
        since, rest = "all", list(args)
        if "--since" in rest:
            i = rest.index("--since")
            if i + 1 >= len(rest):
                print(usage, file=sys.stderr); return 2
            since = rest[i + 1]
            del rest[i:i + 2]
        if len(rest) > 1:
            print(usage, file=sys.stderr); return 2
        out, err = safe(stats, since, rest[0] if rest else None)
    elif cmd == "try" and len(args) >= 2:
        f, line, _ = split_file_line(args[:1])
        out, err = safe(try_, f, args[1:], line or None)
    elif cmd == "audit" and args:
        names, allow, rest = [], [], args[1:]
        while rest:
            if rest[0] == "--allow" and len(rest) > 1:
                allow += rest[1].replace(",", " ").split(); rest = rest[2:]
            else:
                names.append(rest[0]); rest = rest[1:]
        out, err = safe(audit, args[0], names, allow)
    elif cmd == "check" and args:
        opts = {"--allow-stale", "--rebuild", "--all-errors"}
        rest = [x for x in args if x not in opts]
        if len(rest) != 1:
            print(usage, file=sys.stderr); return 2
        out, err = safe(check, rest[0], "--allow-stale" in args, "--rebuild" in args, "--all-errors" in args)
    elif cmd == "compile" and args:
        rest = [x for x in args if x != "--deps-only"]
        if len(rest) != 1:
            print(usage, file=sys.stderr); return 2
        out, err = safe(compile_, rest[0], "--deps-only" in args)
    elif cmd == "impact" and len(args) == 1:
        out, err = safe(impact, args[0])
    elif cmd in ("start", "goto") and args:
        full = "--full" in args
        f, line, rest = split_file_line([x for x in args if x != "--full"])
        if rest:
            print(usage, file=sys.stderr); return 2
        out, err = safe(start if cmd == "start" else goto, f, line, full)
    elif cmd in ("run", "query") and len(args) == 2:
        f, line, _ = split_file_line(args[:1])
        out, err = safe(run if cmd == "run" else query, f, args[1], line or None)
    elif cmd == "back" and len(args) in (1, 2):
        out, err = safe(back, args[0], int(args[1]) if len(args) == 2 else 1)
    elif cmd in ("goals", "stop", "info") and len(args) == 1:
        out, err = safe({"goals": goals, "stop": stop, "info": info}[cmd], args[0])
    elif cmd == "--version":
        out, err = "rocq-live " + VERSION, False
    else:
        print(usage, file=sys.stderr); return 2
    print(out)
    return int(err) if err else 0       # check: 2 = not checked


def entry():
    """Console-script entry point (pip/uv install)."""
    sys.exit(main(sys.argv[1:]))


if __name__ == "__main__":
    entry()
