# SPDX-License-Identifier: AGPL-3.0-or-later
"""Self-host Phase 5: the run entry point.

One test per named shape of the implementer brief: the run-spec load, the
fail-closed configuration refusals, the start drive (acceptance claim and
recorded refusal), the read-only observe, the stop/settle, the pinned import
surface, and the evidence-policy binding.

Every case is slow-marked, because the start/stop cases really execute
sandboxed commands (the project oracle's fast gate deselects slow tests, and
this module is no exception).
"""

from __future__ import annotations

import ast
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

import pytest
import yaml

from orchestrator import events, reducer, run_entry
from orchestrator.executor import AttemptCancelled, AttemptTimedOut
from orchestrator.executor_protocol import ProtocolViolation
from orchestrator.store import EventStore


pytestmark = pytest.mark.slow


_REPO_ROOT = Path(__file__).resolve().parents[1]
_SCRIPT = _REPO_ROOT / "scripts" / "orchestrate.py"


def _clean_env() -> dict:
    """The operator environment without pytest's `pythonpath` injection."""
    return {key: value for key, value in os.environ.items() if key != "PYTHONPATH"}


def _documented_interpreter() -> str:
    """The interpreter the documented CLI form names: the `python3` on PATH.

    The pin runs the literal `python3 scripts/orchestrate.py` form when that
    interpreter can import the CLI's one third-party dependency (`yaml`).
    On a host whose system `python3` cannot, it falls back to the interpreter
    running this suite (`sys.executable`) and the fallback is named here.
    """
    candidate = shutil.which("python3") or "python3"
    probe = subprocess.run([candidate, "-c", "import yaml"], capture_output=True)
    if probe.returncode == 0:
        return candidate
    return sys.executable


def _run_cli(args, *, cwd=None, env=None) -> subprocess.CompletedProcess:
    return subprocess.run(
        [_documented_interpreter(), str(_SCRIPT), *args],
        capture_output=True,
        text=True,
        cwd=cwd or str(_REPO_ROOT),
        env=env if env is not None else _clean_env(),
    )


_GIT_ENV = {
    "GIT_AUTHOR_NAME": "operator",
    "GIT_AUTHOR_EMAIL": "operator@localhost",
    "GIT_COMMITTER_NAME": "operator",
    "GIT_COMMITTER_EMAIL": "operator@localhost",
    "GIT_AUTHOR_DATE": "2000-01-01T00:00:00+0000",
    "GIT_COMMITTER_DATE": "2000-01-01T00:00:00+0000",
}


def _make_repo(root: str) -> tuple[str, str]:
    """A small arbitrary repository with one derivable component."""
    repo = os.path.join(root, "target-repo")
    os.makedirs(os.path.join(repo, "src"))
    with open(os.path.join(repo, "src", "app.py"), "w") as handle:
        handle.write("def value():\n    raise NotImplementedError('value')\n")
    for args in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "base"]):
        subprocess.run(
            ["git", "-C", repo, *args],
            env={**os.environ, **_GIT_ENV},
            check=True,
            capture_output=True,
        )
    commit = subprocess.run(
        ["git", "-C", repo, "rev-parse", "HEAD"],
        capture_output=True,
        text=True,
        check=True,
    ).stdout.strip()
    return repo, commit


def _raw_spec(repo: str, commit: str, run_id: str, command: str, **overrides) -> dict:
    document = {
        "run_id": run_id,
        "repository": repo,
        "base_commit": commit,
        "snapshot_id": f"TARGET-{run_id}",
        "task_statement": "Make the visible check pass.",
        "project_kernel": {"kernel_id": f"KERNEL-{run_id}"},
        "visible_commands": [command],
        "components": [["core", "src/app.py"]],
        "owned_scope": ["src/**"],
        "acceptance_criteria": ["AC-CORE"],
        "budgets": {"MODEL_COST": 10.0},
        "limits": {"actions": 4, "wall_clock_seconds": 60},
        "policy_version": 1,
        "evidence_policy": {"level": "MEDIUM", "version": 1},
        "executor_profile": "command-executor-v1",
    }
    document.update(overrides)
    return document


def _spec(repo: str, commit: str, run_id: str, command: str, **overrides) -> dict:
    return run_entry.validate_run_spec(_raw_spec(repo, commit, run_id, command, **overrides))


# The success command rewrites the target file inside the owned scope and exits
# zero; the failure command exits non-zero, so the attempt is rejected.
_WRITE_AND_PASS = (
    "python3 -c \"open('src/app.py','w').write('def value():\\n    return 1\\n'); "
    "print('visible ok')\""
)
_FAIL = "python3 -c \"raise SystemExit(1)\""
_SLEEP = "python3 -c \"import time; time.sleep(30)\""


# -- Run-spec load shape ------------------------------------------------------


