# SPDX-License-Identifier: AGPL-3.0-or-later
"""Bounded recursive-planning pilot: proposal admission (Phase 4).

Covers the spec's P3 (bounds), P4 (scope containment), P5 (budget authority), the
*refusal is total* half of P2, and P8 (instrumentation), plus the regression pins
for two adversarial reviews of this surface.

The API derives every bound from replayable state: ``state`` and
``parent_node_id`` are required, and the keyword arguments exist only so a caller
can *assert* what it believes. The model producer is a separate, later change.

See ``docs/research/phase4-recursive-planning-pilot-spec.md``.
"""
from __future__ import annotations

import pytest

from orchestrator import planning_pilot as pilot
from orchestrator.decomposition import DecompositionError

GOOD = "src/good/**"


def _child(node_id, scope, amount=1.0, criterion="AC", dimension="MODEL_COST"):
    return {
        "node_id": node_id,
        "mandatory": True,
        "criterion_ids": [criterion],
        "contract": {
            "owned_scope": [scope],
            "acceptance_criteria": [{"id": criterion, "mandatory": True}],
            "budget_id": f"{node_id}-budget",
        },
        "budget_allocation": {dimension: amount},
    }


class TestThePilotPathRequiresState:
    """RR4: the derived bounds were opt-in, so omitting ``state`` re-opened the
    caller-trust the first review found."""

    def test_omitting_the_state_is_refused(self):
        for kwargs in (
            {},
            {"state": None, "parent_node_id": "p"},
            {"parent_node_id": "p"},
            {"state": _state(GOOD)},
        ):
            with pytest.raises(DecompositionError) as error:
                pilot.admit_proposal([_child("c1", "src/good/x.py")], **kwargs)
            assert "requires the replayable state" in str(error.value)

    def test_a_parent_declaring_no_scope_is_refused(self):
        state = _state(GOOD)
        state.nodes["p"].contract.pop("owned_scope")
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")], state=state, parent_node_id="p"
            )
        assert "declares no owned scope" in str(error.value)

    def test_a_parent_with_no_registered_budget_is_refused(self):
        state = _state(GOOD)
        state.ledger.budgets.pop("p-budget")
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")], state=state, parent_node_id="p"
            )
        assert "is not registered" in str(error.value)

    def test_the_stated_scope_is_an_assertion_not_a_restriction(self):
        """A producer may omit `parent_scope`; containment still uses the
        contract's full scope set, so a multi-scope parent is not narrowed to one
        region by the assertion's absence."""
        state = _state(GOOD)
        state.nodes["p"].contract["owned_scope"] = ["src/alpha/**", "src/beta/**"]
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/beta/x.py")], state=state, parent_node_id="p"
        )
        assert len(admitted) == 1

    def test_a_stated_scope_that_disagrees_with_the_contract_is_refused(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")],
                state=_state(GOOD), parent_node_id="p", parent_scope="src/other/**",
            )
        assert "declared scope is authoritative" in str(error.value)


class TestDepthBound:
    def test_a_parent_at_the_pilot_depth_may_not_propose(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")],
                state=_state(GOOD, chain_depth=pilot.MAX_PROPOSAL_DEPTH - 1),
                parent_node_id="p",
            )
        assert "depth" in str(error.value)

    def test_the_exact_depth_boundary_is_pinned(self):
        """R3: the boundary test overshot by one, so `depth == MAX_PROPOSAL_DEPTH`
        was never exercised. Pin the number, not just the refusal."""
        for chain, expect_propose in (
            (pilot.MAX_PROPOSAL_DEPTH - 1, False),   # p at depth 2 == the bound
            (pilot.MAX_PROPOSAL_DEPTH - 2, True),    # p at depth 1
        ):
            state = _state(GOOD, chain_depth=chain)
            assert pilot._node_depth_from_state(state, "p") == (
                pilot.MAX_PROPOSAL_DEPTH if not expect_propose
                else pilot.MAX_PROPOSAL_DEPTH - 1
            )
            if expect_propose:
                admitted, _capability = pilot.admit_proposal(
                    [_child("c1", "src/good/x.py")],
                    state=state, parent_node_id="p",
                )
                assert admitted
            else:
                with pytest.raises(DecompositionError):
                    pilot.admit_proposal(
                        [_child("c1", "src/good/x.py")],
                        state=state, parent_node_id="p",
                    )

    def test_a_parent_below_the_depth_may_propose(self):
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/good/x.py")],
            state=_state(GOOD, chain_depth=0),
            parent_node_id="p",
        )
        assert [c["node_id"] for c in admitted] == ["c1"]

    def test_derived_depth_agrees_with_the_controller(self):
        """RR1: the guard re-implemented the walk and was off by one, refusing
        truthful callers and admitting one level more than the spec allows. It now
        calls the controller, and this compares the two on a chain rather than
        checking the guard against itself."""
        from orchestrator.controller import Controller

        state = _state(GOOD, chain_depth=4)
        for node_id in ("root", "mid0", "mid1", "mid2", "mid3", "p"):
            assert pilot._node_depth_from_state(state, node_id) == (
                Controller._node_depth(state, node_id)
            ), f"depth disagrees with the controller for {node_id!r}"

    def test_a_root_child_reads_depth_one_not_zero(self):
        """The exact off-by-one RR1 found: a root child is at depth 1."""
        state = _state(GOOD, chain_depth=1)
        assert pilot._node_depth_from_state(state, "mid0") == 1
        assert pilot._node_depth_from_state(state, "p") == 2


class TestSizeBound:
    def test_the_existing_fan_out_limit_applies_and_is_not_raised(self):
        limit = pilot.maximum_children_per_node()
        children = [_child(f"c{i}", "src/good/x.py") for i in range(limit + 1)]
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(children, state=_state(GOOD), parent_node_id="p")
        assert "does not raise it" in str(error.value)

    def test_a_proposal_at_the_limit_is_admitted(self):
        limit = pilot.maximum_children_per_node()
        children = [_child(f"c{i}", "src/good/x.py") for i in range(limit)]
        admitted, _capability = pilot.admit_proposal(
            children, state=_state(GOOD), parent_node_id="p"
        )
        assert len(admitted) == limit

    def test_the_per_trial_ceiling_is_enforced_from_derived_state(self):
        """RR4: the count is derived, so under-reporting it does not evade the
        ceiling."""
        from orchestrator.model import NodeRecord, RelationRecord

        # p stays at controller depth 1 so the ceiling is the binding bound, not
        # the depth one.
        state = _state(GOOD, chain_depth=0)
        for index in range(pilot.MAX_PROPOSED_CHILDREN_PER_TRIAL + 4):
            node_id = f"c{index}"
            state.nodes[node_id] = NodeRecord(
                node_id=node_id, state="PROPOSED", cause="DECOMPOSITION",
                contract={"acceptance_criteria": []},
            )
            state.relations[node_id] = RelationRecord(
                relation_id=node_id, relation_type="CHILD_OF",
                from_node_id=node_id, to_node_id="root",
            )
        assert pilot.proposed_children_in_trial(state) > (
            pilot.MAX_PROPOSED_CHILDREN_PER_TRIAL
        )
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("z", "src/good/x.py")], state=state, parent_node_id="p"
            )
        assert "pilot ceiling" in str(error.value)

    def test_a_misstated_proposed_count_is_refused(self):
        state = _state(GOOD)
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")],
                state=state, parent_node_id="p", already_proposed=0,
            )
        assert "derived count is authoritative" in str(error.value)

    def test_a_misstated_parent_depth_is_refused(self):
        state = _state(GOOD, chain_depth=2)
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py")],
                state=state, parent_node_id="p", parent_depth=0,
            )
        assert "derived depth is authoritative" in str(error.value)

    def test_truthful_arguments_are_accepted(self):
        state = _state(GOOD)
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/good/x.py")],
            state=state,
            parent_node_id="p",
            parent_depth=pilot._node_depth_from_state(state, "p"),
            already_proposed=pilot.proposed_children_in_trial(state),
        )
        assert len(admitted) == 1


