# SPDX-License-Identifier: AGPL-3.0-or-later
"""Axis 1 / self-host Phase 1: the model-produced implementation path.

These tests pin the patch-producing `ARTEFACT` boundary and the exit gate from
docs/research/axis1-patch-producer-design.md. The exit gate is the
differential: with everything else frozen, changing only the model reply
changes the produced candidate tree and therefore the hidden oracle's grade —
in the honest direction: a working patch must pass the component it fixes and
a broken patch must fail it. A scripted candidate success is never relabelled
as model coding capability.
"""

from __future__ import annotations

import os

import pytest

from helpers import open_test_spend_ledger

from orchestrator import experiment, patch as patch_module, sandbox
from orchestrator.patch_executor import PatchExecutor, PatchRequest

# The fixed target's stubs (the real preimage of every patch below).
_STUB = "def parse(text):\n    raise NotImplementedError('parse')\n"

# The two model replies the exit gate differentiates. Both are real multi-file
# diffs of the real stubs, so the strict preimage check accepts them exactly as
# `git apply` would. The working reply implements the parser; the broken reply
# leaves it wrong while implementing the other three components, so the
# differential is attributable to the component the reply targets.
_WORKING_PARSE_PATCH = """\
--- a/src/parser/parse.py
+++ b/src/parser/parse.py
@@ -1,2 +1,2 @@
 def parse(text):
-    raise NotImplementedError('parse')
+    return text.split()
--- a/src/render/render.py
+++ b/src/render/render.py
@@ -1,2 +1,2 @@
 def render(ast):
-    raise NotImplementedError('render')
+    return ' '.join(ast)
--- a/src/report/format.py
+++ b/src/report/format.py
@@ -1,2 +1,2 @@
 def format_report(ast):
-    raise NotImplementedError('format_report')
+    return 'REPORT: ' + ' '.join(ast)
--- a/src/report/emit.py
+++ b/src/report/emit.py
@@ -1,2 +1,2 @@
 def emit_report(text):
-    raise NotImplementedError('emit_report')
+    return text.upper()
"""

_BROKEN_PARSE_PATCH = """\
--- a/src/parser/parse.py
+++ b/src/parser/parse.py
@@ -1,2 +1,2 @@
 def parse(text):
-    raise NotImplementedError('parse')
+    return []
--- a/src/render/render.py
+++ b/src/render/render.py
@@ -1,2 +1,2 @@
 def render(ast):
-    raise NotImplementedError('render')
+    return ' '.join(ast)
--- a/src/report/format.py
+++ b/src/report/format.py
@@ -1,2 +1,2 @@
 def format_report(ast):
-    raise NotImplementedError('format_report')
+    return 'REPORT: ' + ' '.join(ast)
--- a/src/report/emit.py
+++ b/src/report/emit.py
@@ -1,2 +1,2 @@
 def emit_report(text):
-    raise NotImplementedError('emit_report')
+    return text.upper()
"""


def test_patch_boundary_form_scope_size_and_metadata():
    # Form: a well-formed unified diff parses to exactly its changed paths.
    parsed = patch_module.parse_patch(
        _WORKING_PARSE_PATCH, owned_scope_include=["src/**"]
    )
    assert parsed.paths == (
        "src/parser/parse.py",
        "src/render/render.py",
        "src/report/format.py",
        "src/report/emit.py",
    )
    applied = patch_module.apply_patch(
        "src/parser/parse.py", parsed.files["src/parser/parse.py"], _STUB
    )
    assert applied == "def parse(text):\n    return text.split()\n"

    # Size: an oversized patch is refused at the boundary.
    big = _WORKING_PARSE_PATCH + "# " + "x" * patch_module.MAX_PATCH_BYTES
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch(big, owned_scope_include=["src/**"])

    # Scope: a path outside the delegated owned_scope is refused.
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch(
            "--- a/outside/x.py\n+++ b/outside/x.py\n@@ -1,1 +1,1 @@\n-a\n+b\n",
            owned_scope_include=["src/**"],
        )

    # Metadata: a .git path is refused outright (R01).
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch(
            "--- a/.git/config\n+++ b/.git/config\n@@ -1,1 +1,1 @@\n-a\n+b\n",
            owned_scope_include=["src/**"],
        )

    # Form: garbage (no unified-diff header) is refused.
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch("not a diff at all", owned_scope_include=["src/**"])

    # Form: a hunk whose body does not match its declared counts is refused.
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch(
            "--- a/src/a.py\n+++ b/src/a.py\n@@ -1,1 +1,1 @@\n+only-add\n",
            owned_scope_include=["src/**"],
        )


