# SPDX-License-Identifier: AGPL-3.0-or-later
"""Conformance entries for the second milestone's new and newly-validated events.

Per AGENTS.md#change-rules, every new event carries a catalogue entry
(docs/event-catalogue.md), a transition entry or an explicit side-effect-only
row, and a conformance test entry. This module is that conformance entry: for
each event added or first validated by milestone 2 it proves the
source-authority, unknown-event, unknown-enum, missing-field, and
referential-integrity rules, and the legal transition paths of
docs/control-plane.md#policy-transition-completeness.

The outcome-precedence cases at the bottom exercise one admitted event
deriving several conditions at once; they are tested separately from
quiescence by admitting events directly against a non-quiescent state.
"""

from __future__ import annotations

import pytest

from orchestrator import events, policy, reducer, tables
from orchestrator.controller import BudgetExhausted, Controller
from orchestrator.decomposition import scheduling_order, scopes_disjoint
from orchestrator.executor import ScriptedExecutor
from orchestrator.model import NodeRecord, RunState
from orchestrator.policy import PolicyRegistryError
from orchestrator.store import EventStore

from helpers import build_run_config


def _event(event_type, payload, idem="k", source="controller"):
    return events.make_event(event_type, payload, idempotency_key=idem, source=source)


def _admit(store, run_id, event):
    return store.admit(run_id, event)


# -- RELATION_RECORDED (step 05) -------------------------------------------------


def test_relation_recorded_requires_referential_integrity():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "a", "contract": {}, "cause": "ROOT"})
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "RELATION_RECORDED",
                {
                    "relation_id": "rel1",
                    "relation_type": "CHILD_OF",
                    "from_node_id": "missing",
                    "to_node_id": "a",
                },
                idem="r1",
            ),
        )


def test_relation_recorded_rejects_hierarchy_cycle():
    state = RunState(run_id="r1")
    for node_id in ("a", "b"):
        state, _ = reducer.reduce(
            state, _event("NODE_PROPOSED", {"node_id": node_id, "contract": {}, "cause": "ROOT"}, idem=f"p-{node_id}")
        )
        state, _ = reducer.reduce(
            state, _event("NODE_ADMITTED", {"node_id": node_id, "contract": {}, "authority": "controller"}, idem=f"a-{node_id}")
        )
    state, _ = reducer.reduce(
        state,
        _event(
            "RELATION_RECORDED",
            {"relation_id": "rel1", "relation_type": "CHILD_OF", "from_node_id": "b", "to_node_id": "a"},
            idem="rel1",
        ),
    )
    # a CHILD_OF b (a is a child of b) plus b CHILD_OF a would close a cycle.
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "RELATION_RECORDED",
                {"relation_id": "rel2", "relation_type": "CHILD_OF", "from_node_id": "a", "to_node_id": "b"},
                idem="rel2",
            ),
        )


def test_relation_recorded_rejects_unknown_relation_type_at_admission():
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            _event(
                "RELATION_RECORDED",
                {
                    "relation_id": "rel1",
                    "relation_type": "NOT_A_RELATION",
                    "from_node_id": "a",
                    "to_node_id": "b",
                },
            )
        )


def test_relation_recorded_duplicate_is_a_retained_no_op():
    state = _two_admitted_nodes()
    payload = {
        "relation_id": "rel-int",
        "relation_type": "INTEGRATES",
        "from_node_id": "new",
        "to_node_id": "old",
    }
    state, effects = reducer.reduce(state, _event("RELATION_RECORDED", payload, idem="rel-int"))
    assert any(e.kind == "relation_recorded" for e in effects)
    state, effects = reducer.reduce(state, _event("RELATION_RECORDED", payload, idem="rel-int"))
    assert effects == [reducer.Effect("late_event_retained", {"relation_id": "rel-int"})]


# -- supersession (step 05) -------------------------------------------------------


def _two_admitted_nodes(cause="DECOMPOSITION"):
    state = RunState(run_id="r1")
    for node_id in ("old", "new"):
        state, _ = reducer.reduce(
            state,
            _event("NODE_PROPOSED", {"node_id": node_id, "contract": {}, "cause": cause}, idem=f"p-{node_id}"),
        )
        state, _ = reducer.reduce(
            state,
            _event("NODE_ADMITTED", {"node_id": node_id, "contract": {}, "authority": "controller"}, idem=f"a-{node_id}"),
        )
    return state


