#!/usr/bin/env python3
"""
Standard Autonomous Long-Running Session Runner (v2.0)
Complies with Council Session Continuity Protocol v1.4 (12 Normative Rules & 18 Acceptance Gates).
100% config-driven, single-instance flock, two-phase journal-before-cursor, exact ack,
purpose-bound outbound ledger, value-aware canary scan, and pinned client verification.
"""
import argparse
import fcntl
import hashlib
import json
import os
import re
import secrets
import stat
import subprocess
import sys
import time
from pathlib import Path

DEFAULT_CONFIG = {
    "agent_slot": "",
    "agent_id": "",
    "target_room": "COMMONS",
    "required_data_class": "SYNTHETIC_PUBLIC_ONLY",
    "client_path": "arc_agent_client.py",
    "client_expected_sha256": "",
    "session_file": ".arc-session-v1.json",
    "cursor_file": "CURSOR",
    "state_file": "runner_state.json",
    "inbox_file": "events_log.jsonl",
    "events_log_file": "events_log.jsonl",
    "lock_file": ".runner.lock",
    "max_cycles_cap": 2147483647,
    "requested_cycles": 2,
    "cycles_per_invocation": 2,
    "budget_seconds": 170,
    "min_cycle_seconds": 0,
    "max_poll_wait_seconds": 300,
    "safety_margin_seconds": 0,
    "sub_polls_per_cycle": 4,
    "poll_wait_seconds": 10,
    "client_call_overhead_seconds": 0,
    "quiet_sleep_seconds": 45,
    "cycle_overhead_seconds": 5,
    "transient_retries": 1,
    "transient_backoff_seconds": 0,
    "owner_senders": ["OWNER"],
    "host_sender_prefixes": ["dj_host"],
    "status_keywords": ["STATUS"],
    "stop_keywords": ["STOP_PILOT"],
    "canary_patterns": [
        r"BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE\s+KEY",
        r"(?:enrollment[_-]?code|master[_-]?key|session[_-]?key)\s*[:=]\s*['\"]?(?!<|REDACTED|MASKED|NONE|NULL)[A-Za-z0-9+/=_-]{3,}",
        r"bot\d+:[A-Za-z0-9_-]{20,}",
    ],
}

BARE_FIELD_KEYWORDS = {
    "enrollment_code",
    "enrollment-code",
    "master_key",
    "master-key",
    "session_key",
    "session-key",
}


class ContinuityBlockedError(RuntimeError):
    pass


class SecurityStopError(RuntimeError):
    pass


MAX_SILENT_PROGRESS_LINE_BYTES = 200


def format_silent_progress_line(cycle_k: int, max_cap: int, seqs_str: str, cursor_val: int, delivery_val: str) -> str:
    line = f"cycle {cycle_k}/{max_cap}: {seqs_str} | cursor={cursor_val} | delivery={delivery_val}"
    raw = line.encode("utf-8")
    if len(raw) > MAX_SILENT_PROGRESS_LINE_BYTES:
        line = raw[: MAX_SILENT_PROGRESS_LINE_BYTES - 3].decode("utf-8", errors="ignore") + "..."
    return line


def decide_next_turn_step(
    batch_outcome: str,
    continuation_active: bool = True,
    stop_condition_hit: bool = False,
    turn_budget_exhausted: bool = False,
) -> str:
    if stop_condition_hit or turn_budget_exhausted or not continuation_active:
        return "ATOMIC_CHECKPOINT_AND_FINAL_REPORT"
    norm = str(batch_outcome or "").strip().lower()
    if norm in ("empty_poll", "action_handled", "commons_report_posted", "silent_batch_completed"):
        return "NEXT_TOOL_CALL"
    if norm in ("action_event", "pending_action_replayed"):
        return "HANDLE_ACTION_THEN_NEXT_TOOL_CALL"
    return "NEXT_TOOL_CALL"


def update_local_lease_state(st: dict, phase: str, call_id: str, expected_ttl_seconds: int) -> None:
    st["lease_state"] = {
        "phase": str(phase),
        "call_id": str(call_id),
        "cursor": int(st.get("cursor", 0)),
        "cycle_count": int(st.get("cycle_count", 0)),
        "expected_ttl_seconds": int(expected_ttl_seconds),
        "semantics": "LOCAL_DIAGNOSTIC_ONLY_SERVER_POLL_LEASE_AUTHORITATIVE",
    }


def record_early_exit_incident(
    cfg: dict,
    st: dict,
    occurred_at: str,
    activity_before: str,
    root_cause: str,
    prevention: str,
    incident_class: str = "DEFECT",
) -> None:
    inc_path = Path(str(cfg.get("incident_log_file") or "early_exit_incident_log.jsonl"))
    rec = {
        "occurred_at": str(occurred_at),
        "activity_before": str(activity_before),
        "root_cause": str(root_cause),
        "prevention": str(prevention),
        "incident_class": str(incident_class),
        "cursor": int(st.get("cursor", 0)),
        "pending_actions_count": len(st.get("pending_actions", [])),
    }
    line_str = json.dumps(rec, ensure_ascii=False) + "\n"
    check_canary_text(cfg, line_str)
    existing = b""
    if inc_path.exists():
        preflight_private_file(inc_path, must_exist=True)
        existing = inc_path.read_bytes()
    atomic_write_private_bytes(inc_path, existing + line_str.encode("utf-8"))


def emit_tool_heartbeat(cfg: dict, st: dict, phase: str = "BEFORE_BATCH") -> tuple[int, dict]:
    slot = str(cfg.get("agent_slot") or "SLOT")
    aid = str(cfg.get("agent_id") or "AGENT")
    cur = int(st.get("cursor", 0))
    cyc = int(st.get("cycle_count", 0))
    pend = len(st.get("pending_actions", []))
    nonce = int(st.get("msg_nonce_seq", 0)) + 1
    txt = f"♥ HB slot={slot} agent_id={aid} phase={phase} cursor={cur} cycle={cyc} pending={pend}"
    purpose = f"hb:{aid}:{phase}:{nonce}:{cur}:{cyc}:{time.monotonic_ns()}"
    return post_message(cfg, st, txt, purpose=purpose)


def emit_pre_exit_notice(cfg: dict, st: dict, reason_enum: str = "turn_boundary_self_yield") -> tuple[int, dict]:
    slot = str(cfg.get("agent_slot") or "SLOT")
    aid = str(cfg.get("agent_id") or "AGENT")
    cur = int(st.get("cursor", 0))
    cyc = int(st.get("cycle_count", 0))
    pend = len(st.get("pending_actions", []))
    txt = (
        f"schema=ARC_PRE_EXIT_NOTICE_V1 | slot={slot} | agent_id={aid} | "
        f"reason_enum={reason_enum} | durable_cursor={cur} | cycle_count={cyc} | pending_actions_left={pend}"
    )
    purpose = f"exit_notice:{aid}:{cur}:{cyc}:{reason_enum}:{time.monotonic_ns()}"
    return post_message(cfg, st, txt, purpose=purpose)



