# SPDX-License-Identifier: AGPL-3.0-or-later
"""Derived obligations (self-host Phase 4, "General Decomposition").

The obligation set is what used to be hand-authored per target. These pin the
properties the derivation must hold — determinism, observed dependencies,
fail-closed behaviour — and the shape of the contract `build_target` produces
from a derived set. See
`docs/research/phase4-decomposition-design.md` for the contract.
"""
from __future__ import annotations

import os
import subprocess
import tempfile

import pytest

from orchestrator import derive_obligations as derive
from orchestrator import experiment, experiment_target


def _repo_with(files: dict) -> tuple:
    """A throwaway git repository containing ``files``; returns (path, commit).

    Uses the project's ``GIT_ENVIRONMENT`` fixture identity: this module is
    collected by the frozen ``check-tests`` gate inside the sandbox, where no
    ambient git identity exists and an unconfigured ``git commit`` fails.
    """
    from orchestrator.conformance import GIT_ENVIRONMENT
    from orchestrator.worktree import _git_environment

    root = tempfile.mkdtemp()
    for relative, content in files.items():
        path = os.path.join(root, relative)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as handle:
            handle.write(content)
    environment = _git_environment(GIT_ENVIRONMENT)
    subprocess.run(("git", "-C", root, "init", "-q"), check=True, env=environment)
    subprocess.run(("git", "-C", root, "add", "-A"), check=True, env=environment)
    subprocess.run(
        ("git", "-C", root, "commit", "-q", "-m", "derivation fixture"),
        check=True, env=environment,
    )
    commit = subprocess.run(
        ("git", "-C", root, "rev-parse", "HEAD"),
        check=True, capture_output=True, text=True, env=environment,
    ).stdout.strip()
    return root, commit


class TestDependencies:
    def test_observed_import_becomes_a_dependency(self):
        """The core claim: a dependency is an import, not an assertion."""
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "from src.alpha import mod\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        assert derive.derive_dependencies(repository, commit, components) == {
            "alpha": (),
            "beta": ("alpha",),
        }

    def test_relative_imports_are_resolved_across_components(self):
        """`from . import sibling` crosses a component boundary exactly as an
        absolute import does, and is the common case in this repository."""
        repository, commit = _repo_with(
            {
                "pkg/core.py": "VALUE = 1\n",
                "pkg/edge.py": "from . import core\n",
            }
        )
        components = (("core", "pkg/core.py"), ("edge", "pkg/edge.py"))
        assert derive.derive_dependencies(repository, commit, components)["edge"] == (
            "core",
        )

    def test_from_dot_import_names_the_submodule(self):
        """`from . import a, b` names submodules; it does not import nothing."""
        repository, commit = _repo_with(
            {
                "pkg/a.py": "VALUE = 1\n",
                "pkg/b.py": "VALUE = 2\n",
                "pkg/user.py": "from . import a, b\n",
            }
        )
        components = (
            ("a", "pkg/a.py"), ("b", "pkg/b.py"), ("user", "pkg/user.py"),
        )
        assert derive.derive_dependencies(repository, commit, components)["user"] == (
            "a", "b",
        )

    def test_standard_library_imports_are_not_edges(self):
        """Third-party and stdlib imports are not the target's own integration
        dependencies, and must not be manufactured into some."""
        repository, commit = _repo_with(
            {
                "src/one/mod.py": "import os\nimport json\nVALUE = 1\n",
                "src/two/mod.py": "from os import path\n",
            }
        )
        components = (("one", "src/one/**"), ("two", "src/two/**"))
        assert derive.derive_dependencies(repository, commit, components) == {
            "one": (), "two": (),
        }

    def test_unparseable_file_yields_no_edge_rather_than_an_error(self):
        """The scan looks for evidence; absence of evidence must not become a
        dependency, and a file that will not parse must not fail the build."""
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "def broken(:\n    pass\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        assert derive.derive_dependencies(repository, commit, components)["beta"] == ()

    def test_a_cycle_in_the_import_graph_is_reported_not_ordered(self):
        """The derivation records edges; acyclicity stays the validator's job
        (`decomposition._ensure_acyclic`), so both directions are visible."""
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "from src.beta import mod as b\n",
                "src/beta/mod.py": "from src.alpha import mod as a\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        edges = derive.derive_dependencies(repository, commit, components)
        assert edges["alpha"] == ("beta",) and edges["beta"] == ("alpha",)

    def test_overlapping_component_globs_fail_closed(self):
        """Ambiguous ownership must fail rather than pick a winner."""
        repository, commit = _repo_with({"src/pkg/mod.py": "VALUE = 1\n"})
        with pytest.raises(derive.DerivationError) as error:
            derive.derive_dependencies(
                repository, commit, (("a", "src/**"), ("b", "src/pkg/**"))
            )
        assert "overlap" in str(error.value)


