# SPDX-License-Identifier: AGPL-3.0-or-later
"""Self-host Phase 2: an arbitrary target repository under the frozen manifest
discipline.

The fixed synthetic target is replaced by a `TargetSnapshot` builder over an
existing repository and base commit: the task statement, project kernel, owned
scopes, visible commands, components, criteria, and obligations are frozen
from the caller describing that repository. The exit gate is the differential
on a **non-self** repository run end to end: pilots, freeze, and a measured
comparison where changing only the model reply changes the produced tree and
therefore the hidden oracle's grade — in the honest direction.
"""

from __future__ import annotations

import dataclasses
import os
import sys
import subprocess

import pytest

from helpers import experiment_authorization, open_test_spend_ledger

from orchestrator import experiment, oracle, sandbox
from orchestrator.hidden_oracle import sandboxed_probe

_WORKING_CORE = "def add(a, b):\n    return a + b\n\ndef mul(a, b):\n    return a * b\n"
_BROKEN_CORE = "def add(a, b):\n    return 0\n\ndef mul(a, b):\n    return a * b\n"
_STUB_CORE = (
    "def add(a, b):\n    raise NotImplementedError('add')\n"
    "\ndef mul(a, b):\n    raise NotImplementedError('mul')\n"
)

_WORKING_PATCH = """\
--- a/calc/core.py
+++ b/calc/core.py
@@ -1,5 +1,5 @@
 def add(a, b):
-    raise NotImplementedError('add')
+    return a + b
 
 def mul(a, b):
-    raise NotImplementedError('mul')
+    return a * b
"""

_BROKEN_PATCH = """\
--- a/calc/core.py
+++ b/calc/core.py
@@ -1,5 +1,5 @@
 def add(a, b):
-    raise NotImplementedError('add')
+    return 0
 
 def mul(a, b):
-    raise NotImplementedError('mul')
+    return a * b
"""


def _calc_repo(root: str) -> str:
    """A small non-self repository: a calculator package with its own tests."""
    repo = os.path.join(root, "calc-repo")
    os.makedirs(os.path.join(repo, "calc"))
    os.makedirs(os.path.join(repo, "tests"))
    with open(os.path.join(repo, "calc", "__init__.py"), "w") as handle:
        handle.write("")
    with open(os.path.join(repo, "calc", "core.py"), "w") as handle:
        handle.write(_STUB_CORE)
    with open(os.path.join(repo, "tests", "test_calc.py"), "w") as handle:
        handle.write(
            "import os, sys, unittest\n"
            "sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n"
            "from calc.core import add, mul\n"
            "class CalcTest(unittest.TestCase):\n"
            "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n"
            "    def test_mul(self):\n        self.assertEqual(mul(2, 3), 6)\n"
        )
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
        ("git", "-C", repo, "add", "-A"),
        ("git", "-C", repo, "commit", "-q", "-m", "calculator skeleton"),
    ):
        subprocess.run(argv, check=True, capture_output=True)
    return repo


def _build_calc_target(repo: str):
    return experiment.build_target(
        repo,
        subprocess.run(
            ("git", "-C", repo, "rev-parse", "HEAD"),
            check=True,
            capture_output=True,
            text=True,
        ).stdout.strip(),
        snapshot_id="TARGET-CALC-1",
        task_statement=(
            "Implement add and mul in calc/core.py so the project's own tests pass."
        ),
        project_kernel={
            "kernel_id": "KERNEL-CALC-1",
            "purpose": "A small calculator library used as a general target.",
            "target_users": "Orchestrator self-host rehearsals.",
            "desired_outcomes": ["A correct calculator core"],
            "current_scope": ["calc/**", "tests/**"],
            "current_non_goals": ["Networking"],
        },
        visible_commands=("python3 -m unittest discover -s tests -q",),
        components=(("calc", "calc/**"),),
        owned_scope=("calc/**",),
        acceptance_criteria=("AC-CALC",),
    )


