#!/usr/bin/env python3
"""Frontier Substrate System reference runtime.

The runtime operationalizes *Residue as Frontier Substrate* without reducing
its ontology to one universal project funnel. Perceptions, voyages, collapses,
residue, claims, contradictions, suspension envelopes, invariants, lineage,
and adaptations retain separate types and gates.

Every mutation advances one governed tick and appends a durable receipt. The
runtime is intentionally standard-library only.
"""

from __future__ import annotations

import argparse
import fcntl
import hashlib
import json
import math
import os
import re
import sys
import tempfile
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timezone
from functools import wraps
from pathlib import Path
from typing import Any, Iterable, Iterator, Mapping, Sequence


SCHEMA_VERSION = "rfs.runtime.v1"
SYSTEM_SCHEMA = "rfs.system.v1"
REGISTRY_SCHEMA = "rfs.registry.v1"
EVENT_SCHEMA = "rfs.tick.event.v1"

VOYAGE_STATES = (
    "proposed",
    "authorized",
    "traversing",
    "locally_collapsed",
    "receipted",
    "returned",
    "reconciled",
)
VOYAGE_SIDE_STATES = {
    "retreated",
    "suspended",
    "abandoned_with_receipt",
}
VOYAGE_NEXT = {
    "proposed": "authorized",
    "authorized": "traversing",
    "traversing": "locally_collapsed",
    "locally_collapsed": "receipted",
    "receipted": "returned",
    "returned": "reconciled",
}

RESIDUE_STATES = (
    "debris",
    "indexed",
    "returnability_pending",
    "returnable",
    "substrate_candidate",
    "load_bearing",
    "invariant_candidate",
    "invariant_anchor",
)
RESIDUE_SIDE_STATES = {"demoted", "suspended", "expired", "archived"}

CLAIM_STATES = (
    "projection",
    "local_claim",
    "supported_claim",
    "scoped_invariant",
)
CLAIM_SIDE_STATES = {"contradicted", "suspended", "contracted", "demoted"}

CONTRADICTION_STATES = (
    "registered",
    "active",
    "bounded",
    "resolved",
    "retained",
    "escalated",
    "superseded",
    "withdrawn",
)

RECORD_TYPES = {
    "pressure",
    "perception",
    "voyage",
    "collapse",
    "residue",
    "return_test",
    "bearing_assessment",
    "quiver",
    "suspension",
    "claim",
    "contradiction",
    "tension_report",
    "invariant",
    "adaptation",
    "lineage_bundle",
    "relaunch",
}

TYPE_PREFIX = {
    "pressure": "prs",
    "perception": "per",
    "voyage": "voy",
    "collapse": "col",
    "residue": "res",
    "return_test": "rtn",
    "bearing_assessment": "brg",
    "quiver": "qvr",
    "suspension": "sus",
    "claim": "clm",
    "contradiction": "ctr",
    "tension_report": "tns",
    "invariant": "inv",
    "adaptation": "adp",
    "lineage_bundle": "lin",
    "relaunch": "rlx",
}

RECORD_DIR = {
    "pressure": "00_REGISTRY/pressures",
    "perception": "00_REGISTRY/perceptions",
    "quiver": "00_REGISTRY/quivers",
    "claim": "00_REGISTRY/claims",
    "contradiction": "00_REGISTRY/contradictions",
    "voyage": "01_VOYAGES",
    "collapse": "02_COLLAPSES",
    "residue": "03_RESIDUE",
    "return_test": "04_RETURNABILITY/tests",
    "bearing_assessment": "05_SUBSTRATE/bearing",
    "suspension": "05_SUBSTRATE/suspension",
    "invariant": "06_INVARIANTS",
    "tension_report": "07_TENSION",
    "lineage_bundle": "08_LINEAGE",
    "adaptation": "09_ADAPTATION",
    "relaunch": "10_RELAUNCH",
}

SIX_FACETS = {
    "kataphatic",
    "apophatic",
    "complement",
    "failure_mode",
    "enactive",
    "telic",
}

RFS1_CONDITIONS = (
    "registered_origin",
    "behavioral_meaning",
    "positive_and_negative_scope",
    "independent_paths",
    "support_diversity",
    "pilot_removal",
    "contradictions_governed",
    "audit_supports_radius",
    "owner_review_expiry_demotion",
    "decision_and_dissent_receipted",
)

UNKNOWN_VALUES = {"", "unknown", "unresolved", "tbd", "todo", "replace-me"}


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()


def slugify(value: str) -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
    return slug or "untitled"


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def is_resolved(value: Any) -> bool:
    if value is None:
        return False
    if isinstance(value, str):
        return value.strip().lower() not in UNKNOWN_VALUES
    if isinstance(value, (list, dict)):
        return bool(value)
    return True


def require_fields(payload: Mapping[str, Any], fields: Iterable[str]) -> None:
    missing = [name for name in fields if not is_resolved(payload.get(name))]
    if missing:
        raise FrontierError("required fields unresolved: " + ", ".join(missing))


def require_list(payload: Mapping[str, Any], name: str) -> list[Any]:
    value = payload.get(name)
    if not isinstance(value, list) or not value:
        raise FrontierError(f"{name} must be a non-empty list")
    return value


def numeric_score(value: Any, label: str) -> float:
    try:
        score = float(value)
    except (TypeError, ValueError) as exc:
        raise FrontierError(f"{label} must be numeric") from exc
    if not 0.0 <= score <= 1.0:
        raise FrontierError(f"{label} must be between 0 and 1")
    return score


