# SPDX-License-Identifier: AGPL-3.0-or-later
"""Self-host Phase 3: the project-owned oracle (exit gate).

An acceptance manifest whose checks are this repository's own gates, with the
meta-registry floors frozen as gates and bound R12-style
(docs/research/phase3-project-oracle-design.md). The exit gate is the
five-case corpus on a real repository — the orchestrator itself:
bidirectional coverage validation and correct classification of known-good,
known-bad, unchanged, timeout, and infrastructure-failure candidates.

The `unchanged` case is the phase's whole claim: its registry is *internally
consistent* (the demotion lowers `min_covered` along with the covered count),
so the repository's own meta-gate passes it and only the **frozen floor**
catches it.
"""

from __future__ import annotations

import ast
import dataclasses
import os
import shutil
import subprocess
import sys
import tempfile
import types

import pytest

from orchestrator import experiment, oracle, project_oracle, sandbox


pytestmark = pytest.mark.slow


_TREE_IGNORE = shutil.ignore_patterns(
    ".git", ".venv", "evidence", "__pycache__", ".pytest_cache", ".hypothesis", ".ruff_cache"
)


def _repo_root() -> str:
    return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def _snapshot_repo(root: str) -> str:
    """Commit an exact snapshot of the tree the exit gate will grade.

    The target commit, frozen test/config hashes, trusted gates, and five case
    trees must describe one source state; HEAD plus a dirty working-tree copy
    would bind different inputs (R12).
    """
    source = _repo_root()
    repo = os.path.join(root, "orchestrator-target")
    shutil.copytree(
        source,
        repo,
        ignore=shutil.ignore_patterns(
            ".git", ".venv", "evidence", "__pycache__",
            ".pytest_cache", ".hypothesis", ".ruff_cache", "node_modules",
        ),
    )
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "phase3@example.invalid"),
        ("git", "-C", repo, "config", "user.name", "Phase 3 test snapshot"),
        ("git", "-C", repo, "add", "-A"),
        ("git", "-C", repo, "commit", "-q", "-m", "phase3 oracle test snapshot"),
    ):
        subprocess.run(argv, check=True, capture_output=True)
    # Trusted-side gates use the host's installed toolchain; the sandboxed
    # probes mount this venv as read-only toolchain, never linked into the
    # candidate tree (the probe copier deliberately refuses symlinks).
    return repo


def _case_tree(root: str, repo: str, name: str) -> str:
    tree = os.path.join(root, name)
    shutil.copytree(repo, tree, ignore=_TREE_IGNORE)
    os.makedirs(os.path.join(tree, ".venv"), exist_ok=True)
    return tree


def _demote_a_finding(tree: str) -> None:
    """The `unchanged` candidate: demote one covered finding to pending and
    lower `min_covered` to match — internally consistent (the repository's own
    meta-gate passes it), and caught only by the frozen floor."""
    path = os.path.join(tree, "tests", "counterexamples.yaml")
    text = open(path, encoding="utf-8").read()
    assert "min_covered: 23" in text
    text = text.replace("min_covered: 23", "min_covered: 22")
    old = (
        "  R23:\n"
        "    prefix_revision: c698bf660e50be90496d85f58239f73e2e57ed4d\n"
        "    tests:\n"
        "    - tests/test_milestone5_acceptance.py::"
        "test_oracle_manifest_bidirectional_coverage_validation\n"
        "    title: Unsupported non-test oracles can be ignored during classification"
    )
    new = (
        "  R23:\n"
        "    prefix_revision: c698bf660e50be90496d85f58239f73e2e57ed4d\n"
        "    remediation_batch: phase3-corpus\n"
        "    title: Unsupported non-test oracles can be ignored during classification"
    )
    assert old in text, "the R23 entry moved; update the corpus mutation"
    text = text.replace(old, new, 1)
    open(path, "w", encoding="utf-8").write(text)