# The sanctioned probe shape (the Phase 2 review's probe-oracle ruling): the
# driver is inputs-only — it computes the candidate's answers for given inputs
# and reports them as a COLLECT payload — and the expected comparison lives
# here, controller-side. A hostile candidate reading its own command line or
# module source sees the inputs and never the expected values (review F2).
_CALC_DRIVER = (
    "import json, sys\n"
    "sys.path.insert(0, '/work')\n"
    "from calc.core import add, mul\n"
    "print('COLLECT:' + json.dumps({"
    "'add(2,3)': add(2, 3), "
    "'add(-1,1)': add(-1, 1), "
    "'mul(2,3)': mul(2, 3), "
    "'mul(-2,3)': mul(-2, 3)}))\n"
)

_CALC_EXPECTED = {
    "add(2,3)": 5,
    "add(-1,1)": 0,
    "mul(2,3)": 6,
    "mul(-2,3)": -6,
}


def _calc_compare(payload):
    return oracle.GRADE_PASS if payload == _CALC_EXPECTED else oracle.GRADE_FAIL


_calc_probe = sandboxed_probe(
    driver=_CALC_DRIVER, compare=_calc_compare, timeout_seconds=5.0
)


def _calc_oracle(target) -> oracle.OracleManifest:
    manifest = oracle.OracleManifest(
        "oracle-calc-1",
        (oracle.OracleCriterion("AC-CALC", mandatory=True, weight=1.0),),
        (
            oracle.OracleCheck(
                "calc-held-out",
                ("AC-CALC",),
                1.0,
                oracle.GRADE_PASS,
                30.0,
                True,
                probe=_calc_probe,
            ),
        ),
        target_binding="",
    )
    return dataclasses.replace(
        manifest, target_binding=experiment.oracle_target_binding(target, manifest)
    )


def _calibration(target, manifest, workdir: str):
    """The full calibration discipline on the general target, through the
    public `calibrate_oracle`/`CalibrationCases` path (re-review F7): five
    cases — known-good, unchanged, known-broken, known-timeout, and injected
    infrastructure failure — must classify as the oracle says before anything
    is frozen."""
    trees = {}
    for name, core in (
        ("known-good", _WORKING_CORE),
        ("unchanged", _STUB_CORE),
        ("known-broken", _BROKEN_CORE),
        ("known-timeout", "def add(a, b):\n    while True:\n        pass\n\ndef mul(a, b):\n    return a * b\n"),
    ):
        path = os.path.join(workdir, f"cal-{name}")
        os.makedirs(os.path.join(path, "calc"))
        with open(os.path.join(path, "calc", "core.py"), "w") as handle:
            handle.write(core)
        trees[name] = path
    return experiment.calibrate_oracle(
        target,
        manifest,
        workdir,
        cases=experiment.CalibrationCases(
            trees=trees,
            timeout_check_id="calc-held-out",
            infrastructure_check_id="calc-held-out",
        ),
    )


def _prepare(target, manifest, workdir: str, patch_text: str):
    """The shared freeze inputs: the calibration corpus and one pilots run.
    Both differential runs freeze from these, so the manifests are identical
    by construction and the model reply is the only variable. The pilots run
    under the patch profile like every other trial of the general target."""
    client = experiment.PatchModelClient(
        experiment.PATCH_MODEL_PROFILE, default_patch=patch_text
    )
    # Capture the binding *before* mutating it. Restoring by re-reading
    # ``experiment.MODEL_PROFILE`` in the ``finally`` would restore the value
    # this block just installed, leaking the patch profile past the module (F5).
    previous_profile = experiment.MODEL_PROFILE
    previous_factory = experiment.MODEL_CLIENT_FACTORY
    experiment.set_model_client_factory(lambda profile, seed: client)
    experiment.set_model_profile(experiment.PATCH_MODEL_PROFILE)
    try:
        ledger = open_test_spend_ledger(workdir)
        calibration = _calibration(target, manifest, os.path.join(workdir, "cal"))
        pilots = experiment.run_pilots(target, manifest, workdir, spend_ledger=ledger)
        return calibration, pilots
    finally:
        experiment.set_model_client_factory(previous_factory)
        experiment.set_model_profile(previous_profile)