def _two_nodes_with_supersedes_relation():
    state = _two_admitted_nodes()
    state, _ = reducer.reduce(
        state,
        _event(
            "RELATION_RECORDED",
            {"relation_id": "rel-sup", "relation_type": "SUPERSEDES", "from_node_id": "new", "to_node_id": "old"},
            idem="rel-sup",
        ),
    )
    return state


def test_node_superseded_requires_valid_replacement_relation():
    state = RunState(run_id="r1")
    for node_id in ("old", "other"):
        state, _ = reducer.reduce(
            state,
            _event("NODE_PROPOSED", {"node_id": node_id, "contract": {}, "cause": "ROOT"}, idem=f"p-{node_id}"),
        )
    # No SUPERSEDES relation from 'other' to 'old': supersession is invalid.
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event("NODE_SUPERSEDED", {"node_id": "old", "replacement_id": "other"}, idem="sup"),
        )


def test_node_superseded_transitions_non_root_node():
    state = _two_nodes_with_supersedes_relation()
    state, effects = reducer.reduce(
        state, _event("NODE_SUPERSEDED", {"node_id": "old", "replacement_id": "new"}, idem="sup")
    )
    assert state.nodes["old"].state == "SUPERSEDED"
    assert state.outcome is None


def test_node_superseded_is_illegal_on_the_active_root():
    state = _two_nodes_with_supersedes_relation()
    state.nodes["old"].is_root = True
    state.root_node_id = "old"
    with pytest.raises(tables.UnknownTransition):
        NODE_TABLE = tables.node_table()
        NODE_TABLE.resolve(state.nodes["old"].state, "NODE_SUPERSEDED", is_root=True)


def test_root_replaced_atomically_switches_active_root():
    state = _two_nodes_with_supersedes_relation()
    # The replacement root is admitted with cause ROOT_REPLACEMENT and cannot
    # itself become the active root while the old root lives.
    state.nodes["new"].cause = "ROOT_REPLACEMENT"
    state.nodes["old"].is_root = True
    state.root_node_id = "old"
    state, effects = reducer.reduce(
        state,
        _event(
            "ROOT_REPLACED",
            {"old_root": "old", "new_root": "new"},
            idem="replace",
        ),
    )
    assert state.nodes["old"].state == "SUPERSEDED"
    assert state.root_node_id == "new"
    assert state.outcome is None, "an admitted replacement root continues the run"
    supersession = [
        r for r in state.relations.values() if r.relation_type == "SUPERSEDES"
    ]
    assert len(supersession) == 1 and supersession[0].from_node_id == "new"


def test_root_replaced_requires_non_terminal_replacement_with_authority():
    state = _two_nodes_with_supersedes_relation()
    state.nodes["new"].cause = "ROOT"  # not a ROOT_REPLACEMENT proposal
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state, _event("ROOT_REPLACED", {"old_root": "old", "new_root": "new"}, idem="replace")
        )


# -- timers (step 08 trusted subset) ----------------------------------------------


def _attempt_in(state_event_pairs):
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {"budgets": {"MODEL_COST": 10}}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(
        state, _event("ATTEMPT_PLANNED", {"attempt_id": "a1", "node_id": "n1", "cause": "INITIAL"})
    )
    for event_type, payload in state_event_pairs:
        state, _ = reducer.reduce(state, _event(event_type, {**payload}, idem=f"k-{event_type}"))
    return state