def test_patch_application_is_hunk_faithful():
    """A partial hunk preserves everything outside it; a preimage mismatch
    fails closed; a created file must arrive as a whole-file addition."""
    source = "a\nb\nc\nd\ne\n"
    partial = "--- a/x.py\n+++ b/x.py\n@@ -3,1 +3,1 @@\n-c\n+CC\n"
    parsed = patch_module.parse_patch(partial, owned_scope_include=["**"])
    assert patch_module.apply_patch("x.py", parsed.files["x.py"], source) == "a\nb\nCC\nd\ne\n"

    # Preimage mismatch: refused, nothing applied.
    with pytest.raises(patch_module.PatchRejected) as refused:
        patch_module.apply_patch("x.py", parsed.files["x.py"], "x\ny\nWRONG\n")
    assert "preimage" in refused.value.reason

    # A created file with a preimage is refused.
    create = "--- /dev/null\n+++ b/new.py\n@@ -1,1 +1,1 @@\n-old\n+new\n"
    parsed = patch_module.parse_patch(create, owned_scope_include=["**"])
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("new.py", parsed.files["new.py"], None)

    # A created file without preimage is created whole.
    create = "--- /dev/null\n+++ b/new.py\n@@ -0,0 +1,2 @@\n+one\n+two\n"
    parsed = patch_module.parse_patch(create, owned_scope_include=["**"])
    assert patch_module.apply_patch("new.py", parsed.files["new.py"], None) == "one\ntwo\n"