def atomic_write_json(path: Path, value: Mapping[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    descriptor, temp_name = tempfile.mkstemp(
        dir=path.parent, prefix=f".{path.name}.", suffix=".tmp"
    )
    temp_path = Path(temp_name)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
            json.dump(value, handle, indent=2, ensure_ascii=False)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temp_path, path)
    finally:
        if temp_path.exists():
            temp_path.unlink()


def atomic_write_text(path: Path, value: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    descriptor, temp_name = tempfile.mkstemp(
        dir=path.parent, prefix=f".{path.name}.", suffix=".tmp"
    )
    temp_path = Path(temp_name)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
            handle.write(value)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temp_path, path)
    finally:
        if temp_path.exists():
            temp_path.unlink()


def read_json(path: Path) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError as exc:
        raise FrontierError(f"required file is missing: {path}") from exc
    except json.JSONDecodeError as exc:
        raise FrontierError(
            f"invalid JSON in {path}: line {exc.lineno}, column {exc.colno}"
        ) from exc
    if not isinstance(value, dict):
        raise FrontierError(f"expected a JSON object in {path}")
    return value


def load_payload(path: Path | None) -> dict[str, Any]:
    if path is None:
        return {}
    return read_json(path.expanduser().resolve())


def append_jsonl(path: Path, value: Mapping[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    serialized = json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n"
    with path.open("a", encoding="utf-8") as handle:
        handle.write(serialized)
        handle.flush()
        os.fsync(handle.fileno())


class FrontierError(RuntimeError):
    """Fail-closed, user-facing runtime error."""


def locked_mutation(method):
    """Serialize one complete read-validate-write mutation."""

    @wraps(method)
    def wrapper(self, *args, **kwargs):
        with self._locked():
            return method(self, *args, **kwargs)

    return wrapper


@dataclass
class ValidationReport:
    root: Path
    ok: bool = True
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    counts: dict[str, int] = field(default_factory=dict)

    def fail(self, message: str) -> None:
        self.ok = False
        self.errors.append(message)

    def as_dict(self) -> dict[str, Any]:
        return {
            "schema": "rfs.validation.report.v1",
            "generated_at": utc_now(),
            "root": str(self.root),
            "ok": self.ok,
            "errors": self.errors,
            "warnings": self.warnings,
            "counts": self.counts,
        }


class FrontierSystem:
    """One registered frontier system."""

    def __init__(self, root: Path | str):
        self.root = Path(root).expanduser().resolve()
        self.system_path = self.root / "system.json"
        self.registry_path = self.root / "registry.json"
        self.events_path = self.root / "events/ticks.jsonl"
        self.lock_path = self.root / ".rfs.lock"

    @classmethod
    def initialize(
        cls,
        root: Path | str,
        *,
        title: str,
        owner: str,
        telos: str,
        bearing_threshold: float = 0.72,
        critical_factor_floor: float = 0.50,
        force: bool = False,
    ) -> "FrontierSystem":
        root_path = Path(root).expanduser().resolve()
        if root_path.exists() and any(root_path.iterdir()) and not force:
            raise FrontierError(
                f"system directory is not empty: {root_path}; use --force only "
                "for a deliberate initialization into existing storage"
            )
        root_path.mkdir(parents=True, exist_ok=True)
        system = cls(root_path)
        now = utc_now()
        system_id = f"rfs-{slugify(title)}-{now[:10].replace('-', '')}"
        for record_dir in set(RECORD_DIR.values()):
            (root_path / record_dir).mkdir(parents=True, exist_ok=True)
        (root_path / "events").mkdir(parents=True, exist_ok=True)
        (root_path / "exports").mkdir(parents=True, exist_ok=True)
        system_data = {
            "schema": SYSTEM_SCHEMA,
            "runtime_schema": SCHEMA_VERSION,
            "system_id": system_id,
            "title": title,
            "owner": owner,
            "telos": telos,
            "created_at": now,
            "updated_at": now,
            "current_tick": 0,
            "status": "active",
            "thresholds": {
                "bearing_index": numeric_score(
                    bearing_threshold, "bearing_threshold"
                ),
                "critical_factor_floor": numeric_score(
                    critical_factor_floor, "critical_factor_floor"
                ),
                "minimum_independent_paths": 2,
                "minimum_constraint_retention": 0.75,
            },
            "legitimacy": {
                "current_radius": "local_only",
                "last_tension_report_id": None,
            },
            "governance_lock": "RFS-1_NO_UNREGISTERED_GLOBAL_CLAIM",
        }
        registry = {
            "schema": REGISTRY_SCHEMA,
            "system_id": system_id,
            "updated_at": now,
            "objects": {},
        }
        atomic_write_json(system.system_path, system_data)
        atomic_write_json(system.registry_path, registry)
        atomic_write_text(system.events_path, "")
        atomic_write_text(system.lock_path, "")
        return system

    @contextmanager
    def _locked(self) -> Iterator[None]:
        if not self.root.exists():
            raise FrontierError(f"system directory does not exist: {self.root}")
        self.lock_path.touch(exist_ok=True)
        with self.lock_path.open("r+") as handle:
            fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
            try:
                yield
            finally:
                fcntl.flock(handle.fileno(), fcntl.LOCK_UN)

    def system(self) -> dict[str, Any]:
        return read_json(self.system_path)

    def registry(self) -> dict[str, Any]:
        return read_json(self.registry_path)

    def _object_path(self, record_type: str, object_id: str) -> Path:
        if record_type not in RECORD_TYPES:
            raise FrontierError(f"unknown record type: {record_type}")
        return self.root / RECORD_DIR[record_type] / f"{object_id}.json"

    def _new_id(self, record_type: str) -> str:
        return f"{TYPE_PREFIX[record_type]}-{uuid.uuid4().hex[:12]}"

    def get(self, object_id: str, expected_type: str | None = None) -> dict[str, Any]:
        registry = self.registry()
        entry = registry.get("objects", {}).get(object_id)
        if not entry:
            raise FrontierError(f"object is not registered: {object_id}")
        if expected_type and entry.get("type") != expected_type:
            raise FrontierError(
                f"{object_id} is {entry.get('type')}, expected {expected_type}"
            )
        return read_json(self.root / entry["path"])

    def _commit(
        self,
        *,
        event_type: str,
        actor: str,
        writes: Sequence[tuple[str, dict[str, Any]]],
        details: Mapping[str, Any] | None = None,
    ) -> dict[str, Any]:
        require_fields({"actor": actor}, ("actor",))
        system = self.system()
        registry = self.registry()
        tick = int(system.get("current_tick", 0)) + 1
        now = utc_now()
        changed: list[dict[str, Any]] = []

        for record_type, record in writes:
            if record_type not in RECORD_TYPES:
                raise FrontierError(f"unknown record type: {record_type}")
            object_id = record.get("id")
            if not is_resolved(object_id):
                raise FrontierError(f"{record_type} record requires id")
            updated = dict(record)
            if "created_at" not in updated:
                updated["created_at"] = now
                updated["created_tick"] = tick
            updated["updated_at"] = now
            updated["updated_tick"] = tick
            updated.setdefault("schema", f"rfs.{record_type}.v1")
            path = self._object_path(record_type, str(object_id))
            atomic_write_json(path, updated)
            relative = str(path.relative_to(self.root))
            registry.setdefault("objects", {})[str(object_id)] = {
                "type": record_type,
                "path": relative,
                "state": updated.get("state", "registered"),
                "updated_tick": tick,
                "updated_at": now,
            }
            changed.append(
                {
                    "id": str(object_id),
                    "type": record_type,
                    "path": relative,
                    "state": updated.get("state", "registered"),
                }
            )

        registry["updated_at"] = now
        system["current_tick"] = tick
        system["updated_at"] = now
        atomic_write_json(self.registry_path, registry)
        atomic_write_json(self.system_path, system)
        event = {
            "schema": EVENT_SCHEMA,
            "event_id": f"tick-{tick:08d}",
            "tick": tick,
            "event_type": event_type,
            "actor": actor,
            "occurred_at": now,
            "changed_objects": changed,
            "details": dict(details or {}),
        }
        append_jsonl(self.events_path, event)
        return event

    def _create(
        self,
        record_type: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
        event_type: str,
        state: str = "registered",
    ) -> dict[str, Any]:
        record = dict(payload)
        record["id"] = str(payload.get("id") or self._new_id(record_type))
        record["state"] = state
        event = self._commit(
            event_type=event_type,
            actor=actor,
            writes=((record_type, record),),
            details={"created_id": record["id"]},
        )
        return {"object": self.get(record["id"]), "event": event}

    @locked_mutation
    def register_pressure(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "observed_change",
                "affected",
                "inaction_consequence",
                "map_insufficiency",
            ),
        )
        return self._create(
            "pressure",
            payload,
            actor=actor,
            event_type="pressure_registered",
        )

    @locked_mutation
    def register_perception(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "decoder_id",
                "decoder_class",
                "available_signal",
                "context",
                "observation",
                "interpretation",
                "uncertainty",
                "six_facets",
            ),
        )
        facets = payload["six_facets"]
        if not isinstance(facets, dict):
            raise FrontierError("six_facets must be an object")
        missing = sorted(
            facet for facet in SIX_FACETS if not is_resolved(facets.get(facet))
        )
        if missing:
            raise FrontierError(
                "six_facets unresolved: " + ", ".join(missing)
            )
        return self._create(
            "perception",
            payload,
            actor=actor,
            event_type="perception_registered",
        )

    @locked_mutation
    def open_voyage(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "title",
                "pressure_id",
                "purpose",
                "telos",
                "positive_scope",
                "excluded_scope",
                "resource_budget",
                "recursion_budget",
                "collapse_authority",
                "stop_rule",
                "retreat_rule",
                "suspension_rule",
                "expected_residue",
                "residue_custodian",
                "independent_return_tester",
                "relaunch_question",
            ),
        )
        self.get(str(payload["pressure_id"]), "pressure")
        return self._create(
            "voyage",
            payload,
            actor=actor,
            event_type="voyage_proposed",
            state="proposed",
        )

    @locked_mutation
    def advance_voyage(
        self,
        voyage_id: str,
        target_state: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        voyage = self.get(voyage_id, "voyage")
        current = voyage["state"]
        if target_state in VOYAGE_SIDE_STATES:
            require_fields(payload, ("reason", "residue_disposition"))
        else:
            expected = VOYAGE_NEXT.get(current)
            if target_state != expected:
                raise FrontierError(
                    f"voyage transition must be {current} -> {expected}; "
                    f"requested {target_state}"
                )
            if target_state == "authorized":
                require_fields(payload, ("authorization",))
            elif target_state == "traversing":
                require_fields(payload, ("launch_receipt",))
            elif target_state == "receipted":
                residue_ids = require_list(payload, "residue_ids")
                for residue_id in residue_ids:
                    residue = self.get(str(residue_id), "residue")
                    if residue.get("origin_voyage_id") != voyage_id:
                        raise FrontierError(
                            f"residue {residue_id} does not originate from {voyage_id}"
                        )
            elif target_state == "returned":
                test_ids = require_list(payload, "return_test_ids")
                passed = False
                for test_id in test_ids:
                    test = self.get(str(test_id), "return_test")
                    if test.get("result") in {"pass", "conditional_pass"}:
                        passed = True
                if not passed:
                    raise FrontierError(
                        "returned voyage requires at least one passing return test"
                    )
            elif target_state == "reconciled":
                require_fields(
                    payload,
                    (
                        "global_reconstruction",
                        "changed_boundary",
                        "next_voyage_condition",
                    ),
                )
        voyage["state"] = target_state
        voyage.setdefault("transitions", []).append(
            {
                "from": current,
                "to": target_state,
                "actor": actor,
                "at": utc_now(),
                "evidence": dict(payload),
            }
        )
        event = self._commit(
            event_type=f"voyage_{target_state}",
            actor=actor,
            writes=(("voyage", voyage),),
            details={"voyage_id": voyage_id, "from": current, "to": target_state},
        )
        return {"object": self.get(voyage_id), "event": event}

    @locked_mutation
    def record_collapse(
        self,
        voyage_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        voyage = self.get(voyage_id, "voyage")
        if voyage.get("state") != "traversing":
            raise FrontierError(
                "collapse requires voyage state traversing; "
                f"found {voyage.get('state')}"
            )
        require_fields(
            payload,
            (
                "commitment",
                "action_enabled",
                "authority",
                "supporting_evidence",
                "environment",
                "positive_scope",
                "excluded_scope",
                "alternatives_excluded",
                "active_contradictions",
                "reversibility",
                "review_trigger",
                "legitimacy_radius",
                "expected_remainder",
                "exact_state_handle",
                "semantic_interpretation",
                "semantic_decoder",
            ),
        )
        collapse = dict(payload)
        collapse["id"] = str(payload.get("id") or self._new_id("collapse"))
        collapse["voyage_id"] = voyage_id
        collapse["state"] = "receipted"
        collapse["binding_receipt"] = {
            "exact_state_handle": collapse["exact_state_handle"],
            "semantic_interpretation": collapse["semantic_interpretation"],
            "semantic_decoder": collapse["semantic_decoder"],
            "bound_at": utc_now(),
        }
        prior = voyage["state"]
        voyage["state"] = "locally_collapsed"
        voyage["collapse_id"] = collapse["id"]
        voyage.setdefault("transitions", []).append(
            {
                "from": prior,
                "to": "locally_collapsed",
                "actor": actor,
                "at": utc_now(),
                "evidence": {"collapse_id": collapse["id"]},
            }
        )
        event = self._commit(
            event_type="local_collapse_receipted",
            actor=actor,
            writes=(("collapse", collapse), ("voyage", voyage)),
            details={
                "voyage_id": voyage_id,
                "collapse_id": collapse["id"],
            },
        )
        return {
            "collapse": self.get(collapse["id"]),
            "voyage": self.get(voyage_id),
            "event": event,
        }

    @locked_mutation
    def index_residue(
        self,
        collapse_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        collapse = self.get(collapse_id, "collapse")
        require_fields(
            payload,
            (
                "description",
                "originator_decoder",
                "provenance",
                "exact_state_handle",
                "semantic_signatures",
                "constraints",
                "exclusions",
                "return_path",
                "dependencies",
                "owner",
                "purpose",
                "review_trigger",
                "disposal_rule",
            ),
        )
        require_list(payload, "constraints")
        require_list(payload, "exclusions")
        residue = dict(payload)
        residue["id"] = str(payload.get("id") or self._new_id("residue"))
        residue["collapse_id"] = collapse_id
        residue["origin_voyage_id"] = collapse["voyage_id"]
        residue["state"] = "indexed"
        residue["maturity_history"] = [
            {
                "from": "debris",
                "to": "indexed",
                "actor": actor,
                "at": utc_now(),
                "evidence": "registry and provenance complete",
            }
        ]
        return_event = self._commit(
            event_type="residue_indexed",
            actor=actor,
            writes=(("residue", residue),),
            details={
                "residue_id": residue["id"],
                "collapse_id": collapse_id,
            },
        )
        return {"object": self.get(residue["id"]), "event": return_event}

    @locked_mutation
    def test_returnability(
        self,
        residue_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        residue = self.get(residue_id, "residue")
        if residue.get("state") not in {"indexed", "returnability_pending"}:
            raise FrontierError(
                "returnability test requires indexed or returnability_pending "
                f"residue; found {residue.get('state')}"
            )
        require_fields(
            payload,
            (
                "independent_decoder",
                "independence_basis",
                "bundle_handle",
                "environment",
                "continuation_task",
                "constraints_expected",
                "constraints_recovered",
                "pilot_interventions",
                "outcome",
                "safe_actions",
                "unsafe_actions_avoided",
            ),
        )
        independent_decoder = str(payload["independent_decoder"])
        if independent_decoder == str(residue.get("originator_decoder")):
            raise FrontierError(
                "originating decoder cannot certify independent returnability"
            )
        expected = set(str(value) for value in payload["constraints_expected"])
        recovered = set(str(value) for value in payload["constraints_recovered"])
        if not expected:
            raise FrontierError("constraints_expected must not be empty")
        retention = len(expected & recovered) / len(expected)
        pilot_interventions = payload["pilot_interventions"]
        if isinstance(pilot_interventions, (int, float)):
            intervention_count = int(pilot_interventions)
        elif isinstance(pilot_interventions, list):
            intervention_count = len(pilot_interventions)
        else:
            raise FrontierError("pilot_interventions must be a number or list")
        claimed_success = bool(payload.get("success"))
        threshold = float(
            self.system()["thresholds"]["minimum_constraint_retention"]
        )
        if claimed_success and retention >= threshold and intervention_count == 0:
            result = "pass"
            new_state = "returnable"
        elif claimed_success and retention >= threshold:
            result = "conditional_pass"
            new_state = "returnable"
        else:
            result = "fail"
            new_state = "returnability_pending"
        test = dict(payload)
        test["id"] = str(payload.get("id") or self._new_id("return_test"))
        test["residue_id"] = residue_id
        test["state"] = "complete"
        test["constraint_retention"] = round(retention, 6)
        test["returnability_score"] = numeric_score(
            payload.get("returnability_score", retention),
            "returnability_score",
        )
        test["result"] = result
        prior = residue["state"]
        residue["state"] = new_state
        residue.setdefault("return_test_ids", []).append(test["id"])
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": new_state,
                "actor": actor,
                "at": utc_now(),
                "evidence": {"return_test_id": test["id"], "result": result},
            }
        )
        event = self._commit(
            event_type="returnability_test_completed",
            actor=actor,
            writes=(("return_test", test), ("residue", residue)),
            details={
                "residue_id": residue_id,
                "return_test_id": test["id"],
                "result": result,
            },
        )
        return {
            "test": self.get(test["id"]),
            "residue": self.get(residue_id),
            "event": event,
        }

    @locked_mutation
    def score_bearing(
        self,
        residue_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        residue = self.get(residue_id, "residue")
        if residue.get("state") != "returnable":
            raise FrontierError(
                f"bearing assessment requires returnable residue; found {residue.get('state')}"
            )
        require_fields(
            payload,
            (
                "proposed_load",
                "scores",
                "evidence",
                "independent_paths",
                "support_diversity",
                "observed_failures",
                "audit_cost",
            ),
        )
        scores_payload = payload["scores"]
        if not isinstance(scores_payload, dict):
            raise FrontierError("scores must be an object")
        factors = {}
        for key in ("R", "P", "I", "X", "G"):
            factors[key] = numeric_score(scores_payload.get(key), key)
        bearing = math.prod(factors.values()) ** (1.0 / 5.0)
        paths = payload["independent_paths"]
        if not isinstance(paths, list):
            raise FrontierError("independent_paths must be a list")
        system = self.system()
        threshold = float(system["thresholds"]["bearing_index"])
        floor = float(system["thresholds"]["critical_factor_floor"])
        minimum_paths = int(system["thresholds"]["minimum_independent_paths"])
        eligible = (
            bearing >= threshold
            and min(factors.values()) >= floor
            and len(paths) >= minimum_paths
            and bool(payload.get("support_diversity"))
        )
        assessment = dict(payload)
        assessment["id"] = str(
            payload.get("id") or self._new_id("bearing_assessment")
        )
        assessment["residue_id"] = residue_id
        assessment["state"] = "complete"
        assessment["bearing_index"] = round(bearing, 6)
        assessment["threshold"] = threshold
        assessment["critical_factor_floor"] = floor
        assessment["eligible_for_substrate_candidate"] = eligible
        prior = residue["state"]
        if eligible:
            residue["state"] = "substrate_candidate"
        residue["bearing_assessment_id"] = assessment["id"]
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": residue["state"],
                "actor": actor,
                "at": utc_now(),
                "evidence": {
                    "bearing_assessment_id": assessment["id"],
                    "bearing_index": round(bearing, 6),
                },
            }
        )
        event = self._commit(
            event_type="bearing_assessed",
            actor=actor,
            writes=(("bearing_assessment", assessment), ("residue", residue)),
            details={
                "residue_id": residue_id,
                "bearing_index": round(bearing, 6),
                "eligible": eligible,
            },
        )
        return {
            "assessment": self.get(assessment["id"]),
            "residue": self.get(residue_id),
            "event": event,
        }

    @locked_mutation
    def authorize_load_bearing(
        self,
        residue_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        residue = self.get(residue_id, "residue")
        if residue.get("state") != "substrate_candidate":
            raise FrontierError(
                "load-bearing authorization requires substrate_candidate "
                f"residue; found {residue.get('state')}"
            )
        require_fields(
            payload,
            (
                "authorized_load",
                "reuse_evidence",
                "independent_decoders",
                "constraint_retention_evidence",
                "bounded_failures",
                "authority",
            ),
        )
        reuse = require_list(payload, "reuse_evidence")
        decoders = set(str(value) for value in require_list(payload, "independent_decoders"))
        minimum = int(self.system()["thresholds"]["minimum_independent_paths"])
        if len(reuse) < minimum or len(decoders) < minimum:
            raise FrontierError(
                f"load-bearing authorization requires at least {minimum} "
                "reuse events and independent decoders"
            )
        prior = residue["state"]
        residue["state"] = "load_bearing"
        residue["authorized_load"] = payload["authorized_load"]
        residue["load_authorization"] = dict(payload)
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": "load_bearing",
                "actor": actor,
                "at": utc_now(),
                "evidence": dict(payload),
            }
        )
        event = self._commit(
            event_type="load_bearing_scope_authorized",
            actor=actor,
            writes=(("residue", residue),),
            details={"residue_id": residue_id},
        )
        return {"object": self.get(residue_id), "event": event}

    @locked_mutation
    def register_claim(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "text",
                "behavioral_meaning",
                "positive_scope",
                "negative_scope",
                "evidence",
                "authority",
                "action_enabled",
                "legitimacy_radius",
            ),
        )
        if bool(payload.get("global")):
            raise FrontierError(
                "RFS-1 blocks direct global claims; register a projection, "
                "build independent support, and use invariant promotion"
            )
        return self._create(
            "claim",
            payload,
            actor=actor,
            event_type="claim_projection_registered",
            state="projection",
        )

    @locked_mutation
    def advance_claim(
        self,
        claim_id: str,
        target_state: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        claim = self.get(claim_id, "claim")
        current = claim["state"]
        if target_state == "scoped_invariant":
            raise FrontierError(
                "claim cannot self-transition to scoped_invariant; use RFS-1 "
                "invariant nomination and promotion"
            )
        if target_state in CLAIM_SIDE_STATES:
            require_fields(payload, ("reason", "resulting_scope"))
        else:
            expected = {
                "projection": "local_claim",
                "local_claim": "supported_claim",
            }.get(current)
            if target_state != expected:
                raise FrontierError(
                    f"claim transition must be {current} -> {expected}; "
                    f"requested {target_state}"
                )
            if target_state == "local_claim":
                require_fields(payload, ("collapse_id", "local_scope"))
                self.get(str(payload["collapse_id"]), "collapse")
            if target_state == "supported_claim":
                support = require_list(payload, "independent_support")
                if len(support) < 2:
                    raise FrontierError(
                        "supported_claim requires at least two independent paths"
                    )
        claim.setdefault("history", []).append(
            {
                "from": current,
                "to": target_state,
                "actor": actor,
                "at": utc_now(),
                "evidence": dict(payload),
            }
        )
        claim["state"] = target_state
        claim.update(
            {
                key: value
                for key, value in payload.items()
                if key not in {"id", "state", "schema"}
            }
        )
        event = self._commit(
            event_type=f"claim_{target_state}",
            actor=actor,
            writes=(("claim", claim),),
            details={"claim_id": claim_id, "from": current, "to": target_state},
        )
        return {"object": self.get(claim_id), "event": event}

    @locked_mutation
    def register_quiver(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "decoder_or_lane",
                "purpose",
                "decision_horizon",
                "nodes",
                "edges",
                "expansion_gate",
                "recursion_budget",
            ),
        )
        require_list(payload, "nodes")
        require_list(payload, "edges")
        return self._create(
            "quiver",
            payload,
            actor=actor,
            event_type="quiver_registered",
        )

    @locked_mutation
    def suspend_object(
        self,
        object_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        target = self.get(object_id)
        require_fields(
            payload,
            (
                "reason",
                "owner",
                "review_trigger",
                "exact_handles",
                "semantic_signatures",
                "positive_bounds",
                "apophatic_bounds",
                "transformations",
                "contradictions",
                "drift_markers",
                "next_expansion_gate",
                "next_lawful_collapse_condition",
            ),
        )
        require_list(payload, "exact_handles")
        require_list(payload, "semantic_signatures")
        suspension = dict(payload)
        suspension["id"] = str(
            payload.get("id") or self._new_id("suspension")
        )
        suspension["object_id"] = object_id
        suspension["object_type"] = target.get("schema", "unknown")
        suspension["state"] = "active"
        event = self._commit(
            event_type="object_suspended",
            actor=actor,
            writes=(("suspension", suspension),),
            details={
                "object_id": object_id,
                "suspension_id": suspension["id"],
            },
        )
        return {"object": self.get(suspension["id"]), "event": event}

    @locked_mutation
    def register_contradiction(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "objects_in_tension",
                "description",
                "source_perceptions",
                "severity",
                "decision_consequence",
                "resolution_evidence",
                "owner",
            ),
        )
        severity = str(payload["severity"]).upper()
        if severity not in {"C0", "C1", "C2", "C3", "C4"}:
            raise FrontierError("severity must be C0, C1, C2, C3, or C4")
        record = dict(payload)
        record["severity"] = severity
        return self._create(
            "contradiction",
            record,
            actor=actor,
            event_type="contradiction_registered",
            state="registered",
        )

    @locked_mutation
    def dispose_contradiction(
        self,
        contradiction_id: str,
        target_state: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        contradiction = self.get(contradiction_id, "contradiction")
        if target_state not in CONTRADICTION_STATES[2:]:
            raise FrontierError(
                "contradiction disposition must be bounded, resolved, retained, "
                "escalated, superseded, or withdrawn"
            )
        require_fields(payload, ("disposition", "evidence", "visible_remainder"))
        current = contradiction["state"]
        contradiction["state"] = target_state
        contradiction.setdefault("history", []).append(
            {
                "from": current,
                "to": target_state,
                "actor": actor,
                "at": utc_now(),
                "evidence": dict(payload),
            }
        )
        contradiction.update(dict(payload))
        event = self._commit(
            event_type=f"contradiction_{target_state}",
            actor=actor,
            writes=(("contradiction", contradiction),),
            details={"contradiction_id": contradiction_id},
        )
        return {"object": self.get(contradiction_id), "event": event}

    @locked_mutation
    def measure_tension(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "global_claim",
                "proposed_legitimacy_radius",
                "lanes",
                "active_contradictions",
                "audit_queue",
                "response_authority",
            ),
        )
        lanes = require_list(payload, "lanes")
        unsafe: list[str] = []
        normalized: list[dict[str, Any]] = []
        for lane in lanes:
            if not isinstance(lane, dict):
                raise FrontierError("each tension lane must be an object")
            require_fields(lane, ("lane_id", "slack_growth", "audit_velocity"))
            slack = float(lane["slack_growth"])
            audit = float(lane["audit_velocity"])
            safe = audit >= slack
            if not safe:
                unsafe.append(str(lane["lane_id"]))
            normalized.append({**lane, "safe": safe})
        outcome = "maintain" if not unsafe else "contract_or_resource"
        report = dict(payload)
        report["id"] = str(
            payload.get("id") or self._new_id("tension_report")
        )
        report["lanes"] = normalized
        report["unsafe_lanes"] = unsafe
        report["state"] = "complete"
        report["outcome"] = outcome
        report["resulting_legitimacy_radius"] = (
            payload["proposed_legitimacy_radius"]
            if not unsafe
            else payload.get("contracted_radius", "local_only")
        )
        system = self.system()
        system["legitimacy"] = {
            "current_radius": report["resulting_legitimacy_radius"],
            "last_tension_report_id": report["id"],
        }
        event = self._commit(
            event_type="tension_measured",
            actor=actor,
            writes=(("tension_report", report),),
            details={
                "tension_report_id": report["id"],
                "outcome": outcome,
                "unsafe_lanes": unsafe,
            },
        )
        refreshed = self.system()
        refreshed["legitimacy"] = system["legitimacy"]
        atomic_write_json(self.system_path, refreshed)
        return {"object": self.get(report["id"]), "event": event}

    @locked_mutation
    def nominate_invariant(
        self,
        residue_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        residue = self.get(residue_id, "residue")
        if residue.get("state") != "load_bearing":
            raise FrontierError(
                f"invariant nomination requires load_bearing residue; found {residue.get('state')}"
            )
        require_fields(
            payload,
            (
                "text",
                "behavioral_meaning",
                "positive_scope",
                "negative_scope",
                "supporting_paths",
                "support_diversity",
                "pilot_removal",
                "contradictions",
                "failure_test",
                "owner",
                "review_trigger",
                "expiry",
                "demotion_trigger",
                "replacement_plan",
            ),
        )
        paths = require_list(payload, "supporting_paths")
        if len(paths) < int(
            self.system()["thresholds"]["minimum_independent_paths"]
        ):
            raise FrontierError(
                "invariant nomination requires multiple independent paths"
            )
        pilot = payload["pilot_removal"]
        if not isinstance(pilot, dict) or pilot.get("result") != "pass":
            raise FrontierError("pilot_removal must be an object with result=pass")
        invariant = dict(payload)
        invariant["id"] = str(
            payload.get("id") or self._new_id("invariant")
        )
        invariant["residue_id"] = residue_id
        invariant["state"] = "candidate"
        invariant["rfs1"] = {
            condition: False for condition in RFS1_CONDITIONS
        }
        prior = residue["state"]
        residue["state"] = "invariant_candidate"
        residue["invariant_id"] = invariant["id"]
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": "invariant_candidate",
                "actor": actor,
                "at": utc_now(),
                "evidence": {"invariant_id": invariant["id"]},
            }
        )
        event = self._commit(
            event_type="invariant_nominated",
            actor=actor,
            writes=(("invariant", invariant), ("residue", residue)),
            details={
                "invariant_id": invariant["id"],
                "residue_id": residue_id,
            },
        )
        return {
            "invariant": self.get(invariant["id"]),
            "residue": self.get(residue_id),
            "event": event,
        }

    @locked_mutation
    def promote_invariant(
        self,
        invariant_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        invariant = self.get(invariant_id, "invariant")
        if invariant.get("state") != "candidate":
            raise FrontierError(
                f"promotion requires candidate invariant; found {invariant.get('state')}"
            )
        require_fields(
            payload,
            (
                "rfs1",
                "council_decision",
                "council_members",
                "dissent_receipt",
                "tension_report_id",
                "certificate_scope",
            ),
        )
        checklist = payload["rfs1"]
        if not isinstance(checklist, dict):
            raise FrontierError("rfs1 must be an object")
        failed = [
            condition
            for condition in RFS1_CONDITIONS
            if checklist.get(condition) is not True
        ]
        if failed:
            raise FrontierError(
                "RFS-1 promotion conditions failed: " + ", ".join(failed)
            )
        if str(payload["council_decision"]).lower() != "approve":
            raise FrontierError("council_decision must be approve")
        council = require_list(payload, "council_members")
        if len(set(str(member) for member in council)) < 2:
            raise FrontierError("promotion requires at least two council members")
        tension = self.get(str(payload["tension_report_id"]), "tension_report")
        if tension.get("outcome") != "maintain":
            raise FrontierError(
                "RFS-1 promotion requires a tension report that maintains the claimed radius"
            )
        residue = self.get(str(invariant["residue_id"]), "residue")
        invariant["state"] = "anchor"
        invariant["rfs1"] = dict(checklist)
        invariant["certificate"] = {
            **dict(payload),
            "promoted_by": actor,
            "promoted_at": utc_now(),
        }
        prior = residue["state"]
        residue["state"] = "invariant_anchor"
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": "invariant_anchor",
                "actor": actor,
                "at": utc_now(),
                "evidence": {"invariant_id": invariant_id},
            }
        )
        event = self._commit(
            event_type="rfs1_invariant_promoted",
            actor=actor,
            writes=(("invariant", invariant), ("residue", residue)),
            details={
                "invariant_id": invariant_id,
                "residue_id": residue["id"],
            },
        )
        return {
            "invariant": self.get(invariant_id),
            "residue": self.get(residue["id"]),
            "event": event,
        }

    @locked_mutation
    def demote_invariant(
        self,
        invariant_id: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        invariant = self.get(invariant_id, "invariant")
        if invariant.get("state") not in {"candidate", "anchor"}:
            raise FrontierError(
                f"cannot demote invariant in state {invariant.get('state')}"
            )
        require_fields(
            payload,
            (
                "reason",
                "evidence",
                "target_residue_state",
                "resulting_scope",
                "replacement_or_retest",
            ),
        )
        target = str(payload["target_residue_state"])
        if target not in {
            "load_bearing",
            "returnable",
            "suspended",
            "archived",
        }:
            raise FrontierError(
                "target_residue_state must be load_bearing, returnable, "
                "suspended, or archived"
            )
        residue = self.get(str(invariant["residue_id"]), "residue")
        invariant["state"] = "demoted"
        invariant.setdefault("demotions", []).append(
            {**dict(payload), "actor": actor, "at": utc_now()}
        )
        prior = residue["state"]
        residue["state"] = "demoted"
        residue["demoted_to"] = target
        residue.setdefault("maturity_history", []).append(
            {
                "from": prior,
                "to": "demoted",
                "actor": actor,
                "at": utc_now(),
                "evidence": dict(payload),
            }
        )
        event = self._commit(
            event_type="invariant_demoted",
            actor=actor,
            writes=(("invariant", invariant), ("residue", residue)),
            details={
                "invariant_id": invariant_id,
                "target_residue_state": target,
            },
        )
        return {
            "invariant": self.get(invariant_id),
            "residue": self.get(residue["id"]),
            "event": event,
        }

    @locked_mutation
    def record_adaptation(
        self,
        kind: str,
        payload: Mapping[str, Any],
        *,
        actor: str,
    ) -> dict[str, Any]:
        if kind not in {"mutation", "modulation"}:
            raise FrontierError("adaptation kind must be mutation or modulation")
        if kind == "mutation":
            require_fields(
                payload,
                (
                    "structural_change",
                    "affected_structure",
                    "affected_objects",
                    "migration_plan",
                    "compatibility_boundary",
                    "recovery_plan",
                    "independent_validation",
                    "new_audit_obligations",
                    "lineage_update",
                    "authority",
                ),
            )
            if payload.get("reversible_only") is True:
                raise FrontierError(
                    "a reversible-only change should be classified as modulation"
                )
        else:
            require_fields(
                payload,
                (
                    "existing_pathway",
                    "prior_state",
                    "proposed_state",
                    "activation_condition",
                    "expiry",
                    "rollback_condition",
                    "rollback_method",
                    "metrics",
                    "authority",
                ),
            )
            if payload.get("changes_schema") or payload.get("changes_policy"):
                raise FrontierError(
                    "modulation cannot change persistent schema or policy; "
                    "classify as mutation"
                )
        record = dict(payload)
        record["kind"] = kind
        return self._create(
            "adaptation",
            record,
            actor=actor,
            event_type=f"{kind}_receipted",
            state="active" if kind == "modulation" else "applied",
        )

    @locked_mutation
    def compile_lineage(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "successor_decoder",
                "scope",
                "anti_claim",
                "components",
                "environment",
                "next_lawful_actions",
                "blocked_gates",
            ),
        )
        for list_field in (
            "active_claims",
            "contradictions",
            "residue_ids",
            "invariant_ids",
        ):
            if list_field not in payload or not isinstance(
                payload[list_field], list
            ):
                raise FrontierError(f"{list_field} must be a list")
        components = payload["components"]
        if not isinstance(components, dict):
            raise FrontierError("components must be an object")
        required_components = {
            "global_abstraction",
            "local_quivers",
            "legitimacy_radius",
            "adaptation_history",
        }
        missing = sorted(
            name
            for name in required_components
            if not is_resolved(components.get(name))
        )
        if missing:
            raise FrontierError(
                "lineage components unresolved: " + ", ".join(missing)
            )
        for object_id in (
            list(payload.get("residue_ids", []))
            + list(payload.get("invariant_ids", []))
            + list(payload.get("contradictions", []))
            + list(payload.get("active_claims", []))
        ):
            self.get(str(object_id))
        record = dict(payload)
        record["bundle_hash_basis"] = hashlib.sha256(
            json.dumps(record, sort_keys=True).encode("utf-8")
        ).hexdigest()
        return self._create(
            "lineage_bundle",
            record,
            actor=actor,
            event_type="lineage_bundle_compiled",
            state="compiled",
        )

    @locked_mutation
    def record_relaunch(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(
            payload,
            (
                "prior_voyage_id",
                "returned_residue_ids",
                "changed_boundary",
                "retired_assumption",
                "new_pressure",
                "next_objective",
                "next_collapse",
                "return_owner",
                "action_change_evidence",
            ),
        )
        voyage = self.get(str(payload["prior_voyage_id"]), "voyage")
        if voyage.get("state") != "reconciled":
            raise FrontierError("relaunch requires a reconciled prior voyage")
        for residue_id in require_list(payload, "returned_residue_ids"):
            residue = self.get(str(residue_id), "residue")
            if residue.get("state") not in {
                "returnable",
                "substrate_candidate",
                "load_bearing",
                "invariant_candidate",
                "invariant_anchor",
            }:
                raise FrontierError(
                    f"relaunch residue {residue_id} is not returnable"
                )
        return self._create(
            "relaunch",
            payload,
            actor=actor,
            event_type="frontier_relaunched",
            state="ready",
        )

    @locked_mutation
    def advance_tick(
        self, payload: Mapping[str, Any], *, actor: str
    ) -> dict[str, Any]:
        require_fields(payload, ("summary", "decision_or_boundary"))
        event = self._commit(
            event_type="governed_boundary_tick",
            actor=actor,
            writes=(),
            details=dict(payload),
        )
        return {"event": event}

    def status(self) -> dict[str, Any]:
        system = self.system()
        registry = self.registry()
        counts: dict[str, int] = {}
        states: dict[str, dict[str, int]] = {}
        for entry in registry.get("objects", {}).values():
            record_type = str(entry["type"])
            state = str(entry.get("state", "registered"))
            counts[record_type] = counts.get(record_type, 0) + 1
            states.setdefault(record_type, {})[state] = (
                states.setdefault(record_type, {}).get(state, 0) + 1
            )
        contradictions = [
            (object_id, entry)
            for object_id, entry in registry.get("objects", {}).items()
            if entry.get("type") == "contradiction"
            and entry.get("state") not in {
                "resolved",
                "superseded",
                "withdrawn",
            }
        ]
        return {
            "schema": "rfs.status.v1",
            "generated_at": utc_now(),
            "system_id": system["system_id"],
            "title": system["title"],
            "current_tick": system["current_tick"],
            "status": system["status"],
            "legitimacy": system["legitimacy"],
            "counts": counts,
            "states": states,
            "active_contradiction_count": len(contradictions),
        }

    def validate(self) -> ValidationReport:
        report = ValidationReport(root=self.root)
        try:
            system = self.system()
            registry = self.registry()
        except FrontierError as exc:
            report.fail(str(exc))
            return report
        if system.get("schema") != SYSTEM_SCHEMA:
            report.fail("system schema mismatch")
        if registry.get("schema") != REGISTRY_SCHEMA:
            report.fail("registry schema mismatch")
        object_counts: dict[str, int] = {}
        for object_id, entry in registry.get("objects", {}).items():
            record_type = entry.get("type")
            object_counts[record_type] = object_counts.get(record_type, 0) + 1
            path = self.root / str(entry.get("path", ""))
            if not path.exists():
                report.fail(f"registered object file missing: {object_id}")
                continue
            try:
                record = read_json(path)
            except FrontierError as exc:
                report.fail(str(exc))
                continue
            if record.get("id") != object_id:
                report.fail(f"object id mismatch: {object_id}")
            if record.get("state") != entry.get("state"):
                report.fail(f"registry state mismatch: {object_id}")
            if record_type == "voyage":
                state = record.get("state")
                if state not in set(VOYAGE_STATES) | VOYAGE_SIDE_STATES:
                    report.fail(f"invalid voyage state {state}: {object_id}")
            if record_type == "residue":
                state = record.get("state")
                if state not in set(RESIDUE_STATES) | RESIDUE_SIDE_STATES:
                    report.fail(f"invalid residue state {state}: {object_id}")
            if record_type == "claim":
                state = record.get("state")
                if state not in set(CLAIM_STATES) | CLAIM_SIDE_STATES:
                    report.fail(f"invalid claim state {state}: {object_id}")
                if record.get("global") and state != "scoped_invariant":
                    report.fail(f"RFS-1 global claim violation: {object_id}")
            if record_type == "invariant" and record.get("state") == "anchor":
                checklist = record.get("rfs1", {})
                for condition in RFS1_CONDITIONS:
                    if checklist.get(condition) is not True:
                        report.fail(
                            f"promoted invariant missing RFS-1 {condition}: {object_id}"
                        )
        ticks: list[int] = []
        if self.events_path.exists():
            for line_number, line in enumerate(
                self.events_path.read_text(encoding="utf-8").splitlines(),
                start=1,
            ):
                if not line.strip():
                    continue
                try:
                    event = json.loads(line)
                except json.JSONDecodeError:
                    report.fail(f"invalid tick JSON at line {line_number}")
                    continue
                ticks.append(int(event.get("tick", -1)))
        expected = list(range(1, int(system.get("current_tick", 0)) + 1))
        if ticks != expected:
            report.fail(
                f"tick ledger is not consecutive: expected {expected}, found {ticks}"
            )
        report.counts = object_counts
        return report

    def export_context(self, destination: Path | str) -> dict[str, Any]:
        destination_path = Path(destination).expanduser().resolve()
        registry = self.registry()
        objects: list[dict[str, Any]] = []
        for object_id in sorted(registry.get("objects", {})):
            record = self.get(object_id)
            objects.append(
                {
                    "id": object_id,
                    "type": registry["objects"][object_id]["type"],
                    "state": record.get("state"),
                    "updated_tick": record.get("updated_tick"),
                    "summary": (
                        record.get("title")
                        or record.get("text")
                        or record.get("description")
                        or record.get("commitment")
                        or record.get("purpose")
                    ),
                }
            )
        export = {
            "schema": "rfs.context.export.v1",
            "generated_at": utc_now(),
            "system": self.system(),
            "status": self.status(),
            "objects": objects,
            "validation": self.validate().as_dict(),
        }
        atomic_write_json(destination_path, export)
        return export


def print_json(value: Any) -> None:
    print(json.dumps(value, indent=2, ensure_ascii=False))


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=(
            "Operate a Frontier Substrate System with registered objects, "
            "separate lifecycles, fail-closed gates, and append-only ticks."
        )
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    init = subparsers.add_parser("init", help="initialize a frontier system")
    init.add_argument("root", type=Path)
    init.add_argument("--title", required=True)
    init.add_argument("--owner", required=True)
    init.add_argument("--telos", required=True)
    init.add_argument("--bearing-threshold", type=float, default=0.72)
    init.add_argument("--critical-factor-floor", type=float, default=0.50)
    init.add_argument("--force", action="store_true")

    def mutation(name: str, help_text: str) -> argparse.ArgumentParser:
        child = subparsers.add_parser(name, help=help_text)
        child.add_argument("root", type=Path)
        child.add_argument("--actor", required=True)
        child.add_argument("--payload", type=Path, required=True)
        return child

    mutation("register-pressure", "register frontier pressure")
    mutation("register-perception", "register decoder-relative perception")
    mutation("open-voyage", "propose a bounded voyage")

    advance_voyage = mutation("advance-voyage", "advance one voyage state")
    advance_voyage.add_argument("--voyage-id", required=True)
    advance_voyage.add_argument("--target-state", required=True)

    collapse = mutation("record-collapse", "receipt a local collapse")
    collapse.add_argument("--voyage-id", required=True)

    residue = mutation("index-residue", "index residue from a collapse")
    residue.add_argument("--collapse-id", required=True)

    return_test = mutation(
        "test-returnability", "run an independent returnability test"
    )
    return_test.add_argument("--residue-id", required=True)

    bearing = mutation("score-bearing", "calculate a Bearing Index")
    bearing.add_argument("--residue-id", required=True)

    load = mutation(
        "authorize-load-bearing", "authorize bounded load-bearing substrate"
    )
    load.add_argument("--residue-id", required=True)

    mutation("register-claim", "register a bounded claim projection")
    advance_claim = mutation("advance-claim", "advance or contract a claim")
    advance_claim.add_argument("--claim-id", required=True)
    advance_claim.add_argument("--target-state", required=True)

    mutation("register-quiver", "register a local perception-action quiver")
    suspend = mutation("suspend-object", "create a suspension envelope")
    suspend.add_argument("--object-id", required=True)

    mutation("register-contradiction", "register visible contradiction")
    dispose = mutation(
        "dispose-contradiction", "govern a contradiction disposition"
    )
    dispose.add_argument("--contradiction-id", required=True)
    dispose.add_argument("--target-state", required=True)

    mutation("measure-tension", "measure slack and audit velocity")

    nominate = mutation("nominate-invariant", "nominate a scoped invariant")
    nominate.add_argument("--residue-id", required=True)
    promote = mutation("promote-invariant", "apply RFS-1 promotion")
    promote.add_argument("--invariant-id", required=True)
    demote = mutation("demote-invariant", "demote an invariant")
    demote.add_argument("--invariant-id", required=True)

    adaptation = mutation(
        "record-adaptation", "receipt mutation or modulation"
    )
    adaptation.add_argument("--kind", choices=("mutation", "modulation"), required=True)

    mutation("compile-lineage", "compile a successor lineage bundle")
    mutation("record-relaunch", "record a changed frontier launch boundary")
    mutation("advance-tick", "record a governed boundary tick")

    status = subparsers.add_parser("status", help="show bounded system status")
    status.add_argument("root", type=Path)

    validate = subparsers.add_parser("validate", help="validate system integrity")
    validate.add_argument("root", type=Path)

    export = subparsers.add_parser("export-context", help="export hydration context")
    export.add_argument("root", type=Path)
    export.add_argument("--destination", type=Path, required=True)
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        if args.command == "init":
            system = FrontierSystem.initialize(
                args.root,
                title=args.title,
                owner=args.owner,
                telos=args.telos,
                bearing_threshold=args.bearing_threshold,
                critical_factor_floor=args.critical_factor_floor,
                force=args.force,
            )
            print_json(system.status())
            return 0

        system = FrontierSystem(args.root)
        if args.command == "status":
            print_json(system.status())
            return 0
        if args.command == "validate":
            report = system.validate()
            print_json(report.as_dict())
            return 0 if report.ok else 2
        if args.command == "export-context":
            print_json(system.export_context(args.destination))
            return 0

        payload = load_payload(args.payload)
        actor = args.actor
        dispatch = {
            "register-pressure": lambda: system.register_pressure(
                payload, actor=actor
            ),
            "register-perception": lambda: system.register_perception(
                payload, actor=actor
            ),
            "open-voyage": lambda: system.open_voyage(payload, actor=actor),
            "advance-voyage": lambda: system.advance_voyage(
                args.voyage_id,
                args.target_state,
                payload,
                actor=actor,
            ),
            "record-collapse": lambda: system.record_collapse(
                args.voyage_id, payload, actor=actor
            ),
            "index-residue": lambda: system.index_residue(
                args.collapse_id, payload, actor=actor
            ),
            "test-returnability": lambda: system.test_returnability(
                args.residue_id, payload, actor=actor
            ),
            "score-bearing": lambda: system.score_bearing(
                args.residue_id, payload, actor=actor
            ),
            "authorize-load-bearing": lambda: system.authorize_load_bearing(
                args.residue_id, payload, actor=actor
            ),
            "register-claim": lambda: system.register_claim(
                payload, actor=actor
            ),
            "advance-claim": lambda: system.advance_claim(
                args.claim_id,
                args.target_state,
                payload,
                actor=actor,
            ),
            "register-quiver": lambda: system.register_quiver(
                payload, actor=actor
            ),
            "suspend-object": lambda: system.suspend_object(
                args.object_id, payload, actor=actor
            ),
            "register-contradiction": lambda: system.register_contradiction(
                payload, actor=actor
            ),
            "dispose-contradiction": lambda: system.dispose_contradiction(
                args.contradiction_id,
                args.target_state,
                payload,
                actor=actor,
            ),
            "measure-tension": lambda: system.measure_tension(
                payload, actor=actor
            ),
            "nominate-invariant": lambda: system.nominate_invariant(
                args.residue_id, payload, actor=actor
            ),
            "promote-invariant": lambda: system.promote_invariant(
                args.invariant_id, payload, actor=actor
            ),
            "demote-invariant": lambda: system.demote_invariant(
                args.invariant_id, payload, actor=actor
            ),
            "record-adaptation": lambda: system.record_adaptation(
                args.kind, payload, actor=actor
            ),
            "compile-lineage": lambda: system.compile_lineage(
                payload, actor=actor
            ),
            "record-relaunch": lambda: system.record_relaunch(
                payload, actor=actor
            ),
            "advance-tick": lambda: system.advance_tick(
                payload, actor=actor
            ),
        }
        print_json(dispatch[args.command]())
        return 0
    except FrontierError as exc:
        print(f"rfs: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())
