# SPDX-License-Identifier: AGPL-3.0-or-later
"""Conformance entries for the third milestone's events and protocol rules.

Per AGENTS.md#change-rules every event added or first validated here carries a
conformance entry: ``SANDBOX_VIOLATION_RECORDED`` (source authority, retained
forensic evidence, wildcard transition, and the derived rejection of the
attempt's outputs), the artefact-machine transitions used for integration
(``ARTEFACT_INTEGRATED`` / ``ARTEFACT_VALIDATED`` / ``ARTEFACT_REJECTED``), and
``DISPATCH_FAILED`` with its optional failure detail.

It also pins the executor-protocol response fixtures
(docs/executors.md#executor-protocol): one valid response and a mutation per
invalid case (unknown status/artefact/observation enums, identity and token
mismatch, out-of-scope changed paths, artefact-hash mismatch, missing fields,
unsupported schema version), which is the versioned valid/invalid fixture set
the workflow requires.
"""

from __future__ import annotations

import copy

import pytest

from orchestrator import events, executor_protocol, reducer, sandbox, tables
from orchestrator.model import RunState
from orchestrator.reducer import ReducerError


def _event(event_type, payload, idem="k", source="controller"):
    return events.make_event(event_type, payload, idempotency_key=idem, source=source)


def _admitted_attempt(accounting=True, acknowledged=True):
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state,
        _event(
            "NODE_PROPOSED",
            {"node_id": "n1", "contract": {"budgets": {"MODEL_COST": 100}}, "cause": "ROOT"},
        ),
    )
    state, _ = reducer.reduce(
        state, _event("ATTEMPT_PLANNED", {"attempt_id": "a1", "node_id": "n1", "cause": "INITIAL"})
    )
    state, _ = reducer.reduce(
        state, _event("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5}, source="scheduler")
    )
    if accounting:
        state, _ = reducer.reduce(
            state, _event("ATTEMPT_COMMITMENT_OPENED", {"attempt_id": "a1", "commitment": 5})
        )
    state, _ = reducer.reduce(
        state, _event("ACTION_DISPATCHED", {"attempt_id": "a1", "executor": "command-executor"})
    )
    if acknowledged:
        state, _ = reducer.reduce(
            state, _event("DISPATCH_ACKNOWLEDGED", {"attempt_id": "a1", "token": "t"}, source="executor")
        )
    return state


# -- SANDBOX_VIOLATION_RECORDED -------------------------------------------------


def test_sandbox_violation_source_authority_is_sandbox_only():
    wrong = events.make_event(
        "SANDBOX_VIOLATION_RECORDED",
        {"attempt_id": "a1", "evidence": {"kind": "FORBIDDEN_SYSCALL"}},
        source="controller",
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(wrong)
    right = events.make_event(
        "SANDBOX_VIOLATION_RECORDED",
        {"attempt_id": "a1", "evidence": {"kind": "FORBIDDEN_SYSCALL"}},
        source="sandbox",
    )
    events.validate_event(right)


def test_sandbox_violation_requires_evidence_and_rejects_unknown_fields():
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(
            _event("SANDBOX_VIOLATION_RECORDED", {"attempt_id": "a1"}, source="sandbox")
        )
    with pytest.raises(events.AdmissionError):
        events.validate_event(
            _event(
                "SANDBOX_VIOLATION_RECORDED",
                {"attempt_id": "a1", "evidence": {}, "unexpected": 1},
                source="sandbox",
            )
        )


def test_sandbox_violation_transitions_every_non_terminal_attempt_state():
    node_table = tables.attempt_table()
    for state in ("PLANNED", "RESERVED", "DISPATCHED", "RUNNING", "OBSERVATION_RECEIVED"):
        assert node_table.resolve(state, "SANDBOX_VIOLATION_RECORDED").target == "FAILED"
    for terminal in ("RESULT_PRODUCED", "FAILED", "TIMED_OUT", "CANCELLED"):
        with pytest.raises(tables.UnknownTransition):
            node_table.resolve(terminal, "SANDBOX_VIOLATION_RECORDED")


def test_sandbox_violation_records_evidence_and_rejects_the_attempts_outputs():
    state = _admitted_attempt()
    state, _ = reducer.reduce(
        state,
        _event(
            "ARTEFACT_ADMITTED",
            {"artefact_id": "art-1", "type": "GIT_CANDIDATE", "hash": "sha256:x", "attempt_id": "a1"},
        ),
    )
    evidence = {"kind": sandbox.VIOLATION_OUT_OF_SCOPE_WRITE, "paths": ["escape.txt"]}
    state, effects = reducer.reduce(
        state,
        _event(
            "SANDBOX_VIOLATION_RECORDED",
            {"attempt_id": "a1", "evidence": evidence, "violation_kind": evidence["kind"]},
            source="sandbox",
        ),
    )
    assert state.attempts["a1"].state == "FAILED"
    assert state.attempts["a1"].violation == evidence
    rejections = [e for e in effects if e.kind == "reject_artefact_requested"]
    assert [r.data["artefact_id"] for r in rejections] == ["art-1"]
    # The controller's effect executor turns each intent into ARTEFACT_REJECTED.
    state, _ = reducer.reduce(
        state,
        _event("ARTEFACT_REJECTED", {"artefact_id": "art-1", "reason": "SANDBOX_VIOLATION"}),
    )
    assert state.artefacts["art-1"].state == "REJECTED"


def test_sandbox_violation_against_terminal_attempt_is_a_retained_no_op():
    state = _admitted_attempt()
    state, _ = reducer.reduce(
        state, _event("CANCELLATION_CONFIRMED", {"attempt_id": "a1"})
    )
    state, effects = reducer.reduce(
        state,
        _event(
            "SANDBOX_VIOLATION_RECORDED",
            {"attempt_id": "a1", "evidence": {"kind": sandbox.VIOLATION_FORBIDDEN_SYSCALL}},
            source="sandbox",
        ),
    )
    assert state.attempts["a1"].state == "CANCELLED"
    assert effects == [reducer.Effect("late_event_retained", {"attempt_id": "a1"})]


# -- artefact-machine integration transitions -----------------------------------


def _candidate_artefact():
    state = _admitted_attempt()
    state, _ = reducer.reduce(
        state,
        _event(
            "ARTEFACT_ADMITTED",
            {"artefact_id": "art-1", "type": "GIT_CANDIDATE", "hash": "sha256:x", "attempt_id": "a1"},
        ),
    )
    return state


def test_artefact_integration_and_validation_paths():
    state = _candidate_artefact()
    state, _ = reducer.reduce(
        state, _event("ARTEFACT_INTEGRATED", {"artefact_id": "art-1", "merge_info": {"reference": "c1"}})
    )
    assert state.artefacts["art-1"].state == "INTEGRATED"
    state, _ = reducer.reduce(
        state, _event("ARTEFACT_VALIDATED", {"artefact_id": "art-1", "validator": "fixture"})
    )
    assert state.artefacts["art-1"].state == "VALIDATED"


def test_artefact_rejected_from_candidate_and_terminal_is_a_no_op():
    state = _candidate_artefact()
    state, _ = reducer.reduce(
        state, _event("ARTEFACT_REJECTED", {"artefact_id": "art-1", "reason": "RESULT_NOT_PRODUCED"})
    )
    assert state.artefacts["art-1"].state == "REJECTED"
    state, effects = reducer.reduce(
        state, _event("ARTEFACT_INTEGRATED", {"artefact_id": "art-1", "merge_info": {}})
    )
    assert effects == [reducer.Effect("late_event_retained", {"artefact_id": "art-1"})]


def test_artefact_integration_requires_a_candidate():
    state = _candidate_artefact()
    state, _ = reducer.reduce(
        state, _event("ARTEFACT_INTEGRATED", {"artefact_id": "art-1", "merge_info": {}})
    )
    with pytest.raises(tables.UnknownTransition):
        tables.artefact_table().resolve("INTEGRATED", "ARTEFACT_INTEGRATED")
    with pytest.raises(ReducerError):
        reducer.reduce(
            state, _event("ARTEFACT_INTEGRATED", {"artefact_id": "missing", "merge_info": {}})
        )


def test_artefact_type_enum_is_enforced_at_admission():
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            _event(
                "ARTEFACT_ADMITTED",
                {"artefact_id": "art-1", "type": "NOT_A_TYPE", "hash": "sha256:x", "attempt_id": "a1"},
            )
        )


# -- DISPATCH_FAILED ------------------------------------------------------------


def test_dispatch_failed_accepts_optional_failure_detail():
    events.validate_event(
        _event("DISPATCH_FAILED", {"attempt_id": "a1", "failure": {"reason": "sandbox unavailable"}})
    )
    state = _admitted_attempt(accounting=False, acknowledged=False)
    state, _ = reducer.reduce(
        state,
        _event("DISPATCH_FAILED", {"attempt_id": "a1", "failure": {"reason": "sandbox unavailable"}}),
    )
    assert state.attempts["a1"].state == "FAILED"


# -- executor protocol: valid and invalid fixtures ------------------------------


def _valid_request_and_response():
    token = "tok-1"
    request = executor_protocol.build_request(
        run_id="RUN-1",
        action_id="ACTION-1",
        attempt_id="ATTEMPT-1",
        attempt_token=token,
        node_id="NODE-1",
        node_contract_version=3,
        action_type="EXECUTE",
        resolved_inputs=[executor_protocol.ResolvedInput("ARTEFACT-1", 1, "sha256:in")],
        owned_scope_include=["src/**"],
        owned_scope_exclude=[".git/**"],
        base_commit="a1b2c3",
        worktree_id="WT-1",
        timeout_seconds=60,
        cancellation_token="cancel-1",
        budget_commitment={"dimension": "MODEL_COST", "hard_limit": 10},
        environment_version="fixture-v1",
    )
    response = {
        "run_id": "RUN-1",
        "action_id": "ACTION-1",
        "attempt_id": "ATTEMPT-1",
        "attempt_token": token,
        "self_reported_status": "COMPLETED",
        "artefacts": [
            {"type": "GIT_CANDIDATE", "reference": "commit-1", "content_hash": "sha256:out"}
        ],
        "observations": [
            {
                "type": "COMMAND_RESULT",
                "command_id": "BUILD",
                "exit_code": 0,
                "stdout_hash": "sha256:s",
                "stderr_hash": "sha256:e",
            }
        ],
        "changed_paths": ["src/app.txt"],
        "cost_report": {"committed": 10, "actual": 0, "units": "COST_UNITS"},
        "started_at": "t0",
        "finished_at": "t1",
        "executor_version": "command-executor/1",
        "response_schema_version": 1,
    }
    return request, response, token


def test_valid_protocol_fixture_passes_every_check():
    request, response, token = _valid_request_and_response()
    executor_protocol.validate_response(
        request,
        response,
        expected_token=token,
        producer_authority="command-executor",
        artefact_hashes={"commit-1": "sha256:out"},
        input_versions={"ARTEFACT-1": 1},
    )


@pytest.mark.parametrize(
    "mutate",
    [
        lambda r: r.__setitem__("self_reported_status", "SOMETIMES"),
        lambda r: r["artefacts"][0].__setitem__("type", "NOT_A_TYPE"),
        lambda r: r["observations"][0].__setitem__("type", "NOT_AN_OBSERVATION"),
        lambda r: r.__setitem__("attempt_token", "forged"),
        lambda r: r.__setitem__("attempt_id", "OTHER"),
        lambda r: r.__setitem__("run_id", "OTHER"),
        lambda r: r["changed_paths"].append("secrets/leak.txt"),
        lambda r: r.__setitem__("response_schema_version", 99),
        lambda r: r.pop("cost_report"),
        lambda r: r["cost_report"].pop("actual"),
    ],
    ids=[
        "unknown-status",
        "unknown-artefact-type",
        "unknown-observation-type",
        "token-mismatch",
        "attempt-mismatch",
        "run-mismatch",
        "out-of-scope-path",
        "unsupported-schema-version",
        "missing-cost-report",
        "missing-cost-field",
    ],
)
def test_invalid_protocol_fixtures_are_rejected(mutate):
    request, response, token = _valid_request_and_response()
    broken = copy.deepcopy(response)
    mutate(broken)
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.validate_response(
            request, broken, expected_token=token, producer_authority="command-executor"
        )


def test_artefact_hash_mismatch_is_rejected():
    request, response, token = _valid_request_and_response()
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.validate_response(
            request,
            response,
            expected_token=token,
            producer_authority="command-executor",
            artefact_hashes={"commit-1": "sha256:tampered"},
        )


def test_unimported_artefact_is_rejected():
    request, response, token = _valid_request_and_response()
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.validate_response(
            request,
            response,
            expected_token=token,
            producer_authority="command-executor",
            artefact_hashes={},
        )


def test_resolved_input_version_change_is_rejected():
    request, response, token = _valid_request_and_response()
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.validate_response(
            request,
            response,
            expected_token=token,
            producer_authority="command-executor",
            input_versions={"ARTEFACT-1": 2},
        )


def test_status_mapping_requires_result_checks_to_pass():
    assert (
        executor_protocol.map_status_to_attempt_state("COMPLETED", result_checks_pass=True)
        == "RESULT_PRODUCED"
    )
    assert (
        executor_protocol.map_status_to_attempt_state("COMPLETED", result_checks_pass=False)
        == "FAILED"
    )
    assert (
        executor_protocol.map_status_to_attempt_state("FAILED", result_checks_pass=True) == "FAILED"
    )
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.map_status_to_attempt_state("UNKNOWN", result_checks_pass=True)


def test_sandbox_violation_taxonomy_kinds():
    for kind in sandbox.VIOLATION_KINDS:
        assert sandbox.probe_violation(kind, {})["kind"] == kind
    with pytest.raises(ValueError):
        sandbox.probe_violation("NOT_A_KIND", {})


# -- recursive scope matching ---------------------------------------------------


def test_glob_match_supports_recursive_double_star():
    assert executor_protocol.glob_match("src/health/**", "src/health/api/routes.py")
    assert executor_protocol.glob_match("src/**", "src/a/x.py")
    assert executor_protocol.glob_match("hidden-tests/**", "hidden-tests/sub/t.py")
    assert executor_protocol.glob_match("**", "any/nested/path.py")
    # `**` matches zero segments too, so the directory root itself matches.
    assert executor_protocol.glob_match("src/health/**", "src/health")
    assert executor_protocol.glob_match("src/**", "src")
    # A single `*` does not cross a segment boundary.
    assert executor_protocol.glob_match("src/*.py", "src/a.py")
    assert not executor_protocol.glob_match("src/*.py", "src/sub/a.py")
    assert not executor_protocol.glob_match("src/**", "tests/a.py")


def test_path_in_scope_supports_nested_includes_and_excludes():
    includes = ["src/health/**"]
    excludes = [".git/**", ".orchestrator/**", "hidden-tests/**"]
    assert executor_protocol.path_in_scope("src/health/api/routes.py", includes, excludes)
    assert executor_protocol.path_in_scope("src/health", includes, excludes)
    assert not executor_protocol.path_in_scope("src/metrics/x.py", includes, excludes)
    # A recursive exclude is enforced on nested paths.
    assert not executor_protocol.path_in_scope("hidden-tests/sub/t.py", ["**"], excludes)
    assert not executor_protocol.path_in_scope(".git/config", ["**"], excludes)
    # A glob-free include naming a directory covers its subtree.
    assert executor_protocol.path_in_scope("src/health/api/routes.py", ["src/health"], excludes)


def test_controller_owned_scope_defaults_are_the_canonical_excludes(tmp_path):
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor
    from orchestrator.store import EventStore

    from helpers import build_run_config

    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = Controller(store, ScriptedExecutor({"RUN-DEF-root": lambda request: {
            "self_reported_status": "COMPLETED",
            "artefacts": [],
            "observations": [],
            "cost_report": {"committed": 1, "actual": 0, "units": "COST_UNITS"},
        }}))
        controller.submit_run(build_run_config("RUN-DEF"))
        attempt = controller.plan_attempt("RUN-DEF", "RUN-DEF-root", 1.0)
        controller.dispatch_attempt("RUN-DEF", attempt, "RUN-DEF-root")
        request = controller._dispatch_requests[attempt]
        assert request["owned_scope"]["exclude"] == list(
            executor_protocol.DEFAULT_OWNED_SCOPE_EXCLUDES
        )
    finally:
        store.close()