def _delete_a_mapped_test(tree: str) -> None:
    """The `known-broken` candidate: a mapped regression pin disappears — the
    registry's own meta-gate and the frozen completeness rule both catch it."""
    path = os.path.join(tree, "tests", "test_milestone8_readiness.py")
    text = open(path, encoding="utf-8").read()
    needle = "def test_candidate_git_metadata_is_rejected_before_import"
    assert needle in text
    text = text.replace(needle, "def test_renamed_away_by_a_bad_candidate", 1)
    open(path, "w", encoding="utf-8").write(text)


def _edit_candidate_source(tree: str) -> None:
    """Give the `known-good` candidate a real, behaviour-preserving source edit.

    The acceptance gate is only meaningful if it accepts a candidate that
    actually changed its source. An oracle that froze `src/**` alongside the
    test corpus would reject this tree, so the corpus proves the frozen suite
    grades the candidate's own source rather than a replay of the freeze.
    """
    path = os.path.join(tree, "src", "orchestrator", "reducer.py")
    text = open(path, encoding="utf-8").read()
    needle = "NODE_TABLE = tables.node_table()"
    assert needle in text, "the reducer's table load moved; update the corpus mutation"
    text = text.replace(
        needle,
        needle + "\n# candidate change: a benign source edit the oracle must accept",
        1,
    )
    open(path, "w", encoding="utf-8").write(text)


def _break_candidate_source(tree: str) -> None:
    """The `known-broken-source` candidate: an existing source file is broken.

    This is the counterpart to `_edit_candidate_source`: if the oracle accepts a
    benign source edit it must also reject a behaviour-changing one, which is
    only observable because the gate runs the candidate's source.
    """
    path = os.path.join(tree, "src", "orchestrator", "reducer.py")
    text = open(path, encoding="utf-8").read()
    needle = "NODE_TABLE = tables.node_table()"
    assert needle in text
    text = text.replace(
        needle, needle + "\nNODE_TABLE = {}  # candidate regression", 1
    )
    open(path, "w", encoding="utf-8").write(text)


def _add_a_nested_gate_config(tree: str) -> None:
    """The `known-bypass` candidate: a nested config shadows the gate's own.

    A candidate-added `ruff.toml` cannot appear in a freeze-time inventory, so
    only a closed-set policy over control basenames rejects it.
    """
    with open(
        os.path.join(tree, "src", "orchestrator", "ruff.toml"), "w", encoding="utf-8"
    ) as handle:
        handle.write('[lint.per-file-ignores]\n"*.py" = ["BLE001", "S110"]\n')
    with open(
        os.path.join(tree, "src", "orchestrator", "p0_violation.py"), "w", encoding="utf-8"
    ) as handle:
        handle.write(
            "def swallowed(error):\n    try:\n        raise error\n"
            "    except Exception:\n        pass\n"
        )


def _hang_the_suite(tree: str) -> None:
    """The `known-timeout` candidate: it hangs its own gate (a conftest that
    sleeps forever at import)."""
    path = os.path.join(tree, "conftest.py")
    open(path, "w", encoding="utf-8").write("import time\nwhile True:\n    time.sleep(1)\n")


def _build_self_target(repo: str):
    commit = subprocess.run(
        ("git", "-C", repo, "rev-parse", "HEAD"),
        check=True, capture_output=True, text=True,
    ).stdout.strip()
    # No obligations: the self-target derives them from its single component
    # (Phase 4, option (e)). The manifest path is independent of
    # `target.obligations`, so derivation is sufficient here.
    return experiment.build_target(
        repo, commit, snapshot_id="TARGET-SELF-1",
        task_statement="Satisfy the repository's own acceptance gates.",
        project_kernel={
            "kernel_id": "KERNEL-SELF-1",
            "purpose": "The orchestrator repository as its own acceptance target.",
            "target_users": "Self-host rehearsals.",
            "desired_outcomes": ["The repository's gates stay green under its frozen floors."],
            "current_scope": ["**"],
            "current_non_goals": ["Candidate production"],
        },
        visible_commands=("true",),
        components=(("core", "**"),), owned_scope=("**",),
        acceptance_criteria=project_oracle.CRITERIA,
    )