def test_timer_fired_requires_a_recorded_timer_for_the_attempt():
    state = _attempt_in([("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5})])
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "TIMER_FIRED",
                {
                    "timer_id": "t1",
                    "attempt_id": "a1",
                    "configured_deadline": 5.0,
                    "observed_firing_time": 5.0,
                },
                idem="fire",
                source="timer",
            ),
        )


def test_timer_fired_rejects_mismatched_deadline_and_foreign_attempt():
    state = _attempt_in([("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5})])
    state, _ = reducer.reduce(
        state,
        _event(
            "TIMER_SCHEDULED",
            {"timer_id": "t1", "attempt_id": "a1", "deadline": 30.0},
            idem="sched",
        ),
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "TIMER_FIRED",
                {
                    "timer_id": "t1",
                    "attempt_id": "a1",
                    "configured_deadline": 99.0,
                    "observed_firing_time": 99.0,
                },
                idem="fire",
                source="timer",
            ),
        )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "TIMER_FIRED",
                {
                    "timer_id": "t1",
                    "attempt_id": "a2",
                    "configured_deadline": 30.0,
                    "observed_firing_time": 30.0,
                },
                idem="fire2",
                source="timer",
            ),
        )


def test_timer_fired_times_out_running_attempt_through_the_attempt_machine():
    state = _attempt_in(
        [
            ("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5}),
            ("ACTION_DISPATCHED", {"attempt_id": "a1", "executor": "x"}),
            ("DISPATCH_ACKNOWLEDGED", {"attempt_id": "a1", "token": "tok"}),
        ]
    )
    state, _ = reducer.reduce(
        state,
        _event(
            "TIMER_SCHEDULED",
            {"timer_id": "t1", "attempt_id": "a1", "deadline": 30.0},
            idem="sched",
        ),
    )
    state, _ = reducer.reduce(
        state,
        _event(
            "TIMER_FIRED",
            {
                "timer_id": "t1",
                "attempt_id": "a1",
                "configured_deadline": 30.0,
                "observed_firing_time": 30.0,
            },
            idem="fire",
            source="timer",
        ),
    )
    assert state.attempts["a1"].state == "TIMED_OUT"
    assert state.timers["t1"].fired is True


def test_timer_fired_after_terminal_attempt_is_a_retained_no_op():
    state = _attempt_in([("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5})])
    state, _ = reducer.reduce(
        state,
        _event(
            "TIMER_SCHEDULED",
            {"timer_id": "t1", "attempt_id": "a1", "deadline": 30.0},
            idem="sched",
        ),
    )
    state, _ = reducer.reduce(
        state,
        _event(
            "CANCELLATION_CONFIRMED",
            {"attempt_id": "a1"},
            idem="cancel",
        ),
    )
    state, effects = reducer.reduce(
        state,
        _event(
            "TIMER_FIRED",
            {
                "timer_id": "t1",
                "attempt_id": "a1",
                "configured_deadline": 30.0,
                "observed_firing_time": 30.0,
            },
            idem="fire",
            source="timer",
        ),
    )
    assert state.attempts["a1"].state == "CANCELLED"
    assert state.timers["t1"].fired is False
    assert effects == [reducer.Effect("late_event_retained", {"attempt_id": "a1"})]


def test_timer_scheduled_source_authority_is_controller_only():
    event = events.make_event(
        "TIMER_SCHEDULED",
        {"timer_id": "t1", "attempt_id": "a1", "deadline": 30.0},
        source="executor",
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(event)


# -- budget ledger events (step 07) ------------------------------------------------


def test_budget_reservation_reclaimed_requires_matching_active_reservation():
    state = _attempt_in([("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5})])
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event("BUDGET_RESERVATION_RECLAIMED", {"attempt_id": "a1", "amount": 4}, idem="recl"),
        )
    state, effects = reducer.reduce(
        state,
        _event("BUDGET_RESERVATION_RECLAIMED", {"attempt_id": "a1", "amount": 5.0}, idem="recl"),
    )
    assert state.ledger.reservations == {}
    assert any(e.kind == "reservation_reclaimed" for e in effects)


def test_commitment_without_reservation_is_rejected():
    state = _attempt_in([])
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ATTEMPT_COMMITMENT_OPENED",
                {"attempt_id": "a1", "commitment": 5},
                idem="open",
            ),
        )


# -- conflicts (step 12) ------------------------------------------------------------


def test_conflict_recorded_nested_enums_are_enforced_at_admission():
    base = {"node_id": "n1", "conflict": {"conflict_id": "c1", "parties": ["n1"]}}
    valid = dict(
        base,
        conflict={
            **base["conflict"],
            "type": "WRITE_CONFLICT",
            "severity": "BLOCKING",
            "resolution_policy": "FIRST_WRITER_WINS",
        },
    )
    events.validate_event(_event("CONFLICT_RECORDED", valid))  # must not raise
    for field, bad in (
        ("type", "NOT_A_CONFLICT"),
        ("severity", "COSMIC"),
        ("resolution_policy", "ROCK_PAPER_SCISSORS"),
    ):
        broken = dict(base)
        broken["conflict"] = {**base["conflict"], **{field: bad}}
        with pytest.raises(events.InvalidEnumValue):
            events.validate_event(_event("CONFLICT_RECORDED", broken))


def test_conflict_lifecycle_through_policy_paths():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(
        state, _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"}, idem="adm")
    )
    state, _ = reducer.reduce(
        state, _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, idem="ready", source="scheduler")
    )
    conflict = {
        "conflict_id": "c1",
        "type": "WRITE_CONFLICT",
        "parties": ["n1"],
        "severity": "BLOCKING",
        "resolution_policy": "INTEGRATION_OWNER_ADJUDICATION",
    }
    state, _ = reducer.reduce(state, _event("CONFLICT_RECORDED", {"node_id": "n1", "conflict": conflict}, idem="rec"))
    assert state.nodes["n1"].state == "CONFLICTED"
    assert state.conflicts["c1"].lifecycle_state == "OPEN"
    state, _ = reducer.reduce(
        state, _event("CONFLICT_RESOLVED", {"node_id": "n1", "conflict_id": "c1"}, idem="res")
    )
    assert state.nodes["n1"].state == "BLOCKED"
    assert state.conflicts["c1"].lifecycle_state == "RESOLVED"


def test_conflict_party_must_be_an_admitted_node():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "CONFLICT_RECORDED",
                {
                    "node_id": "n1",
                    "conflict": {
                        "conflict_id": "c1",
                        "type": "WRITE_CONFLICT",
                        "parties": ["ghost"],
                        "severity": "BLOCKING",
                        "resolution_policy": "FIRST_WRITER_WINS",
                    },
                },
                idem="rec",
            ),
        )


def test_conflict_policy_mismatched_with_registry_is_rejected():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "CONFLICT_RECORDED",
                {
                    "node_id": "n1",
                    "conflict": {
                        "conflict_id": "c1",
                        "type": "WRITE_CONFLICT",
                        "parties": ["n1"],
                        "severity": "BLOCKING",
                        # A catalogued policy, but not the one the registry
                        # selects for WRITE_CONFLICT.
                        "resolution_policy": "EVIDENCE_BASED",
                    },
                },
                idem="rec",
            ),
        )


# -- replan (retry-prohibited failures) ------------------------------------------------


def _validated_node_state():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(
        state, _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"}, idem="adm")
    )
    state, _ = reducer.reduce(
        state, _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, idem="ready", source="scheduler")
    )
    return state