def _compare(target, manifest, workdir: str, patch_text: str, calibration, pilots):
    client = experiment.PatchModelClient(
        experiment.PATCH_MODEL_PROFILE, default_patch=patch_text
    )
    previous_profile = experiment.MODEL_PROFILE
    previous_factory = experiment.MODEL_CLIENT_FACTORY
    experiment.set_model_client_factory(lambda profile, seed: client)
    experiment.set_model_profile(experiment.PATCH_MODEL_PROFILE)
    try:
        ledger = open_test_spend_ledger(workdir)
        frozen = experiment.freeze_manifest(
            target=target,
            oracle_manifest=manifest,
            limits=pilots.calibrated_limits,
            calibration=calibration,
            model_profile=experiment.PATCH_MODEL_PROFILE,
            pilot_calibration_method=pilots.method,
            trial_seeds=(1001,),
            arm_assignment=tuple((arm, (1001,)) for arm in experiment.ARM_ORDER),
        )
        comparison = experiment.run_measured_comparison(
            frozen, manifest, workdir, spend_ledger=ledger
        )
        return frozen, comparison
    finally:
        experiment.set_model_client_factory(previous_factory)
        experiment.set_model_profile(previous_profile)


# -- builder validation -------------------------------------------------------


def test_build_target_refuses_an_unresolvable_base_commit(tmp_path):
    repo = _calc_repo(str(tmp_path))
    with pytest.raises(experiment.ExperimentError):
        experiment.build_target(
            repo, "0" * 40,
            snapshot_id="S", task_statement="t",
            project_kernel={"kernel_id": "K"},
            visible_commands=("true",), components=(("c", "c/**"),),
            owned_scope=("c/**",), acceptance_criteria=("AC",),
        )


def test_build_target_refuses_empty_pieces_and_criterion_mismatch(tmp_path):
    repo = _calc_repo(str(tmp_path))
    commit = subprocess.run(
        ("git", "-C", repo, "rev-parse", "HEAD"),
        check=True, capture_output=True, text=True,
    ).stdout.strip()
    base = dict(
        repository=repo, base_commit=commit,
        snapshot_id="S", task_statement="t",
        project_kernel={"kernel_id": "K"},
        visible_commands=("true",),
        # Real globs against the repository this fixture actually builds, and two
        # components over two real files so the named ALLOCATION axis is genuinely
        # measured (review F11: the previous `c/**` scope matched no tracked file
        # and `("AC",)` equalled the full set, so the base was inadmissible and
        # every case passed only because it raised before projection).
        components=(("calc-core", "calc/core.py"), ("calc-init", "calc/__init__.py")),
        owned_scope=("calc/**",), acceptance_criteria=("AC-A", "AC-B"),
        obligations=(
            {
                "child_id": "calc-core",
                "criterion_ids": ("AC-A",),
                "scope": "calc/core.py",
                "acceptance": ({"id": "AC-A", "mandatory": True},),
            },
            {
                "child_id": "calc-init",
                "criterion_ids": ("AC-B",),
                "scope": "calc/__init__.py",
                "acceptance": ({"id": "AC-B", "mandatory": True},),
            },
        ),
        non_derivable_axes=("ALLOCATION",),
        non_derivable_reason="the leaf owns one criterion, not the whole set",
    )
    for field, value in (
        ("task_statement", ""), ("visible_commands", ()), ("components", ()),
        ("owned_scope", ()), ("acceptance_criteria", ()), ("obligations", ()),
    ):
        with pytest.raises(experiment.ExperimentError):
            experiment.build_target(**{**base, field: value})
    # An obligation referencing an undeclared criterion is refused, and so is a
    # declared criterion no obligation owns (bidirectional coverage).
    with pytest.raises(experiment.ExperimentError):
        experiment.build_target(
            **{
                **base,
                "obligations": (
                    {
                        "child_id": "calc-core",
                        "criterion_ids": ("OTHER",),
                        "scope": "calc/core.py",
                        "acceptance": ({"id": "OTHER", "mandatory": True},),
                    },
                ),
            }
        )
    with pytest.raises(experiment.ExperimentError):
        experiment.build_target(
            **{
                **base,
                "acceptance_criteria": ("AC-A", "AC-B", "UNOWNED"),
            }
        )
    # The base itself is admissible: a case that reaches the predicate must fail
    # for its own reason, not because the scaffold was already inadmissible.
    experiment.build_target(**base)