class TestScopeContainment:
    def test_a_child_scope_inside_its_parent_is_admitted(self):
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/good/deep/x.py")], state=_state(GOOD),
            parent_node_id="p",
        )
        assert admitted

    def test_a_sibling_reach_is_refused(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/evil/x.py")], state=_state(GOOD),
                parent_node_id="p",
            )
        assert "escapes its parent's scope" in str(error.value)

    def test_a_non_sequence_owned_scope_is_refused(self):
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [{"node_id": "c1", "contract": {"owned_scope": "src/good/x.py"}}],
                state=_state(GOOD), parent_node_id="p",
            )


class TestMultiScopeParent:
    """R1: a parent may own several disjoint regions, and containment is "inside
    any of them", not "inside the first"."""

    def test_a_child_in_the_parents_second_scope_is_admitted(self):
        state = _state(GOOD)
        state.nodes["p"].contract["owned_scope"] = ["src/alpha/**", "src/beta/**"]
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/beta/x.py")], state=state, parent_node_id="p"
        )
        assert len(admitted) == 1

    def test_a_child_outside_every_parent_scope_is_refused(self):
        state = _state(GOOD)
        state.nodes["p"].contract["owned_scope"] = ["src/alpha/**", "src/beta/**"]
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/gamma/x.py")], state=state, parent_node_id="p"
            )
        assert "escapes its parent's scopes" in str(error.value)


class TestSharedContainment:
    """Review F8: two containment implementations that disagreed, and an empty or
    all-glob parent reading as containing everything."""

    def _both(self, child, parent):
        from orchestrator.decomposition import scope_contained as shared

        return shared(child, parent), pilot.scope_contained(child, parent)

    @pytest.mark.parametrize(
        "child,parent,contained",
        [
            ("src/a/x.py", "src/a/**", True),
            ("src/report/format.py", "src/report/**", True),
            ("src/b/x.py", "src/a/**", False),
            ("src/ab/x.py", "src/a", False),
            ("**", "src/a/**", False),
            ("", "src/a/**", False),
            ("src/a/x.py", "", False),
            ("src/a/x.py", "**", False),
            ("src/a/../b/x.py", "src/a/**", False),
        ],
    )
    def test_the_guard_and_the_shared_rule_agree(self, child, parent, contained):
        shared_answer, pilot_answer = self._both(child, parent)
        assert shared_answer == pilot_answer == contained


class TestContainmentIsSingleLayer:
    """Review F1, recorded rather than fixed.

    `validate_decomposition` does **not** enforce scope containment, so the pilot
    guard is its only enforcement. Enforcing it there is a change to the harness's
    decomposition contract, not defence-in-depth: existing *admitted* proposals
    have children whose scopes escape their parent's declared scope (a `src/m/**`
    child under a `src/health/**` parent is in the milestone acceptance corpus),
    so enforcing it rewrites semantics the committed evidence was measured under.
    The second remedy the review offers is the same check in the same place. The
    gap is pinned here so it cannot be forgotten, and so the day a second layer
    lands is the day this test changes.
    """

    def test_the_validator_does_not_enforce_containment_today(self):
        from orchestrator.decomposition import validate_decomposition

        state = _state(GOOD)
        proposal = _proposal_with_child_scope(["src/evil/x.py"])
        # Accepted: the harness has no containment rule today. If this ever
        # raises, the second layer landed and the guard stops being load-bearing.
        assert validate_decomposition(proposal, state) is None

    def test_the_guard_is_what_refuses_the_escaping_child(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/evil/x.py")], state=_state(GOOD),
                parent_node_id="p",
            )
        assert "escapes its parent's scope" in str(error.value)

    def test_a_deep_copy_means_a_post_admission_mutation_cannot_bypass_it(self):
        child = _child("c1", "src/good/x.py")
        admitted, _capability = pilot.admit_proposal(
            [child], state=_state(GOOD), parent_node_id="p"
        )
        admitted[0]["contract"]["owned_scope"][0] = "src/evil/x.py"
        assert child["contract"]["owned_scope"] == ["src/good/x.py"]


class TestBudgetAuthority:
    """Budgets are per-dimension mappings, so every comparison is per dimension."""

    def test_a_child_may_not_exceed_the_parent_on_a_dimension(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", amount=11.0)],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"MODEL_COST": 10.0},
            )
        assert "more than its parent's" in str(error.value)

    def test_dimensions_are_not_summed_together(self):
        admitted, _capability = pilot.admit_proposal(
            [
                _child("c1", "src/good/x.py", 8.0, dimension="MODEL_COST"),
                _child("c2", "src/good/y.py", 80.0, dimension="MODEL_TOKENS"),
            ],
            state=_state(GOOD), parent_node_id="p",
            parent_budget={"MODEL_COST": 10.0, "MODEL_TOKENS": 100.0},
        )
        assert len(admitted) == 2

    def test_a_different_dimension_has_its_own_limit(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 5.0, dimension="MODEL_TOKENS")],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"MODEL_COST": 10.0, "MODEL_TOKENS": 3.0},
            )
        assert "MODEL_TOKENS" in str(error.value)

    def test_children_may_not_sum_beyond_the_parent_on_one_dimension(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [
                    _child("c1", "src/good/x.py", 6.0),
                    _child("c2", "src/good/y.py", 6.0),
                ],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"MODEL_COST": 10.0},
            )
        assert "total" in str(error.value)

    def test_a_subdivision_within_the_parent_is_admitted(self):
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/good/x.py", 4.0), _child("c2", "src/good/y.py", 6.0)],
            state=_state(GOOD), parent_node_id="p",
            parent_budget={"MODEL_COST": 10.0},
        )
        assert len(admitted) == 2

    def test_an_uncatalogued_child_dimension_is_refused(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1.0, dimension="VIBES")],
                state=_state(GOOD), parent_node_id="p",
            )
        assert "not a catalogued budget dimension" in str(error.value)

    def test_a_dimension_the_parent_does_not_limit_is_refused(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1.0, dimension="MODEL_TOKENS")],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"MODEL_COST": 10.0},
            )
        assert "unbounded" in str(error.value)

    @pytest.mark.parametrize("bad", [float("nan"), float("inf"), -1.0, "ten"])
    def test_a_malformed_child_allocation_is_refused(self, bad):
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", bad)],
                state=_state(GOOD), parent_node_id="p",
            )


