# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-scope-as-non-transferable-across-re-authentication-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-scope-as-non-transferable-across-re-authentication-boundaries.warrant.json
# Markdown SHA-256:   63d1d840c5dd253bfbd481ecc60880152e6fb3bac5068f2330870e5dba6700bb
# Code AST SHA-256:   0565d0e262b89a578a283409603a961c1df6186c987e66bb6f5f2893f8f30577
# Verified Classes:   ScopeTransferViolation, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeTransferViolation(RuntimeError):
    """Raised when a memory scope would be inherited across an unstable or
    unproven identity boundary."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str          # durable principal id, issuer-guaranteed stable
    session_id: str       # rotates on every refresh -- MUST NOT enter scope key
    write_provenance_enforced: bool
    slot_reuse_enabled: bool


def derive_scope_key(cred: Credential) -> str:
    # Scope key is a function of the durable subject ONLY.
    # session_id is deliberately excluded.
    return hashlib.sha256(f"subject:{cred.subject}".encode()).hexdigest()


def resume_scope(cred: Credential, prior_scope_key: str | None) -> str:
    if not cred.write_provenance_enforced:
        raise ScopeTransferViolation(
            "cannot resume scope: write provenance not enforced; "
            "retrieved entries cannot be attributed to current subject"
        )
    if cred.slot_reuse_enabled:
        raise ScopeTransferViolation(
            "cannot resume scope: slot reuse enabled; reclaimed slots may alias "
            "another principal's residual entries"
        )

    new_key = derive_scope_key(cred)
    if prior_scope_key is not None and prior_scope_key != new_key:
        # The subject representation changed -> continuity break, not continuation.
        raise ScopeTransferViolation(
            f"scope key changed across session boundary "
            f"({prior_scope_key} -> {new_key}); refusing transfer, cold-start required"
        )
    return new_key


def establish_session(cred: Credential, prior_scope_key: str | None) -> str:
    try:
        return resume_scope(cred, prior_scope_key)
    except ScopeTransferViolation:
        # Prefer a detectable cold start over an undetectable inheritance.
        return derive_scope_key(cred)