def preflight_workspace_dir(d: Path) -> None:
    st = d.lstat()
    if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
        raise SecurityStopError(f"S0.X: workspace {d} is not a real directory")
    if st.st_uid != os.getuid():
        raise SecurityStopError(f"S0.X: workspace {d} uid mismatch")
    if (st.st_mode & 0o777) != 0o700:
        os.chmod(d, 0o700)
        print(f"PERMISSION_REPAIR_PASS: {d.name} -> 0700", flush=True)


def preflight_private_file(p: Path, must_exist: bool = True) -> None:
    if not p.exists() and not p.is_symlink():
        if must_exist:
            raise ContinuityBlockedError(f"S0.X: missing required private file {p}")
        return
    st = p.lstat()
    if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
        raise SecurityStopError(f"S0.X: {p} is symlink or non-regular file")
    if st.st_nlink != 1 or st.st_uid != os.getuid():
        raise SecurityStopError(f"S0.X: {p} hardlink count ({st.st_nlink}) or uid mismatch")
    if (st.st_mode & 0o777) != 0o600:
        os.chmod(p, 0o600)
        print(f"PERMISSION_REPAIR_PASS: {p.name} -> 0600", flush=True)


def atomic_write_private_bytes(p: Path, data: bytes, crash_hook=None) -> None:
    parent = p.parent.resolve()
    preflight_workspace_dir(parent)
    if p.exists() or p.is_symlink():
        preflight_private_file(p, must_exist=True)
    tmp_name = f".tmp.{p.name}.{os.getpid()}.{time.monotonic_ns()}"
    tmp_path = parent / tmp_name
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
    fd = os.open(str(tmp_path), flags, 0o600)
    try:
        view = memoryview(data)
        total = 0
        while total < len(view):
            written = os.write(fd, view[total:])
            if written <= 0:
                raise OSError(f"short write on {tmp_path}")
            total += written
        os.fsync(fd)
    except Exception:
        try:
            os.close(fd)
        except Exception:
            pass
        try:
            os.unlink(str(tmp_path))
        except Exception:
            pass
        raise
    os.close(fd)
    if callable(crash_hook):
        crash_hook("before_replace", p, tmp_path)
    os.replace(str(tmp_path), str(p))
    dir_fd = os.open(str(parent), os.O_RDONLY)
    try:
        os.fsync(dir_fd)
    finally:
        os.close(dir_fd)
    preflight_private_file(p, must_exist=True)


def acquire_single_instance_lock(lock_path: Path) -> int:
    parent = lock_path.parent.resolve()
    preflight_workspace_dir(parent)
    if lock_path.exists() or lock_path.is_symlink():
        preflight_private_file(lock_path, must_exist=True)
    flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
    fd = os.open(str(lock_path), flags, 0o600)
    st = os.fstat(fd)
    if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1 or st.st_uid != os.getuid():
        os.close(fd)
        raise SecurityStopError(f"S0.X: invalid lock file {lock_path}")
    if (st.st_mode & 0o777) != 0o600:
        os.fchmod(fd, 0o600)
        print(f"PERMISSION_REPAIR_PASS: {lock_path.name} -> 0600", flush=True)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(fd)
        raise ContinuityBlockedError("SINGLE_INSTANCE_LOCKED: another runner instance holds lock")
    os.ftruncate(fd, 0)
    os.write(fd, f"{os.getpid()}\n".encode("utf-8"))
    os.fsync(fd)
    return fd


KNOWN_CONFIG_KEYS = set(DEFAULT_CONFIG.keys()) | {
    "worst_case_cycle_seconds",
    "usable_budget_seconds",
    "effective_cycles",
    "min_cycle_seconds",
    "max_poll_wait_seconds",
    "incident_log_file",
    "enable_pre_exit_notice",
    "heartbeat_enabled",
    "skip_sequences",
    "skip_authority_seq",
}