class TestFalsinessAndShapeOfParentBudget:
    """Review F2/F3: a falsy or unusable parent budget used to disable the whole
    bound, admitting an arbitrarily large child."""

    @pytest.mark.parametrize("bad", [0, 0.0, "", [], {}, 10.0, [10.0]])
    def test_a_non_mapping_or_falsy_parent_budget_is_refused(self, bad):
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1e9)],
                state=_state(GOOD), parent_node_id="p", parent_budget=bad,
            )

    @pytest.mark.parametrize("bad", [float("nan"), float("inf"), -1.0, "ten"])
    def test_a_non_finite_or_non_numeric_parent_limit_is_refused(self, bad):
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1e9)],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"MODEL_COST": bad},
            )

    def test_an_uncatalogued_parent_dimension_is_refused(self):
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1.0)],
                state=_state(GOOD), parent_node_id="p",
                parent_budget={"VIBES": 10.0},
            )

    def test_omitting_the_budget_derives_it_rather_than_disabling_the_bound(self):
        """RR3: `None` used to skip the whole check. It now falls through to the
        ledger, so omitting it is bounded rather than unbounded."""
        state = _state(GOOD)
        admitted, _capability = pilot.admit_proposal(
            [_child("c1", "src/good/x.py", 5.0)],
            state=state, parent_node_id="p",
        )
        assert admitted
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [_child("c1", "src/good/x.py", 1e9)],
                state=state, parent_node_id="p",
            )


class TestRefusalIsTotal:
    def test_a_refused_proposal_returns_nothing_at_all(self):
        """The failure mode this pilot exists to avoid: a half-applied
        proposal."""
        with pytest.raises(DecompositionError):
            pilot.admit_proposal(
                [
                    _child("good", "src/good/x.py", 1.0),
                    _child("bad", "src/evil/x.py", 1.0),
                ],
                state=_state(GOOD), parent_node_id="p",
            )

    def test_an_empty_proposal_is_refused(self):
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal([], state=_state(GOOD), parent_node_id="p")
        assert "at least one child" in str(error.value)

    def test_an_empty_proposal_says_so_not_which_bound_failed(self):
        """R4: the empty check ran after scope and budget derivation, so an
        unregistered parent budget masked the real diagnosis."""
        state = _state(GOOD)
        state.ledger.budgets.pop("p-budget")
        with pytest.raises(DecompositionError) as error:
            pilot.admit_proposal([], state=state, parent_node_id="p")
        assert "at least one child" in str(error.value)

    def test_a_refusal_leaves_the_caller_s_input_unchanged(self):
        child = _child("c1", "src/evil/x.py")
        before = dict(child)
        with pytest.raises(DecompositionError):
            pilot.admit_proposal([child], state=_state(GOOD), parent_node_id="p")
        assert child == before


class TestIsolationFromTheCaller:
    """Review F6: a shallow copy let a post-admission mutation change the
    structure that would be admitted."""

    def test_mutating_a_returned_child_does_not_touch_the_caller_s_child(self):
        child = _child("c1", "src/good/x.py")
        admitted, _capability = pilot.admit_proposal(
            [child], state=_state(GOOD), parent_node_id="p"
        )
        admitted[0]["contract"]["owned_scope"].append("src/evil/x.py")
        admitted[0]["budget_allocation"]["MODEL_COST"] = 1e9
        assert child["contract"]["owned_scope"] == ["src/good/x.py"]
        assert child["budget_allocation"]["MODEL_COST"] == 1.0


class TestInstrumentation:
    def test_a_refusal_names_its_stage_and_records_no_acceptance(self):
        record = pilot.record_outcome(
            False, refusing_stage="SCOPE", proposed=2, accepted=0, depth_reached=1
        )
        assert record == {
            "admitted": False,
            "refusing_stage": "SCOPE",
            "proposed_children": 2,
            "accepted_children": 0,
            "depth_reached": 1,
        }

    def test_an_admission_records_no_refusing_stage(self):
        record = pilot.record_outcome(
            True, refusing_stage="", proposed=2, accepted=2, depth_reached=1
        )
        assert record["refusing_stage"] is None
        assert record["accepted_children"] == 2


# --------------------------------------------------------------------------
# Constructed state
# --------------------------------------------------------------------------

def _state(parent_scope, chain_depth: int = 0):
    """A RunState whose node ``p`` owns ``parent_scope``, reached through a
    ``CHILD_OF`` chain of ``chain_depth`` intermediate nodes below the run root.

    A chain of 0 puts ``p`` at controller depth 1, since a root child reads 1 —
    the off-by-one the first re-review found.
    """
    from orchestrator.model import (
        BudgetRecord, NodeRecord, RelationRecord, RunState,
    )

    state = RunState(run_id="RUN-PILOT", root_node_id="root")
    state.nodes["root"] = NodeRecord(
        node_id="root", state="PROPOSED", cause="ROOT",
        contract={"acceptance_criteria": []}, is_root=True,
    )
    parent = "root"
    for level in range(chain_depth):
        node_id = f"mid{level}"
        state.nodes[node_id] = NodeRecord(
            node_id=node_id, state="PROPOSED", cause="DECOMPOSITION",
            contract={"acceptance_criteria": []},
        )
        state.relations[f"r{level}"] = RelationRecord(
            relation_id=f"r{level}", relation_type="CHILD_OF",
            from_node_id=node_id, to_node_id=parent,
        )
        parent = node_id
    state.nodes["p"] = NodeRecord(
        node_id="p", state="PROPOSED", cause="DECOMPOSITION",
        contract={
            "owned_scope": [parent_scope],
            "acceptance_criteria": [{"id": "AC", "mandatory": True}],
            "budget_id": "p-budget",
        },
    )
    state.relations["rp"] = RelationRecord(
        relation_id="rp", relation_type="CHILD_OF",
        from_node_id="p", to_node_id=parent,
    )
    state.ledger.register_budget(
        BudgetRecord(budget_id="p-budget", node_id="p", limits={"MODEL_COST": 10.0})
    )
    return state


def _proposal_with_child_scope(child_scopes):
    return {
        "node_id": "p",
        "children": [
            {
                "node_id": "c1",
                "mandatory": True,
                "criterion_ids": ["AC"],
                "contract": {
                    "owned_scope": child_scopes,
                    "acceptance_criteria": [{"id": "AC", "mandatory": True}],
                    "budget_id": "c1-budget",
                },
                "budget_allocation": {"MODEL_COST": 1.0},
            }
        ],
        "criterion_coverage": [
            {"criterion_id": "AC", "child_id": "c1", "mandatory_cover": True}
        ],
        "dependencies": [],
        "integration_owner": "c1",
    }


