# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-workload-identity-binding-has-silently-detached-from-its-execution-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-workload-identity-binding-has-silently-detached-from-its-execution-context.warrant.json
# Markdown SHA-256:   59e5f1cb2e130d96fdd7166afbed4b3f5653cb4fd208960387e6529062e382c4
# Code AST SHA-256:   f0b06a564f5dc62edee17108753a800858da31c9eaff8b39bc29397afcd9cf36
# Verified Classes:   BindingDetachedError, ExecutionContext, WorkloadCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class BindingDetachedError(RuntimeError):
    """Raised when an AAIF workload credential is valid but no longer bound
    to the live execution context presenting it."""
    pass


@dataclass(frozen=True)
class ExecutionContext:
    node_id: str
    process_start_ns: int
    boot_nonce: str

    def ctx_id(self) -> str:
        raw = f"{self.node_id}|{self.process_start_ns}|{self.boot_nonce}"
        return hashlib.sha256(raw.encode()).hexdigest()[:32]


@dataclass(frozen=True)
class WorkloadCredential:
    subject: str
    audience: str
    ctx_id: str          # context the credential was attested for
    not_after: float     # epoch seconds


def assert_binding_live(
    cred: WorkloadCredential,
    live_ctx: ExecutionContext,
    audience: str,
    liveness_registry: dict[str, set[str]],
    now: float | None = None,
) -> None:
    """Gate a mutating tool call on binding liveness, not just validity."""
    now = time.time() if now is None else now

    if now >= cred.not_after:
        raise BindingDetachedError(
            f"credential for {cred.subject} expired at {cred.not_after}"
        )

    if cred.audience != audience:
        raise BindingDetachedError(
            f"audience mismatch: cred={cred.audience} expected={audience}"
        )

    recomputed = live_ctx.ctx_id()
    if cred.ctx_id != recomputed:
        # Credential is cryptographically valid but was minted for a
        # different execution context. This is the detach condition:
        # a resumed/forked/migrated process inherited a credential it
        # did not attest for.
        raise BindingDetachedError(
            f"binding detached: cred ctx_id={cred.ctx_id} "
            f"live ctx_id={recomputed} subject={cred.subject}"
        )

    competitors = liveness_registry.get(cred.subject, set()) - {recomputed}
    if competitors:
        # Another live context asserts the same workload subject.
        # Sole-liveness invariant violated; mutating calls must halt.
        raise BindingDetachedError(
            f"workload {cred.subject} has {len(competitors)} competing "
            f"live context(s): {sorted(competitors)}"
        )


def guarded_tool_call(
    cred: WorkloadCredential,
    live_ctx: ExecutionContext,
    audience: str,
    liveness_registry: dict[str, set[str]],
    is_mutating: bool,
) -> str:
    if is_mutating:
        assert_binding_live(cred, live_ctx, audience, liveness_registry)
        return "mutating call admitted"
    # pure reads may proceed under validity-only checking
    return "read admitted (validity-only)"