@pytest.fixture(scope="module")
def project_oracle_context(tmp_path_factory):
    """Build the trusted manifest once for the Phase 3 slow-test module."""
    repo = _snapshot_repo(str(tmp_path_factory.mktemp("phase3-target")))
    target = _build_self_target(repo)
    manifest = project_oracle.build_project_oracle(
        target,
        repo_root=repo,
        venv_path=os.path.join(_repo_root(), ".venv"),
    )
    return target, manifest


def _calibration(target, manifest, root: str):
    from orchestrator.experiment_phases import _calibrate_case

    good = _case_tree(root, target.repository, "tree-known-good")
    # The acceptance gate must accept a candidate that actually changed its
    # source, so the accepted tree is not a byte-identical replay of the freeze.
    _edit_candidate_source(good)
    unchanged = _case_tree(root, target.repository, "tree-unchanged")
    _demote_a_finding(unchanged)
    broken = _case_tree(root, target.repository, "tree-known-broken")
    _delete_a_mapped_test(broken)
    timeout = _case_tree(root, target.repository, "tree-known-timeout")
    _hang_the_suite(timeout)

    return experiment.CalibrationReport(
        cases=(
            _calibrate_case(
                manifest, "known-good",
                "the intact repository plus a benign source edit",
                oracle.TRIAL_CORRECT_ACCEPTANCE, good,
                controller_outcome=oracle.ACCEPTANCE_CLAIMED,
            ),
            _calibrate_case(
                manifest, "unchanged", "an internally consistent floor demotion",
                oracle.TRIAL_CORRECTLY_UNRESOLVED, unchanged,
                controller_outcome=None,
            ),
            _calibrate_case(
                manifest, "known-broken", "a mapped regression pin deleted",
                oracle.TRIAL_CORRECTLY_UNRESOLVED, broken,
                controller_outcome=None,
            ),
            _calibrate_case(
                manifest, "known-timeout", "a candidate that hangs its own gate",
                oracle.TRIAL_FALSE_SUCCESS, timeout,
                controller_outcome=oracle.ACCEPTANCE_CLAIMED,
                expect_candidate_timeout="gate-check-tests",
            ),
            _calibrate_case(
                manifest, "infrastructure", "an injected oracle infrastructure failure",
                oracle.TRIAL_INDETERMINATE, good,
                controller_outcome=None,
                inject={"gate-check-static": oracle.GRADE_INFRASTRUCTURE_ERROR},
                allow_rerun=True,
            ),
        )
    )