class TestTheProducer:
    """The producer: a provider's output is proposed, never trusted (P2, P6, P8).

    The provider is the seam a model adapter plugs into. The harness has no model
    call for recursive planning, so it is injected and these tests use
    deterministic doubles.
    """

    def _payload(self, children=None, **kwargs):
        # A chain of 0 puts p at controller depth 1, the only depth the pilot
        # admits a proposal from.
        state = _state(GOOD, chain_depth=0)
        children = children if children is not None else [
            _child("c1", "src/good/x.py", 4.0)
        ]

        def provider(_state, _parent):
            return [dict(child) for child in children]

        return pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1", **kwargs
        )

    def test_an_admitted_proposal_yields_a_payload_and_a_record(self):
        payload, record, _capability = self._payload()
        assert payload["node_id"] == "p"
        assert [c["node_id"] for c in payload["children"]] == ["c1"]
        assert record == {
            "admitted": True,
            "refusing_stage": None,
            "proposed_children": 1,
            "accepted_children": 1,
            # F5: the depth the proposal reaches is the children's depth, one
            # level below the parent at depth 1.
            "depth_reached": 2,
        }

    def test_coverage_is_derived_from_the_admitted_children(self):
        payload, _, _capability = self._payload()
        assert payload["criterion_coverage"] == [
            {"criterion_id": "AC", "child_id": "c1", "mandatory_cover": True}
        ]

    def test_a_refused_proposal_yields_no_payload_and_names_its_stage(self):
        payload, record, _capability = self._payload(
            children=[_child("c1", "src/evil/x.py", 4.0)]
        )
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "SCOPE"
        assert record["accepted_children"] == 0
        assert record["proposed_children"] == 1

    def test_the_refusing_stage_is_the_check_that_fired(self):
        _, over_budget, _capability = self._payload(
            children=[_child("c1", "src/good/x.py", 1e9)]
        )
        assert over_budget["refusing_stage"] == "BUDGET"
        _, too_many, _capability = self._payload(
            children=[
                _child(f"c{i}", "src/good/x.py", 1.0)
                for i in range(pilot.maximum_children_per_node() + 1)
            ]
        )
        assert too_many["refusing_stage"] == "BOUNDS"

    def test_a_refusal_is_total_through_the_producer(self):
        """A good child beside a bad one yields nothing, not the good one."""
        payload, record, _capability = self._payload(
            children=[
                _child("good", "src/good/x.py", 1.0),
                _child("bad", "src/evil/x.py", 1.0),
            ]
        )
        assert payload is None
        assert record["accepted_children"] == 0

    def test_the_producer_does_not_touch_the_declared_path(self):
        """P6: a pilot-admitted structure is derived. No obligation-source field,
        no axis name, and no target snapshot may appear in the payload."""
        payload, _, _capability = self._payload()
        serialised = repr(payload)
        for forbidden in (
            "obligations_source", "non_derivable_axes", "non_derivable_reason",
            "DECLARED", "DERIVED", "TargetSnapshot",
        ):
            assert forbidden not in serialised, f"pilot payload leaks {forbidden!r}"

    def test_the_provider_cannot_mutate_state_through_the_result(self):
        provider_child = _child("c1", "src/good/x.py", 4.0)
        payload, _, _capability = self._payload(children=[provider_child])
        payload["children"][0]["contract"]["owned_scope"][0] = "src/evil/x.py"
        assert provider_child["contract"]["owned_scope"] == ["src/good/x.py"]

    def test_the_kernel_records_the_pilot_lift_with_its_bounds(self):
        """P7: the non-goal is amended at admission, naming the bounds."""
        from orchestrator.experiment_target import PROJECT_KERNEL

        non_goals = " ".join(PROJECT_KERNEL["current_non_goals"])
        assert "bounded recursive-planning pilot" in non_goals
        assert "maximum_children_per_node" in non_goals
        # And the original exclusion is narrowed, not dropped.
        assert "beyond the experiment arms" in non_goals

    def test_the_kernel_named_bounds_equal_the_enforced_bounds(self):
        """Concern 1, ruled on: a substring check does not bind the claim.

        The reviewer changed the enforced depth, the per-trial ceiling, and the
        fan-out table on a scratch copy and all 74 pilot tests still passed,
        because the old test grepped for the literals "depth 2" and
        "32-proposed-children-per-trial" rather than comparing numbers. The kernel
        text stays a frozen literal -- interpolating module constants would couple
        a target's contract text to code state at import time -- so the test parses
        the numbers out and compares them to the running code.
        """
        import re

        from orchestrator.experiment_target import PROJECT_KERNEL

        text = " ".join(PROJECT_KERNEL["current_non_goals"])
        depth = int(re.search(r"depth (\d+)", text).group(1))
        ceiling = int(re.search(r"(\d+)-proposed-children-per-trial", text).group(1))
        fanout = int(re.search(r"maximum_children_per_node of (\d+)", text).group(1))
        assert depth == pilot.MAX_PROPOSAL_DEPTH
        assert ceiling == pilot.MAX_PROPOSED_CHILDREN_PER_TRIAL
        assert fanout == pilot.maximum_children_per_node()


class TestProducerRecordIsNeverLost:
    """P8: every proposal produces a record. A refusal raised *outside* the
    guarded region escapes with no instrumentation, which is the gap the
    implementer found while writing this brief."""

    def _run(self, mutate):
        state = _state(GOOD, chain_depth=0)
        child = _child("c1", "src/good/x.py", 4.0)
        mutate(child)

        def provider(_state, _parent):
            return [child]

        return pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )

    def test_a_malformed_criterion_ids_still_records(self):
        payload, record, _capability = self._run(lambda c: c.update(criterion_ids="AC"))
        assert payload is None
        assert record["admitted"] is False
        # R1 moved the shape check into the guard, so it refuses at the pre-check
        # rather than during coverage derivation.
        assert record["refusing_stage"] == "GUARD"
        assert record["accepted_children"] == 0

    def test_a_child_omitting_criterion_ids_is_admitted_with_empty_coverage(self):
        """The guard admits it and the *reducer* is what refuses an uncovered
        mandatory criterion. Pin the division of labour rather than blurring it."""
        payload, record, _capability = self._run(lambda c: c.pop("criterion_ids"))
        assert payload is not None
        assert payload["criterion_coverage"] == []
        assert record["admitted"] is True
        # ...and the reducer does refuse it, which is the authority's job.
        from orchestrator.decomposition import validate_decomposition

        with pytest.raises(DecompositionError) as error:
            validate_decomposition(payload, _state(GOOD, chain_depth=0))
        assert "criterion_coverage must not be empty" in str(error.value)