def test_run_spec_load_shape(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-LOAD", _WRITE_AND_PASS)
    target = run_entry.freeze_target(spec)
    assert target.repository == os.path.abspath(repo)
    assert target.commit == commit
    assert target.owned_scope == ("src/**",)
    assert target.acceptance_criteria == ("AC-CORE",)

    config = run_entry.run_configuration(spec, target)
    store = EventStore(os.path.join(str(tmp_path), "load.db"))
    try:
        controller = run_entry.build_run(spec, store=store, workdir=str(tmp_path))[0]
        root = store.state("RUN-LOAD").root_node_id
        contract = store.state("RUN-LOAD").nodes[root].contract
        # The configured scopes, budgets, and limits are observable on the
        # admitted root contract.
        assert contract["owned_scope"] == ["src/**"]
        assert contract["budgets"] == {"MODEL_COST": 10.0}
        assert contract["run_limits"] == {"actions": 4.0, "wall_clock_seconds": 60.0}
        # The control-policy version and the evidence policy are frozen beside
        # each other in the run-specification binding.
        binding = contract["run_specification"]
        assert binding["policy_version"] == 1
        assert binding["evidence_policy"]["level"] == "MEDIUM"
        assert binding["evidence_policy"]["version"] == 1
        # The configuration was admitted by the controller (a root exists).
        assert root == "RUN-LOAD-root"
        assert controller.get_outcome("RUN-LOAD") is None
    finally:
        store.close()


# -- Configuration refusal shape ----------------------------------------------


def _valid_spec_document(repo: str, commit: str) -> dict:
    return {
        "run_id": "RUN-REFUSE",
        "repository": repo,
        "base_commit": commit,
        "snapshot_id": "TARGET-REFUSE",
        "task_statement": "task",
        "project_kernel": {"kernel_id": "K"},
        "visible_commands": ["true"],
        "components": [["core", "src/app.py"]],
        "owned_scope": ["src/**"],
        "acceptance_criteria": ["AC-CORE"],
        "budgets": {"MODEL_COST": 1.0},
        "limits": {"actions": 1},
        "policy_version": 1,
        "evidence_policy": {"level": "MEDIUM", "version": 1},
        "executor_profile": "p",
    }


@pytest.mark.parametrize(
    "mutate",
    [
        pytest.param(lambda d: d.__setitem__("repository", ""), id="empty-repository"),
        pytest.param(lambda d: d.pop("repository"), id="missing-repository"),
        pytest.param(lambda d: d.__setitem__("base_commit", ""), id="empty-base-commit"),
        pytest.param(lambda d: d.pop("base_commit"), id="missing-base-commit"),
        pytest.param(
            lambda d: d.__setitem__("evidence_policy", {"level": "NOT_A_LEVEL", "version": 1}),
            id="unknown-evidence-level",
        ),
        pytest.param(
            lambda d: d.__setitem__("evidence_policy", {"level": "MEDIUM", "version": 0}),
            id="non-positive-evidence-version",
        ),
        pytest.param(
            lambda d: d.__setitem__("evidence_policy", {"level": "MEDIUM", "version": "1"}),
            id="string-evidence-version",
        ),
        pytest.param(
            lambda d: d.__setitem__("budgets", {"NOT_A_DIMENSION": 1.0}),
            id="unknown-budget-dimension",
        ),
        pytest.param(lambda d: d.__setitem__("budgets", {}), id="empty-budgets"),
        pytest.param(lambda d: d.__setitem__("policy_version", 999), id="mismatched-policy"),
        pytest.param(lambda d: d.__setitem__("executor_profile", ""), id="empty-executor"),
        pytest.param(lambda d: d.__setitem__("run_id", ""), id="empty-run-id"),
    ],
)
def test_configuration_refusal_shape(tmp_path, mutate):
    repo, commit = _make_repo(str(tmp_path))
    document = _valid_spec_document(repo, commit)
    mutate(document)
    store = EventStore(os.path.join(str(tmp_path), "refuse.db"))
    try:
        with pytest.raises(run_entry.RunSpecError):
            run_entry.start_run(document, store=store, workdir=str(tmp_path))
        # Nothing was admitted and no run state exists.
        assert store.history("RUN-REFUSE") == []
        assert store.state("RUN-REFUSE").root_node_id is None
    finally:
        store.close()


def test_run_configuration_schema_is_a_second_boundary(tmp_path):
    """A configuration the RunConfiguration schema would reject is wrapped as a
    named load-time error rather than escaping as a SchemaValidationError."""
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-SCHEMA", _WRITE_AND_PASS)
    target = run_entry.freeze_target(spec)
    # Bypass the run-spec validator to reach the builder's own schema check.
    bad = dict(spec)
    bad["evidence_policy"] = {"level": "NOT_A_LEVEL", "version": 1}
    with pytest.raises(run_entry.RunSpecError):
        run_entry.run_configuration(bad, target)


# -- Start shape --------------------------------------------------------------


def test_start_shape_authorises_acceptance(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-START", _WRITE_AND_PASS)
    store = EventStore(os.path.join(str(tmp_path), "start.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.accepted is True
        assert result.outcome == "ACCEPTANCE_CLAIMED"
        state = store.state("RUN-START")
        attempt = state.attempts[result.attempt_id]
        assert attempt.state == "RESULT_PRODUCED"
        assert attempt.accounting_state == "FINALLY_SETTLED"
        # The evidence was admitted and is visible.
        assert result.evidence_id in state.evidence
        assert state.nodes[result.root_node_id].state == "ACCEPTED"
        assert result.outcome in ("ACCEPTANCE_CLAIMED",)
    finally:
        store.close()


def test_start_shape_records_a_refusal_without_authorising(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-REFUSE-CMD", _FAIL)
    store = EventStore(os.path.join(str(tmp_path), "refuse-cmd.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.accepted is False
        assert result.outcome == "INFEASIBLE"
        state = store.state("RUN-REFUSE-CMD")
        # Failing checks were recorded as evidence and the attempt settled.
        evidence = state.evidence[result.evidence_id]
        assert any(not check.get("passed") for check in evidence.checks)
        assert state.attempts[result.attempt_id].accounting_state == "FINALLY_SETTLED"
        # Acceptance was never authorised: no ACCEPTANCE_AUTHORISED event.
        types = [event.event_type for event in store.history("RUN-REFUSE-CMD")]
        assert "ACCEPTANCE_AUTHORISED" not in types
        assert "VALIDATION_PASSED" not in types
        # One observed failure is one recorded failure: the terminal outcome
        # comes from the deterministic-infeasibility route, not from a
        # manufactured repeat.
        assert types.count("FAILURE_RECORDED") == 1
        replans = [
            event.payload.get("reason")
            for event in store.history("RUN-REFUSE-CMD")
            if event.event_type == "REPLAN_REQUESTED"
        ]
        assert "REPEATED_FAILURE_WITHOUT_NEW_EVIDENCE" not in replans
    finally:
        store.close()


# -- Observe shape ------------------------------------------------------------


def test_observe_shape_is_read_only(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-OBSERVE", _WRITE_AND_PASS)
    store_path = os.path.join(str(tmp_path), "observe.db")
    store = EventStore(store_path)
    try:
        started = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        before = len(store.history("RUN-OBSERVE"))
        # A second controller over the same store (the "other process") reads
        # the run without admitting anything.
        document = run_entry.inspect_run(store, "RUN-OBSERVE")
        assert len(store.history("RUN-OBSERVE")) == before
        assert document["outcome"] == started.outcome
        assert document["status"]["node_id"] == "RUN-OBSERVE-root"
        assert document["candidate_reference"] is not None
        assert document["evidence"]
        assert document["evidence"][0]["check_class"] == "VISIBLE"
        assert set(document["costs"]) == {
            "total_charged",
            "total_overrun",
            "by_attempt",
            "overruns",
            "open_reservations",
            "open_commitments",
        }
        assert document["event_history"]
    finally:
        store.close()

    # A fresh store connection over the same file sees the same run, still
    # without admitting anything.
    reopened = EventStore(store_path)
    try:
        document = run_entry.inspect_run(reopened, "RUN-OBSERVE")
        assert document["outcome"] == started.outcome
    finally:
        reopened.close()


# -- Stop shape ---------------------------------------------------------------


def test_stop_shape_settles_live_attempts(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-STOP", _WRITE_AND_PASS)
    store = EventStore(os.path.join(str(tmp_path), "stop.db"))
    try:
        controller, _target, run_id, root = run_entry.build_run(
            spec, store=store, workdir=str(tmp_path)
        )
        # In flight: a planned, reserved attempt that was never dispatched.
        dimension, amount = run_entry._budget_dimension(spec["budgets"])
        attempt_id = controller.plan_attempt(
            run_id, root, {"amount": amount, "dimension": dimension}
        )
        assert store.state(run_id).outcome is None
        outcome = run_entry.stop_run(store, run_id)
        assert outcome == "CANCELLED"
        attempt = store.state(run_id).attempts[attempt_id]
        assert attempt.state == "CANCELLED"
        assert attempt.accounting_state == "FINALLY_SETTLED"
        assert store.state(run_id).nodes[root].state == "CANCELLED"
    finally:
        store.close()


def test_stop_never_rewrites_a_settled_outcome(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-SETTLED", _WRITE_AND_PASS)
    store = EventStore(os.path.join(str(tmp_path), "settled.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.outcome == "ACCEPTANCE_CLAIMED"
        assert run_entry.stop_run(store, result.run_id) == "ACCEPTANCE_CLAIMED"
        assert store.state(result.run_id).outcome == "ACCEPTANCE_CLAIMED"
    finally:
        store.close()


# -- No-harness-import shape --------------------------------------------------

_FORBIDDEN_MODULES = {
    "experiment",
    "experiment_spec",
    "experiment_phases",
    "trial_driver",
    "smoke_run",
}


def _imported_module_names(path: Path) -> set[str]:
    tree = ast.parse(path.read_text())
    names: set[str] = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                names.add(alias.name)
        elif isinstance(node, ast.ImportFrom):
            prefix = "." * node.level
            if node.module is not None:
                names.add(f"{prefix}{node.module}")
                for alias in node.names:
                    # `from orchestrator import experiment` names a module in
                    # the alias, not only in `node.module`.
                    names.add(f"{prefix}{node.module}.{alias.name}")
            else:
                # A relative `from . import experiment` carries no module; the
                # alias is the imported name.
                for alias in node.names:
                    names.add(f"{prefix}{alias.name}")
    return names


def _module_segments(name: str) -> set[str]:
    """Every dotted segment of one import path.

    The leaf-only collapse missed a dotted absolute import such as
    ``import orchestrator.experiment_spec.sub``: the forbidden module is an
    interior segment, not the leaf. The dynamic-import forms
    (``__import__("orchestrator.experiment")``, ``importlib.import_module``)
    are outside the AST and remain a known unenforced class for this static pin.
    """
    return set(name.lstrip(".").split("."))


def test_no_harness_import_shape():
    import orchestrate

    for path in (
        Path(run_entry.__file__ or ""),
        Path(orchestrate.__file__ or ""),
    ):
        segments: set[str] = set()
        for name in _imported_module_names(path):
            segments |= _module_segments(name)
        assert not (segments & _FORBIDDEN_MODULES), (
            f"{path.name} imports a harness module: {segments & _FORBIDDEN_MODULES}"
        )
    # The allowed seam is present in the run-entry module.
    run_entry_segments: set[str] = set()
    for name in _imported_module_names(Path(run_entry.__file__ or "")):
        run_entry_segments |= _module_segments(name)
    assert "experiment_target" in run_entry_segments


# Each spelling a future drift could take. The helper must flag every one of
# them, including the two the review's mutants reached green: a named import
# (`from orchestrator import experiment`) and a relative import
# (`from . import experiment`), and the dotted absolute import whose forbidden
# segment is interior rather than the leaf.
_IMPORT_SPELLINGS = {
    "absolute-import": "import orchestrator.experiment_spec\n",
    "dotted-import": "import orchestrator.experiment_spec.sub\n",
    "named-import": "from orchestrator import experiment\n",
    "relative-import": "from . import experiment\n",
    "late-function-import": "def late():\n    import experiment_phases\n",
}


@pytest.mark.parametrize("spelling", sorted(_IMPORT_SPELLINGS))
def test_import_spelling_shape(tmp_path, spelling):
    path = tmp_path / "mutant.py"
    path.write_text(_IMPORT_SPELLINGS[spelling])
    segments: set[str] = set()
    for name in _imported_module_names(path):
        segments |= _module_segments(name)
    assert segments & _FORBIDDEN_MODULES, (
        f"the pin misses the {spelling!r} spelling: {sorted(segments)!r}"
    )


# -- Evidence-policy shape ----------------------------------------------------


def test_evidence_policy_shape_binds_the_run(tmp_path):
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(
        repo,
        commit,
        "RUN-POLICY",
        _WRITE_AND_PASS,
        evidence_policy={"level": "HIGH", "version": 7},
    )
    store = EventStore(os.path.join(str(tmp_path), "policy.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        document = run_entry.inspect_run(store, result.run_id)
        assert document["policy_version"] == 1
        assert document["evidence_policy"]["level"] == "HIGH"
        assert document["evidence_policy"]["version"] == 7
        binding = store.state(result.run_id).nodes[result.root_node_id].contract[
            "run_specification"
        ]
        assert binding["evidence_policy"]["level"] == "HIGH"
        assert binding["evidence_policy"]["version"] == 7
    finally:
        store.close()


# -- Settled-start shape (F11, F12) -------------------------------------------


def _src_env() -> dict:
    """An operator environment with `src` importable without pytest's config."""
    env = _clean_env()
    env["PYTHONPATH"] = str(_REPO_ROOT / "src")
    return env


def test_settled_start_shape_relative_workdir(tmp_path):
    """Every documented `start` form settles the run: a relative workdir and
    store resolve to absolute paths at entry rather than crashing the executor
    and leaving a live run (F11)."""
    repo, commit = _make_repo(str(tmp_path))

    accept_spec = tmp_path / "accept.yaml"
    accept_spec.write_text(yaml.safe_dump(_raw_spec(repo, commit, "RUN-REL", _WRITE_AND_PASS)))
    completed = _run_cli(
        ["start", "--spec", str(accept_spec), "--workdir", "rel-work", "--store", "rel.db"],
        cwd=str(tmp_path),
        env=_src_env(),
    )
    assert completed.returncode == 0, completed.stderr
    assert "Traceback" not in completed.stderr
    document = json.loads(completed.stdout)
    assert document["accepted"] is True
    assert document["outcome"] == "ACCEPTANCE_CLAIMED"

    fail_spec = tmp_path / "fail.yaml"
    fail_spec.write_text(yaml.safe_dump(_raw_spec(repo, commit, "RUN-REL-FAIL", _FAIL)))
    completed = _run_cli(
        ["start", "--spec", str(fail_spec), "--workdir", "rel-work-2", "--store", "rel-fail.db"],
        cwd=str(tmp_path),
        env=_src_env(),
    )
    assert completed.returncode != 0
    assert "Traceback" not in completed.stderr
    document = json.loads(completed.stdout)
    assert document["accepted"] is False
    assert document["outcome"] == "INFEASIBLE"


def test_settled_start_shape_wall_clock_overrun(tmp_path):
    """A wall-clock overrun of the root's visible command settles the run
    through the recorded-refusal path instead of escaping (F12)."""
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(
        repo,
        commit,
        "RUN-TIMEOUT",
        _SLEEP,
        limits={"actions": 4, "wall_clock_seconds": 1},
    )
    store = EventStore(os.path.join(str(tmp_path), "timeout.db"))
    try:
        try:
            result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        except (AttemptCancelled, AttemptTimedOut) as error:
            raise AssertionError(
                f"start_run escaped with {type(error).__name__} instead of "
                "settling the run through the recorded-refusal path"
            ) from error
        assert result.accepted is False
        assert result.outcome == "INFEASIBLE"
        state = store.state("RUN-TIMEOUT")
        attempt = state.attempts[result.attempt_id]
        assert attempt.state == "TIMED_OUT"
        assert attempt.accounting_state == "FINALLY_SETTLED"
        assert state.nodes[result.root_node_id].state == "INFEASIBLE"
        # One observed overrun is exactly one recorded failure. The terminal
        # outcome is reached through NODE_MARKED_INFEASIBLE, not by forging the
        # repeated-failure rule's two-fingerprint precondition.
        fingerprints = state.failure_fingerprints.get(result.root_node_id, [])
        assert len(fingerprints) == 1
        types = [event.event_type for event in store.history("RUN-TIMEOUT")]
        assert "NODE_MARKED_INFEASIBLE" in types
        replans = [
            event.payload.get("reason")
            for event in store.history("RUN-TIMEOUT")
            if event.event_type == "REPLAN_REQUESTED"
        ]
        assert "REPEATED_FAILURE_WITHOUT_NEW_EVIDENCE" not in replans
        # `inspect` reads the honest failure history back: one failure for one
        # overrun.
        document = run_entry.inspect_run(store, "RUN-TIMEOUT")
        assert document["outcome"] == "INFEASIBLE"
        assert sum(
            event["event_type"] == "FAILURE_RECORDED"
            for event in document["event_history"]
        ) == 1
    finally:
        store.close()


# -- ProtocolViolation-refusal shape (F19) ------------------------------------


def test_protocol_violation_refusal_shape(tmp_path, monkeypatch):
    """A mid-dispatch `ProtocolViolation` settles through the same
    recorded-refusal path as a timeout or cancellation: a settled refusal and
    a terminal outcome, never a traceback with a live run (F19)."""
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-PROTO", _WRITE_AND_PASS)
    store = EventStore(os.path.join(str(tmp_path), "proto.db"))
    real_build = run_entry.build_command_executor

    def build_with_violation(target, *, workdir, limits=None):
        executor = real_build(target, workdir=workdir, limits=limits)

        def refusing_dispatch(request):
            raise ProtocolViolation("injected for the protocol-violation pin")

        executor.dispatch = refusing_dispatch
        return executor

    monkeypatch.setattr(run_entry, "build_command_executor", build_with_violation)
    try:
        try:
            result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        except ProtocolViolation as error:
            raise AssertionError(
                "start_run escaped with ProtocolViolation instead of settling "
                "the run through the recorded-refusal path"
            ) from error
        assert result.accepted is False
        assert result.outcome == "INFEASIBLE"
        state = store.state("RUN-PROTO")
        attempt = state.attempts[result.attempt_id]
        assert attempt.accounting_state == "FINALLY_SETTLED"
        assert state.nodes[result.root_node_id].state == "INFEASIBLE"
        assert state.outcome == "INFEASIBLE"
    finally:
        store.close()


# -- Cancelled-launcher shape (F12's second half) -----------------------------


def test_cancelled_launcher_shape(tmp_path):
    """After a mid-run `stop` from a second process, the launcher exits
    non-zero with the settled outcome as its JSON document and no traceback."""
    repo, commit = _make_repo(str(tmp_path))
    spec_path = tmp_path / "cancel.yaml"
    spec_path.write_text(
        yaml.safe_dump(
            _raw_spec(
                repo,
                commit,
                "RUN-CANCEL",
                _SLEEP,
                limits={"actions": 4, "wall_clock_seconds": 3},
            )
        )
    )
    store_path = tmp_path / "cancel.db"
    workdir = tmp_path / "cancel-work"
    env = _src_env()
    launcher = subprocess.Popen(
        [
            sys.executable,
            str(_SCRIPT),
            "start",
            "--spec",
            str(spec_path),
            "--workdir",
            str(workdir),
            "--store",
            str(store_path),
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        cwd=str(_REPO_ROOT),
        env=env,
    )
    dispatched = False
    try:
        deadline = time.time() + 30
        while time.time() < deadline:
            if store_path.exists():
                store = EventStore(str(store_path))
                try:
                    dispatched = any(
                        event.event_type == "ACTION_DISPATCHED"
                        for event in store.history("RUN-CANCEL")
                    )
                finally:
                    store.close()
                if dispatched:
                    break
            time.sleep(0.05)
        assert dispatched, "the launcher never dispatched its root attempt"
        stopped = _run_cli(
            ["stop", "--run-id", "RUN-CANCEL", "--store", str(store_path)], env=env
        )
        assert stopped.returncode == 0, stopped.stderr
        stdout, stderr = launcher.communicate(timeout=60)
    finally:
        if launcher.poll() is None:
            launcher.kill()
            launcher.communicate()
    assert launcher.returncode != 0
    assert "Traceback" not in stderr
    document = json.loads(stdout)
    assert document["accepted"] is False
    assert document["outcome"] == "CANCELLED"


# -- Settle-claim shape (F20) -------------------------------------------------


def _stop_from_second_process(store_path: str, run_id: str) -> None:
    """Run the documented `stop` workflow from a second store connection."""
    second = EventStore(store_path)
    try:
        run_entry.stop_run(second, run_id)
    finally:
        second.close()


def test_settle_claim_shape_stale_outcome_read(tmp_path, monkeypatch):
    """The launcher's document equals the durable fresh outcome when a second
    process's `stop` completes between the launcher's decision read and its
    settle emissions: the point-of-emission re-read skips the node-level chain
    and the attempt is still settled (F20)."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-INTERLEAVE-STALE"
    spec = _spec(
        repo, commit, run_id, _SLEEP, limits={"actions": 4, "wall_clock_seconds": 1}
    )
    store_path = os.path.join(str(tmp_path), "stale.db")
    store = EventStore(store_path)
    real_replay = store.replay_fresh
    calls = {"n": 0}

    def interleaved_replay_fresh(rid):
        calls["n"] += 1
        result = real_replay(rid)
        if calls["n"] == 1:
            # The decision read returned None; the second process now
            # completes its whole stop before the launcher emits anything.
            _stop_from_second_process(store_path, run_id)
        return result

    monkeypatch.setattr(store, "replay_fresh", interleaved_replay_fresh)
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.accepted is False
        # The document names the durable settled outcome, not a stale
        # projection's value.
        assert result.outcome == "CANCELLED"
        assert (
            store.state(run_id).attempts[result.attempt_id].accounting_state
            == "FINALLY_SETTLED"
        )
        types = [event.event_type for event in store.history(run_id)]
        # No node-level settlement chain was admitted after the stop.
        assert "NODE_MARKED_INFEASIBLE" not in types
        assert "FAILURE_RECORDED" not in types
        assert store.replay_fresh(run_id).outcome == "CANCELLED"
    finally:
        store.close()


def test_settle_claim_shape_fresh_outcome_read(tmp_path, monkeypatch):
    """When the second process's `stop` completes before the launcher's
    outcome read, the launcher skips the node chain but still settles the
    timed-out attempt's accounting: a terminal run never leaves it
    PROVISIONALLY_SETTLED (F20)."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-INTERLEAVE-FRESH"
    spec = _spec(
        repo, commit, run_id, _SLEEP, limits={"actions": 4, "wall_clock_seconds": 1}
    )
    store_path = os.path.join(str(tmp_path), "fresh.db")
    store = EventStore(store_path)
    real_replay = store.replay_fresh
    calls = {"n": 0}

    def interleaved_replay_fresh(rid):
        calls["n"] += 1
        if calls["n"] == 1:
            # The second process's complete stop precedes the launcher's
            # first (and only) decision read.
            _stop_from_second_process(store_path, run_id)
        return real_replay(rid)

    monkeypatch.setattr(store, "replay_fresh", interleaved_replay_fresh)
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.accepted is False
        assert result.outcome == "CANCELLED"
        assert (
            store.state(run_id).attempts[result.attempt_id].accounting_state
            == "FINALLY_SETTLED"
        )
        types = [event.event_type for event in store.history(run_id)]
        assert "NODE_MARKED_INFEASIBLE" not in types
        assert "FAILURE_RECORDED" not in types
    finally:
        store.close()


def test_settle_claim_shape_double_stop_after_settled_timeout(tmp_path):
    """A settled timed-out run is idempotent under a second `stop`: the outcome
    is not rewritten, the late-event rule holds, and the attempt's accounting
    stays finally settled (F20)."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-DOUBLE-STOP"
    spec = _spec(
        repo, commit, run_id, _SLEEP, limits={"actions": 4, "wall_clock_seconds": 1}
    )
    store_path = os.path.join(str(tmp_path), "double.db")
    store = EventStore(store_path)
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.outcome == "INFEASIBLE"
        assert run_entry.stop_run(store, run_id) == "INFEASIBLE"
        assert run_entry.stop_run(store, run_id) == "INFEASIBLE"
        fresh = store.replay_fresh(run_id)
        assert fresh.outcome == "INFEASIBLE"
        assert fresh.attempts[result.attempt_id].state == "TIMED_OUT"
        assert fresh.attempts[result.attempt_id].accounting_state == "FINALLY_SETTLED"
    finally:
        store.close()


# -- Clean-env CLI shape (F14) ------------------------------------------------


def test_clean_env_cli_shape(tmp_path):
    """The documented `python3 scripts/orchestrate.py` form runs from a clean
    env at the repo root without `PYTHONPATH`: its `--help`, a real `start`,
    `inspect`, and `stop`.

    The pin runs the `python3` on PATH when it can import `yaml`, as
    `_documented_interpreter` documents; on a host whose system `python3`
    cannot, it falls back to `sys.executable` and this sentence is the record
    of the substitution."""
    completed = _run_cli(["--help"])
    assert completed.returncode == 0, completed.stderr
    assert "ModuleNotFoundError" not in completed.stderr

    repo, commit = _make_repo(str(tmp_path))
    spec_path = tmp_path / "cli.yaml"
    spec_path.write_text(yaml.safe_dump(_raw_spec(repo, commit, "RUN-CLI", _WRITE_AND_PASS)))
    store_path = tmp_path / "cli.db"
    workdir = tmp_path / "cli-work"

    completed = _run_cli(
        ["start", "--spec", str(spec_path), "--workdir", str(workdir), "--store", str(store_path)]
    )
    assert completed.returncode == 0, completed.stderr
    assert "ModuleNotFoundError" not in completed.stderr
    assert json.loads(completed.stdout)["accepted"] is True

    completed = _run_cli(["inspect", "--run-id", "RUN-CLI", "--store", str(store_path)])
    assert completed.returncode == 0, completed.stderr
    assert json.loads(completed.stdout)["outcome"] == "ACCEPTANCE_CLAIMED"

    completed = _run_cli(["stop", "--run-id", "RUN-CLI", "--store", str(store_path)])
    assert completed.returncode == 0, completed.stderr
    assert json.loads(completed.stdout)["outcome"] == "ACCEPTANCE_CLAIMED"


# -- Honest-label shape (F15) -------------------------------------------------


def test_honest_label_shape_records_no_executor_profile(tmp_path):
    """`executor_profile` is a schema-required label and is recorded nowhere:
    the corrected `docs/run-entry.md` row is pinned by its absence from the
    event log and the inspect document."""
    repo, commit = _make_repo(str(tmp_path))
    spec = _spec(repo, commit, "RUN-LABEL", _WRITE_AND_PASS)
    assert spec["executor_profile"] == "command-executor-v1"
    store = EventStore(os.path.join(str(tmp_path), "label.db"))
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.outcome == "ACCEPTANCE_CLAIMED"
        event_log = json.dumps([event.to_record() for event in store.history("RUN-LABEL")])
        assert "command-executor-v1" not in event_log
        document = json.dumps(run_entry.inspect_run(store, "RUN-LABEL"))
        assert "command-executor-v1" not in document
    finally:
        store.close()


# -- Fail-closed-load shape (F16) ---------------------------------------------


def test_fail_closed_load_shape_obligations_refused_before_store(tmp_path):
    """The obligations completeness check is a load-time refusal: an
    obligations-without-axes spec is refused before any store is opened."""
    repo, commit = _make_repo(str(tmp_path))
    document = _raw_spec(repo, commit, "RUN-AXES", _WRITE_AND_PASS)
    document["obligations"] = [
        {
            "obligation_id": "OBL-CORE",
            "criterion_ids": ["AC-CORE"],
            "component": "core",
            "scope": "src/app.py",
        }
    ]
    with pytest.raises(run_entry.RunSpecError):
        run_entry.validate_run_spec(document)

    spec_path = tmp_path / "axes.yaml"
    spec_path.write_text(yaml.safe_dump(document))
    store_path = tmp_path / "axes.db"
    completed = _run_cli(
        [
            "start",
            "--spec",
            str(spec_path),
            "--workdir",
            str(tmp_path / "axes-work"),
            "--store",
            str(store_path),
        ],
        env=_src_env(),
    )
    assert completed.returncode != 0
    assert not store_path.exists()


def test_fail_closed_load_shape_freeze_boundary_admits_zero_events(tmp_path):
    """A freeze-boundary refusal — the DECLARED divergence class with a fully
    valid obligation schema and an unfreezable repository — admits zero events
    but is raised after the CLI has created the store file. The narrowed
    wording in `docs/run-entry.md` and `run_entry`'s module docstring says
    exactly this (F21)."""
    repo, commit = _make_repo(str(tmp_path))

    divergent = _raw_spec(repo, commit, "RUN-DIV", _WRITE_AND_PASS)
    divergent["obligations"] = [
        {
            "child_id": "core",
            "criterion_ids": ["AC-CORE"],
            "scope": "src/app.py",
            "acceptance": [{"id": "AC-CORE", "mandatory": True}],
        }
    ]
    divergent["non_derivable_axes"] = ["ALLOCATION"]
    divergent["non_derivable_reason"] = "declared divergence pin"

    documents = (
        (divergent, "RUN-DIV"),
        (
            _raw_spec("/nonexistent/repository", commit, "RUN-NOREPO", _WRITE_AND_PASS),
            "RUN-NOREPO",
        ),
    )
    for document, run_id in documents:
        spec_path = tmp_path / f"{run_id}.yaml"
        spec_path.write_text(yaml.safe_dump(document))
        store_path = tmp_path / f"{run_id}.db"
        completed = _run_cli(
            [
                "start",
                "--spec",
                str(spec_path),
                "--workdir",
                str(tmp_path / f"{run_id}-work"),
                "--store",
                str(store_path),
            ],
            env=_src_env(),
        )
        assert completed.returncode != 0
        # The CLI creates the store file at construction, before the freeze
        # boundary refuses; the narrowed claim is that the class admits zero
        # events, not that no file exists.
        assert store_path.exists()
        store = EventStore(str(store_path))
        try:
            assert store.history(run_id) == []
        finally:
            store.close()


# -- Cancel-race class shape (F29) --------------------------------------------


def test_cancel_race_class_shape(tmp_path):
    """F29: a second process's documented `stop` landing while the launcher's
    root execution is live must settle the launcher honestly — its JSON carries
    the durable fresh outcome (`accepted: false`, `CANCELLED`), its exit is
    non-zero, neither process traces back, the documented `inspect` head runs
    clean on the produced store and agrees with a brand-new connection's
    replay, and a new connection replays the log from genesis without raising."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-CANCEL-RACE"
    spec_path = tmp_path / "race.yaml"
    spec_path.write_text(
        yaml.safe_dump(
            _raw_spec(
                repo,
                commit,
                run_id,
                "python3 -c \"import time; time.sleep(6)\"",
                limits={"actions": 4, "wall_clock_seconds": 120},
            )
        )
    )
    store_path = tmp_path / "race.db"
    workdir = tmp_path / "race-work"
    env = _src_env()
    launcher = subprocess.Popen(
        [
            _documented_interpreter(),
            str(_SCRIPT),
            "start",
            "--spec",
            str(spec_path),
            "--workdir",
            str(workdir),
            "--store",
            str(store_path),
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        cwd=str(_REPO_ROOT),
        env=env,
    )
    try:
        deadline = time.time() + 60
        dispatched = False
        while time.time() < deadline:
            if store_path.exists():
                store = EventStore(str(store_path))
                try:
                    dispatched = any(
                        event.event_type == "ACTION_DISPATCHED"
                        for event in store.history(run_id)
                    )
                finally:
                    store.close()
                if dispatched:
                    break
            time.sleep(0.05)
        assert dispatched, "the launcher never dispatched its root attempt"
        stopped = _run_cli(
            ["stop", "--run-id", run_id, "--store", str(store_path)], env=env
        )
        assert stopped.returncode == 0, stopped.stderr
        assert "Traceback" not in stopped.stderr
        stdout, stderr = launcher.communicate(timeout=120)
    finally:
        if launcher.poll() is None:
            launcher.kill()
            launcher.communicate()
    assert launcher.returncode != 0, (
        "F29: the launcher of a run a second process cancelled exited zero"
    )
    assert "Traceback" not in stderr
    document = json.loads(stdout)
    assert document["accepted"] is False
    assert document["outcome"] == "CANCELLED"
    # The documented `inspect` head runs clean against the produced store.
    inspected = _run_cli(
        ["inspect", "--run-id", run_id, "--store", str(store_path)], env=env
    )
    assert inspected.returncode == 0, inspected.stderr
    assert "Traceback" not in inspected.stderr
    inspected_document = json.loads(inspected.stdout)
    # Every new connection replays the durable log to the same outcome.
    fresh_store = EventStore(str(store_path))
    try:
        fresh = fresh_store.replay_fresh(run_id)
    finally:
        fresh_store.close()
    assert inspected_document["outcome"] == fresh.outcome == "CANCELLED"


def test_cancel_race_shape_stop_after_observation(tmp_path, monkeypatch):
    """F29: a second process's `stop` landing after the launcher admitted the
    observation, result, and artefact but before acceptance must not authorise
    acceptance: the returned document is the durable fresh cancelled outcome and
    no acceptance event reaches the log."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-CANCEL-OBS"
    spec = _spec(repo, commit, run_id, _WRITE_AND_PASS)
    store_path = os.path.join(str(tmp_path), "race-obs.db")
    store = EventStore(store_path)
    real_replay = store.replay_fresh
    calls = {"n": 0}

    def interleaved_replay_fresh(rid):
        calls["n"] += 1
        if calls["n"] == 2:
            # The stop lands after `admit_observation_and_result` completed and
            # before `_bind_acceptance`'s admission.
            _stop_from_second_process(store_path, run_id)
        return real_replay(rid)

    monkeypatch.setattr(store, "replay_fresh", interleaved_replay_fresh)
    try:
        result = run_entry.start_run(spec, store=store, workdir=str(tmp_path))
        assert result.accepted is False
        fresh = store.replay_fresh(run_id)
        assert result.outcome == fresh.outcome == "CANCELLED"
        assert fresh.nodes[result.root_node_id].state == "CANCELLED"
        types = [event.event_type for event in store.history(run_id)]
        assert "ACCEPTANCE_AUTHORISED" not in types
    finally:
        store.close()


def test_stale_admission_race_log_replays(tmp_path):
    """F29's log half: the durable race order — the second process's
    CANCELLATION_CONFIRMED/NODE_CANCELLED, then the launcher's execution-phase
    admissions through ARTEFACT_ADMITTED/ARTEFACT_INTEGRATED — replays to
    CANCELLED with no ReducerError, without creating or integrating the
    cancelled attempt's candidate, while a genuinely unknown artefact_id still
    fails closed."""
    repo, commit = _make_repo(str(tmp_path))
    run_id = "RUN-RACE-LOG"
    spec = _spec(repo, commit, run_id, "true")
    store_path = os.path.join(str(tmp_path), "race-log.db")
    store = EventStore(store_path)
    try:
        controller, _target, run_id, root = run_entry.build_run(
            spec, store=store, workdir=str(tmp_path)
        )
        dimension, amount = run_entry._budget_dimension(spec["budgets"])
        attempt_id = controller.plan_attempt(
            run_id, root, {"amount": amount, "dimension": dimension}
        )
        controller._emit(
            run_id,
            "ACTION_DISPATCHED",
            {"attempt_id": attempt_id, "executor": "command-executor-v1"},
            f"dispatch-{attempt_id}",
        )
        # The second process's documented stop, committed through its own
        # connection while this launcher's projection stays stale.
        _stop_from_second_process(store_path, run_id)
        # The launcher continues the live lifecycle on its stale projection.
        controller._emit(
            run_id,
            "DISPATCH_ACKNOWLEDGED",
            {"attempt_id": attempt_id, "token": "token-race"},
            f"ack-{attempt_id}",
            source="executor",
        )
        controller._emit(
            run_id,
            "EXECUTOR_OBSERVATION_ADMITTED",
            {"attempt_id": attempt_id, "observation": {"attempt_token": "token-race"}},
            f"observe-{attempt_id}",
            source="executor",
        )
        controller._emit(
            run_id,
            "ATTEMPT_EXECUTION_ENDED_UNRECONCILED",
            {"attempt_id": attempt_id},
            f"end-unreconciled-{attempt_id}",
        )
        controller._emit(
            run_id,
            "ATTEMPT_COST_RECONCILED",
            {"attempt_id": attempt_id, "actual": 0.0, "reclamation": amount},
            f"reconcile-{attempt_id}",
        )
        controller._emit(
            run_id,
            "RESULT_ADMITTED",
            {"attempt_id": attempt_id, "result": {"result_id": f"{attempt_id}-result"}},
            f"result-{attempt_id}",
        )
        artefact_id = f"{attempt_id}-artefact"
        controller._emit(
            run_id,
            "ARTEFACT_ADMITTED",
            {
                "artefact_id": artefact_id,
                "type": "GIT_CANDIDATE",
                "hash": "sha256:c",
                "attempt_id": attempt_id,
            },
            f"artefact-{attempt_id}",
        )
        controller._emit(
            run_id,
            "ARTEFACT_INTEGRATED",
            {"artefact_id": artefact_id, "merge_info": {"reference": "r1"}},
            f"integrate-{attempt_id}",
        )
    finally:
        store.close()
    # A brand-new connection replays the log from genesis without error.
    try:
        fresh_store = EventStore(store_path)
        try:
            fresh = fresh_store.replay_fresh(run_id)
        finally:
            fresh_store.close()
    except reducer.ReducerError as error:
        pytest.fail(f"F29: the durable race log did not replay: {error!r}")
    assert fresh.outcome == "CANCELLED"
    assert artefact_id not in fresh.artefacts, (
        "F29: the cancelled attempt's candidate must be retained, never created"
    )
    # A genuinely unknown artefact_id (owned by no terminal attempt) still
    # fails closed.
    unknown = events.make_event(
        "ARTEFACT_INTEGRATED",
        {"artefact_id": "never-admitted-artefact", "merge_info": {}},
        idempotency_key="unknown-artefact",
        schema_version=1,
        policy_version=1,
        source="controller",
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(fresh, unknown)