def test_validation_failed_requires_explicit_retry_eligible_in_the_reducer():
    state = _validated_node_state()
    # Reducer-level enforcement: reduce() receives raw events, so the guard
    # context must be explicit there too, not defaulted silently.
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event("VALIDATION_FAILED", {"node_id": "n1", "evidence": {}}, idem="vf"),
        )


def test_plan_admitted_requires_new_evidence_or_changed_contract():
    state = _validated_node_state()
    state, _ = reducer.reduce(
        state, _event("VALIDATION_STARTED", {"node_id": "n1"}, idem="vs")
    )
    state, _ = reducer.reduce(
        state,
        _event("VALIDATION_FAILED", {"node_id": "n1", "evidence": {}, "retry_eligible": False}, idem="vf"),
    )
    assert state.nodes["n1"].state == "REPLAN_REQUIRED"
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state, _event("PLAN_ADMITTED", {"plan_id": "p1", "node_id": "n1"}, idem="plan")
        )
    state, _ = reducer.reduce(
        state,
        _event(
            "PLAN_ADMITTED",
            {"plan_id": "p1", "node_id": "n1", "changed_contract": {"description": "v2"}},
            idem="plan",
        ),
    )
    assert state.nodes["n1"].state == "BLOCKED"


# -- sandbox violations and deferred acceptance -------------------------------------------