def test_axis1_exit_gate_model_reply_changes_tree_and_grade(tmp_path):
    """The Axis 1 exit gate: changing only the model reply changes the produced
    tree and therefore the hidden oracle's grade — in the honest direction: the
    working patch passes the component it fixes and the broken patch fails it."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")

    target = experiment.build_fixed_target(str(tmp_path))
    oracle_manifest = experiment.build_hidden_oracle(target)

    def _run_with_patch(patch_text: str, workdir_name: str) -> experiment.TrialMetrics:
        workdir = str(tmp_path / workdir_name)
        os.makedirs(workdir, exist_ok=True)
        ledger = open_test_spend_ledger(workdir)
        client = experiment.PatchModelClient(
            experiment.PATCH_MODEL_PROFILE, default_patch=patch_text
        )
        experiment.set_model_client_factory(lambda profile, seed: client)
        try:
            return experiment.run_trial(
                target,
                oracle_manifest,
                experiment.placeholder_limits(),
                experiment.PATCH_MODEL_PROFILE,
                experiment.ARM_DIRECT,
                1001,
                workdir,
                spend_ledger=ledger,
            )
        finally:
            experiment.set_model_client_factory(None)

    working = _run_with_patch(_WORKING_PARSE_PATCH, "working")
    broken = _run_with_patch(_BROKEN_PARSE_PATCH, "broken")

    working_outcomes = dict(working.oracle_outcomes)
    broken_outcomes = dict(broken.oracle_outcomes)
    # The parser component is the one the reply targets: its hidden check is
    # the one that moves, and it moves in the honest direction.
    assert working_outcomes["hidden-parse"] == "PASS", working_outcomes
    assert broken_outcomes["hidden-parse"] == "FAIL", broken_outcomes
    assert working_outcomes != broken_outcomes, (
        "changing only the model reply must change the produced grade"
    )


def test_patch_executor_no_patch_fails_closed(tmp_path):
    """A patch-producing attempt with no admissible patch fails closed: no
    artefact is imported and the attempt self-reports failure."""
    from orchestrator import sandbox
    from orchestrator.command_executor import CommandExecutorConfiguration
    from orchestrator.hashing import TOOLCHAIN_PATHS

    config = CommandExecutorConfiguration(
        repository=str(tmp_path / "repo"),
        base_commit="0" * 40,
        worktree_root=str(tmp_path / "worktrees"),
        artefact_root=str(tmp_path / "artefacts"),
        toolchain_paths=TOOLCHAIN_PATHS,
        commands={},
    )
    executor = PatchExecutor(config)
    request = {
        "run_id": "r",
        "action_id": "a",
        "attempt_id": "att",
        "attempt_token": executor.issue_token("att"),
        "node_id": "n",
        "node_contract_version": 1,
        "action_type": "EXECUTE",
        "owned_scope": {"include": ["src/**"], "exclude": []},
        "base_commit": "0" * 40,
        "worktree_id": "WT-att",
        "timeout_seconds": 30.0,
        "cancellation_token": "cancel-att",
        "budget_commitment": {"dimension": "COST_UNITS", "hard_limit": 5.0},
        "environment_version": "experiment-image-v1",
        "resolved_inputs": [],
        "output_schema_version": 1,
        "policy_version": 1,
    }
    response = executor.dispatch(request)
    assert response["self_reported_status"] == "FAILED"
    assert response["artefacts"] == []
    assert response["observations"][0]["type"] == "PATCH_REJECTED"


def test_patch_with_stale_preimage_fails_the_attempt(tmp_path):
    """A patch that does not describe the tree it edits fails the attempt
    closed: nothing is applied and no artefact is imported."""
    from orchestrator import sandbox
    from orchestrator.command_executor import CommandExecutorConfiguration
    from orchestrator.hashing import TOOLCHAIN_PATHS

    repo = str(tmp_path / "repo")
    os.makedirs(os.path.join(repo, "src"), exist_ok=True)
    subprocess = __import__("subprocess")
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
    ):
        subprocess.run(argv, check=True, capture_output=True)
    with open(os.path.join(repo, "src", "a.py"), "w") as handle:
        handle.write("one\ntwo\n")
    subprocess.run(("git", "-C", repo, "add", "-A"), check=True, capture_output=True)
    subprocess.run(
        ("git", "-C", repo, "commit", "-q", "-m", "base"), check=True, capture_output=True
    )
    base = subprocess.run(
        ("git", "-C", repo, "rev-parse", "HEAD"), check=True, capture_output=True, text=True
    ).stdout.strip()

    config = CommandExecutorConfiguration(
        repository=repo,
        base_commit=base,
        worktree_root=str(tmp_path / "worktrees"),
        artefact_root=str(tmp_path / "artefacts"),
        toolchain_paths=TOOLCHAIN_PATHS,
        commands={},
    )
    executor = PatchExecutor(config)
    stale = "--- a/src/a.py\n+++ b/src/a.py\n@@ -1,1 +1,1 @@\n-not-the-content\n+changed\n"
    executor.set_patch(PatchRequest(attempt_id="att", patch_text=stale, path="src/a.py"))
    request = {
        "run_id": "r",
        "action_id": "a",
        "attempt_id": "att",
        "attempt_token": executor.issue_token("att"),
        "node_id": "n",
        "node_contract_version": 1,
        "action_type": "EXECUTE",
        "owned_scope": {"include": ["**"], "exclude": []},
        "base_commit": base,
        "worktree_id": "WT-att",
        "timeout_seconds": 30.0,
        "cancellation_token": "cancel-att",
        "budget_commitment": {"dimension": "COST_UNITS", "hard_limit": 5.0},
        "environment_version": "experiment-image-v1",
        "resolved_inputs": [],
        "output_schema_version": 1,
        "policy_version": 1,
    }
    response = executor.dispatch(request)
    assert response["self_reported_status"] == "FAILED"
    assert response["artefacts"] == []
    assert response["observations"][0]["type"] == "PATCH_REJECTED"
    assert "preimage" in response["observations"][0]["reason"]


def test_line_endings_are_byte_exact_like_git_apply():
    """Review F1 (P0): line endings and in-line separators are content. An
    LF-context diff against CRLF content is refused (as `git apply` refuses
    it), a CRLF-context diff applies with its CRLF bytes preserved, and
    content outside the hunks survives byte-for-byte."""
    crlf = "def parse(text):\r\n    raise NotImplementedError('parse')\r\n"
    lf_context = (
        "--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n def parse(text):\n"
        "-    raise NotImplementedError('parse')\n+    return text.split()\n"
    )
    parsed = patch_module.parse_patch(lf_context, owned_scope_include=["**"])
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], crlf)

    crlf_context = (
        "--- a/x\r\n+++ b/x\r\n@@ -1,2 +1,2 @@\r\n def parse(text):\r\n"
        "-    raise NotImplementedError('parse')\r\n+    return text.split()\r\n"
    )
    parsed = patch_module.parse_patch(crlf_context, owned_scope_include=["**"])
    assert patch_module.apply_patch("x", parsed.files["x"], crlf) == (
        "def parse(text):\r\n    return text.split()\r\n"
    )

    # NEL and form feed are in-line content, never line boundaries.
    source = "one\u0085TWO\nthree\x0cfour\n"
    change = "--- a/x\n+++ b/x\n@@ -2 +2 @@\n-three\x0cfour\n+THREE\x0cfour\n"
    parsed = patch_module.parse_patch(change, owned_scope_include=["**"])
    assert patch_module.apply_patch("x", parsed.files["x"], source) == (
        "one\u0085TWO\nTHREE\x0cfour\n"
    )


def test_no_newline_marker_rules_and_delete_missing():
    """Review F3/F4: the no-newline marker is accepted only where it is
    truthful and at the file's end, and deleting a nonexistent path is
    refused."""
    # A marker with more content of its side after it is refused.
    mid = (
        "--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n-a\n\\ No newline at end of file\n"
        "-b\n+A\n+B\n"
    )
    with pytest.raises(patch_module.PatchRejected):
        patch_module.parse_patch(mid, owned_scope_include=["**"])

    # A truthful marker reproduces the no-newline end state.
    patch = (
        "--- a/x\n+++ b/x\n@@ -2 +2 @@\n-b\n\\ No newline at end of file\n"
        "+B\n\\ No newline at end of file\n"
    )
    parsed = patch_module.parse_patch(patch, owned_scope_include=["**"])
    assert patch_module.apply_patch("x", parsed.files["x"], "a\nb") == "a\nB"

    # A marker that lies about the file's end state is refused at application.
    parsed = patch_module.parse_patch(patch, owned_scope_include=["**"])
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], "a\nb\n")

    # Deleting a path that does not exist is refused (not a silent no-op).
    deletion = "--- a/gone\n+++ /dev/null\n@@ -1 +0,0 @@\n-x\n"
    parsed = patch_module.parse_patch(deletion, owned_scope_include=["**"])
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("gone", parsed.files["gone"], None)


def test_stale_patch_never_reaches_another_attempt(tmp_path):
    """Review F12: a patch bound to one attempt is never applied to another.
    A patch left pending by a cancelled or failed cycle must fail the next
    attempt closed, not silently contribute its content."""
    from orchestrator import sandbox
    from orchestrator.command_executor import CommandExecutorConfiguration
    from orchestrator.hashing import TOOLCHAIN_PATHS

    repo = str(tmp_path / "repo")
    os.makedirs(os.path.join(repo, "src"))
    subprocess = __import__("subprocess")
    for argv in (
        ("git", "init", "-q", repo),
        ("git", "-C", repo, "config", "user.email", "t@example.com"),
        ("git", "-C", repo, "config", "user.name", "t"),
    ):
        subprocess.run(argv, check=True, capture_output=True)
    with open(os.path.join(repo, "src", "a.py"), "w") as handle:
        handle.write("one\ntwo\n")
    subprocess.run(("git", "-C", repo, "add", "-A"), check=True, capture_output=True)
    subprocess.run(
        ("git", "-C", repo, "commit", "-q", "-m", "base"), check=True, capture_output=True
    )
    base = subprocess.run(
        ("git", "-C", repo, "rev-parse", "HEAD"), check=True, capture_output=True, text=True
    ).stdout.strip()

    config = CommandExecutorConfiguration(
        repository=repo,
        base_commit=base,
        worktree_root=str(tmp_path / "worktrees"),
        artefact_root=str(tmp_path / "artefacts"),
        toolchain_paths=TOOLCHAIN_PATHS,
        commands={},
    )
    executor = PatchExecutor(config)
    good = "--- a/src/a.py\n+++ b/src/a.py\n@@ -1,2 +1,2 @@\n one\n-two\n+TWO\n"
    # The patch is produced for attempt att1 of node n ...
    executor.set_patch(
        PatchRequest(attempt_id="att1", patch_text=good, node_id="n", path="src/a.py")
    )
    # ... and att1 is never dispatched (a cancel). A later attempt must not
    # receive it.
    request = {
        "run_id": "r",
        "action_id": "a",
        "attempt_id": "att2",
        "attempt_token": executor.issue_token("att2"),
        "node_id": "n",
        "node_contract_version": 1,
        "action_type": "EXECUTE",
        "owned_scope": {"include": ["src/**"], "exclude": []},
        "base_commit": base,
        "worktree_id": "WT-att2",
        "timeout_seconds": 30.0,
        "cancellation_token": "cancel-att2",
        "budget_commitment": {"dimension": "COST_UNITS", "hard_limit": 5.0},
        "environment_version": "experiment-image-v1",
        "resolved_inputs": [],
        "output_schema_version": 1,
        "policy_version": 1,
    }
    response = executor.dispatch(request)
    assert response["self_reported_status"] == "FAILED"
    assert response["artefacts"] == []
    assert response["observations"][0]["type"] == "PATCH_REJECTED"
    assert response["changed_paths"] == []


def test_insertion_hunk_placement_matches_git_diff_u0():
    """Re-review N1: for an insertion (`old_count == 0`) unified diff makes
    `old_start` the line *before* the insertion point (`git diff -U0` emits
    `@@ -2,0 +3 @@` to insert after line 2). The canonical placements, pinned
    against `git apply --unidiff-zero` semantics: mid-file insert, EOF append,
    and insert-at-start."""
    source = "a\nb\nc\nd\n"
    cases = (
        ("@@ -2,0 +3 @@\n+NEW\n", "a\nb\nNEW\nc\nd\n"),
        ("@@ -4,0 +5 @@\n+NEW\n", "a\nb\nc\nd\nNEW\n"),
        ("@@ -0,0 +1 @@\n+NEW\n", "NEW\na\nb\nc\nd\n"),
    )
    for header, expected in cases:
        patch = f"--- a/x\n+++ b/x\n{header}"
        parsed = patch_module.parse_patch(patch, owned_scope_include=["**"])
        assert patch_module.apply_patch("x", parsed.files["x"], source) == expected, header


def test_no_newline_claim_is_symmetric_review_n2():
    """Re-review N2: an *absent* no-newline marker asserts the old side is
    newline-terminated. On an unterminated file a marker-less EOF hunk is
    refused exactly as `git apply` refuses it — in every hunk position."""
    unterminated = "a\nb\nc\nd\ne"

    # Single EOF hunk without markers: refused.
    parsed = patch_module.parse_patch(
        "--- a/x\n+++ b/x\n@@ -5 +5 @@\n-e\n+E\n", owned_scope_include=["**"]
    )
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], unterminated)

    # A later hunk touching EOF without markers: refused.
    parsed = patch_module.parse_patch(
        "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+A\n@@ -5 +5 @@\n-e\n+E\n",
        owned_scope_include=["**"],
    )
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], unterminated)

    # A zero-count insertion at the file's end without the old-side claim:
    # refused (the file's last line is unterminated).
    parsed = patch_module.parse_patch(
        "--- a/x\n+++ b/x\n@@ -5,0 +6 @@\n+F\n", owned_scope_include=["**"]
    )
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], unterminated)

    # The converse (existing): a terminated file and a lying old marker is
    # refused; truthful markers on the unterminated file apply and reproduce
    # the end state.
    parsed = patch_module.parse_patch(
        "--- a/x\n+++ b/x\n@@ -5 +5 @@\n-e\n\\ No newline at end of file\n"
        "+E\n\\ No newline at end of file\n",
        owned_scope_include=["**"],
    )
    with pytest.raises(patch_module.PatchRejected):
        patch_module.apply_patch("x", parsed.files["x"], "a\nb\nc\nd\ne\n")
    assert patch_module.apply_patch("x", parsed.files["x"], unterminated) == "a\nb\nc\nd\nE"

    # A terminated file and a marker-less EOF hunk is the normal case: applied.
    parsed = patch_module.parse_patch(
        "--- a/x\n+++ b/x\n@@ -5 +5 @@\n-e\n+E\n", owned_scope_include=["**"]
    )
    assert patch_module.apply_patch("x", parsed.files["x"], "a\nb\nc\nd\ne\n") == (
        "a\nb\nc\nd\nE\n"
    )


def test_self_inconsistent_insert_headers_follow_git_review_r1():
    """Review R1: a zero-count hunk is placed by its *new* side
    (`git apply` inserts at `new_start - 1`; the old side of an insertion
    carries no position information). For conforming `git diff -U0` headers
    the two readings coincide (`new_start == old_start + 1`); for a
    self-inconsistent header an LLM can emit, the boundary must land the lines
    exactly where `git apply` lands them — never elsewhere."""
    source = "a\nb\nc\nd\n"
    cases = (
        ("@@ -3,0 +3 @@\n+NEW\n", "a\nb\nNEW\nc\nd\n"),
        ("@@ -2,0 +2 @@\n+NEW\n", "a\nNEW\nb\nc\nd\n"),
        ("@@ -2,0 +4 @@\n+NEW\n", "a\nb\nc\nNEW\nd\n"),
        ("@@ -1,0 +5 @@\n+NEW\n", "a\nb\nc\nd\nNEW\n"),
    )
    for header, expected in cases:
        patch = f"--- a/x\n+++ b/x\n{header}"
        parsed = patch_module.parse_patch(patch, owned_scope_include=["**"])
        assert patch_module.apply_patch("x", parsed.files["x"], source) == expected, header