def test_build_target_freezes_the_repository_state(tmp_path):
    repo = _calc_repo(str(tmp_path))
    target = _build_calc_target(repo)
    assert target.task_statement.startswith("Implement add and mul")
    assert target.owned_scope == ("calc/**",)
    assert target.acceptance_criteria == ("AC-CALC",)
    assert target.obligations[0]["child_id"] == "calc"
    assert target.visible_commands == ("python3 -m unittest discover -s tests -q",)
    assert target.trial_scripts == {}
    # The frozen commit resolves in the repository.
    assert (
        subprocess.run(
            ("git", "-C", target.repository, "cat-file", "-e", f"{target.commit}^{{commit}}"),
            capture_output=True,
        ).returncode
        == 0
    )


# -- exit gate ---------------------------------------------------------------


def test_phase2_non_self_repository_runs_end_to_end(tmp_path):
    """The Phase 2 exit gate: a non-self repository runs end to end under the
    frozen manifest discipline, and changing only the model reply changes the
    produced tree and the hidden oracle's grade — in the honest direction."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    repo = _calc_repo(str(tmp_path))
    target = _build_calc_target(repo)
    manifest = _calc_oracle(target)

    prep_dir = str(tmp_path / "prep")
    working_dir = str(tmp_path / "working")
    broken_dir = str(tmp_path / "broken")
    for name in (prep_dir, working_dir, broken_dir):
        os.makedirs(name)
    calibration, pilots = _prepare(target, manifest, prep_dir, _WORKING_PATCH)
    frozen_working, working = _compare(
        target, manifest, working_dir, _WORKING_PATCH, calibration, pilots
    )
    frozen_broken, broken = _compare(
        target, manifest, broken_dir, _BROKEN_PATCH, calibration, pilots
    )

    # The frozen manifests are identical: the same target, the same oracle
    # binding, the same budgets, seeds, and arms — the model reply is the only
    # variable between the two runs.
    assert frozen_working.content_hash() == frozen_broken.content_hash()

    # Every arm's trial on the general target: the working reply is graded
    # correct, the broken reply is not — across the whole frozen matrix.
    assert [trial.arm for trial in working.trials] == [arm for arm in experiment.ARM_ORDER]
    for working_trial, broken_trial in zip(working.trials, broken.trials):
        assert dict(working_trial.oracle_outcomes) == {"calc-held-out": "PASS"}, (
            working_trial.arm, working_trial.oracle_outcomes
        )
        assert dict(broken_trial.oracle_outcomes) == {"calc-held-out": "FAIL"}, (
            broken_trial.arm, broken_trial.oracle_outcomes
        )
        # The direction is honest: the working reply is accepted and correct;
        # the broken reply is never relabelled as success.
        assert working_trial.classification == oracle.TRIAL_CORRECT_ACCEPTANCE, working_trial.arm
        assert broken_trial.classification in (
            oracle.TRIAL_CORRECTLY_UNRESOLVED,
            oracle.TRIAL_MISSED_SUCCESS,
        ), (broken_trial.arm, broken_trial.classification)
        assert working_trial.classification != broken_trial.classification


def test_crlf_base_refuses_the_lf_context_reply_review_f1(tmp_path):
    """Review F1 (P0) whole-trial reproducer, pinned: a CRLF target file and
    an LF-context reply. `git apply` refuses such a reply; the boundary must
    refuse it too — a reply that would rewrite line endings must never be
    graded CORRECT_ACCEPTANCE."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    repo = os.path.join(str(tmp_path), "crlf-calc")
    os.makedirs(os.path.join(repo, "calc"))
    os.makedirs(os.path.join(repo, "tests"))
    with open(os.path.join(repo, "calc", "__init__.py"), "w", newline="") as handle:
        handle.write("")
    with open(os.path.join(repo, "calc", "core.py"), "w", newline="") as handle:
        handle.write(_STUB_CORE.replace("\n", "\r\n"))
    with open(os.path.join(repo, "tests", "test_calc.py"), "w", newline="") as handle:
        handle.write(
            "import os, sys, unittest\n"
            "sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n"
            "from calc.core import add, mul\n"
            "class CalcTest(unittest.TestCase):\n"
            "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n"
            "    def test_mul(self):\n        self.assertEqual(mul(2, 3), 6)\n"
        )
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
        ("git", "-C", repo, "add", "-A"),
        ("git", "-C", repo, "commit", "-q", "-m", "crlf skeleton"),
    ):
        subprocess.run(argv, check=True, capture_output=True)

    target = _build_calc_target(repo)
    manifest = _calc_oracle(target)
    prep_dir = str(tmp_path / "prep")
    run_dir = str(tmp_path / "run")
    os.makedirs(prep_dir)
    os.makedirs(run_dir)
    calibration, pilots = _prepare(target, manifest, prep_dir, _WORKING_PATCH)
    # The working reply is LF-context: git apply refuses it against CRLF
    # content and so must the boundary (no silent normalisation).
    frozen, comparison = _compare(
        target, manifest, run_dir, _WORKING_PATCH, calibration, pilots
    )
    for trial in comparison.trials:
        assert trial.classification != oracle.TRIAL_CORRECT_ACCEPTANCE, (
            trial.arm,
            dict(trial.oracle_outcomes),
        )