class TestTheProviderCannotRewriteItsOwnBounds:
    """F1 (P0): the provider was handed the live RunState and ran before the
    guard derived every bound from that same state, so it could clear its own
    depth and inflate its own budget, then be admitted against what it edited."""

    def _state_with_tight_bounds(self):
        """p at depth 2 (which the pilot must refuse) and a 10.0 budget limit."""
        state = _state(GOOD, chain_depth=pilot.MAX_PROPOSAL_DEPTH - 1)
        assert pilot._node_depth_from_state(state, "p") == pilot.MAX_PROPOSAL_DEPTH
        return state

    def _snapshot(self, state):
        return (
            sorted(state.nodes), sorted(state.relations),
            {k: dict(v.limits) for k, v in state.ledger.budgets.items()},
        )

    def test_a_provider_cannot_inflate_its_own_budget_or_clear_its_depth(self):
        state = self._state_with_tight_bounds()
        before = self._snapshot(state)

        def provider(s, _parent):
            s.relations.clear()                          # p would read depth 0
            s.ledger.budgets["p-budget"].limits["MODEL_COST"] = 1e12
            return [_child("c1", "src/good/x.py", 1e9)]

        payload, record, _capability = pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )
        assert payload is None, "a provider must not be able to grant itself budget"
        assert record["admitted"] is False
        assert record["refusing_stage"] == "BOUNDS", (
            "the depth bound must still refuse, from the live state"
        )
        assert self._snapshot(state) == before, "the provider mutated live state"

    def test_a_refused_proposal_cannot_leave_state_side_effects(self):
        """The review's second F1 probe: a refused proposal still left the
        provider's `ghost` node in state. Refusal is total over the payload, and
        now over the state too."""
        state = self._state_with_tight_bounds()
        before = self._snapshot(state)

        def provider(s, _parent):
            s.nodes["ghost"] = s.nodes["p"]
            return [_child("c1", "src/evil/x.py", 1.0)]

        payload, _, _capability = pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )
        assert payload is None
        assert "ghost" not in state.nodes
        assert self._snapshot(state) == before

    def test_a_mutating_provider_gets_the_same_outcome_as_a_clean_one(self):
        state = self._state_with_tight_bounds()
        clean, clean_record, _capability = pilot.propose_decomposition(
            state, "p",
            lambda s, p: [_child("c1", "src/good/x.py", 1.0)],
            proposal_id="PROP-1",
        )

        def provider(s, _parent):
            s.relations.clear()
            return [_child("c1", "src/good/x.py", 1.0)]

        mutated, mutated_record, _capability = pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )
        assert (mutated is None) == (clean is None)
        assert mutated_record["refusing_stage"] == clean_record["refusing_stage"]


class TestEveryProposalIsInstrumented:
    """F2/F3 (P1): the `except PilotRefusal` net covered three checks and
    nothing else, so thirteen input classes produced no record."""

    def _state(self):
        return _state(GOOD, chain_depth=0)

    def _run(self, provider, state=None, **kwargs):
        return pilot.propose_decomposition(
            state or self._state(), "p", provider, proposal_id="PROP-1", **kwargs
        )

    def test_a_provider_that_raises_is_recorded_not_raised(self):
        def provider(_s, _p):
            raise RuntimeError("the model adapter failed")

        payload, record, _capability = self._run(provider)
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "PROVIDER"

    def test_a_non_callable_provider_is_recorded(self):
        payload, record, _capability = self._run(None)
        assert payload is None
        assert record["refusing_stage"] == "PROVIDER"

    @pytest.mark.parametrize(
        "returned", [5, {"a": 1}, [1, 2], ["not-a-mapping"], "ab", b"ab"]
    )
    def test_a_malformed_provider_return_is_recorded(self, returned):
        payload, record, _capability = self._run(lambda s, p: returned)
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] in {"PROVIDER", "GUARD"}

    def test_a_generator_that_raises_mid_iteration_is_recorded(self):
        def provider(_s, _p):
            def generate():
                yield _child("c1", "src/good/x.py")
                raise RuntimeError("stream broke")

            return generate()

        payload, record, _capability = self._run(provider)
        assert payload is None
        assert record["refusing_stage"] == "PROVIDER"

    @pytest.mark.parametrize("returned", [[], None])
    def test_an_empty_or_absent_proposal_is_recorded(self, returned):
        payload, record, _capability = self._run(lambda s, p: returned)
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] in {"PROVIDER", "GUARD"}

    def test_an_unknown_parent_is_recorded(self):
        payload, record, _capability = self._run(
            lambda s, p: [_child("c1", "src/good/x.py")], state=self._state()
        )
        payload, record, _capability = pilot.propose_decomposition(
            self._state(), "nope", lambda s, p: [_child("c1", "src/good/x.py")],
            proposal_id="PROP-1",
        )
        assert payload is None
        assert record["refusing_stage"] == "GUARD"

    def test_a_parent_with_no_registered_budget_is_recorded(self):
        state = self._state()
        state.ledger.budgets.pop("p-budget")
        payload, record, _capability = self._run(
            lambda s, p: [_child("c1", "src/good/x.py")], state=state
        )
        assert payload is None
        assert record["refusing_stage"] == "GUARD"

    def test_a_child_with_a_non_mapping_contract_is_recorded(self):
        payload, record, _capability = self._run(
            lambda s, p: [{"node_id": "c1", "contract": 7}]
        )
        assert payload is None
        assert record["admitted"] is False

    def test_a_child_missing_node_id_is_recorded(self):
        payload, record, _capability = self._run(
            lambda s, p: [{"criterion_ids": ["AC"], "contract": {
                "owned_scope": ["src/good/x.py"],
                "acceptance_criteria": [{"id": "AC", "mandatory": True}],
                "budget_id": "c1-budget",
            }}]
        )
        assert payload is None
        assert record["admitted"] is False

    def test_a_malformed_dependencies_entry_is_recorded(self):
        payload, record, _capability = self._run(
            lambda s, p: [_child("c1", "src/good/x.py")], dependencies=[7]
        )
        assert payload is None
        assert record["refusing_stage"] == "ASSEMBLY"

    def test_a_malformed_expected_versions_entry_is_recorded(self):
        payload, record, _capability = self._run(
            lambda s, p: [_child("c1", "src/good/x.py")], expected_versions={"n": 7}
        )
        assert payload is None
        assert record["refusing_stage"] == "ASSEMBLY"


class TestIdentifiersTheReducerCanKey:
    """R1: the guard admitted children whose identifiers the reducer cannot use.

    A provider returning `node_id=["c1"]` was admitted, and the reducer then
    raised a bare `TypeError: unhashable type: 'list'` on a well-formed proposal —
    the authority crashed instead of refusing, which breaks the seam's promise
    that what the guard admits is something the reducer can evaluate.
    """

    def _run(self, child):
        state = _state(GOOD, chain_depth=0)
        return pilot.propose_decomposition(
            state, "p", lambda s, p: [child], proposal_id="PROP-1"
        )

    @pytest.mark.parametrize(
        "node_id", [["c1"], {"c1": 1}, None, "", 7, ("c1",)]
    )
    def test_a_non_string_or_empty_node_id_is_refused(self, node_id):
        child = _child("c1", "src/good/x.py")
        child["node_id"] = node_id
        payload, record, _capability = self._run(child)
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "GUARD"

    @pytest.mark.parametrize(
        "criterion_ids", [[["AC"]], [{"AC": 1}], [None], [7], [""], [{"a"}]]
    )
    def test_a_non_string_criterion_id_is_refused(self, criterion_ids):
        child = _child("c1", "src/good/x.py")
        child["criterion_ids"] = criterion_ids
        payload, record, _capability = self._run(child)
        assert payload is None
        assert record["admitted"] is False

    def test_an_omitted_node_id_is_refused(self):
        child = _child("c1", "src/good/x.py")
        child.pop("node_id")
        payload, record, _capability = self._run(child)
        assert payload is None
        assert record["admitted"] is False

    def test_a_well_formed_child_is_unaffected(self):
        payload, record, _capability = self._run(_child("c1", "src/good/x.py", 4.0))
        assert payload is not None
        assert record["admitted"] is True


