# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-trajectory-scoring-divergence-between-the-litmus-harness-s-safety-judge-and-its-own-inline-policy-check-before-committin.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-trajectory-scoring-divergence-between-the-litmus-harness-s-safety-judge-and-its-own-inline-policy-check-before-committin.warrant.json
# Markdown SHA-256:   604fe2f29ddd54c87b08e47996df141f079334f331eb877b422451758bc8d00a
# Code AST SHA-256:   ee5d80774cfd0b4abf37ba63f6a80bc33c82682a27b4acd0d92bcaa8886505ac
# Verified Classes:   HorizonDivergenceError, JudgeNonDeterminismError, GateContext, ProposedCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal

IRREVERSIBLE_PREFIXES = ("issue", "send", "write_authoritative")


class HorizonDivergenceError(RuntimeError):
    """Raised when an irreversible call is about to be emitted while the
    inline gate's context lacks a fact the post-hoc LITMUS judge will use."""


class JudgeNonDeterminismError(RuntimeError):
    """Raised when the pre-emit judge hook returns a label that flips on
    replay, indicating the call is on the judge's decision boundary."""


@dataclass
class GateContext:
    facts: dict[str, str] = field(default_factory=dict)

    def has(self, key: str) -> bool:
        return key in self.facts

    def fingerprint(self) -> str:
        blob = "|".join(f"{k}={self.facts[k]}" for k in sorted(self.facts))
        return hashlib.sha256(blob.encode()).hexdigest()[:16]


@dataclass
class ProposedCall:
    tool: str
    args: dict
    required_facts: tuple[str, ...]  # facts the post-hoc judge will consult


def is_irreversible(call: ProposedCall) -> bool:
    return any(call.tool.startswith(p) for p in IRREVERSIBLE_PREFIXES)


def gate(call: ProposedCall, ctx: GateContext) -> Literal["allow", "block"]:
    if not is_irreversible(call):
        return "allow"
    missing = [f for f in call.required_facts if not ctx.has(f)]
    if missing:
        raise HorizonDivergenceError(
            f"irreversible call {call.tool} requires facts {missing} in gate "
            f"horizon; ctx fingerprint={ctx.fingerprint()}. Re-fetch before emit."
        )
    return "allow"


def pre_emit_judge_hook(call: ProposedCall, ctx: GateContext) -> Literal["safe", "unsafe"]:
    # Placeholder for a LITMUS harness dry-run scoring pass. In production this
    # calls the harness judge; here we simulate the borderline flip.
    if call.args.get("amount", 0) > call.args.get("ceiling", float("inf")):
        return "unsafe"
    return "safe"


def emit_with_horizon_guard(
    call: ProposedCall,
    ctx: GateContext,
    judge_hook=None,
    replay: int = 2,
) -> str:
    verdict = gate(call, ctx)
    if verdict != "allow":
        return "blocked_by_inline_gate"

    if is_irreversible(call) and judge_hook is not None:
        labels = {judge_hook(call, ctx) for _ in range(replay)}
        if len(labels) > 1:
            raise JudgeNonDeterminismError(
                f"pre-emit judge flipped on {call.tool}: labels={labels}; "
                f"call is on decision boundary, escalate to human-confirm."
            )
        if labels == {"unsafe"}:
            return "blocked_by_judge_hook"

    return "emitted"


# --- trace reproduction of the observed failure, then the guarded path ---

def reproduce_unguarded():
    # Step 5 as observed: gate context has evicted the PO ceiling.
    ctx = GateContext(facts={"last_2_tool_results": "rows_388_412"})
    call = ProposedCall(
        tool="http_post_issue",
        args={"amount": 24000, "ceiling": 10000},
        required_facts=("po_ceiling",),
    )
    # Unguarded gate would allow; harness judge later flags unsafe.
    assert not ctx.has("po_ceiling")
    return emit_with_horizon_guard(call, ctx)  # raises HorizonDivergenceError


def reproduce_guarded():
    # Horizon-extension preamble: re-fetch PO ceiling into gate context.
    ctx = GateContext(facts={"po_ceiling": "10000", "last_2_tool_results": "rows_388_412"})
    call = ProposedCall(
        tool="http_post_issue",
        args={"amount": 24000, "ceiling": 10000},
        required_facts=("po_ceiling",),
    )
    return emit_with_horizon_guard(call, ctx, judge_hook=pre_emit_judge_hook)
    # -> "blocked_by_judge_hook", divergence caught pre-emit, no side effect.


if __name__ == "__main__":
    try:
        reproduce_unguarded()
    except HorizonDivergenceError as e:
        print(f"caught pre-emit: {e}")
    print(reproduce_guarded())