class TestDerivation:
    def test_one_obligation_per_component_with_its_own_scope(self):
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "from src.alpha import mod\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        obligations = derive.derive_obligations(
            repository, commit, components, ("AC-ONE", "AC-TWO")
        )
        assert [o["child_id"] for o in obligations] == ["alpha", "beta"]
        assert [o["scope"] for o in obligations] == ["src/alpha/**", "src/beta/**"]
        # Every declared criterion is owned, and nothing undeclared is referenced.
        assert all(o["criterion_ids"] == ("AC-ONE", "AC-TWO") for o in obligations)
        assert obligations[1]["depends_on"] == ("alpha",)

    def test_derivation_is_deterministic(self):
        """No clock, no model call: the same snapshot yields the same set."""
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "from src.alpha import mod\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        first = derive.derive_obligations(repository, commit, components, ("AC",))
        second = derive.derive_obligations(repository, commit, components, ("AC",))
        assert first == second

    def test_no_components_or_no_criteria_fails_closed(self):
        repository, commit = _repo_with({"a.py": "X = 1\n"})
        with pytest.raises(derive.DerivationError):
            derive.derive_obligations(repository, commit, (), ("AC",))
        with pytest.raises(derive.DerivationError):
            derive.derive_obligations(repository, commit, (("a", "**"),), ())

    def test_duplicate_component_names_fail_closed(self):
        repository, commit = _repo_with({"a.py": "X = 1\n"})
        with pytest.raises(derive.DerivationError):
            derive.derive_obligations(
                repository, commit, (("a", "**"), ("a", "**")), ("AC",)
            )

    def test_a_single_component_yields_one_obligation_not_fake_children(self):
        """A one-component target is honestly one child. Manufacturing a child
        per criterion would be the crudeness this phase removes."""
        repository, commit = _repo_with({"src/only/mod.py": "VALUE = 1\n"})
        obligations = derive.derive_obligations(
            repository, commit, (("core", "src/only/**"),), ("AC-A", "AC-B", "AC-C")
        )
        assert len(obligations) == 1
        assert obligations[0]["criterion_ids"] == ("AC-A", "AC-B", "AC-C")