class TestProviderFaultCountsAreHonest:
    """R2: the record's counts under-reported on a provider fault."""

    def test_a_generator_yielding_children_then_raising_counts_them(self):
        state = _state(GOOD, chain_depth=0)

        def provider(_s, _p):
            def generate():
                yield _child("c1", "src/good/x.py")
                yield _child("c2", "src/good/y.py")
                raise RuntimeError("stream broke")

            return generate()

        payload, record, _capability = pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )
        assert payload is None
        assert record["refusing_stage"] == "PROVIDER"
        assert record["proposed_children"] == 2, (
            "the two children the provider did produce must be counted"
        )

    def test_a_provider_fault_still_records_the_parents_depth(self):
        state = _state(GOOD, chain_depth=1)

        def provider(_s, _p):
            raise RuntimeError("boom")

        _, record, _capability = pilot.propose_decomposition(
            state, "p", provider, proposal_id="PROP-1"
        )
        assert record["refusing_stage"] == "PROVIDER"
        assert record["depth_reached"] == pilot._node_depth_from_state(state, "p")


class TestContractKeysTheReducerHashes:
    """R5: `contract.budget_id` is provider-controlled and becomes a ledger key, so
    an unhashable value raised a bare `TypeError` the reducer's handler did not
    catch -- the same defect R1 found for `node_id`, on a field not yet reached."""

    def _run(self, mutate):
        state = _state(GOOD, chain_depth=0)
        child = _child("c1", "src/good/x.py", 4.0)
        mutate(child)
        return pilot.propose_decomposition(
            state, "p", lambda s, p: [child], proposal_id="PROP-1"
        )

    @pytest.mark.parametrize(
        "budget_id", [["b"], {"b": 1}, None, "", 7, ("b",), {"b"}]
    )
    def test_an_unhashable_or_empty_budget_id_is_refused(self, budget_id):
        payload, record, _capability = self._run(
            lambda c: c["contract"].update(budget_id=budget_id)
        )
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "GUARD"

    @pytest.mark.parametrize("contract", [7, "c", None, ["a"]])
    def test_a_non_mapping_contract_is_refused(self, contract):
        payload, record, _capability = self._run(lambda c: c.update(contract=contract))
        assert payload is None
        assert record["refusing_stage"] == "GUARD"

    @pytest.mark.parametrize("criteria", [[], "AC", None, 7, [7], [{}], [{"id": ""}]])
    def test_malformed_acceptance_criteria_are_refused(self, criteria):
        payload, record, _capability = self._run(
            lambda c: c["contract"].update(acceptance_criteria=criteria)
        )
        assert payload is None
        assert record["refusing_stage"] == "GUARD"

    def test_a_well_formed_contract_is_unaffected(self):
        payload, record, _capability = self._run(lambda c: None)
        assert payload is not None
        assert record["admitted"] is True

    def test_omitting_criterion_ids_does_not_skip_the_contract_checks(self):
        """A `continue` in the criterion loop used to skip the contract checks
        entirely, so omitting `criterion_ids` reached the same identifier gaps
        through a different door."""
        def run(mutate):
            child = _child("c1", "src/good/x.py", 4.0)
            child.pop("criterion_ids")
            mutate(child)
            state = _state(GOOD, chain_depth=0)
            return pilot.propose_decomposition(
                state, "p", lambda s, p: [child], proposal_id="PROP-1"
            )

        payload, record, _capability = run(lambda c: None)
        assert payload is not None, "a well-formed child without criterion_ids is admitted"
        assert record["admitted"] is True
        for mutate in (
            lambda c: c["contract"].pop("budget_id"),
            lambda c: c["contract"].update(budget_id=["b"]),
            lambda c: c.update(contract=7),
            lambda c: c["contract"].update(acceptance_criteria=[]),
        ):
            payload, record, _capability = run(mutate)
            assert payload is None
            assert record["refusing_stage"] == "GUARD"


class TestDependencyEntryShape:
    """R6: caller-supplied dependencies reached the reducer as a bare KeyError or
    TypeError, because `_ensure_acyclic` reads both endpoints with no shape check."""

    def _run(self, dependencies):
        state = _state(GOOD, chain_depth=0)
        return pilot.propose_decomposition(
            state, "p",
            lambda s, p: [_child("c1", "src/good/x.py", 4.0)],
            proposal_id="PROP-1", dependencies=dependencies,
        )

    @pytest.mark.parametrize(
        "entry",
        [
            {},
            {"from_node_id": "c1"},
            {"to_node_id": "c1"},
            {"from_node_id": ["c1"], "to_node_id": "c1"},
            {"from_node_id": "c1", "to_node_id": None},
            {"from_node_id": 7, "to_node_id": 7},
        ],
    )
    def test_a_malformed_dependency_is_refused(self, entry):
        payload, record, _capability = self._run([entry])
        assert payload is None
        assert record["refusing_stage"] == "ASSEMBLY"

    def test_a_well_formed_dependency_is_admitted(self):
        payload, record, _capability = self._run(
            [{"from_node_id": "c1", "to_node_id": "c2"}]
        )
        assert payload is not None
        assert payload["dependencies"] == [
            {"from_node_id": "c1", "to_node_id": "c2"}
        ]


class TestBudgetIdIsUsableNotJustWellFormed:
    """R7: a `budget_id` that is a valid string can still be a key the reducer
    cannot *use*. `Ledger.register_budget` raises `LedgerStateError` when the id is
    present, and `reduce` wraps the handler with nothing, so the error escaped as
    neither `DecompositionError` nor `ReducerError`."""

    def _run(self, children):
        state = _state(GOOD, chain_depth=0)
        return pilot.propose_decomposition(
            state, "p", lambda s, p: children, proposal_id="PROP-1"
        )

    def test_a_child_reusing_the_parents_budget_id_is_refused(self):
        child = _child("c1", "src/good/x.py", 4.0)
        child["contract"]["budget_id"] = "p-budget"
        payload, record, _capability = self._run([child])
        assert payload is None
        assert record["admitted"] is False
        assert record["refusing_stage"] == "GUARD"

    def test_two_siblings_claiming_one_budget_id_are_refused(self):
        first = _child("c1", "src/good/x.py", 4.0)
        second = _child("c2", "src/good/y.py", 4.0)
        second["contract"]["budget_id"] = first["contract"]["budget_id"]
        payload, record, _capability = self._run([first, second])
        assert payload is None
        assert record["refusing_stage"] == "GUARD"

    def test_distinct_fresh_budget_ids_are_admitted(self):
        payload, record, _capability = self._run(
            [_child("c1", "src/good/x.py", 4.0), _child("c2", "src/good/y.py", 4.0)]
        )
        assert payload is not None
        assert record["admitted"] is True
        ids = [c["contract"]["budget_id"] for c in payload["children"]]
        assert ids == ["c1-budget", "c2-budget"]