def test_sandbox_violation_fails_a_non_terminal_attempt():
    state = _attempt_in([("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5})])
    state, _ = reducer.reduce(
        state,
        _event(
            "SANDBOX_VIOLATION_RECORDED",
            {"attempt_id": "a1", "evidence": {"escape": True}},
            idem="sandbox",
            source="sandbox",
        ),
    )
    assert state.attempts["a1"].state == "FAILED"


def test_sandbox_violation_source_authority_is_sandbox_only():
    event = events.make_event(
        "SANDBOX_VIOLATION_RECORDED", {"attempt_id": "a1", "evidence": {}}, source="controller"
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(event)


def test_acceptance_deferred_and_validation_invalidated_are_legal_paths():
    state = _validated_node_state()
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}, idem="vs"))
    state, _ = reducer.reduce(state, _event("VALIDATION_PASSED", {"node_id": "n1", "evidence": {}}, idem="vp"))
    state, _ = reducer.reduce(
        state, _event("ACCEPTANCE_DEFERRED", {"node_id": "n1", "reason": "approval pending"}, idem="def")
    )
    assert state.nodes["n1"].state == "BLOCKED"

    # Validation can also be invalidated from VALIDATING, sending the node
    # back to BLOCKED (docs/control-plane.md node lifecycle).
    state, _ = reducer.reduce(
        state,
        _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, idem="ready2", source="scheduler"),
    )
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}, idem="vs2"))
    state, _ = reducer.reduce(
        state,
        _event(
            "VALIDATION_INVALIDATED",
            {"node_id": "n1", "invalidation": {"type": "INPUT_CHANGED"}},
            idem="inv",
        ),
    )
    assert state.nodes["n1"].state == "BLOCKED"


def test_acceptance_authorised_requires_explicit_acceptance_id():
    state = _validated_node_state()
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}, idem="vs"))
    state, _ = reducer.reduce(state, _event("VALIDATION_PASSED", {"node_id": "n1", "evidence": {}}, idem="vp"))
    state, _ = reducer.reduce(
        state,
        _event(
            "EVIDENCE_ADMITTED",
            {
                "evidence_id": "ev-1",
                "node_id": "n1",
                "check_class": "VISIBLE",
                "checks": [{"name": "BUILD", "passed": True}],
                "artefact_hashes": {},
                "versions": {},
            },
            idem="ev",
        ),
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ACCEPTANCE_AUTHORISED",
                {"node_id": "n1", "bindings": {"evidence_ids": ["ev-1"]}},
                idem="acc",
            ),
        )
    state, _ = reducer.reduce(
        state,
        _event(
            "ACCEPTANCE_AUTHORISED",
            {"node_id": "n1", "bindings": {"acceptance_id": "acc-1", "evidence_ids": ["ev-1"]}},
            idem="acc",
        ),
    )
    assert state.freshness["acc-1"] is not None


def test_acceptance_authorised_rejects_empty_or_foreign_or_missing_result_evidence():
    """R09: the authoritative admission path enforces the acceptance invariant,
    so a direct event cannot bypass the controller helpers."""
    state = _validated_node_state()
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}, idem="vs"))
    state, _ = reducer.reduce(state, _event("VALIDATION_PASSED", {"node_id": "n1", "evidence": {}}, idem="vp"))
    # Empty evidence binding.
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ACCEPTANCE_AUTHORISED",
                {"node_id": "n1", "bindings": {"acceptance_id": "acc-x"}},
                idem="acc-x",
            ),
        )
    # A fabricated inline checks list is a declaration, not evidence: a direct
    # event cannot mint acceptance from it (SPEND review F4).
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ACCEPTANCE_AUTHORISED",
                {
                    "node_id": "n1",
                    "bindings": {
                        "acceptance_id": "acc-z",
                        "evidence": {"checks": [{"name": "FAKE", "passed": True}]},
                    },
                },
                idem="acc-z",
            ),
        )
    # An admitted but failing evidence record cannot support acceptance.
    state, _ = reducer.reduce(
        state,
        _event(
            "EVIDENCE_ADMITTED",
            {
                "evidence_id": "ev-fail",
                "node_id": "n1",
                "check_class": "VISIBLE",
                "checks": [{"name": "BUILD", "passed": False}],
                "artefact_hashes": {},
                "versions": {},
            },
            idem="ev-fail",
        ),
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ACCEPTANCE_AUTHORISED",
                {
                    "node_id": "n1",
                    "bindings": {
                        "acceptance_id": "acc-f",
                        "evidence_ids": ["ev-fail"],
                    },
                },
                idem="acc-f",
            ),
        )
    # A bound result that the node never produced.
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "ACCEPTANCE_AUTHORISED",
                {
                    "node_id": "n1",
                    "bindings": {
                        "acceptance_id": "acc-y",
                        "result_id": "n1-attempt-1-result",
                        "evidence_ids": ["ev-fail"],
                    },
                },
                idem="acc-y",
            ),
        )