def compute_budget_plan(cfg: dict) -> dict:
    merged = dict(DEFAULT_CONFIG)
    merged.update(cfg)
    if "min_cycle_seconds" in cfg and int(cfg.get("min_cycle_seconds") or 0) > 0:
        merged["quiet_sleep_seconds"] = max(int(merged.get("quiet_sleep_seconds", 0)), int(cfg["min_cycle_seconds"]))
    retries = max(1, int(merged.get("transient_retries", 1)))
    backoff = max(0, int(merged.get("transient_backoff_seconds", 0)))
    call_ovh = max(3, int(merged.get("client_call_overhead_seconds", 3)))
    sub_polls = max(1, int(merged.get("sub_polls_per_cycle", 4)))
    wait_s = max(1, int(merged.get("poll_wait_seconds", 10)))
    max_wait_s = int(merged.get("max_poll_wait_seconds", 300))
    if wait_s > max_wait_s:
        raise SecurityStopError(f"INVALID_CONFIG: poll_wait_seconds={wait_s} exceeds max_poll_wait_seconds={max_wait_s}")
    q_sleep = max(0, int(merged.get("quiet_sleep_seconds", 45)))
    cyc_ovh = max(0, int(merged.get("cycle_overhead_seconds", 5)))

    health_worst = retries * call_ovh + max(0, retries - 1) * backoff
    single_poll_worst = retries * (wait_s + call_ovh) + max(0, retries - 1) * backoff
    polls_worst = sub_polls * single_poll_worst
    worst_case_cycle = max(1, health_worst + polls_worst + q_sleep + cyc_ovh)

    budget = int(merged.get("budget_seconds", 210))
    margin = int(merged.get("safety_margin_seconds", 0))
    usable = budget - margin
    if usable < worst_case_cycle:
        raise ContinuityBlockedError(
            f"BUDGET_BELOW_WORST_CASE: usable={usable}s (budget={budget}s - margin={margin}s) < worst_case_cycle={worst_case_cycle}s"
        )
    req_cycles = int(merged.get("requested_cycles", merged.get("cycles_per_invocation", 2)))
    req_cycles = max(1, req_cycles)
    effective_cycles = min(req_cycles, usable // worst_case_cycle)
    merged["worst_case_cycle_seconds"] = worst_case_cycle
    merged["usable_budget_seconds"] = usable
    merged["effective_cycles"] = effective_cycles
    return merged


def load_config(config_path: Path, args=None, cli_overrides: dict | None = None) -> dict:
    cfg = dict(DEFAULT_CONFIG)
    if config_path.exists() or config_path.is_symlink():
        preflight_private_file(config_path, must_exist=True)
        raw = json.loads(config_path.read_text(encoding="utf-8"))
        if isinstance(raw, dict):
            unk = set(raw.keys()) - KNOWN_CONFIG_KEYS
            if unk:
                raise SecurityStopError(f"INVALID_CONFIG: unknown config keys {sorted(unk)}")
            cfg.update(raw)
    for env_key, cfg_key, cast in (
        ("AGENT_SLOT", "agent_slot", str),
        ("AGENT_ID", "agent_id", str),
        ("ARC_CLIENT_SHA256", "client_expected_sha256", str),
        ("RUNNER_CYCLES", "requested_cycles", int),
        ("RUNNER_BUDGET_SECONDS", "budget_seconds", int),
    ):
        val = os.environ.get(env_key)
        if val is not None and str(val).strip() != "":
            cfg[cfg_key] = cast(val.strip())
    if args is not None:
        if getattr(args, "cycles", None) is not None:
            cfg["requested_cycles"] = int(args.cycles)
            cfg["cycles_per_invocation"] = int(args.cycles)
        if getattr(args, "budget_seconds", None) is not None:
            cfg["budget_seconds"] = int(args.budget_seconds)
    if cli_overrides:
        for k, v in cli_overrides.items():
            if v is not None:
                cfg[k] = v
    if cfg.get("skip_sequences") or cfg.get("skip_authority_seq") is not None:
        _skip_pair_from_cfg(cfg)
    for pat in cfg.get("canary_patterns", []):
        s_pat = str(pat or "").strip()
        if s_pat.lower() in BARE_FIELD_KEYWORDS or re.fullmatch(r"[A-Za-z0-9_-]+", s_pat):
            raise SecurityStopError(
                f"INVALID_CONFIG: bare credential field canary {s_pat!r} must be rejected at config load"
            )
    return compute_budget_plan(cfg)


def verify_pinned_client(cfg: dict) -> Path:
    expected = str(cfg.get("client_expected_sha256") or "").strip().lower()
    if not re.fullmatch(r"[0-9a-f]{64}", expected):
        raise SecurityStopError("CLIENT_PIN_MISSING: client_expected_sha256 must be an explicit 64-hex SHA256")
    cpath = Path(str(cfg.get("client_path") or "arc_agent_client.py"))
    preflight_private_file(cpath, must_exist=True)
    actual = hashlib.sha256(cpath.read_bytes()).hexdigest().lower()
    if actual != expected:
        raise SecurityStopError(f"CLIENT_PIN_MISMATCH: expected {expected}, got {actual}")
    return cpath


def load_and_reconcile_state(cfg: dict) -> dict:
    sfile = Path(str(cfg.get("state_file") or "runner_state.json"))
    cfile = Path(str(cfg.get("cursor_file") or "CURSOR"))
    has_state_file = sfile.exists() or sfile.is_symlink()
    if has_state_file:
        preflight_private_file(sfile, must_exist=True)
        st = json.loads(sfile.read_text(encoding="utf-8"))
        state_cur = int(st.get("cursor", 0))
        jcur = int(st.get("journal_cursor", state_cur))
        if state_cur > jcur:
            raise ContinuityBlockedError(
                f"CURSOR_AHEAD_OF_JOURNAL: state cursor={state_cur} > journal_cursor={jcur}"
            )
        if cfile.exists() or cfile.is_symlink():
            preflight_private_file(cfile, must_exist=True)
            ctxt = cfile.read_text(encoding="utf-8").strip()
            if ctxt.isdigit():
                disk_cur = int(ctxt)
                if disk_cur > jcur:
                    raise ContinuityBlockedError(
                        f"CURSOR_AHEAD_OF_JOURNAL: disk cursor={disk_cur} > journal_cursor={jcur}"
                    )
        if jcur > state_cur:
            st["cursor"] = jcur
        else:
            st["journal_cursor"] = state_cur
    else:
        cur = 0
        if cfile.exists() or cfile.is_symlink():
            preflight_private_file(cfile, must_exist=True)
            txt = cfile.read_text(encoding="utf-8").strip()
            if txt.isdigit():
                cur = int(txt)
        st = {
            "cycle_count": 0,
            "session_start_ts": int(time.time()),
            "last_outbound_ts": 0,
            "last_receipt_seq": cur,
            "last_delivery": "—",
            "cursor": cur,
            "journal_cursor": cur,
            "msg_nonce_seq": 0,
            "pending_actions": [],
            "handled_action_seqs": [],
            "outbound_ledger": {},
            "used_idempotency_keys": [],
        }
    st.setdefault("msg_nonce_seq", 0)
    st.setdefault("pending_actions", [])
    st.setdefault("handled_action_seqs", [])
    st.setdefault("outbound_ledger", {})
    st.setdefault("used_idempotency_keys", [])
    save_state_and_cursor(cfg, st)
    return st


load_state = load_and_reconcile_state


def save_journal_state_only(cfg: dict, st: dict, crash_hook=None) -> None:
    sfile = Path(str(cfg.get("state_file") or "runner_state.json"))
    atomic_write_private_bytes(
        sfile, json.dumps(st, indent=2, sort_keys=True).encode("utf-8"), crash_hook=crash_hook
    )


def save_state_and_cursor(cfg: dict, st: dict, crash_hook=None) -> None:
    sfile = Path(str(cfg.get("state_file") or "runner_state.json"))
    cfile = Path(str(cfg.get("cursor_file") or "CURSOR"))
    atomic_write_private_bytes(
        sfile, json.dumps(st, indent=2, sort_keys=True).encode("utf-8"), crash_hook=crash_hook
    )
    atomic_write_private_bytes(
        cfile, f"{int(st['cursor'])}\n".encode("utf-8"), crash_hook=crash_hook
    )


save_state = save_state_and_cursor


def _compile_effective_canary_regex(pat: str) -> re.Pattern:
    clean = str(pat).strip()
    if clean.lower() in BARE_FIELD_KEYWORDS or re.fullmatch(r"[A-Za-z0-9_-]+", clean):
        # A bare field identifier must only match when paired with an assignment/value, not benign discussion of the field name
        expr = rf"{re.escape(clean)}\s*[:=]\s*['\"]?(?!<|REDACTED|MASKED|NONE|NULL)[A-Za-z0-9+/=_-]{{3,}}"
        return re.compile(expr, re.IGNORECASE)
    return re.compile(clean, re.IGNORECASE)


def check_canary_text(cfg: dict, text: str) -> None:
    for pat in cfg.get("canary_patterns", DEFAULT_CONFIG["canary_patterns"]):
        rx = _compile_effective_canary_regex(str(pat))
        if rx.search(text):
            raise SecurityStopError(f"P0_CANARY_TRIGGERED: matched pattern {pat}")


def classify_event(cfg: dict, ev: dict) -> str:
    req_dc = str(cfg.get("required_data_class") or "SYNTHETIC_PUBLIC_ONLY")
    if ev.get("data_class") != req_dc:
        raise SecurityStopError(f"DATA_CLASS_VIOLATION: expected {req_dc}, got {ev.get('data_class')}")
    sender = str(ev.get("sender") or ev.get("agent_id") or "")
    text = str(ev.get("text") or "")
    check_canary_text(cfg, sender)
    check_canary_text(cfg, text)

    slot = str(cfg.get("agent_slot") or "").strip()
    aid = str(cfg.get("agent_id") or "").strip()
    if (aid and sender == aid) or (slot and sender.startswith(slot)):
        return "SELF"
    owner_set = {str(s).upper() for s in cfg.get("owner_senders", ["OWNER"])}
    is_owner = sender.upper() in owner_set
    is_host = any(
        pref and sender.lower().startswith(str(pref).lower())
        for pref in cfg.get("host_sender_prefixes", ["dj_host"])
    )
    if is_owner or is_host:
        first_line = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
        first_cmd = re.sub(r"^(?:(?:【[^】]{1,40}】|\[[^\]]{1,40}\])\s*)*(?:最高執行指示[\s:：—-]*)*(?:owner[\s:：—-]*)*", "", first_line, flags=re.IGNORECASE).strip()
        for kw in cfg.get("stop_keywords", ["STOP_PILOT"]):
            if kw and re.match(rf"^{re.escape(str(kw))}(?:\b|[\s:：!！,，。]|$)", first_cmd, re.IGNORECASE):
                return "STOP_PILOT"
        for skw in cfg.get("status_keywords", ["STATUS"]):
            if skw and re.match(rf"^{re.escape(str(skw))}(?:\b|[\s:：!！,，。]|$)", first_cmd, re.IGNORECASE):
                return "STATUS"
        return "OWNER_MSG" if is_owner else "HOST_MSG"
    slot = str(cfg.get("agent_slot") or "").strip()
    aid = str(cfg.get("agent_id") or "").strip()
    if (slot and f"@{slot}" in text) or (aid and f"@{aid}" in text):
        return "PEER_MENTION"
    if re.match(r"^(?:\[[^\]]{1,40}\]\s*)?♥\s+HB\b", text.strip()):
        return "PEER_HEARTBEAT"
    return "PEER_OTHER"


def append_to_safe_inbox(cfg: dict, safe_events: list[dict]) -> None:
    log_path_str = str(cfg.get("events_log_file") or cfg.get("inbox_file") or "events_log.jsonl")
    paths = {Path(log_path_str)}
    if cfg.get("inbox_file"):
        paths.add(Path(str(cfg["inbox_file"])))
    rows = []
    for ev in safe_events:
        rec = {
            "sequence": int(ev["sequence"]),
            "room_id": str(ev.get("room_id") or "COMMONS"),
            "data_class": str(ev.get("data_class") or "SYNTHETIC_PUBLIC_ONLY"),
            "sender": str(ev.get("sender") or ""),
            "sha12": str(ev.get("event_sha256") or "")[:12],
            "event_sha256": str(ev.get("event_sha256") or ""),
            "head150": str(ev.get("text") or "")[:150],
            "text": str(ev.get("text") or ""),
        }
        rows.append(json.dumps(rec, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n")
    payload = b"".join(rows)
    for ifile in paths:
        existing = b""
        if ifile.exists() or ifile.is_symlink():
            preflight_private_file(ifile, must_exist=True)
            existing = ifile.read_bytes()
        atomic_write_private_bytes(ifile, existing + payload)


def invoke_client(cfg: dict, args_list: list[str], deadline: float) -> tuple[int, dict, str]:
    sess = Path(str(cfg.get("session_file") or ".arc-session-v1.json"))
    preflight_private_file(sess, must_exist=True)
    cpath = verify_pinned_client(cfg)
    retries = max(1, int(cfg.get("transient_retries", 1)))
    backoff = max(0, int(cfg.get("transient_backoff_seconds", 0)))
    call_ovh = max(3, int(cfg.get("client_call_overhead_seconds", 3)))
    wait_s = int(cfg.get("poll_wait_seconds", 10)) if "poll" in " ".join(args_list) else 0
    per_call_timeout = float(wait_s + call_ovh)
    last_err = ""

    for attempt in range(1, retries + 1):
        rem = deadline - time.monotonic()
        if rem <= 0.5:
            return 0, {"reason": "DEADLINE_EXCEEDED"}, "deadline reached"
        cmd = ["python3", "-B", str(cpath)] + args_list
        try:
            res = subprocess.run(
                cmd, capture_output=True, text=True, timeout=min(per_call_timeout, max(1.0, rem))
            )
        except subprocess.TimeoutExpired:
            last_err = "subprocess timeout"
            return 0, {"reason": "SUBPROCESS_TIMEOUT"}, last_err

        last_err = (res.stderr or "").strip()
        out = (res.stdout or "").strip()
        if args_list[0] == "health":
            if res.returncode == 0:
                return 200, {"ok": True}, ""
            if "401" in last_err or "403" in last_err or "401" in out or "403" in out:
                raise ContinuityBlockedError(f"CONTINUITY_BLOCKED: health auth error: {last_err or out}")
        elif out:
            try:
                data = json.loads(out)
                http_status = int(data.get("http_status", 0))
                resp_obj = data.get("response", {})
                if http_status in (401, 403):
                    raise ContinuityBlockedError(
                        f"CONTINUITY_BLOCKED: HTTP {http_status} on {args_list[:3]}"
                    )
                if 500 <= http_status < 600 and attempt < retries:
                    sleep_s = min(float(backoff), max(0.0, deadline - time.monotonic() - 0.5))
                    if sleep_s > 0:
                        time.sleep(sleep_s)
                    continue
                return http_status, resp_obj, last_err
            except ContinuityBlockedError:
                raise
            except Exception:
                pass
        if attempt < retries:
            sleep_s = min(float(backoff), max(0.0, deadline - time.monotonic() - 0.5))
            if sleep_s > 0:
                time.sleep(sleep_s)
    return 0, {"reason": "TRANSIENT_EXHAUSTED"}, last_err


def mark_action_handled(cfg: dict, st: dict, ack_seq: int, cumulative: bool = False) -> None:
    ack_i = int(ack_seq)
    handled = set(int(x) for x in st.get("handled_action_seqs", []))
    if cumulative:
        for item in st.get("pending_actions", []):
            seq_v = int(item.get("sequence", -1))
            if 0 <= seq_v <= ack_i:
                handled.add(seq_v)
        st["pending_actions"] = [
            item for item in st.get("pending_actions", []) if int(item.get("sequence", 0)) > ack_i
        ]
    else:
        pending_list = st.get("pending_actions", [])
        pending_seqs = {int(item.get("sequence", -1)) for item in pending_list}
        if ack_i in handled and ack_i not in pending_seqs:
            return
        if ack_i not in pending_seqs:
            raise ContinuityBlockedError(
                f"CONTINUITY_BLOCKED: exact ack sequence {ack_i} is neither pending nor already handled"
            )
        handled.add(ack_i)
        st["pending_actions"] = [
            item for item in pending_list if int(item.get("sequence", -1)) != ack_i
        ]
    st["handled_action_seqs"] = sorted(handled)
    save_state_and_cursor(cfg, st)


def post_message(
    cfg: dict, st: dict, text: str, purpose: str, ack_seq: int | None = None, deadline: float | None = None
) -> tuple[int, dict]:
    check_canary_text(cfg, text)
    if deadline is None:
        deadline = time.monotonic() + float(cfg.get("usable_budget_seconds", cfg.get("budget_seconds", 210)))
    body_sha256 = hashlib.sha256(text.encode("utf-8")).hexdigest()
    ledger = st.setdefault("outbound_ledger", {})
    used_keys = set(st.setdefault("used_idempotency_keys", []))

    if purpose in ledger:
        entry = ledger[purpose]
        if entry.get("body_sha256") != body_sha256 or entry.get("ack_seq") != ack_seq:
            raise SecurityStopError(
                f"IDEMPOTENCY_PURPOSE_MISMATCH: purpose={purpose!r} bound to different body_sha256 or ack_seq"
            )
        if entry.get("status") == "ACCEPTED_201":
            if ack_seq is not None:
                mark_action_handled(cfg, st, ack_seq, cumulative=False)
            return 201, dict(entry.get("response") or {})
        if entry.get("status") == "UNCERTAIN_TRANSPORT":
            raise ContinuityBlockedError(
                f"OUTBOUND_UNCERTAIN_RECONCILE_REQUIRED: purpose={purpose} key={entry.get('idempotency_key')}"
            )
        idem_key = str(entry["idempotency_key"])
    else:
        st["msg_nonce_seq"] = int(st.get("msg_nonce_seq", 0)) + 1
        nonce = st["msg_nonce_seq"]
        while True:
            cand = secrets.token_hex(16)
            if cand not in used_keys:
                idem_key = cand
                break
        used_keys.add(idem_key)
        st["used_idempotency_keys"] = sorted(used_keys)
        ledger[purpose] = {
            "purpose": purpose,
            "nonce": nonce,
            "body_sha256": body_sha256,
            "idempotency_key": idem_key,
            "status": "PENDING",
            "ack_seq": ack_seq,
            "created_ts": int(time.time()),
        }
        save_state_and_cursor(cfg, st)

    body = {
        "room_id": str(cfg.get("target_room") or "COMMONS"),
        "data_class": str(cfg.get("required_data_class") or "SYNTHETIC_PUBLIC_ONLY"),
        "text": text,
        "idempotency_key": idem_key,
    }
    tmp_body = Path(f".tmp.msg.{os.getpid()}.{time.monotonic_ns()}.json")
    try:
        atomic_write_private_bytes(
            tmp_body,
            json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8"),
        )
        status, resp, _ = invoke_client(
            cfg, ["request", "POST", "/v1/messages", "--body", str(tmp_body)], deadline
        )
        if status == 201 and isinstance(resp, dict):
            r_seq = resp.get("sequence") if resp.get("sequence") is not None else resp.get("seq")
            delivery = str(resp.get("telegram_delivery") or "UNKNOWN")
            ledger[purpose]["status"] = "ACCEPTED_201"
            ledger[purpose]["http_status"] = 201
            ledger[purpose]["receipt_sequence"] = int(r_seq) if r_seq is not None else None
            ledger[purpose]["telegram_delivery"] = delivery
            ledger[purpose]["response"] = resp
            if r_seq is not None:
                st["last_receipt_seq"] = int(r_seq)
            st["last_outbound_ts"] = int(time.time())
            st["last_delivery"] = delivery
            if ack_seq is not None:
                mark_action_handled(cfg, st, ack_seq, cumulative=False)
            else:
                save_state_and_cursor(cfg, st)
            return 201, resp
        ledger[purpose]["status"] = "UNCERTAIN_TRANSPORT"
        ledger[purpose]["http_status"] = int(status)
        save_state_and_cursor(cfg, st)
        raise ContinuityBlockedError(
            f"OUTBOUND_UNCERTAIN_RECONCILE_REQUIRED: HTTP {status} for purpose={purpose}"
        )
    finally:
        if tmp_body.exists():
            try:
                tmp_body.unlink()
            except Exception:
                pass


AUTHORISED_SKIP_SEQS = (61748,)
AUTHORISED_SKIP_AUTHORITY = 61990


def _skip_pair_from_cfg(cfg: dict) -> list:
    """INV-1/2/3: validate the authorised skip pair. Pure config check, safe to call at load time so a
    bad config fails closed even when the poll returns no events (A28 62055 CASE-34)."""
    raw = cfg.get("skip_sequences")
    if raw in (None, "", [], ()):
        return []
    if not isinstance(raw, (list, tuple)):
        raise SecurityStopError("INVALID_CONFIG: skip_sequences must be a JSON list of integers")
    out = []
    for item in raw:
        if isinstance(item, bool) or not isinstance(item, int) or int(item) <= 0:
            raise SecurityStopError("INVALID_CONFIG: skip_sequences entry %r is not a positive int" % (item,))
        out.append(int(item))
    authority = cfg.get("skip_authority_seq")
    if isinstance(authority, bool) or not isinstance(authority, int) or int(authority) <= 0:
        raise SecurityStopError("INVALID_CONFIG: skip_sequences requires explicit skip_authority_seq (host ruling seq)")
    if tuple(sorted(set(out))) != tuple(AUTHORISED_SKIP_SEQS) or int(authority) != int(AUTHORISED_SKIP_AUTHORITY):
        raise SecurityStopError(
            "SKIP_NOT_AUTHORISED: skip pair %s/%s is outside the baked-in authorisation %s/%s"
            % (sorted(set(out)), int(authority), list(AUTHORISED_SKIP_SEQS), AUTHORISED_SKIP_AUTHORITY)
        )
    return sorted(set(out))


def _parse_skip_config(cfg: dict, head_seq: int, cursor_seq: int) -> list:
    """Same validation as at load time; head/cursor are unused on purpose (pagination is decided by the
    three-state gate, so a seat that is still behind the target never self-locks)."""
    return _skip_pair_from_cfg(cfg)


def _logged_skip_seqs(st: dict) -> set:
    """Provenance already on disk (including legacy `skipped_seq`), integers > 0 only; never raises."""
    out = set()
    for rec in st.get("authorized_skip_log", []) or []:
        if not isinstance(rec, dict):
            continue
        for key_name in ("seq", "sequence", "skipped_seq"):
            if key_name not in rec:
                continue
            try:
                val = int(rec[key_name])
            except Exception:
                continue
            if val > 0:
                out.add(val)
    for key in ("skipped_sequences", "skipped_seqs", "skipped_seq"):
        val = st.get(key)
        if val is None:
            continue
        items = val if isinstance(val, (list, tuple)) else [val]
        for it in items:
            if isinstance(it, dict):
                it = it.get("seq", it.get("sequence", it.get("skipped_seq")))
            try:
                num = int(it)
            except Exception:
                continue
            if num > 0:
                out.add(num)
    return out


def _record_skip_provenance(cfg: dict, st: dict, skipped: list, head_seq: int) -> None:
    """INV-4: provenance is written before any cursor movement; the credential status stays UNRESOLVED."""
    if not skipped:
        return
    log = st.setdefault("authorized_skip_log", [])
    seen = set()
    for rec in log:
        if not isinstance(rec, dict):
            continue
        try:
            num = int(rec.get("seq", -1))
        except Exception:
            continue
        if num > 0:
            seen.add(num)
    now = int(time.time())
    for seq in skipped:
        if seq in seen:
            continue
        log.append(
            {
                "seq": int(seq),
                "authority_seq": int(cfg.get("skip_authority_seq")),
                "no_ingest": True,
                "no_copy": True,
                "no_transmit": True,
                "not_used_as_credential": True,
                "credential_status": "UNRESOLVED",
                "head_at_skip": int(head_seq),
                "ts": now,
            }
        )
    st["provenance_unresolved"] = True
    valid = set()
    for rec in log:
        if not isinstance(rec, dict):
            continue
        try:
            val = int(rec.get("seq", -1))
        except Exception:
            continue
        if val > 0:
            valid.add(val)
    st["skip_list_size"] = len(valid)


def _decimal_digits(token: str):
    """Canonical decimal digit string for any Unicode decimal spelling (full-width, Arabic-Indic, ...).
    Returns None when the token contains a non-decimal character. No int() conversion, so Python's
    int-from-string digit cap can never be hit (A20 62052/1)."""
    import unicodedata

    digits = []
    for ch in token:
        if ch in "+-":
            continue
        try:
            dig = unicodedata.decimal(ch, None)
        except Exception:
            dig = None
        if dig is None:
            return None
        digits.append(str(dig))
    if not digits:
        return None
    return "".join(digits).lstrip("0") or "0"


def _tokenize_decimals(text: str) -> list:
    """Tokenise decimal numbers using unicodedata.decimal per character: covers EVERY Unicode Nd block
    (Devanagari, Bengali, ...), not a hardcoded range list, and merges PEP-515 single underscores
    between digits ("61_748" == 61748). Returns canonical digit strings."""
    import unicodedata

    toks = []
    cur = []
    start = -1
    i = 0
    n = len(text)
    while i < n:
        ch = text[i]
        try:
            dig = unicodedata.decimal(ch, None)
        except Exception:
            dig = None
        if dig is not None:
            if not cur:
                start = i
            cur.append(str(dig))
            i += 1
            continue
        if cur and ch == "_" and i + 1 < n:
            try:
                nxt = unicodedata.decimal(text[i + 1], None)
            except Exception:
                nxt = None
            if nxt is not None:
                i += 1
                continue
        if not cur and ch in "+-" and i + 1 < n:
            try:
                nxt = unicodedata.decimal(text[i + 1], None)
            except Exception:
                nxt = None
            if nxt is not None:
                i += 1
                continue
        if cur:
            # A dangling underscore on either side means Python int() would reject the spelling,
            # so the token is not a sequence number at all (A87 62075 over-identification).
            if not (start > 0 and text[start - 1] == "_") and not (i < n and text[i] == "_"):
                toks.append("".join(cur).lstrip("0") or "0")
            cur = []
            start = -1
        i += 1
    if cur:
        if not (start > 0 and text[start - 1] == "_"):
            toks.append("".join(cur).lstrip("0") or "0")
    return toks


def _is_plain_decimal(text: str) -> bool:
    """True when the whole token is a plain decimal integer spelling: optional sign, Nd digits, and
    single underscores only between digits (PEP 515)."""
    import unicodedata

    body = text.strip()
    if body[:1] in ("+", "-"):
        body = body[1:]
    if not body or body.startswith("_") or body.endswith("_"):
        return False
    seen_digit = False
    prev_underscore = False
    for ch in body:
        if ch == "_":
            if prev_underscore or not seen_digit:
                return False
            prev_underscore = True
            continue
        try:
            dig = unicodedata.decimal(ch, None)
        except Exception:
            dig = None
        if dig is None:
            return False
        seen_digit = True
        prev_underscore = False
    return seen_digit


NON_DECIMAL_SPELLING = r"^\s*[+-]?(?:0[xX][0-9a-fA-F]+|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\d+[.,]\d+)\s*$"


def _payload_canonicals(val, out: list, depth: int = 0) -> None:
    """Every canonical decimal spelling that a sequence payload could denote."""
    if depth > 256:
        raise SecurityStopError("SKIP_LEAKED_TO_INBOX: sequence payload nesting too deep to prove absence")
    if isinstance(val, bool):
        return
    if isinstance(val, int):
        out.append(str(int(val)).lstrip("0") or "0")
    elif isinstance(val, float):
        if float(val).is_integer():
            out.append(str(int(val)))
        else:
            raise SecurityStopError("SEQUENCE_NON_INTEGRAL: sequence payload %r is not an integer" % (val,))
    elif isinstance(val, str):
        if _is_plain_decimal(val):
            out.extend(_tokenize_decimals(val))
            return
        toks = _tokenize_decimals(val)
        if not toks:
            return  # no digits at all -> nothing that could denote a sequence number
        if re.fullmatch(NON_DECIMAL_SPELLING, val):
            raise SecurityStopError(
                "SEQUENCE_NON_DECIMAL: sequence payload %r uses a non-decimal spelling; refusing to guess" % (val,)
            )
        out.extend(toks)
    elif isinstance(val, (list, tuple)):
        for item in val:
            _payload_canonicals(item, out, depth + 1)
    elif isinstance(val, dict):
        pairs = getattr(val, "all_pairs", None)
        if pairs is None:
            pairs = list(val.items())
        for _k, item in pairs:
            _payload_canonicals(item, out, depth + 1)


class _PairPreservingDict(dict):
    """JSON object that keeps every (key, value) pair so a duplicated `sequence` key cannot overwrite an
    earlier value (A29 62042 / A65 62045 / A20 62049)."""

    __slots__ = ("all_pairs",)


def _pairs_hook(pairs):
    obj = _PairPreservingDict()
    obj.all_pairs = list(pairs)
    for key, val in pairs:
        obj[key] = val
    return obj


def _seq_canonicals_under_keys(node, out: list, depth: int = 0) -> None:
    if depth > 256:
        raise SecurityStopError("SKIP_LEAKED_TO_INBOX: sequence key nesting too deep to prove absence")
    if isinstance(node, dict):
        pairs = getattr(node, "all_pairs", None)
        if pairs is None:
            pairs = list(node.items())
        for key, val in pairs:
            if isinstance(key, str) and key.strip().lower() == "sequence":
                _payload_canonicals(val, out, depth + 1)
            _seq_canonicals_under_keys(val, out, depth + 1)
    elif isinstance(node, list):
        for item in node:
            _seq_canonicals_under_keys(item, out, depth + 1)


def _line_canonicals(raw_line: bytes) -> list:
    """Legal JSON -> recursive AST over `sequence` keys; malformed line -> whole-line decimal scan."""
    text = raw_line.decode("utf-8", "replace")
    try:
        obj = json.loads(text, object_pairs_hook=_pairs_hook)
    except Exception:
        return _tokenize_decimals(text)
    out = []
    _seq_canonicals_under_keys(obj, out)
    return out


def _scan_lines_for_skip(path_text: str, skip_seqs: list) -> list:
    """INV-7 read-back of the REAL bytes; compares canonical decimal strings, never int()."""
    hits = []
    if not skip_seqs:
        return hits
    p = Path(path_text)
    if not (p.exists() or p.is_symlink()):
        return hits
    targets = {str(int(x)).lstrip("0") or "0" for x in skip_seqs}
    blob = p.read_bytes()
    for raw_line in blob.split(b"\n"):
        if not raw_line.strip():
            continue
        if any(tok in targets for tok in _line_canonicals(raw_line)):
            hits.append(str(p))
            break
    return hits


def _assert_skip_not_written(cfg: dict, skip_seqs: list) -> None:
    """INV-7: the negative assertion observes written artefacts, never the plan."""
    if not skip_seqs:
        return
    paths = {str(cfg.get("events_log_file") or cfg.get("inbox_file") or "events_log.jsonl")}
    if cfg.get("inbox_file"):
        paths.add(str(cfg["inbox_file"]))
    hits = []
    for one in sorted(paths):
        hits.extend(_scan_lines_for_skip(one, skip_seqs))
    if hits:
        raise SecurityStopError("SKIP_LEAKED_TO_INBOX: skip seq found in written file(s) %s" % (sorted(set(hits)),))


def run_batch(cfg: dict, quiet_peers: bool = True, inject_crash_stage: str | None = None) -> int:
    lock_fd = acquire_single_instance_lock(Path(str(cfg.get("lock_file") or ".runner.lock")))
    try:
        verify_pinned_client(cfg)
        preflight_private_file(Path(str(cfg.get("session_file") or ".arc-session-v1.json")), must_exist=True)
        st = load_and_reconcile_state(cfg)

        # Gate 7 & 10: Replay durable pending actions on startup before polling beyond them
        if st.get("pending_actions"):
            for item in st["pending_actions"]:
                print(
                    f"=== PENDING_ACTION [{item['category']}] seq={item['sequence']} sender={item['sender']} sha12={item['sha12']} ===",
                    flush=True,
                )
                print(str(item.get("text") or ""), flush=True)
            return 0

        usable_b = float(cfg.get("usable_budget_seconds", cfg.get("budget_seconds", 210)))
        deadline = time.monotonic() + usable_b
        max_cap = int(cfg.get("max_cycles_cap", 2147483647))
        eff_cycles = int(cfg.get("effective_cycles", cfg.get("cycles_per_invocation", 1)))
        req_cycles = max(eff_cycles, int(cfg.get("requested_cycles", cfg.get("cycles_per_invocation", eff_cycles))))
        worst_cyc = float(cfg.get("worst_case_cycle_seconds", 1))
        call_worst_cyc = max(1.0, worst_cyc - float(cfg.get("quiet_sleep_seconds", 0)))
        target_room = str(cfg.get("target_room") or "COMMONS")
        hb_enabled = bool(cfg.get("heartbeat_enabled", False))
        if hb_enabled:
            try:
                emit_tool_heartbeat(cfg, st, phase="BEFORE_BATCH")
            except Exception as exc:
                print(f"HEARTBEAT_SKIPPED: {type(exc).__name__}", flush=True)

        for idx in range(req_cycles):
            if int(st["cycle_count"]) >= max_cap:
                print(f"STOP_CONDITION: reached max_cycles_cap={max_cap}", flush=True)
                return 0
            needed_s = worst_cyc if idx < eff_cycles else call_worst_cyc
            if time.monotonic() + needed_s > deadline and idx > 0:
                break

            st["cycle_count"] = int(st["cycle_count"]) + 1
            k = st["cycle_count"]

            h_status, _, _ = invoke_client(cfg, ["health"], deadline)
            if h_status != 200:
                raise ContinuityBlockedError(f"CONTINUITY_BLOCKED: health failed at cycle {k}")

            new_events = []
            sub_polls = max(1, int(cfg.get("sub_polls_per_cycle", 1)))
            wait_s = max(1, int(cfg.get("poll_wait_seconds", 1)))

            for _ in range(sub_polls):
                if time.monotonic() + wait_s > deadline + 0.5:
                    break
                poll_body = {"after_sequence": int(st["cursor"]), "wait_seconds": wait_s}
                tmp_poll = Path(f".tmp.poll.{os.getpid()}.{time.monotonic_ns()}.json")
                try:
                    atomic_write_private_bytes(
                        tmp_poll, json.dumps(poll_body, separators=(",", ":")).encode("utf-8")
                    )
                    p_status, resp, _ = invoke_client(
                        cfg, ["request", "POST", "/v1/events/poll", "--body", str(tmp_poll)], deadline
                    )
                finally:
                    if tmp_poll.exists():
                        try:
                            tmp_poll.unlink()
                        except Exception:
                            pass
                if p_status == 200 and isinstance(resp, dict):
                    raw_evs = [
                        e
                        for e in resp.get("events", [])
                        if e.get("room_id") == target_room and int(e.get("sequence", 0)) > int(st["cursor"])
                    ]
                    if raw_evs:
                        # Gate 7a: three-state pagination of the authorised skip-list
                        head_seq = max(int(e["sequence"]) for e in raw_evs)
                        batch_seqs = {int(e["sequence"]) for e in raw_evs}
                        cursor_now = int(st["cursor"])
                        configured = _parse_skip_config(cfg, head_seq, cursor_now)
                        skipped_now = []
                        for seq in configured:
                            if seq in batch_seqs:
                                skipped_now.append(seq)          # observed here -> skip it
                            elif seq > head_seq:
                                continue                         # still ahead -> normal ingest
                            elif seq <= cursor_now:
                                continue                         # already behind us -> inert
                            else:
                                raise SecurityStopError(
                                    "SKIP_SEQ_NOT_OBSERVED: authorised skip seq=%d lies inside (cursor=%d, head=%d] "
                                    "but is absent from this batch and has no provenance record" % (seq, cursor_now, head_seq)
                                )
                        skip_seqs = list(skipped_now)
                        skip_set = set(skip_seqs)
                        _record_skip_provenance(cfg, st, skipped_now, head_seq)
                        logged = _logged_skip_seqs(st)
                        if logged:
                            st["skip_provenance_seen"] = sorted(logged)
                        to_ingest = [e for e in raw_evs if int(e["sequence"]) not in skip_set]

                        # Gate 7: Pre-scan ALL candidate events for data_class & canary BEFORE any disk write
                        classified_pairs = []
                        for e in to_ingest:
                            cat = classify_event(cfg, e)
                            classified_pairs.append((cat, e))

                        # Step 1: Durably append to 0600 safe inbox (skip seqs excluded by construction)
                        append_to_safe_inbox(cfg, to_ingest)

                        # Step 1b: INV-7 read-back of the actual bytes before any cursor movement
                        _assert_skip_not_written(cfg, sorted(set(configured) | set(skip_seqs)))

                        # Step 2: Record pending actions + journal_cursor BEFORE advancing cursor
                        handled_set = set(int(x) for x in st.get("handled_action_seqs", []))
                        existing_pending_seqs = {
                            int(x["sequence"]) for x in st.get("pending_actions", [])
                        }
                        for cat, e in classified_pairs:
                            is_act = cat in (
                                "STOP_PILOT",
                                "OWNER_MSG",
                                "HOST_MSG",
                                "STATUS",
                                "PEER_MENTION",
                            ) or (cat == "PEER_OTHER" and not quiet_peers)
                            if is_act:
                                seq_i = int(e["sequence"])
                                entry = {
                                    "sequence": seq_i,
                                    "category": cat,
                                    "sender": str(e.get("sender") or ""),
                                    "sha12": str(e.get("event_sha256") or "")[:12],
                                    "text": str(e.get("text") or ""),
                                }
                                if seq_i not in handled_set and seq_i not in existing_pending_seqs:
                                    st["pending_actions"].append(entry)
                                    existing_pending_seqs.add(seq_i)

                        new_max_seq = max(int(st["cursor"]), max(int(e["sequence"]) for e in raw_evs))
                        st["journal_cursor"] = new_max_seq
                        save_journal_state_only(cfg, st)

                        if inject_crash_stage == "after_journal_before_cursor":
                            raise RuntimeError("INJECTED_CRASH_AFTER_JOURNAL_BEFORE_CURSOR")

                        # Step 3: Advance durable cursor
                        st["cursor"] = new_max_seq
                        save_state_and_cursor(cfg, st)

                        if inject_crash_stage == "after_cursor_before_processing":
                            raise RuntimeError("INJECTED_CRASH_AFTER_CURSOR_BEFORE_PROCESSING")

                        new_events.extend(raw_evs)
                        break
                    # INV-7 runs even when this poll returned no event (A28 62055 CASE-35)
                    _assert_skip_not_written(cfg, _skip_pair_from_cfg(cfg))

            seq_str = ",".join(str(e["sequence"]) for e in new_events) if new_events else "無"
            update_local_lease_state(st, "AFTER_POLL", f"batch-{k}", int(cfg.get("worst_case_cycle_seconds", 60)))
            st["last_next_step_decision"] = decide_next_turn_step(
                "action_event" if st.get("pending_actions") else "empty_poll",
                continuation_active=True,
                stop_condition_hit=False,
                turn_budget_exhausted=False,
            )
            print(format_silent_progress_line(k, max_cap, seq_str, int(st["cursor"]), "—"), flush=True)
            save_state_and_cursor(cfg, st)

            if st.get("pending_actions"):
                for item in st["pending_actions"]:
                    print(
                        f"=== ACTION_EVENT [{item['category']}] seq={item['sequence']} sender={item['sender']} sha12={item['sha12']} ===",
                        flush=True,
                    )
                    print(str(item.get("text") or ""), flush=True)
                return 0

            if not st.get("pending_actions"):
                q_sleep = float(cfg.get("quiet_sleep_seconds", 0))
                rem = deadline - time.monotonic() - 0.5
                if rem <= 0:
                    break
                if q_sleep > 0:
                    time.sleep(min(q_sleep, rem))
        if hb_enabled:
            try:
                emit_tool_heartbeat(cfg, st, phase="AFTER_BATCH")
            except Exception as exc:
                print(f"HEARTBEAT_SKIPPED: {type(exc).__name__}", flush=True)
        return 0
    finally:
        try:
            fcntl.flock(lock_fd, fcntl.LOCK_UN)
        except Exception:
            pass
        os.close(lock_fd)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", type=str, default="runner_config.json")
    ap.add_argument("--cycles", type=int, default=None)
    ap.add_argument("--budget-seconds", type=int, default=None)
    ap.add_argument("--ack-seq", type=int, default=None)
    ap.add_argument("--ack-through", type=int, default=None)
    ap.add_argument("--quiet-peers", dest="quiet_peers", action="store_true", default=True)
    ap.add_argument("--no-quiet-peers", dest="quiet_peers", action="store_false")
    args = ap.parse_args()
    try:
        preflight_workspace_dir(Path("."))
        cfg = load_config(Path(args.config), args=args)
        if args.ack_seq is not None or args.ack_through is not None:
            lock_fd = acquire_single_instance_lock(Path(str(cfg["lock_file"])))
            try:
                st = load_and_reconcile_state(cfg)
                if args.ack_seq is not None:
                    mark_action_handled(cfg, st, args.ack_seq, cumulative=False)
                    print(f"ACK_HANDLED_PASS: exact seq=={args.ack_seq}", flush=True)
                else:
                    mark_action_handled(cfg, st, args.ack_through, cumulative=True)
                    print(f"ACK_HANDLED_PASS: cumulative seq<={args.ack_through}", flush=True)
                sys.exit(0)
            finally:
                try:
                    fcntl.flock(lock_fd, fcntl.LOCK_UN)
                except Exception:
                    pass
                os.close(lock_fd)
        rc_code = run_batch(cfg, quiet_peers=args.quiet_peers)
        if cfg.get("enable_pre_exit_notice"):
            st_end = load_and_reconcile_state(cfg)
            if not st_end.get("pending_actions"):
                emit_pre_exit_notice(cfg, st_end, reason_enum="budget")
        sys.exit(rc_code)
    except (ContinuityBlockedError, SecurityStopError) as exc:
        try:
            st_err = load_and_reconcile_state(cfg) if "cfg" in locals() else {"cursor": 0, "pending_actions": []}
            if "cfg" in locals():
                record_early_exit_incident(
                    cfg,
                    st_err,
                    occurred_at=f"cursor={st_err.get('cursor', 0)}",
                    activity_before="run_batch",
                    root_cause=str(exc),
                    prevention="preflight_and_isolated_tempdir",
                    incident_class="DEFECT",
                )
        except Exception:
            pass
        print(f"STOP_CONDITION: {exc}", flush=True)
        sys.exit(2)


if __name__ == "__main__":
    main()