class TestBuildTargetIntegration:
    def test_obligations_are_derived_when_omitted(self):
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "from src.alpha import mod\n",
            }
        )
        target = experiment.build_target(
            repository, commit,
            snapshot_id="TARGET-DERIVED-1",
            task_statement="Do the thing.",
            project_kernel={"kernel_id": "K", "purpose": "p"},
            visible_commands=("true",),
            components=(("alpha", "src/alpha/**"), ("beta", "src/beta/**")),
            owned_scope=("src/**",),
            acceptance_criteria=("AC-ONE",),
        )
        assert [o["child_id"] for o in target.obligations] == ["alpha", "beta"]
        assert target.obligations[1]["depends_on"] == ("alpha",)

    def test_a_divergent_override_is_admitted_and_an_equivalent_one_refused(self):
        """The S11 disposition: `obligations=` implies DECLARED, so it is no
        longer an unconditional escape hatch. A declaration that diverges on a
        named axis is admitted; one identical to the derived set is refused,
        because there is nothing for it to justify.

        Both halves use two components, because a one-component target cannot
        diverge on ALLOCATION while still satisfying coverage: one component must
        own every declared criterion, which is exactly the derived allocation.
        """
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/beta/mod.py": "OTHER = 2\n",
            }
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        criteria = ("AC-ALPHA", "AC-BETA")
        common = dict(
            repository=repository,
            base_commit=commit,
            task_statement="Do the thing.",
            project_kernel={"kernel_id": "K", "purpose": "p"},
            visible_commands=("true",),
            components=components,
            owned_scope=("src/**",),
            acceptance_criteria=criteria,
        )

        # Refused: coverage-valid and identical to the derived set (each child
        # carries both criteria, no nesting, no edges), so no axis diverges.
        equivalent = (
            {
                "child_id": "alpha",
                "criterion_ids": criteria,
                "scope": "src/alpha/**",
                "depends_on": (),
                "description": "alpha",
                "budget": 30.0,
                "acceptance": (
                    {"id": "AC-ALPHA", "mandatory": True},
                    {"id": "AC-BETA", "mandatory": True},
                ),
            },
            {
                "child_id": "beta",
                "criterion_ids": criteria,
                "scope": "src/beta/**",
                "depends_on": (),
                "description": "beta",
                "budget": 30.0,
                "acceptance": (
                    {"id": "AC-ALPHA", "mandatory": True},
                    {"id": "AC-BETA", "mandatory": True},
                ),
            },
        )
        with pytest.raises(experiment.ExperimentError) as refused:
            experiment.build_target(
                **common,
                snapshot_id="TARGET-EQUIVALENT-1",
                obligations=equivalent,
                non_derivable_axes=("ALLOCATION",),
                non_derivable_reason="looks necessary but is not",
            )
        assert "not admissible" in str(refused.value)

        # Admitted: the same components, each owning only its own criterion.
        divergent = (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA",),
                "scope": "src/alpha/**",
                "depends_on": (),
                "description": "alpha holds AC-ALPHA",
                "budget": 12.0,
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/**",
                "depends_on": (),
                "description": "beta holds AC-BETA",
                "budget": 12.0,
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
            },
        )
        target = experiment.build_target(
            **common,
            snapshot_id="TARGET-DIVERGENT-1",
            obligations=divergent,
            non_derivable_axes=("ALLOCATION",),
            non_derivable_reason=(
                "Each component owns a disjoint criterion, so a leaf that patches "
                "one module must not be held to the other's criterion. Derivation "
                "stamps every declared criterion on every child."
            ),
        )
        assert target.obligations_source == "DECLARED"
        assert target.non_derivable_axes == ("ALLOCATION",)
        assert target.obligations[0]["budget"] == 12.0

    def test_derived_set_passes_the_existing_coverage_validation(self):
        """Derivation replaces the hand-authoring, not the checks: the derived
        obligations must satisfy the same bidirectional coverage rule."""
        repository, commit = _repo_with({"src/only/mod.py": "VALUE = 1\n"})
        target = experiment.build_target(
            repository, commit,
            snapshot_id="TARGET-COVERAGE-1",
            task_statement="Do the thing.",
            project_kernel={"kernel_id": "K", "purpose": "p"},
            visible_commands=("true",),
            components=(("only", "src/only/**"),),
            owned_scope=("src/**",),
            acceptance_criteria=("AC-ONE", "AC-TWO"),
        )
        owned = {c for o in target.obligations for c in o["criterion_ids"]}
        assert owned == {"AC-ONE", "AC-TWO"}

    def test_the_fixed_target_is_declared_through_the_manifest_and_admitted(self):
        """The fixture routes through the single validated builder, is DECLARED
        with its measured axes, and keeps the ordering and nesting that
        derivation cannot express."""
        snapshot = experiment_target.build_fixed_target(tempfile.mkdtemp())
        assert snapshot.obligations_source == "DECLARED"
        # Exact equality, not a subset (review F12): under the permissive
        # predicate a dropped axis still admitted, so a subset pin could not
        # notice the claim quietly shrinking. The predicate now requires exact
        # equality, so the measured set is pinned here too.
        manifest = experiment_target.load_fixed_target_obligations()
        measured = derive.measure_divergent_axes(
            snapshot.repository,
            snapshot.commit,
            snapshot.components,
            snapshot.acceptance_criteria,
            snapshot.obligations,
        )
        assert set(snapshot.non_derivable_axes) == set(measured) == {
            "EDGES", "NESTING", "ALLOCATION",
        }
        assert set(manifest["non_derivable_axes"]) == set(measured)
        assert snapshot.non_derivable_reason.strip()
        children = {o["child_id"] for o in snapshot.obligations}
        assert children == {"parse", "render", "report"}
        report = next(o for o in snapshot.obligations if o["child_id"] == "report")
        assert tuple(report["depends_on"]) == ("parse", "render")
        assert [n["child_id"] for n in report["obligations"]] == [
            "report-format", "report-emit",
        ]
        # The typed fields are provenance, not contract: the fixture's contract
        # identity must be unchanged by moving the declaration into a manifest.
        assert snapshot.contract_hash == (
            "sha256:157bbd15b2d3e6cf86cd13f44f2ac6a4d94ee79561dd76c9173c95fdf40cf848"
        )
        assert dict(snapshot.trial_scripts) == dict(experiment_target.TRIAL_SCRIPTS)
        assert os.path.isabs(snapshot.repository)


class TestPredicateAndShape:
    """The remaining normative cases from the option (e) spec."""

    def _two_component_repo(self):
        return _repo_with(
            {"src/alpha/mod.py": "VALUE = 1\n", "src/beta/mod.py": "OTHER = 2\n"}
        )

    def _call(self, repository, commit, **overrides):
        common = dict(
            repository=repository,
            base_commit=commit,
            snapshot_id="TARGET-SHAPE-1",
            task_statement="Do the thing.",
            project_kernel={"kernel_id": "K", "purpose": "p"},
            visible_commands=("true",),
            components=(("alpha", "src/alpha/**"), ("beta", "src/beta/**")),
            owned_scope=("src/**",),
            acceptance_criteria=("AC-ALPHA", "AC-BETA"),
        )
        common.update(overrides)
        return experiment.build_target(**common)

    def test_raising_derivation_is_fatal_even_with_a_supplied_declaration(self):
        """S5: derivation is always recomputed, so an overlapping-glob target
        cannot buy its way past the check by supplying obligations."""
        repository, commit = self._two_component_repo()
        supplied = (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA",),
                "scope": "src/alpha/**",
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/**",
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
            },
        )
        with pytest.raises(experiment.ExperimentError) as error:
            self._call(
                repository, commit,
                components=(("a", "src/**"), ("b", "src/alpha/**")),
                obligations=supplied,
                non_derivable_axes=("ALLOCATION",),
                non_derivable_reason="declares around the overlap",
            )
        assert "divergence" in str(error.value) or "overlap" in str(error.value)

    def test_derived_target_may_not_carry_axes_or_a_reason(self):
        """S1 discipline: a DERIVED target with a stale rationale is refused."""
        repository, commit = self._two_component_repo()
        for overrides in (
            {"non_derivable_axes": ("EDGES",)},
            {"non_derivable_reason": "stale rationale"},
        ):
            with pytest.raises(experiment.ExperimentError):
                self._call(repository, commit, **overrides)

    def test_declared_target_must_name_an_axis_and_a_reason(self):
        """S1 discipline: a DECLARED target with neither is refused."""
        repository, commit = self._two_component_repo()
        supplied = (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA",),
                "scope": "src/alpha/**",
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/**",
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
            },
        )
        for overrides in (
            {"non_derivable_axes": (), "non_derivable_reason": "r"},
            {"non_derivable_axes": ("ALLOCATION",), "non_derivable_reason": "  "},
            {"non_derivable_axes": ("NOT_AN_AXIS",), "non_derivable_reason": "r"},
        ):
            with pytest.raises(experiment.ExperimentError):
                self._call(repository, commit, obligations=supplied, **overrides)

    def test_nested_validation_rejects_bad_children(self):
        """S7: nested obligations carry the top-level shape rules, plus
        non-vacuity — a child must name at least one of its parent's criteria."""
        repository, commit = self._two_component_repo()

        def with_nested(nested):
            return (
                {
                    "child_id": "alpha",
                    "criterion_ids": ("AC-ALPHA",),
                    "scope": "src/alpha/**",
                    "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
                    "obligations": nested,
                },
                {
                    "child_id": "beta",
                    "criterion_ids": ("AC-BETA",),
                    "scope": "src/beta/**",
                    "acceptance": ({"id": "AC-BETA", "mandatory": True},),
                },
            )

        good = {
            "child_id": "alpha-part",
            "criterion_ids": ("AC-ALPHA",),
            "scope": "src/alpha/mod.py",
            "budget": 5.0,
            "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
        }
        for nested in (
            {**good, "child_id": ""},                       # empty child id
            {**good, "criterion_ids": ("AC-UNDECLARED",)},  # undeclared criterion
            {**good, "criterion_ids": ("AC-BETA",)},         # outside the parent
            {**good, "criterion_ids": ()},                   # vacuous
            {**good, "budget": float("inf")},                # non-finite budget
        ):
            with pytest.raises(experiment.ExperimentError):
                self._call(
                    repository, commit,
                    obligations=with_nested((nested,)),
                    non_derivable_axes=("NESTING",),
                    non_derivable_reason="nested for the pin",
                )

    def test_commands_for_keys_track_the_manifest_child_ids(self):
        """Drift pin: the scripted command map must name exactly the fixture
        manifest's children at the depth its arm plans.

        `FIXED_ONE_LEVEL` plans one level, so it names the top-level children.
        The recursive arms descend into `report`, replacing it with its two
        children — recursion decomposes a node away — so they name the nested
        ids and drop the parent.
        """
        manifest = experiment_target.load_fixed_target_obligations()
        top_level = {o["child_id"] for o in manifest["obligations"]}
        nested = {
            child["child_id"]
            for o in manifest["obligations"]
            for child in (o.get("obligations") or ())
        }
        decomposed_parents = {
            o["child_id"] for o in manifest["obligations"] if o.get("obligations")
        }
        for arm in experiment_target.ARM_ORDER:
            if arm == experiment_target.ARM_DIRECT:
                continue
            expected = (
                top_level
                if arm == experiment_target.ARM_FIXED_ONE_LEVEL
                else (top_level - decomposed_parents) | nested
            )
            keys = {
                key.split("-", 1)[1]
                for key in experiment_target._commands_for("run", arm, "NORMAL")
            }
            assert keys == expected, f"arm {arm} drifted from the fixture manifest"


class TestReviewerFindings:
    """Regression pins for the option (e) adversarial review (NO-GO, F1-F12)."""

    def _two_component_repo(self):
        return _repo_with(
            {"src/alpha/mod.py": "VALUE = 1\n", "src/beta/mod.py": "OTHER = 2\n"}
        )

    def _build(self, repository, commit, **overrides):
        common = dict(
            repository=repository,
            base_commit=commit,
            snapshot_id="TARGET-FIX-1",
            task_statement="Do the thing.",
            project_kernel={"kernel_id": "K", "purpose": "p"},
            visible_commands=("true",),
            components=(("alpha", "src/alpha/**"), ("beta", "src/beta/**")),
            owned_scope=("src/**",),
            acceptance_criteria=("AC-ALPHA", "AC-BETA"),
        )
        common.update(overrides)
        return experiment.build_target(**common)

    def _split_obligations(self, **overrides):
        """Two obligations, each owning one criterion: a real ALLOCATION
        divergence, so the declaration is admissible on that axis alone."""
        def obligation(child_id, glob, criterion, **extra):
            base = {
                "child_id": child_id,
                "criterion_ids": (criterion,),
                "scope": glob,
                "depends_on": (),
                "acceptance": ({"id": criterion, "mandatory": True},),
            }
            base.update(overrides)
            return base

        return (
            obligation("alpha", "src/alpha/**", "AC-ALPHA"),
            obligation("beta", "src/beta/**", "AC-BETA"),
        )

    def _admit(self, **overrides):
        return dict(
            non_derivable_axes=("ALLOCATION",),
            non_derivable_reason=(
                "Each component owns a disjoint criterion; derivation stamps "
                "every declared criterion on every child."
            ),
            **overrides,
        )

    def test_f1_supplying_obligations_cannot_be_labelled_derived(self):
        """F1 (P0): the source label must not override the implication, or the
        hand-authored hole reopens. `DECLARED` is the consistent label and must
        still be accepted (it is what the fixture manifest passes)."""
        repository, commit = self._two_component_repo()
        with pytest.raises(experiment.ExperimentError) as error:
            self._build(
                repository, commit,
                obligations=self._split_obligations(),
                obligations_source="DERIVED",
                non_derivable_axes=("ALLOCATION",),
                non_derivable_reason="contradictory label",
            )
        assert "contradicts" in str(error.value)
        admitted = self._build(
            repository, commit,
            obligations=self._split_obligations(),
            obligations_source="DECLARED",
            **self._admit(),
        )
        assert admitted.obligations_source == "DECLARED"

    def test_f2_nesting_and_allocation_self_track_against_live_derivation(self):
        """F2: every axis must be a diff against `derive_obligations`' live
        output, so a declaration starts failing once its axis becomes derivable
        — with no change to the declaration or the caller."""
        repository, commit = self._two_component_repo()
        leaf = {
            "child_id": "alpha-leaf",
            "criterion_ids": ("AC-ALPHA",),
            "scope": "src/alpha/**",
            "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
        }
        nested = (
            {**self._split_obligations()[0], "obligations": (leaf,)},
            self._split_obligations()[1],
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        criteria = ("AC-ALPHA", "AC-BETA")

        # As declared, both axes diverge and naming both is required.
        with pytest.raises(experiment.ExperimentError) as refused:
            self._build(
                repository, commit,
                obligations=nested,
                non_derivable_axes=("ALLOCATION",),
                non_derivable_reason="nesting omitted from the claim",
            )
        assert "not admissible" in str(refused.value)

        # Patch derivation so it now produces the same nesting and allocation.
        # NESTING and ALLOCATION must both stop being measured, and the
        # declaration — unchanged — must be refused.
        original = derive.derive_obligations
        derive.derive_obligations = (
            lambda repository, commit, comps, crits, **kwargs: tuple(
                {
                    "child_id": o["child_id"],
                    "criterion_ids": o["criterion_ids"],
                    "scope": o["scope"],
                    "depends_on": (),
                    "acceptance": o["acceptance"],
                    "obligations": o.get("obligations", ()),
                }
                for o in nested
            )
        )
        try:
            axes = derive.measure_divergent_axes(
                repository, commit, components, criteria, nested
            )
            assert axes == frozenset(), (
                f"derivation now matches the declaration, so no axis should be "
                f"measured, got {sorted(axes)!r}"
            )
        finally:
            derive.derive_obligations = original

    def test_f3_a_criterion_order_permutation_does_not_manufacture_divergence(self):
        """F3: `criterion_ids` is a set; a permutation is spelling."""
        repository, commit = self._two_component_repo()
        equivalent = (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA", "AC-BETA"),
                "scope": "src/alpha/**",
                "depends_on": (),
                "acceptance": ({"id": "AC-BETA", "mandatory": True},
                               {"id": "AC-ALPHA", "mandatory": True}),
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA", "AC-ALPHA"),
                "scope": "src/beta/**",
                "depends_on": (),
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},
                               {"id": "AC-BETA", "mandatory": True}),
            },
        )
        with pytest.raises(experiment.ExperimentError) as refused:
            self._build(repository, commit, obligations=equivalent, **self._admit())
        assert "not admissible" in str(refused.value)

    def test_f4_unknown_budget_keys_are_refused_on_both_paths(self):
        """F4: `budgets` must not be dead input on the declared path."""
        repository, commit = self._two_component_repo()
        for obligations in (None, self._split_obligations()):
            with pytest.raises(experiment.ExperimentError):
                self._build(
                    repository, commit,
                    obligations=obligations,
                    budgets={"nope": 1.0},
                    **({} if obligations is None else self._admit()),
                )

    def test_f5_acceptance_shape_is_validated_at_the_boundary(self):
        """F5: S6 names acceptance shape; it must fail in the builder, not as a
        ValueError/TypeError inside plan_decomposition."""
        repository, commit = self._two_component_repo()
        for acceptance in ("not-a-sequence", None, ({"mandatory": True},), 5):
            with pytest.raises(experiment.ExperimentError):
                self._build(
                    repository, commit,
                    obligations=self._split_obligations(acceptance=acceptance),
                    **self._admit(),
                )

    def test_f6_an_unnamed_dependency_is_refused(self):
        """F6: a dependency that names no sibling was silently dropped by both
        the projection and plan_decomposition."""
        repository, commit = self._two_component_repo()
        with pytest.raises(experiment.ExperimentError):
            self._build(
                repository, commit,
                obligations=self._split_obligations(depends_on=("ghost",)),
                **self._admit(),
            )

    def test_f7_a_scope_matching_unowned_files_is_refused(self):
        """F7: `owners.discard(None)` let a scope reach past its component, so a
        file no component owns dropped out of the accounting silently. File-exact
        component globs are what make this reachable."""
        repository, commit = _repo_with(
            {
                "src/alpha/mod.py": "VALUE = 1\n",
                "src/alpha/extra.py": "EXTRA = 2\n",
                "src/beta/mod.py": "OTHER = 3\n",
            }
        )
        declared = (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA",),
                "scope": "src/alpha/**",
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/mod.py",
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
            },
        )
        with pytest.raises(experiment.ExperimentError):
            self._build(
                repository, commit,
                components=(("alpha", "src/alpha/mod.py"), ("beta", "src/beta/mod.py")),
                obligations=declared,
                **self._admit(),
            )

    def test_f8_duplicate_child_ids_are_refused(self):
        """F8: a duplicate child id collapses onto one node id downstream."""
        repository, commit = self._two_component_repo()
        twin = (
            {
                "child_id": "twin",
                "criterion_ids": ("AC-ALPHA",),
                "scope": "src/alpha/**",
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
            },
            {
                "child_id": "twin",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/**",
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
            },
        )
        with pytest.raises(experiment.ExperimentError):
            self._build(
                repository, commit, obligations=twin, **self._admit()
            )

    def test_f9_a_non_iterable_nested_obligations_is_refused(self):
        """F9: `obligations: 5` escaped as a TypeError."""
        repository, commit = self._two_component_repo()
        with pytest.raises(experiment.ExperimentError):
            self._build(
                repository, commit,
                obligations=self._split_obligations(obligations=5),
                non_derivable_axes=("ALLOCATION", "NESTING"),
                non_derivable_reason="nested declared as an int",
            )

    def test_f10_a_nested_scope_may_not_escape_its_parent(self):
        """F10: a nested scope claiming a sibling's files builds."""
        repository, commit = self._two_component_repo()
        escaping = (
            {**self._split_obligations()[0], "obligations": (
                {
                    "child_id": "alpha-leaf",
                    "criterion_ids": ("AC-ALPHA",),
                    "scope": "src/beta/**",
                    "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
                },
            )},
            self._split_obligations()[1],
        )
        with pytest.raises(experiment.ExperimentError):
            self._build(
                repository, commit,
                obligations=escaping,
                non_derivable_axes=("ALLOCATION", "NESTING"),
                non_derivable_reason="nested scope escapes its parent",
            )


class TestRoundTwoFindings:
    """Regression pins for the option (e) re-review (conditional GO, R1-R2)."""

    def _split(self, rename: bool = False):
        """Two obligations owning one criterion each: a real ALLOCATION
        divergence. With `rename`, each child is renamed to something other than
        its component name — spelling only, no semantic change."""
        def obligation(component, glob, criterion, child_id=None):
            return {
                "child_id": child_id or component,
                "criterion_ids": (criterion,),
                "scope": glob,
                "depends_on": (),
                "acceptance": ({"id": criterion, "mandatory": True},),
            }

        return (
            obligation(
                "alpha", "src/alpha/**", "AC-ALPHA",
                child_id="renamed-alpha" if rename else None,
            ),
            obligation(
                "beta", "src/beta/**", "AC-BETA",
                child_id="renamed-beta" if rename else None,
            ),
        )

    def test_r1_a_pure_rename_does_not_manufacture_allocation(self):
        """R1 (P1): the shapes are keyed by raw child_id while a derived child id
        is always the component name, so a rename plus a named ALLOCATION used to
        build with zero semantic divergence. S4 rule 4 excludes spelling."""
        repository, commit = _repo_with(
            {"src/alpha/mod.py": "VALUE = 1\n", "src/beta/mod.py": "OTHER = 2\n"}
        )
        components = (("alpha", "src/alpha/**"), ("beta", "src/beta/**"))
        criteria = ("AC-ALPHA", "AC-BETA")
        renamed = self._split(rename=True)
        # A derived-equivalent set under different child names: identical
        # structure, different spelling. No axis may be measured, so a
        # declaration claiming one is refused.
        spelling_only = tuple(
            {
                **dict(o),
                "criterion_ids": criteria,
                "acceptance": tuple({"id": c, "mandatory": True} for c in criteria),
            }
            for o in renamed
        )
        assert derive.measure_divergent_axes(
            repository, commit, components, criteria, spelling_only
        ) == frozenset()
        with pytest.raises(experiment.ExperimentError) as refused:
            experiment.build_target(
                repository=repository, base_commit=commit,
                snapshot_id="TARGET-RENAME-1",
                task_statement="Do the thing.",
                project_kernel={"kernel_id": "K", "purpose": "p"},
                visible_commands=("true",),
                components=components, owned_scope=("src/**",),
                acceptance_criteria=criteria,
                obligations=spelling_only,
                non_derivable_axes=("ALLOCATION",),
                non_derivable_reason="a rename is not an allocation",
            )
        assert "not admissible" in str(refused.value)
        # The genuine allocation divergence still measures, so the pin is not
        # vacuous: renaming does not make the axis stop working.
        assert derive.measure_divergent_axes(
            repository, commit, components, criteria, renamed
        ) == frozenset({"ALLOCATION"})


class TestP1NestedSpellingExcluded:
    """P1 (pilot spec): nested spelling is excluded from the NESTING shape, so a
    nested rename cannot manufacture divergence once derivation can nest.

    Derivation produces no nesting today, so the axis can only be exercised
    through the shape's invariance and sensitivity directly. The property under
    test is: renaming a nested child does not change the measured shape, while
    adding, removing, or re-parenting one does.
    """

    def _repo(self):
        return _repo_with(
            {"src/alpha/mod.py": "VALUE = 1\n", "src/beta/mod.py": "OTHER = 2\n"}
        )

    def _nested(self, child_ids=("leaf-a", "leaf-b"), reparented=False, alpha_leaves=2):
        """alpha owns `alpha_leaves` nested leaves; beta owns one. `reparented`
        moves beta's leaf under alpha, which is a structural change, not a
        rename."""
        leaf = lambda cid, criterion: {  # noqa: E731 - terse fixture builder
            "child_id": cid,
            "criterion_ids": (criterion,),
            "scope": "src/alpha/**",
            "acceptance": ({"id": criterion, "mandatory": True},),
        }
        beta_leaf = {
            "child_id": "beta-leaf",
            "criterion_ids": ("AC-BETA",),
            "scope": "src/beta/**",
            "acceptance": ({"id": "AC-BETA", "mandatory": True},),
        }
        criteria = ("AC-ALPHA", "AC-ALPHA-2")[:alpha_leaves]
        alpha_children = [
            leaf(child_ids[index], criterion) for index, criterion in enumerate(criteria)
        ]
        if reparented:
            alpha_children.append(beta_leaf)
        return (
            {
                "child_id": "alpha",
                "criterion_ids": ("AC-ALPHA", "AC-ALPHA-2"),
                "scope": "src/alpha/**",
                "acceptance": ({"id": "AC-ALPHA", "mandatory": True},),
                "obligations": alpha_children,
            },
            {
                "child_id": "beta",
                "criterion_ids": ("AC-BETA",),
                "scope": "src/beta/**",
                "acceptance": ({"id": "AC-BETA", "mandatory": True},),
                "obligations": [] if reparented else [beta_leaf],
            },
        )

    def _shape(self, obligations, components=(("alpha", "src/alpha/**"), ("beta", "src/beta/**"))):
        return derive._nesting_shape(
            obligations, {o["child_id"]: c for c, o in zip(components, obligations)}
        )

    def test_renaming_a_nested_child_does_not_change_the_shape(self):
        original = self._nested()
        renamed = self._nested(child_ids=("x", "y"))
        assert self._shape(original) == self._shape(renamed), (
            "a nested rename must not register as a structural difference"
        )

    def test_adding_and_removing_a_nested_child_changes_the_shape(self):
        two = self._nested(alpha_leaves=2)
        one = self._nested(alpha_leaves=1)
        assert self._shape(two) != self._shape(one), (
            "arity is structural: a removed nested child must register"
        )

    def test_re_parenting_a_nested_child_changes_the_shape(self):
        assert self._shape(self._nested()) != self._shape(
            self._nested(reparented=True)
        )

    def test_the_fixed_target_still_measures_nesting(self):
        """P1 must not regress the fixture: the manifest's two-level structure is
        real divergence and must still be reported."""
        snapshot = experiment_target.build_fixed_target(tempfile.mkdtemp())
        measured = derive.measure_divergent_axes(
            snapshot.repository,
            snapshot.commit,
            snapshot.components,
            snapshot.acceptance_criteria,
            snapshot.obligations,
        )
        assert "NESTING" in measured
        assert set(snapshot.non_derivable_axes) == set(measured)