# -- versioned proposals (step 04): admission rules ------------------------------------------


def test_version_conflict_recorded_requires_an_admitted_node():
    state = RunState(run_id="r1")
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(
            state,
            _event(
                "VERSION_CONFLICT_RECORDED",
                {"node_id": "ghost", "entity": {"kind": "node", "entity_id": "ghost"}},
                idem="vc",
            ),
        )


def test_version_conflict_recorded_is_a_catalogued_side_effect_only_event():
    spec = events.EVENT_CATALOGUE["VERSION_CONFLICT_RECORDED"]
    assert spec.affected_machines == (), "side-effect-only events affect no state machine"


# -- decomposition, replan, and budget admission rules ----------------------------------------


def test_decomposition_admitted_required_fields_are_enforced_at_admission():
    event = events.make_event("DECOMPOSITION_ADMITTED", {"proposal_id": "p1", "node_id": "n1"})
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(event)
    complete = events.make_event(
        "DECOMPOSITION_ADMITTED",
        {
            "proposal_id": "p1",
            "node_id": "n1",
            "children": [],
            "criterion_coverage": [],
        },
    )
    events.validate_event(complete)  # must not raise (structural payload checks
    # happen deterministically in the decomposition gate, tests/test_reducer.py
    # and tests/test_milestone2_acceptance.py exercise them through the store).


def test_replan_requested_required_fields_are_enforced_at_admission():
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(_event("REPLAN_REQUESTED", {"node_id": "n1"}))
    events.validate_event(_event("REPLAN_REQUESTED", {"node_id": "n1", "reason": "failed validation"}))


def test_new_side_effect_only_events_have_explicit_catalogue_rows():
    # Per AGENTS.md#change-rules, events that affect no state machine must
    # carry an explicit side-effect-only row in the catalogue.
    for event_type in ("VERSION_CONFLICT_RECORDED", "BUDGET_RESERVATION_RECLAIMED"):
        assert events.EVENT_CATALOGUE[event_type].affected_machines == ()
        # and unknown-event / source-authority rules still apply:
        with pytest.raises(events.UnknownEventType):
            events.validate_event(_event("NOT_A_REAL_EVENT", {}))
        wrong_source = events.make_event(
            "BUDGET_RESERVATION_RECLAIMED", {"attempt_id": "a1", "amount": 1}, source="executor"
        )
        with pytest.raises(events.InvalidSourceAuthority):
            events.validate_event(wrong_source)


# -- outcome precedence, tested separately from quiescence ------------------------------------