def test_unterminated_file_refuses_the_markerless_eof_reply_review_n2(tmp_path):
    """Re-review N2 whole-trial reproducer, pinned: an unterminated target
    file and an EOF reply with no no-newline markers. `git apply` refuses such
    a reply; the boundary must refuse it too — never silently rewrite the
    end-of-file newline state and grade CORRECT_ACCEPTANCE."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    repo = os.path.join(str(tmp_path), "unterm-calc")
    os.makedirs(os.path.join(repo, "calc"))
    os.makedirs(os.path.join(repo, "tests"))
    with open(os.path.join(repo, "calc", "__init__.py"), "w") as handle:
        handle.write("")
    # Five lines, no trailing newline.
    with open(os.path.join(repo, "calc", "core.py"), "w", newline="") as handle:
        handle.write(_STUB_CORE.rstrip("\n"))
    with open(os.path.join(repo, "tests", "test_calc.py"), "w") as handle:
        handle.write(
            "import os, sys, unittest\n"
            "sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n"
            "from calc.core import add, mul\n"
            "class CalcTest(unittest.TestCase):\n"
            "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n"
            "    def test_mul(self):\n        self.assertEqual(mul(2, 3), 6)\n"
        )
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
        ("git", "-C", repo, "add", "-A"),
        ("git", "-C", repo, "commit", "-q", "-m", "unterminated skeleton"),
    ):
        subprocess.run(argv, check=True, capture_output=True)

    target = _build_calc_target(repo)
    manifest = _calc_oracle(target)
    prep_dir = str(tmp_path / "prep")
    run_dir = str(tmp_path / "run")
    os.makedirs(prep_dir)
    os.makedirs(run_dir)
    calibration, pilots = _prepare(target, manifest, prep_dir, _WORKING_PATCH)
    # The re-review's exact reply: an EOF replacement with no markers.
    markerless = (
        "--- a/calc/core.py\n+++ b/calc/core.py\n@@ -5 +5 @@\n"
        "    raise NotImplementedError('mul')\n+    return a * b\n"
    )
    frozen, comparison = _compare(
        target, manifest, run_dir, markerless, calibration, pilots
    )
    for trial in comparison.trials:
        assert trial.classification != oracle.TRIAL_CORRECT_ACCEPTANCE, (
            trial.arm,
            dict(trial.oracle_outcomes),
        )


# -- re-review N7: patch mode never batches -------------------------------

_GREET_CORE_STUB = "def hello(name):\n    raise NotImplementedError('hello')\n"
_GREET_UTIL_STUB = "def shout(name):\n    raise NotImplementedError('shout')\n"

_GREET_CORE_PATCH = (
    "--- a/greet/core.py\n+++ b/greet/core.py\n@@ -1,2 +1,2 @@\n"
    " def hello(name):\n-    raise NotImplementedError('hello')\n+    return 'hello ' + name\n"
)
_GREET_UTIL_PATCH = (
    "--- a/greet/util.py\n+++ b/greet/util.py\n@@ -1,2 +1,2 @@\n"
    " def shout(name):\n-    raise NotImplementedError('shout')\n+    return name.upper() + '!'\n"
)

_GREET_DRIVER = (
    "import json, sys\n"
    "sys.path.insert(0, '/work')\n"
    "from greet.core import hello\n"
    "from greet.util import shout\n"
    "print('COLLECT:' + json.dumps({'hello': hello('a'), 'shout': shout('b')}))\n"
)


def _greet_compare(payload):
    expected = {"hello": "hello a", "shout": "B!"}
    return oracle.GRADE_PASS if payload == expected else oracle.GRADE_FAIL


_greet_probe = sandboxed_probe(
    driver=_GREET_DRIVER, compare=_greet_compare, timeout_seconds=5.0
)


def test_patch_mode_never_batches_review_n7(tmp_path):
    """Re-review N7: a concurrent arm with two ready disjoint leaves in patch
    mode must execute per-leaf (one model reply per planned attempt). Batching
    would dispatch batch members with no patch and silently zero the
    differential for that arm."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    repo = os.path.join(str(tmp_path), "greet-repo")
    os.makedirs(os.path.join(repo, "greet"))
    os.makedirs(os.path.join(repo, "tests"))
    with open(os.path.join(repo, "greet", "__init__.py"), "w") as handle:
        handle.write("")
    with open(os.path.join(repo, "greet", "core.py"), "w") as handle:
        handle.write(_GREET_CORE_STUB)
    with open(os.path.join(repo, "greet", "util.py"), "w") as handle:
        handle.write(_GREET_UTIL_STUB)
    with open(os.path.join(repo, "tests", "test_greet.py"), "w") as handle:
        handle.write(
            "import os, sys, unittest\n"
            "sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n"
            "from greet.core import hello\n"
            "from greet.util import shout\n"
            "class GreetTest(unittest.TestCase):\n"
            "    def test_hello(self):\n        self.assertEqual(hello('a'), 'hello a')\n"
            "    def test_shout(self):\n        self.assertEqual(shout('b'), 'B!')\n"
        )
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
        ("git", "-C", repo, "add", "-A"),
        ("git", "-C", repo, "commit", "-q", "-m", "greet skeleton"),
    ):
        subprocess.run(argv, check=True, capture_output=True)

    target = experiment.build_target(
        repo,
        subprocess.run(
            ("git", "-C", repo, "rev-parse", "HEAD"),
            check=True, capture_output=True, text=True,
        ).stdout.strip(),
        snapshot_id="TARGET-GREET-1",
        task_statement="Implement hello and shout so the project's tests pass.",
        project_kernel={
            "kernel_id": "KERNEL-GREET-1",
            "purpose": "A two-component target for the batching pin.",
            "target_users": "Re-review N7.",
            "desired_outcomes": ["A correct greeting library"],
            "current_scope": ["greet/**", "tests/**"],
            "current_non_goals": ["Networking"],
        },
        # The visible gate is the cheap per-attempt gate: compile and import.
        # Each child patches one module, so a whole-suite visible gate could
        # never pass on a partial tree; the held-out probe is the behavioural
        # grader (the R08 split). Per-node visible commands are a later
        # target-schema concern, not this pin's.
        visible_commands=(
            "python3 -B -c \"import greet.core, greet.util\"",
        ),
        components=(("core", "greet/core.py"), ("util", "greet/util.py")),
        owned_scope=("greet/**",),
        acceptance_criteria=("AC-CORE", "AC-UTIL"),
        obligations=(
            {
                "child_id": "core",
                "criterion_ids": ("AC-CORE",),
                "scope": "greet/core.py",
                "depends_on": (),
                "description": "Greeting core",
                "budget": 30.0,
                "acceptance": ({"id": "AC-CORE", "mandatory": True},),
            },
            {
                "child_id": "util",
                "criterion_ids": ("AC-UTIL",),
                "scope": "greet/util.py",
                "depends_on": (),
                "description": "Greeting util",
                "budget": 30.0,
                "acceptance": ({"id": "AC-UTIL", "mandatory": True},),
            },
        ),
        # DECLARED on ALLOCATION alone (Phase 4, option (e)). The behavioural
        # necessity: derivation stamps the full declared criteria set on every
        # child, so the `core` leaf — which patches only `greet/core.py` — would
        # carry `AC-UTIL` as mandatory and could never satisfy it. Per-leaf
        # allocation is exactly what one-level derivation cannot express.
        non_derivable_axes=("ALLOCATION",),
        non_derivable_reason=(
            "Each component owns a disjoint criterion, so a leaf that patches only "
            "one module must not be held to the other component's criterion. "
            "Derivation stamps every declared criterion on every child."
        ),
    )
    manifest = oracle.OracleManifest(
        "oracle-greet-1",
        (
            oracle.OracleCriterion("AC-CORE", mandatory=True, weight=1.0),
            oracle.OracleCriterion("AC-UTIL", mandatory=True, weight=1.0),
        ),
        (
            oracle.OracleCheck(
                "greet-held-out",
                ("AC-CORE", "AC-UTIL"),
                1.0,
                oracle.GRADE_PASS,
                30.0,
                True,
                probe=_greet_probe,
            ),
        ),
        target_binding="",
    )
    manifest = dataclasses.replace(
        manifest, target_binding=experiment.oracle_target_binding(target, manifest)
    )

    # Per-node replies: each child patches only its own scope; the root
    # (DIRECT) patches both.
    both = _GREET_CORE_PATCH + _GREET_UTIL_PATCH[_GREET_UTIL_PATCH.index("---"):]
    patches = {}
    for arm in experiment.ARM_ORDER:
        run = f"EXP-{arm}-1001"
        patches[f"{run}-root"] = both
        patches[f"{run}-core"] = _GREET_CORE_PATCH
        patches[f"{run}-util"] = _GREET_UTIL_PATCH

    def _greet_trees(workdir):
        trees = {}
        for name, files in (
            ("known-good", {"core": "def hello(name):\n    return 'hello ' + name\n",
                            "util": "def shout(name):\n    return name.upper() + '!'\n"}),
            ("unchanged", {"core": _GREET_CORE_STUB, "util": _GREET_UTIL_STUB}),
            ("known-broken", {"core": "def hello(name):\n    return 'nope'\n",
                              "util": "def shout(name):\n    return name.upper() + '!'\n"}),
            ("known-timeout", {"core": "def hello(name):\n    while True:\n        pass\n",
                               "util": "def shout(name):\n    return name.upper() + '!'\n"}),
        ):
            path = os.path.join(workdir, f"cal-{name}")
            os.makedirs(os.path.join(path, "greet"))
            for part, content in files.items():
                with open(os.path.join(path, "greet", f"{part}.py"), "w") as handle:
                    handle.write(content)
            trees[name] = path
        return trees

    workdir = str(tmp_path / "run")
    os.makedirs(workdir)
    calibration = experiment.calibrate_oracle(
        target,
        manifest,
        os.path.join(workdir, "prep"),
        cases=experiment.CalibrationCases(
            trees=_greet_trees(os.path.join(workdir, "prep-cases")),
            timeout_check_id="greet-held-out",
            infrastructure_check_id="greet-held-out",
        ),
    )
    client = experiment.PatchModelClient(
        experiment.PATCH_MODEL_PROFILE, patches=patches
    )
    previous_profile = experiment.MODEL_PROFILE
    previous_factory = experiment.MODEL_CLIENT_FACTORY
    experiment.set_model_client_factory(lambda profile, seed: client)
    experiment.set_model_profile(experiment.PATCH_MODEL_PROFILE)
    try:
        ledger = open_test_spend_ledger(workdir)
        frozen = experiment.freeze_manifest(
            target=target,
            oracle_manifest=manifest,
            limits=experiment.placeholder_limits(),
            calibration=calibration,
            model_profile=experiment.PATCH_MODEL_PROFILE,
            trial_seeds=(1001,),
            arm_assignment=tuple((arm, (1001,)) for arm in experiment.ARM_ORDER),
        )
        comparison = experiment.run_measured_comparison(
            frozen, manifest, workdir, spend_ledger=ledger
        )
    finally:
        experiment.set_model_client_factory(previous_factory)
        experiment.set_model_profile(previous_profile)

    by_arm = {trial.arm: trial for trial in comparison.trials}
    concurrent = by_arm[experiment.ARM_RECURSIVE_CONCURRENT]
    assert dict(concurrent.oracle_outcomes) == {"greet-held-out": "PASS"}, (
        concurrent.arm,
        dict(concurrent.oracle_outcomes),
    )
    assert concurrent.classification == oracle.TRIAL_CORRECT_ACCEPTANCE
    for trial in comparison.trials:
        assert trial.classification == oracle.TRIAL_CORRECT_ACCEPTANCE, (
            trial.arm,
            dict(trial.oracle_outcomes),
        )
