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

Per AGENTS.md#change-rules every new event carries a catalogue entry, a
transition entry or explicit side-effect-only row, and a conformance entry:
the approval machine (``APPROVAL_REQUESTED`` / ``APPROVAL_GRANTED`` /
``APPROVAL_DENIED`` / ``APPROVAL_TIMED_OUT`` / ``APPROVAL_ESCALATED``) and the
credential machine (``CREDENTIAL_ISSUED`` / ``CREDENTIAL_RETIRED``), each with
its source-authority, unknown-event, and unknown-enum rules and the
reducer-level guards. The observability backend deliberately adds no event: it
is read-only over the audit output. The resolution-level cross-check in
tests/test_tables_agree_with_scripts.py covers the two new machines
automatically, and the conformance corpus records every transition of both.
"""

from __future__ import annotations

import tempfile

import pytest

from orchestrator import decisions, events, glossary, reducer, secrets, 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 _state():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state,
        _event(
            "NODE_PROPOSED",
            {"node_id": "n1", "contract": {"owned_scope": ["src/**"]}, "cause": "ROOT"},
        ),
    )
    return state


# -- approval events --------------------------------------------------------------


def test_approval_events_enforce_source_authority():
    state = _state()
    request = _event(
        "APPROVAL_REQUESTED",
        {"approval_id": "ap1", "node_id": "n1", "subject": "ACCEPTANCE", "deadline": 5.0},
    )
    events.validate_event(request)
    state, _ = reducer.reduce(state, request)

    granted = events.make_event(
        "APPROVAL_GRANTED", {"approval_id": "ap1", "decision_authority": "human"},
        idempotency_key="g", source="controller",
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(granted)
    events.validate_event(
        events.make_event("APPROVAL_GRANTED",
                          {"approval_id": "ap1", "decision_authority": "human"},
                          idempotency_key="g", source="approval")
    )
    timed = events.make_event(
        "APPROVAL_TIMED_OUT",
        {"approval_id": "ap1", "configured_deadline": 5.0, "observed_firing_time": 6.0},
        idempotency_key="t", source="controller",
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(timed)


def test_approval_unknown_event_and_unknown_subject_are_rejected():
    with pytest.raises(events.UnknownEventType):
        events.validate_event(
            _event("APPROVAL_REJECTED", {"approval_id": "ap1"})
        )
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            _event("APPROVAL_REQUESTED",
                   {"approval_id": "ap1", "node_id": "n1", "subject": "MAYBE", "deadline": 1.0})
        )
    assert "MAYBE" not in glossary.approval_subjects()
    assert set(glossary.approval_subjects()) == {
        "ACCEPTANCE", "PLAN_ADMITTANCE", "ROOT_REPLACEMENT", "BUDGET_EXCEPTION"
    }


def test_approval_machine_lifecycle_and_deadline_guard():
    table = tables.approval_table()
    assert table.resolve(None, "APPROVAL_REQUESTED").target == "PENDING"
    assert table.resolve("PENDING", "APPROVAL_GRANTED").target == "GRANTED"
    assert table.resolve("PENDING", "APPROVAL_DENIED").target == "DENIED"
    assert table.resolve("PENDING", "APPROVAL_TIMED_OUT").target == "TIMED_OUT"
    assert table.resolve("TIMED_OUT", "APPROVAL_ESCALATED").target == "ESCALATED"
    assert table.resolve("ESCALATED", "APPROVAL_GRANTED").target == "GRANTED"
    with pytest.raises(tables.UnknownTransition):
        table.resolve("GRANTED", "APPROVAL_GRANTED")
    with pytest.raises(tables.UnknownTransition):
        table.resolve("PENDING", "APPROVAL_ESCALATED")

    state = _state()
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_REQUESTED",
               {"approval_id": "ap1", "node_id": "n1", "subject": "ACCEPTANCE", "deadline": 5.0}),
    )
    with pytest.raises(ReducerError):
        reducer.reduce(
            state,
            _event("APPROVAL_TIMED_OUT",
                   {"approval_id": "ap1", "configured_deadline": 9.0,
                    "observed_firing_time": 10.0}),
        )
    with pytest.raises(ReducerError):
        reducer.reduce(
            state,
            _event("APPROVAL_REQUESTED",
                   {"approval_id": "ap2", "node_id": "ghost", "subject": "ACCEPTANCE",
                    "deadline": 5.0}),
        )


def test_approval_escalated_request_decided_only_by_escalated_authority():
    state = _state()
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_REQUESTED",
               {"approval_id": "ap1", "node_id": "n1", "subject": "ACCEPTANCE", "deadline": 5.0},
               idem="r"),
    )
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_TIMED_OUT",
               {"approval_id": "ap1", "configured_deadline": 5.0, "observed_firing_time": 6.0},
               idem="t", source="timer"),
    )
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_ESCALATED", {"approval_id": "ap1", "escalated_to": "duty-manager"},
               idem="e"),
    )
    with pytest.raises(ReducerError):
        reducer.reduce(
            state,
            _event("APPROVAL_GRANTED",
                   {"approval_id": "ap1", "decision_authority": "human-1"},
                   idem="g1", source="approval"),
        )
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_GRANTED",
               {"approval_id": "ap1", "decision_authority": "duty-manager"},
               idem="g2", source="approval"),
    )
    assert state.approvals["ap1"].state == "GRANTED"


def test_approval_late_events_after_terminal_state_are_retained():
    state = _state()
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_REQUESTED",
               {"approval_id": "ap1", "node_id": "n1", "subject": "ACCEPTANCE", "deadline": 5.0}),
    )
    state, _ = reducer.reduce(
        state,
        _event("APPROVAL_GRANTED",
               {"approval_id": "ap1", "decision_authority": "human"}, idem="g",
               source="approval"),
    )
    state, effects = reducer.reduce(
        state,
        _event("APPROVAL_DENIED",
               {"approval_id": "ap1", "decision_authority": "human"}, idem="d",
               source="approval"),
    )
    assert effects == [reducer.Effect("late_event_retained", {"approval_id": "ap1"})]


def test_approval_timeout_cannot_fire_before_the_recorded_deadline():
    import os
    import time as time_module

    from helpers import build_run_config

    from orchestrator.controller import Controller, WorkflowError
    from orchestrator.executor import ScriptedExecutor
    from orchestrator.store import EventStore

    with tempfile.TemporaryDirectory() as workdir:
        store = EventStore(os.path.join(workdir, "timeout.db"))
        try:
            controller = Controller(store, ScriptedExecutor({}))
            root = controller.submit_run(build_run_config("r1"))
            controller.request_approval("r1", root, approval_id="ap1",
                                        subject="BUDGET_EXCEPTION",
                                        deadline=time_module.time() + 3600.0)
            with pytest.raises(WorkflowError):
                controller.fire_approval_timeout("r1", "ap1")
            assert store.state("r1").approvals["ap1"].state == "PENDING"
        finally:
            store.close()


# -- credential events --------------------------------------------------------------


def test_credential_events_enforce_source_authority_and_scope_enum():
    issued = events.make_event(
        "CREDENTIAL_ISSUED",
        {"credential_id": "c1", "scope": "SANDBOX_BOUNDARY",
         "redacted_digest": "redacted:sha256:abc", "expires_at": 10.0},
        idempotency_key="i", source="controller",
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(issued)
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            events.make_event("CREDENTIAL_ISSUED",
                              {"credential_id": "c1", "scope": "EVERYWHERE",
                               "redacted_digest": "redacted:sha256:x", "expires_at": 10.0},
                              idempotency_key="i", source="secrets")
        )
    events.validate_event(
        events.make_event("CREDENTIAL_ISSUED",
                          {"credential_id": "c1", "scope": "SANDBOX_BOUNDARY",
                           "redacted_digest": "redacted:sha256:x", "expires_at": 10.0},
                          idempotency_key="i", source="secrets")
    )
    assert set(glossary.credential_scopes()) == {
        "SANDBOX_BOUNDARY", "EXECUTOR_BOUNDARY", "MODEL_ENDPOINT"
    }


def test_credential_machine_issuance_retirement_and_unknown_guard():
    table = tables.credential_table()
    assert table.resolve(None, "CREDENTIAL_ISSUED").target == "ACTIVE"
    assert table.resolve("ACTIVE", "CREDENTIAL_RETIRED").target == "RETIRED"
    with pytest.raises(tables.UnknownTransition):
        table.resolve("RETIRED", "CREDENTIAL_RETIRED")

    state = RunState(run_id="r1")
    with pytest.raises(ReducerError):
        reducer.reduce(
            state,
            _event("CREDENTIAL_RETIRED", {"credential_id": "ghost"}, idem="x"),
        )
    state, _ = reducer.reduce(
        state,
        _event("CREDENTIAL_ISSUED",
               {"credential_id": "c1", "scope": "EXECUTOR_BOUNDARY",
                "redacted_digest": "redacted:sha256:x", "expires_at": 10.0},
               idem="i", source="secrets"),
    )
    state, effects = reducer.reduce(
        state, _event("CREDENTIAL_RETIRED", {"credential_id": "c1"}, idem="r")
    )
    assert state.credentials["c1"].state == "RETIRED"
    state, effects = reducer.reduce(
        state, _event("CREDENTIAL_RETIRED", {"credential_id": "c1"}, idem="r2")
    )
    assert effects == [reducer.Effect("late_event_retained", {"credential_id": "c1"})]


# -- secrets boundary audits ----------------------------------------------------------


def test_secrets_boundaries_refuse_wrong_scope_expiry_and_raw_secrets():
    source = secrets.SecretsSource()
    sandbox_credential = source.issue("SANDBOX_BOUNDARY", credential_id="sb", ttl_seconds=60)
    executor_credential = source.issue("EXECUTOR_BOUNDARY", credential_id="eb", ttl_seconds=60)
    assert secrets.redact_digest("s").startswith("redacted:sha256:")

    base = {"PATH": "/usr/bin:/bin"}
    env = secrets.sandbox_environment_with(sandbox_credential, base)
    secrets.audit_sandbox_boundary(sandbox_credential, env, base_allowlist=base)
    with pytest.raises(secrets.CredentialRefused):
        secrets.audit_sandbox_boundary(executor_credential, env, base_allowlist=base)
    with pytest.raises(secrets.CredentialRefused):
        secrets.audit_sandbox_boundary(
            sandbox_credential, {**env, "AMBIENT_TOKEN": "leak"}, base_allowlist=base
        )
    expired = source.issue("SANDBOX_BOUNDARY", credential_id="old", ttl_seconds=1)
    assert not source.active(expired, at=expired.expires_at + 1)
    with pytest.raises(secrets.CredentialRefused):
        source.require_active(expired, at=expired.expires_at + 1)

    request = {"attempt_token": "t", "credential_digest": executor_credential.redacted_digest}
    secrets.audit_executor_boundary(executor_credential, request)
    with pytest.raises(secrets.CredentialRefused):
        secrets.audit_executor_boundary(sandbox_credential, request)
    with pytest.raises(secrets.CredentialRefused):
        secrets.audit_executor_boundary(
            executor_credential, {"note": f"token={executor_credential.secret}"}
        )
    redacted = secrets.redact_deep({"stdout": f"ran with {executor_credential.secret}"},
                                   [executor_credential])
    assert executor_credential.secret not in redacted["stdout"]
    assert executor_credential.redacted_digest in redacted["stdout"]


def test_every_new_event_is_catalogued_with_a_transition_and_conformance_entry():
    from orchestrator import conformance
    from orchestrator import tables as tables_module

    for event_type in (
        "APPROVAL_REQUESTED", "APPROVAL_GRANTED", "APPROVAL_DENIED",
        "APPROVAL_TIMED_OUT", "APPROVAL_ESCALATED",
        "CREDENTIAL_ISSUED", "CREDENTIAL_RETIRED",
    ):
        assert event_type in events.EVENT_CATALOGUE, event_type
    machines = set()
    for spec in events.EVENT_CATALOGUE.values():
        machines.update(spec.affected_machines)
    assert "approval" in machines and "credential" in machines
    # The conformance corpus records every transition of both new machines.
    for filename in ("approval-lifecycle.yaml", "credential-lifecycle.yaml"):
        table = tables_module.load(filename)
        for rows in table._explicit.values():
            for row in rows:
                assert (
                    (table.machine, row.source, row.event)
                    in conformance.TransitionCoverage().declared()
                ), (table.machine, row.source, row.event)


def test_deferred_decisions_are_recorded_with_real_model_conditions():
    assert decisions.SCRIPTED_EVIDENCE_LIMIT.startswith(
        "A deterministic scripted client differentiates orchestration structure"
    )
    resolved = {
        "EVENT_STORE", "DISPATCH_SUBSTRATE", "OBSERVABILITY_BACKEND",
        "HUMAN_APPROVAL_SURFACE", "SECRETS_MANAGEMENT", "MODEL_PROVIDER_ABSTRACTION",
    }
    decisions_by_id = {decision.decision_id: decision for decision in decisions.DEFERRED_DECISIONS}
    assert resolved <= set(decisions_by_id)
    for decision_id in resolved:
        decision = decisions_by_id[decision_id]
        assert decision.status == "RESOLVED"
        assert decision.real_model_conditions, decision_id
    assert decisions_by_id["REAL_MODEL_MEASURED_RUNS"].status == "EXCLUDED"
    assert decisions_by_id["MULTI_MODEL_ROUTING"].status == "EXCLUDED"
    assert decisions.deferred_decision("EVENT_STORE").resolution.startswith(
        "SQLite in WAL mode is retained"
    )