class TestOutcomePrecedence:
    """docs/control-plane.md#run-termination-and-outcomes: when one admitted
    event derives several terminal conditions at once, the reducer emits the
    terminal transition first, then the run outcome, then derived cancellation
    intents in deterministic order — and exactly one terminal transition.
    These cases admit events directly and involve no quiescence evaluation."""

    def _root_with_running_attempt(self):
        state = RunState(run_id="r1")
        state, _ = reducer.reduce(
            state,
            _event(
                "NODE_PROPOSED",
                {"node_id": "n1", "contract": {"budgets": {"MODEL_COST": 100}}, "cause": "ROOT"},
            ),
        )
        state, _ = reducer.reduce(
            state,
            _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"}, idem="adm"),
        )
        state, _ = reducer.reduce(
            state,
            _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, idem="ready", source="scheduler"),
        )
        state, _ = reducer.reduce(
            state,
            _event("ATTEMPT_PLANNED", {"attempt_id": "a1", "node_id": "n1", "cause": "INITIAL"}, idem="plan"),
        )
        state, _ = reducer.reduce(
            state,
            _event("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5}, idem="res", source="scheduler"),
        )
        state, _ = reducer.reduce(
            state,
            _event("ACTION_DISPATCHED", {"attempt_id": "a1", "executor": "x"}, idem="disp"),
        )
        return state

    def test_one_event_deriving_several_conditions_emits_one_terminal_transition(self):
        state = self._root_with_running_attempt()
        state, effects = reducer.reduce(
            state, _event("BUDGET_EXHAUSTION_RECORDED", {"node_id": "n1"}, idem="budget")
        )
        kinds = [e.kind for e in effects]
        assert kinds == [
            "node_transitioned",
            "run_outcome_recorded",
            "cancel_attempt_requested",
        ]
        assert state.outcome == "BUDGET_EXHAUSTED"
        assert state.nodes["n1"].state == "BUDGET_EXHAUSTED"
        terminal_transitions = kinds.count("node_transitioned")
        assert terminal_transitions == 1
        assert effects[-1].data == {"attempt_id": "a1"}

    def test_late_competing_terminal_events_after_derived_outcome_are_no_ops(self):
        state = self._root_with_running_attempt()
        state, _ = reducer.reduce(
            state, _event("BUDGET_EXHAUSTION_RECORDED", {"node_id": "n1"}, idem="budget")
        )
        # The controller's post-commit effect executor turns the derived
        # cancellation intent into the ordinary CANCELLATION_CONFIRMED event
        # end-to-end (see test below); this unit-level case admits that event
        # directly to prove the attempt machine mutates while the
        # already-admitted run outcome does not.
        state, effects = reducer.reduce(
            state, _event("CANCELLATION_CONFIRMED", {"attempt_id": "a1"}, idem="cancel")
        )
        assert state.attempts["a1"].state == "CANCELLED"
        assert state.outcome == "BUDGET_EXHAUSTED"
        state, effects = reducer.reduce(
            state, _event("NODE_MARKED_INFEASIBLE", {"node_id": "n1"}, idem="infeasible")
        )
        assert effects == [reducer.Effect("late_event_retained", {"node_id": "n1"})]
        assert state.outcome == "BUDGET_EXHAUSTED"

    def test_outcome_precedence_governs_regardless_of_which_condition(self):
        state = self._root_with_running_attempt()
        state, _ = reducer.reduce(
            state, _event("NODE_MARKED_INFEASIBLE", {"node_id": "n1"}, idem="infeasible")
        )
        assert state.outcome == "INFEASIBLE"
        state, _ = reducer.reduce(
            state, _event("BUDGET_EXHAUSTION_RECORDED", {"node_id": "n1"}, idem="budget")
        )
        assert state.outcome == "INFEASIBLE", "the first admitted terminal condition wins"


# -- derived effects are executed end-to-end ------------------------------------------------


def test_derived_cancellation_intent_is_executed_by_the_controller(tmp_path):
    """The cancel_attempt_requested effect of BUDGET_EXHAUSTION_RECORDED is
    turned by the controller's post-commit effect executor into the ordinary
    CANCELLATION_CONFIRMED event, and the cancelled attempt's accounting is
    settled with full reclamation — replay re-derives all of it from the log."""
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = Controller(store, ScriptedExecutor({}))
        config = build_run_config("RUN-C1")
        config["budgets"] = {"MODEL_COST": 10.0}
        root = controller.submit_run(config)
        attempt_id = controller.plan_attempt("RUN-C1", root, 10.0)
        assert store.state("RUN-C1").attempts[attempt_id].state == "RESERVED"
        assert store.state("RUN-C1").ledger.available(f"{root}-budget") == 0.0

        # No permitted action can obtain another commitment: exhaustion is
        # recorded, and the node's non-terminal attempt is cancelled by the
        # derived-effect executor, not left dangling.
        with pytest.raises(BudgetExhausted):
            controller.plan_attempt("RUN-C1", root, 10.0)

        state = store.state("RUN-C1")
        assert state.nodes[root].state == "BUDGET_EXHAUSTED"
        assert state.outcome == "BUDGET_EXHAUSTED"
        assert state.attempts[attempt_id].state == "CANCELLED"
        assert state.attempts[attempt_id].accounting_state == "FINALLY_SETTLED"
        cancellations = [
            e for e in store.history("RUN-C1") if e.event_type == "CANCELLATION_CONFIRMED"
        ]
        assert len(cancellations) == 1
        # Actual 0 for a never-dispatched trusted attempt; the commitment is
        # fully reclaimed and available again.
        assert state.ledger.total_charged == 0.0
        assert state.ledger.available(f"{root}-budget") == 10.0
        assert state.ledger.commitments == {}

        replayed = store.replay_fresh("RUN-C1")
        assert replayed.attempts[attempt_id].state == "CANCELLED"
        assert replayed.attempts[attempt_id].accounting_state == "FINALLY_SETTLED"
        assert replayed.ledger.total_charged == 0.0
        assert replayed.ledger.available(f"{root}-budget") == 10.0
        assert replayed.outcome == "BUDGET_EXHAUSTED"
    finally:
        store.close()


# -- scope disjointness is a proof, not string equality ---------------------------------------


def test_scope_disjointness_is_conservative_for_patterns():
    # Clearly separate subtrees are provably disjoint.
    assert scopes_disjoint([["src/health/**"], ["src/metrics/**"]]) is True
    assert scopes_disjoint([["src/a/x.py"], ["src/b/x.py"]]) is True
    # Glob-overlapping scopes cannot be proven disjoint and must serialise.
    assert scopes_disjoint([["src/**"], ["src/health/**"]]) is False
    assert scopes_disjoint([["src/health/**"], ["src/health/**"]]) is False
    # A parent path segment contains the child path.
    assert scopes_disjoint([["src/a/x.py"], ["src/a"]]) is False
    assert scopes_disjoint([["src/ab"], ["src/a"]]) is True  # segments, not strings
    # A path whose disjointness cannot be proved serialises.
    assert scopes_disjoint([[], ["src/a/**"]]) is False


def test_scheduling_serialises_unprovably_disjoint_scopes():
    state = RunState(run_id="r1")
    for node_id, scope in (("b", "src/**"), ("a", "src/health/**"), ("c", "src/metrics/**")):
        state.nodes[node_id] = NodeRecord(
            node_id=node_id,
            state="READY",
            contract={"owned_scope": [scope]},
            cause="DECOMPOSITION",
        )
    # 'a' (src/health/**) may overlap 'b' (src/**): no proof, so serialised.
    ordered, concurrent = scheduling_order(state, ["a", "b"])
    assert ordered == ["a", "b"] and concurrent is False
    # 'a' and 'c' sit under disjoint subtrees: provably disjoint.
    ordered, concurrent = scheduling_order(state, ["a", "c"])
    assert ordered == ["a", "c"] and concurrent is True


# -- policy registry and policy-completeness paths ---------------------------------------------


class TestPolicyTransitionCompleteness:
    def test_registry_is_deterministic_and_catalogued(self):
        from orchestrator.policy import CONFLICT_RESOLUTION_REGISTRY, resolution_policy_for

        assert resolution_policy_for("WRITE_CONFLICT") == resolution_policy_for("WRITE_CONFLICT")
        for conflict_type, entry in CONFLICT_RESOLUTION_REGISTRY.items():
            assert entry["resolution_policy"] in glossary_policies()
        with pytest.raises(PolicyRegistryError):
            resolution_policy_for("NOT_A_CONFLICT")

    def test_every_policy_completeness_row_resolves_legally(self):
        assert policy.validate_policy_completeness_rows() == ()

    def test_registry_startup_validation_rejects_illegal_outcomes(self):
        policy.validate_policy_registry()  # must not raise for the committed tables


def glossary_policies():
    from orchestrator import glossary

    return glossary.conflict_resolution_policies()