# --------------------------------------------------------------------------
# Admission capability (R1): a required non-data capability, not a marker
# --------------------------------------------------------------------------
#
# The entry that admits a decomposition requires a non-data admission capability
# bound to a digest of the admitted children — never a declarative `source`/
# marker field, which is omittable and forgeable and model output is data. The
# capability has exactly two mint points: `planning_pilot.admit_proposal`
# (guarded) and the deterministic derivation admission path (derived). The
# shapes below are R1's prevention shape as named in this step's brief; the
# transit half is pinned unchanged by
# tests/test_planning_pilot_routing.py::test_admitted_payload_is_forwarded_unmutated.


def _cap_run(tmp_path, name: str, run_id: str = "RUN-CAP", **run_limits):
    """A real run whose root owns ``src/health/**`` and a bounded MODEL_COST.

    The capability shapes cross the pilot's guard and the controller's
    admission entry, so they run against replayable store state rather than
    the constructed ``RunState`` above.
    """
    import copy as _copy  # noqa: F401 - kept local like the helpers above

    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor
    from orchestrator.store import EventStore

    from helpers import build_run_config

    workdir = tmp_path / name
    workdir.mkdir()
    store = EventStore(str(workdir / "events.db"))
    controller = Controller(store, ScriptedExecutor({}))
    limits = {"nodes": 10, "actions": 10}
    limits.update(run_limits)
    config = build_run_config(
        run_id,
        limits=limits,
        root_contract={
            "description": "capability probe run",
            "owned_scope": ["src/health/**"],
            "acceptance_command": "pytest tests/health",
            "acceptance_criteria": [{"id": "AC", "mandatory": True}],
        },
    )
    return store, controller, controller.submit_run(config)


def _cap_children(run_id: str, names=("c1", "c2")):
    """Guard-admissible children: inside the root's declared scope and budget."""
    return [
        _child(f"{run_id}-{name}", "src/health/a/**", 2.0, criterion="AC")
        for name in names
    ]


def _cap_coverage(run_id: str, name: str):
    return [
        {"criterion_id": "AC", "child_id": f"{run_id}-{name}", "mandatory_cover": True}
    ]


def _decomposition_events(store, run_id):
    return [event for event in store.history(run_id) if event.event_type == "DECOMPOSITION_ADMITTED"]


def _dependency_edges(state):
    return sorted(
        (relation.from_node_id, relation.to_node_id)
        for relation in state.relations.values()
        if relation.relation_type == "DEPENDS_ON"
    )


class TestAdmissionCapabilityIsRequired:
    """Capability shape: admitting a decomposition without a valid admission
    capability is refused — a caller holding only data (children, coverage,
    dependencies) cannot construct one, and the refusal is observable (the same
    rejection surface an admission failure uses today, never a second path)."""

    def test_admitting_a_decomposition_without_a_valid_admission_capability_is_refused(self, tmp_path):
        from orchestrator.controller import AdmissionCapability, WorkflowError

        run_id = "RUN-NEEDCAP"
        store, controller, root = _cap_run(tmp_path, "cap", run_id)
        try:
            children = _cap_children(run_id, names=("c1",))
            coverage = _cap_coverage(run_id, "c1")
            # A caller holding only data cannot construct authority: the class is
            # minted, never constructed, and the refusal is the same rejection
            # surface an admission failure uses today.
            with pytest.raises(WorkflowError):
                AdmissionCapability(bound_digest="deadbeef")
            with pytest.raises(WorkflowError) as refused:
                controller.propose_decomposition(
                    run_id, root, "d1", children, coverage
                )
            assert "admission capability" in str(refused.value)
            # The refusal is the admission failure's surface: the rejection an
            # admission failure raises today is the same class, never a second
            # path (an unknown parent is refused as WorkflowError too).
            with pytest.raises(WorkflowError) as failed:
                controller.admit_derived_decomposition(
                    run_id, "nope", "d1", children, coverage
                )
            assert type(refused.value) is type(failed.value) is WorkflowError
        finally:
            store.close()


class TestTheOnlyTwoMintPoints:
    """Two-mint-point shape: the capability is mintable at exactly two places —
    ``planning_pilot.admit_proposal`` (guarded) and the deterministic derivation
    admission path (derived). No third mint exists: construction outside those
    paths is refused, and this test names both mint points as the only ones."""

    def test_the_only_two_mint_points_are_admit_proposal_and_admit_derived_decomposition(self, tmp_path):
        from orchestrator.controller import AdmissionCapability, WorkflowError

        run_id = "RUN-MINTS"
        store, controller, root = _cap_run(tmp_path, "mints", run_id)
        try:
            children = _cap_children(run_id, names=("c1",))
            coverage = _cap_coverage(run_id, "c1")
            # The guarded mint: the guard admits, and mints over exactly what it
            # admitted.
            admitted, guarded = pilot.admit_proposal(
                children, state=store.state(run_id), parent_node_id=root
            )
            assert guarded.admits(admitted)
            # The derived mint: the deterministic derivation admission path
            # admits without any caller-supplied capability.
            child_ids = controller.admit_derived_decomposition(
                run_id, root, "d1", children, coverage
            )
            assert child_ids == [f"{run_id}-c1"]
            # No third mint: construction outside those two paths is refused,
            # and the model-routed entry does not mint either — it refuses
            # without one.
            with pytest.raises(WorkflowError):
                AdmissionCapability()
            with pytest.raises(WorkflowError):
                AdmissionCapability(mint=object(), bound_digest="0" * 64)
            with pytest.raises(WorkflowError):
                controller.propose_decomposition(
                    run_id, root, "d2", _cap_children(run_id, names=("c3",)),
                    _cap_coverage(run_id, "c3"),
                )
        finally:
            store.close()


class TestDigestBinding:
    """Digest-binding shape: the capability is bound to a digest of the admitted
    children — a capability minted over one admitted structure is refused at a
    submission whose children digest differs, and the guarded mint binds exactly
    the structures the guard admitted."""

    def test_the_capability_is_bound_to_a_digest_of_the_admitted_children(self, tmp_path):
        from orchestrator.controller import WorkflowError

        run_id = "RUN-DIGEST"
        store, controller, root = _cap_run(tmp_path, "digest", run_id)
        try:
            children = _cap_children(run_id, names=("c1",))
            coverage = _cap_coverage(run_id, "c1")
            admitted, capability = pilot.admit_proposal(
                children, state=store.state(run_id), parent_node_id=root
            )
            # Exactly the structures the guard admitted: admitted.
            child_ids = controller.propose_decomposition(
                run_id, root, "d1", admitted, coverage,
                admission_capability=capability,
            )
            assert child_ids == [f"{run_id}-c1"]
            # A capability minted over one admitted structure is refused at a
            # submission whose children digest differs ...
            with pytest.raises(WorkflowError) as other:
                controller.propose_decomposition(
                    run_id, root, "d2", _cap_children(run_id, names=("c3",)),
                    _cap_coverage(run_id, "c3"), admission_capability=capability,
                )
            assert "digest differs" in str(other.value)
            # ... including the post-return mutation the admitted payload still
            # permits (PILOT-R1's wiring constraint): the digest is what refuses
            # it here.
            import copy

            mutated = copy.deepcopy(admitted)
            mutated[0]["contract"]["owned_scope"] = ["src/evil/**"]
            with pytest.raises(WorkflowError):
                controller.propose_decomposition(
                    run_id, root, "d3", mutated, coverage,
                    admission_capability=capability,
                )
        finally:
            store.close()