@pytest.mark.timeout(2400)
def test_project_oracle_classifies_the_five_case_corpus_on_a_real_repository(
    tmp_path, project_oracle_context
):
    """The Phase 3 exit gate (docs/self-host.md#phase-3-project-owned-oracle):
    bidirectional coverage validation plus the five-case corpus classify all
    five candidates correctly on this repository under the frozen floors."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    target, manifest = project_oracle_context
    repo = target.repository

    # Bidirectional coverage validation (the exit gate's first half).
    manifest.validate_bidirectional_coverage(project_oracle.CRITERIA)
    # The probe shape is the ruling's sanctioned one — frozen without any
    # unverified-probe allowance.
    for check in manifest.checks:
        assert getattr(check.probe, "_probe_shape", None) == "SANDBOXED_DATA_DRIVER"

    calibration = _calibration(target, manifest, str(tmp_path))

    # The corpus's classifications (asserted inside _calibrate_case) and the
    # frozen-manifest discipline.
    names = [case.case_id for case in calibration.cases]
    assert names == [
        "known-good", "unchanged", "known-broken", "known-timeout", "infrastructure",
    ]
    frozen = experiment.freeze_manifest(
        target=target,
        oracle_manifest=manifest,
        limits=experiment.placeholder_limits(),
        calibration=calibration,
    )
    # The freeze binds the registries and gates by content: the frozen floors
    # are part of the experiment's identity, not a label echo.
    assert frozen.oracle_binding == experiment.oracle_target_binding(target, manifest)
    tampered = dataclasses.replace(
        manifest, oracle_version="project-oracle-2"
    )
    assert experiment.oracle_target_binding(target, tampered) != frozen.oracle_binding


@pytest.mark.timeout(1800)
def test_gate_config_and_test_corpus_neutralization_is_rejected(
    tmp_path, project_oracle_context
):
    """Review P0-1: candidate-controlled ruff/pytest policy and baseline test
    edits cannot neutralise the gate. The reproducers make the local gates pass
    (ruff per-file ignore; pytest collect-only + a failing test); the frozen
    oracle must still grade both trees FAIL by content identity."""
    target, manifest = project_oracle_context
    repo = target.repository
    checks = {check.check_id: check for check in manifest.checks}

    def grade_one(check_id: str, tree: str) -> str:
        check = checks[check_id]
        one = oracle.OracleManifest(
            oracle_version=manifest.oracle_version,
            criteria=manifest.criteria,
            checks=(check,),
            target_binding="",
        )
        return oracle.grade_manifest(one, tree, runner=None).outcomes[check_id]

    # Static-gate neutralisation: a per-file ignore makes a genuine gated-rule
    # violation pass ruff; the frozen config hash must nevertheless fail the
    # oracle gate.
    ruff_tree = os.path.join(str(tmp_path), "ruff-mutant")
    shutil.copytree(repo, ruff_tree, ignore=_TREE_IGNORE)
    with open(os.path.join(ruff_tree, "ruff.toml"), "a", encoding="utf-8") as handle:
        handle.write(
            "\n[lint.per-file-ignores]\n"
            '"src/orchestrator/p0_gate_violation.py" = ["BLE001", "S110"]\n'
        )
    with open(
        os.path.join(ruff_tree, "src", "orchestrator", "p0_gate_violation.py"),
        "w",
        encoding="utf-8",
    ) as handle:
        handle.write(
            "def swallowed(error):\n"
            "    try:\n        raise error\n"
            "    except Exception:\n        pass\n"
        )
    host_venv = os.path.join(_repo_root(), ".venv")
    ruff = subprocess.run(
        (os.path.join(host_venv, "bin", "ruff"), "check", "--select", "BLE001,S110", "src/orchestrator"),
        cwd=ruff_tree, capture_output=True,
    )
    assert ruff.returncode == 0, ruff.stdout.decode(errors="replace") + ruff.stderr.decode(errors="replace")
    assert grade_one("gate-check-static", ruff_tree) == oracle.GRADE_FAIL

    # Pytest/conftest neutralisation: collect-only makes a newly appended
    # failing test appear green, and a collection hook deselects it. The
    # frozen pytest config, conftest, and baseline test hashes must reject it.
    pytest_tree = os.path.join(str(tmp_path), "pytest-mutant")
    shutil.copytree(repo, pytest_tree, ignore=_TREE_IGNORE)
    os.symlink(os.path.join(_repo_root(), ".venv"), os.path.join(pytest_tree, ".venv"))
    with open(os.path.join(pytest_tree, "pytest.ini"), "a", encoding="utf-8") as handle:
        handle.write("\naddopts = --collect-only -q\n")
    test_file = os.path.join(pytest_tree, "tests", "test_executor.py")
    with open(test_file, "a", encoding="utf-8") as handle:
        handle.write("\n\ndef test_p0_gate_neutralization_reproducer():\n    assert False\n")
    conftest = os.path.join(pytest_tree, "tests", "conftest.py")
    with open(conftest, "a", encoding="utf-8") as handle:
        handle.write(
            "\n\ndef pytest_collection_modifyitems(items):\n"
            "    items[:] = [item for item in items if "
            "item.name != 'test_p0_gate_neutralization_reproducer']\n"
        )
    neutered = subprocess.run(
        ("/bin/sh", "scripts/check-tests", "--fast", "-p", "no:cacheprovider"),
        cwd=pytest_tree, capture_output=True, timeout=60,
    )
    assert neutered.returncode == 0, (
        neutered.stdout.decode(errors="replace")[-1000:]
        + neutered.stderr.decode(errors="replace")[-1000:]
    )
    assert grade_one("gate-check-tests", pytest_tree) == oracle.GRADE_FAIL

    # The frozen `-k` expression is substring-based. A candidate renames the
    # excluded coverage test so the expression still deselects it; the frozen
    # test-file identity must reject that tree despite pytest's exit 0.
    k_tree = os.path.join(str(tmp_path), "pytest-k-mutant")
    shutil.copytree(repo, k_tree, ignore=_TREE_IGNORE)
    os.symlink(os.path.join(_repo_root(), ".venv"), os.path.join(k_tree, ".venv"))
    static_test = os.path.join(k_tree, "tests", "test_static_gates.py")
    source = open(static_test, encoding="utf-8").read()
    old_name = "test_frozen_corpus_branch_coverage_meets_the_floor"
    assert old_name in source
    source = source.replace(old_name, "test_renamed_" + old_name, 1)
    source = source.replace(
        '    coverage = pytest.importorskip("coverage")',
        "    assert False, 'renamed test must not be silently deselected'",
        1,
    )
    open(static_test, "w", encoding="utf-8").write(source)
    renamed = subprocess.run(
        (
            "/bin/sh", "scripts/check-tests", "--fast", "-p", "no:cacheprovider", "-k",
            "not test_frozen_corpus_branch_coverage_meets_the_floor and "
            "not test_total_deadline_bounds_a_real_dripping_reply",
            "tests/test_static_gates.py",
        ),
        cwd=k_tree, capture_output=True, timeout=300,
    )
    assert renamed.returncode == 0, (
        renamed.stdout.decode(errors="replace")[-1000:]
        + renamed.stderr.decode(errors="replace")[-1000:]
    )
    assert grade_one("gate-check-tests", k_tree) == oracle.GRADE_FAIL

    # Additive test modules are also part of the frozen executable corpus: a
    # new file is an oracle-definition change and requires a trusted re-freeze.
    added_tree = os.path.join(str(tmp_path), "added-test-module")
    shutil.copytree(repo, added_tree, ignore=_TREE_IGNORE)
    with open(
        os.path.join(added_tree, "tests", "test_candidate_addition.py"),
        "w",
        encoding="utf-8",
    ) as handle:
        handle.write("def test_candidate_addition():\n    assert True\n")
    assert grade_one("gate-check-tests", added_tree) == oracle.GRADE_FAIL

    # N-1: candidate source is graded, not frozen. A behaviour-preserving edit
    # to an existing source module must be ACCEPTED by both command gates, and a
    # behaviour-changing one must be REJECTED. An oracle that froze `src/**`
    # alongside the test corpus fails the first assertion, which is the vacuous
    # acceptance gate this pins shut.
    benign_tree = os.path.join(str(tmp_path), "benign-source-edit")
    shutil.copytree(repo, benign_tree, ignore=_TREE_IGNORE)
    _edit_candidate_source(benign_tree)
    assert grade_one("gate-check-static", benign_tree) == oracle.GRADE_PASS
    assert grade_one("gate-check-tests", benign_tree) == oracle.GRADE_PASS

    broken_source = os.path.join(str(tmp_path), "broken-source-edit")
    shutil.copytree(repo, broken_source, ignore=_TREE_IGNORE)
    _break_candidate_source(broken_source)
    assert grade_one("gate-check-tests", broken_source) == oracle.GRADE_FAIL

    # N-2: a candidate-added nested gate config cannot appear in a freeze-time
    # inventory, so only the closed-set control-basename policy rejects it. Host
    # side, ruff is genuinely neutralised by the nested config.
    bypass_tree = os.path.join(str(tmp_path), "nested-gate-config")
    shutil.copytree(repo, bypass_tree, ignore=_TREE_IGNORE)
    _add_a_nested_gate_config(bypass_tree)
    assert grade_one("gate-check-static", bypass_tree) == oracle.GRADE_FAIL


@pytest.mark.timeout(300)
def test_registry_identity_floors_reject_compensated_replacements(
    tmp_path, project_oracle_context
):
    """Review P1-2: a covered finding/pin cannot be deleted and compensated
    with a filler identity while the count floors and the repository's own
    meta-tests remain green."""
    target, manifest = project_oracle_context
    repo = target.repository

    def grade_one(check_id: str, tree: str) -> str:
        check = next(c for c in manifest.checks if c.check_id == check_id)
        one = oracle.OracleManifest(
            oracle_version=manifest.oracle_version,
            criteria=manifest.criteria,
            checks=(check,),
            target_binding="",
        )
        return oracle.grade_manifest(one, tree, runner=None).outcomes[check_id]

    # Counterexample compensation: demote R23 and add a covered R24 so
    # min_covered stays at 23; update the readiness report so its meta-test is
    # also green. The frozen R23 identity (tests + prefix) must still trip the
    # oracle check.
    tree = os.path.join(str(tmp_path), "counterexample-compensation")
    shutil.copytree(repo, tree, ignore=_TREE_IGNORE)
    registry_path = os.path.join(tree, "tests", "counterexamples.yaml")
    import yaml

    with open(registry_path, encoding="utf-8") as handle:
        registry = yaml.safe_load(handle)
    r23 = registry["findings"]["R23"]
    r23["tests"] = []
    r23["remediation_batch"] = "review-p1-2-compensation"
    registry["findings"]["R24"] = {
        "title": "Filler covered identity compensating for R23",
        "prefix_revision": r23["prefix_revision"],
        "tests": ["tests/test_counterexample_registry.py::test_registry_covers_every_reported_finding_exactly"],
    }
    with open(registry_path, "w", encoding="utf-8") as handle:
        yaml.safe_dump(registry, handle, sort_keys=False)
    report_path = os.path.join(tree, "docs", "report-milestone8-readiness.md")
    with open(report_path, "a", encoding="utf-8") as handle:
        handle.write(
            "\n| R24 | P2 | Oracle | Filler identity for the adversarial floor test |\n"
        )

    # The candidate's own meta-test is internally consistent (the frozen
    # identity check, not the count floor, is what must catch the compensation).
    os.symlink(os.path.join(_repo_root(), ".venv"), os.path.join(tree, ".venv"))
    meta = subprocess.run(
        (os.path.join(tree, ".venv", "bin", "python"), "-m", "pytest",
         "tests/test_counterexample_registry.py", "-q", "-p", "no:cacheprovider"),
        cwd=tree, capture_output=True, timeout=60,
    )
    assert meta.returncode == 0, meta.stdout.decode(errors="replace") + meta.stderr.decode(errors="replace")
    os.unlink(os.path.join(tree, ".venv"))
    assert grade_one("registry-counterexample-floors", tree) == oracle.GRADE_FAIL

    # Open-defect compensation: rename one fixed test_bug_* function out of
    # the bug-pin namespace and clear its registry mapping. The module remains
    # syntactically valid, the meta-registry stays internally consistent, and
    # the fixed-count floor is unchanged; the frozen pin/test-node identity
    # must still reject the tree.
    tree = os.path.join(str(tmp_path), "open-defect-compensation")
    shutil.copytree(repo, tree, ignore=_TREE_IGNORE)
    bug_file = os.path.join(tree, "tests", "test_boundary_mutations.py")
    source = open(bug_file, encoding="utf-8").read()
    marker = "def test_bug_schema_version_accepts_boolean"
    assert marker in source
    source = source.replace(
        marker, "def test_retired_schema_version_case", 1
    )
    open(bug_file, "w", encoding="utf-8").write(source)
    defect_path = os.path.join(tree, "tests", "open_defects.yaml")
    with open(defect_path, encoding="utf-8") as handle:
        defects = yaml.safe_load(handle)
    defects["defects"]["schema-version-accepts-boolean"]["tests"] = []
    with open(defect_path, "w", encoding="utf-8") as handle:
        yaml.safe_dump(defects, handle, sort_keys=False)
    os.symlink(os.path.join(_repo_root(), ".venv"), os.path.join(tree, ".venv"))
    meta = subprocess.run(
        (os.path.join(tree, ".venv", "bin", "python"), "-m", "pytest",
         "tests/test_open_defect_registry.py", "-q", "-p", "no:cacheprovider"),
        cwd=tree, capture_output=True, timeout=60,
    )
    assert meta.returncode == 0, meta.stdout.decode(errors="replace") + meta.stderr.decode(errors="replace")
    os.unlink(os.path.join(tree, ".venv"))
    assert grade_one("registry-open-defect-floors", tree) == oracle.GRADE_FAIL


def test_open_defect_identity_normalizes_parameterized_node_ids():
    """P2-4: parameter ids are variants of one registered bug-pin function,
    not new names that should falsely fail the unregistered-pin comparison."""
    from orchestrator.project_oracle import _normalise_node_id

    assert _normalise_node_id(
        "tests/test_guard_disable_mutation.py::test_bug_limit_guard[param]"
    ) == "tests/test_guard_disable_mutation.py::test_bug_limit_guard"


def test_project_oracle_has_no_trusted_gate_bypass_flag():
    """Review P2-3: the public builder cannot silently skip the trusted-side
    conformance/documentation preconditions."""
    with pytest.raises(TypeError):
        project_oracle.build_project_oracle(
            object(), run_trusted_gates=False
        )


def _driver_identity(driver):
    line = next(
        line for line in driver.splitlines() if line.startswith("env.update(")
    )
    return ast.literal_eval(line[len("env.update("):-1])


def test_only_the_tests_gate_driver_carries_the_pinned_git_identity(monkeypatch):
    """R1: the identity pin reaches only the check whose suite needs it. The
    static gate runs no git, so its formatted driver must carry an empty
    identity mapping; the tests driver carries all four pinned values."""
    captured = {}

    def capture(*, driver, **kwargs):
        captured["driver"] = driver
        return types.SimpleNamespace()

    monkeypatch.setattr(project_oracle, "sandboxed_probe", capture)
    common = dict(
        gate_script="scripts/check-static",
        argv=("/bin/sh", "scripts/check-static"),
        frozen_hash="sha256:unused",
        control_hashes={},
        test_hashes={},
        frozen_control_paths=(),
        frozen_test_paths=(),
        gate_hashes={},
        frozen_corpus=(),
        mount_points=(),
        timeout_seconds=1.0,
        ro_paths=(),
        limits=None,
    )
    project_oracle._gate_check(
        check_id="gate-check-static", criterion_id="AC-STATIC", **common
    )
    static_driver = captured["driver"]
    project_oracle._gate_check(
        check_id="gate-check-tests", criterion_id="AC-TESTS",
        git_identity=project_oracle._GATE_GIT_IDENTITY, **common,
    )
    tests_driver = captured["driver"]

    assert _driver_identity(static_driver) == {}
    assert _driver_identity(tests_driver) == project_oracle._GATE_GIT_IDENTITY
    for name, value in project_oracle._GATE_GIT_IDENTITY.items():
        assert name not in static_driver
        assert f"{name!r}: {value!r}" in tests_driver


def _nested_run_survivors():
    """PIDs whose command line names the nested gate's interpreter
    (/work/.venv) or its launcher: survivors of the nested grading runs
    (R13's orphan probe)."""
    found = []
    for entry in os.listdir("/proc"):
        if not entry.isdigit():
            continue
        try:
            with open(f"/proc/{entry}/cmdline", "rb") as handle:
                cmdline = handle.read().replace(b"\0", b" ").decode(errors="replace")
        except OSError:
            continue
        if "/work/.venv" in cmdline or "sandbox_launcher" in cmdline:
            found.append((int(entry), cmdline.strip()))
    return found


@pytest.mark.timeout(1200)
def test_grading_gate_grades_one_candidate_identically_across_consecutive_runs(
    tmp_path, project_oracle_context
):
    """F8 (R13): the grading gate runs seeded, so one candidate tree grades the
    same verdict on every consecutive run. Five consecutive grades of the
    known-good shape through the manifest's gate-check-tests check must all
    return PASS; a flip to CANDIDATE_TIMEOUT or FAIL is a grader defect, not a
    test annoyance."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    target, manifest = project_oracle_context
    repo = target.repository
    check = next(c for c in manifest.checks if c.check_id == "gate-check-tests")

    def grade_one(tree: str) -> str:
        one = oracle.OracleManifest(
            oracle_version=manifest.oracle_version,
            criteria=manifest.criteria,
            checks=(check,),
            target_binding="",
        )
        return oracle.grade_manifest(one, tree, runner=None).outcomes["gate-check-tests"]

    # The known-good shape the five-case corpus already builds: the intact
    # tree plus a benign source edit, so the stable verdict is PASS.
    tree = _case_tree(str(tmp_path), repo, "tree-determinism")
    _edit_candidate_source(tree)

    runs = 5
    verdicts = [grade_one(tree) for _ in range(runs)]
    assert verdicts == [oracle.GRADE_PASS] * runs, (
        f"the gate graded one candidate tree differently across "
        f"{runs} consecutive runs: {verdicts}"
    )

    # R13's orphan-probe duty: re-walk the process table for survivors of the
    # nested runs. No /work/.venv chain and no sandbox_launcher may survive the
    # sweep; a survivor is a finding, not a pass.
    survivors = _nested_run_survivors()
    assert not survivors, f"survivors of the nested grading runs: {survivors}"


@pytest.mark.timeout(1200)
def test_near_deadline_candidate_grades_fail_under_host_contention(
    tmp_path, project_oracle_context
):
    """F16: the seeding holds past the stable half. The near-deadline candidate
    (the neutralisation test's broken-source tree, whose failing-and-shrinking
    suite sits closest to the deadline) must grade FAIL — the value verdict —
    beside host load, not CANDIDATE_TIMEOUT. The load is this test's own shape:
    a bounded, short-lived worker pool over the host core count, held for the
    grade and joined after it, so the fixture's deadline (the delivered
    default) is exercised against the candidate rather than against the host.
    """
    target, manifest = project_oracle_context
    repo = target.repository
    check = next(c for c in manifest.checks if c.check_id == "gate-check-tests")

    def grade_one(tree: str) -> str:
        one = oracle.OracleManifest(
            oracle_version=manifest.oracle_version,
            criteria=manifest.criteria,
            checks=(check,),
            target_binding="",
        )
        return oracle.grade_manifest(one, tree, runner=None).outcomes["gate-check-tests"]

    tree = _case_tree(str(tmp_path), repo, "tree-near-deadline")
    _break_candidate_source(tree)

    # The contention is a pool of busy worker processes over the host core
    # count, exec'd so no fork of this (possibly multi-threaded) test process
    # outlives the call, terminated and joined after the grade.
    workers = [
        subprocess.Popen(
            [sys.executable, "-c", "while True: pass"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        for _ in range(os.cpu_count() or 1)
    ]
    try:
        verdict = grade_one(tree)
    finally:
        for worker in workers:
            worker.terminate()
        for worker in workers:
            worker.wait(timeout=30)

    assert verdict == oracle.GRADE_FAIL, (
        f"the near-deadline candidate graded {verdict} under host contention, "
        f"not FAIL: the fixture's grading deadline, not the seed, decided the "
        f"verdict"
    )