class TestDerivedOnlyNaming:
    """Derived-only naming shape: the entry the deterministic derivation path
    uses carries a name that declares the derived-only route; the old unguarded
    ``propose_decomposition`` name does not remain callable without a
    capability. Both routes land the same observable admission behaviour as
    today (``DECOMPOSITION_ADMITTED`` payloads, run-limit checks, dependency
    edges)."""

    def test_the_derived_route_entry_declares_the_derived_only_route(self):
        import inspect

        from orchestrator import trial_driver
        from orchestrator.controller import Controller

        # The name declares the derived-only route ...
        assert "derived" in Controller.admit_derived_decomposition.__name__
        # ... and the deterministic derivation admission path is its caller,
        # while the model-routed forward does not use it.
        assert "admit_derived_decomposition" in inspect.getsource(
            trial_driver._admit_decomposition
        )
        assert "admit_derived_decomposition" not in inspect.getsource(
            trial_driver._admit_routed_decomposition
        )

    def test_the_old_unguarded_name_is_not_callable_without_a_capability(self, tmp_path):
        from orchestrator.controller import WorkflowError

        run_id = "RUN-OLDNAME"
        store, controller, root = _cap_run(tmp_path, "oldname", run_id)
        try:
            with pytest.raises(WorkflowError):
                controller.propose_decomposition(
                    run_id, root, "d1",
                    _cap_children(run_id, names=("c1",)),
                    _cap_coverage(run_id, "c1"),
                )
        finally:
            store.close()

    def test_both_routes_land_the_same_decomposition_admitted_payload_and_dependency_edges(self, tmp_path):
        run_id = "RUN-SAME"
        children = _cap_children(run_id)
        coverage = _cap_coverage(run_id, "c1")
        dependencies = [
            {"from_node_id": f"{run_id}-c2", "to_node_id": f"{run_id}-c1"}
        ]
        # Two identical runs, one per route: the deterministic derivation
        # admission path and the model-routed entry with the guard's mint.
        derived_store, derived_controller, derived_root = _cap_run(
            tmp_path, "derived", run_id
        )
        routed_store, routed_controller, routed_root = _cap_run(
            tmp_path, "routed", run_id
        )
        try:
            derived_controller.admit_derived_decomposition(
                run_id, derived_root, "d1", children, coverage,
                dependencies=dependencies,
            )
            admitted, capability = pilot.admit_proposal(
                children, state=routed_store.state(run_id), parent_node_id=routed_root
            )
            routed_controller.propose_decomposition(
                run_id, routed_root, "d1", admitted, coverage,
                dependencies=dependencies, admission_capability=capability,
            )
            # DECOMPOSITION_ADMITTED payloads land identically on both routes.
            derived_event = _decomposition_events(derived_store, run_id)[0]
            routed_event = _decomposition_events(routed_store, run_id)[0]
            assert derived_event.payload == routed_event.payload
            # Dependency edges land identically too: the dependent starts behind
            # its predecessor on both routes.
            derived_state = derived_store.state(run_id)
            routed_state = routed_store.state(run_id)
            assert _dependency_edges(derived_state) == _dependency_edges(routed_state) == [
                (f"{run_id}-c2", f"{run_id}-c1")
            ]
        finally:
            derived_store.close()
            routed_store.close()

    def test_both_routes_land_run_limit_checks(self, tmp_path):
        from orchestrator.controller import RunLimitExhausted

        for name, route in (("derived", "derived"), ("routed", "routed")):
            run_id = "RUN-LIMIT"
            store, controller, root = _cap_run(
                tmp_path, name, run_id, maximum_depth=1
            )
            try:
                # maximum_depth=1 admits exactly one level below the root.
                controller.admit_derived_decomposition(
                    run_id, root, "d1",
                    _cap_children(run_id, names=("c1",)),
                    _cap_coverage(run_id, "c1"),
                )
                grandchild = [
                    _child(f"{run_id}-g", "src/health/a/g.py", 1.0, criterion="AC")
                ]
                coverage = _cap_coverage(run_id, "g")
                if route == "derived":
                    with pytest.raises(RunLimitExhausted):
                        controller.admit_derived_decomposition(
                            run_id, f"{run_id}-c1", "d2", grandchild, coverage
                        )
                else:
                    admitted, capability = pilot.admit_proposal(
                        grandchild, state=store.state(run_id),
                        parent_node_id=f"{run_id}-c1",
                    )
                    with pytest.raises(RunLimitExhausted):
                        controller.propose_decomposition(
                            run_id, f"{run_id}-c1", "d2", admitted, coverage,
                            admission_capability=capability,
                        )
            finally:
                store.close()


class TestNoMarkerField:
    """No-marker shape: no declarative ``source``/marker field exists on the
    payload, the event, or any capability structure — the capability is
    authority, not annotation."""

    def test_no_payload_event_or_capability_carries_a_source_marker(self, tmp_path):
        from orchestrator.controller import AdmissionCapability

        run_id = "RUN-NOMARK"
        store, controller, root = _cap_run(tmp_path, "nomark", run_id)
        try:
            children = _cap_children(run_id, names=("c1",))
            payload, _record, capability = pilot.propose_decomposition(
                store.state(run_id),
                root,
                lambda _state, _parent: [dict(child) for child in children],
                proposal_id="d1",
                dependencies=[],
            )
            assert payload is not None
            controller.propose_decomposition(
                run_id, root, "d1",
                payload["children"], payload["criterion_coverage"],
                dependencies=payload["dependencies"],
                admission_capability=capability,
            )
            event = _decomposition_events(store, run_id)[0]
            forbidden = (
                "source", "marker", "origin", "provenance", "admission_capability",
            )
            for surface in (payload, event.payload):
                for key in forbidden:
                    assert key not in surface
                for child in surface["children"]:
                    for key in forbidden:
                        assert key not in child
                        assert key not in (child.get("contract") or {})
            # The capability structure is authority, not annotation: a non-data
            # object whose only state is the binding and the mint nonce.
            assert not isinstance(capability, dict)
            assert set(AdmissionCapability.__slots__) == {"_bound_digest", "_nonce"}
            for key in forbidden:
                assert not hasattr(capability, key)
        finally:
            store.close()
