# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-write-time-provenance-attestation-as-insufficient-to-detect-memory-poisoning-and-re-derive-trust-at-read-time.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-write-time-provenance-attestation-as-insufficient-to-detect-memory-poisoning-and-re-derive-trust-at-read-time.warrant.json
# Markdown SHA-256:   6bcf37a604077a8b6b21dfca2d24794f5d0a700cc2e5f6e0eb554219d053d91e
# Code AST SHA-256:   f064b798e3e2ec64be59e240829a77d3f79bb4d9946c3a66f3a758368c433ec4
# Verified Classes:   UnboundAttestationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnboundAttestationError(RuntimeError):
    """Raised when a memory record is served as verified on write-time
    provenance alone, without content binding or verified lineage."""
    pass


def admit_for_action(record: dict, now: float) -> bool:
    """
    Read-time trust gate. Returns True only if the record may influence
    action as *verified*. Write-time attestation alone is insufficient.
    """
    env = record.get("attestation", {})
    if not env.get("signature") or not env.get("writer_id"):
        raise UnboundAttestationError(
            f"record {record.get('id')} has no valid write envelope"
        )

    # 1. Does the attestation bind the semantic claim, or only the write event?
    content_bound = env.get("binds_claim") is True and env.get("claim_hash") == record.get("claim_hash")

    # 2. Was every upstream tool deterministic and internally sourced?
    chain_closed = env.get("tool_chain_closed") is True

    # 3. Is lineage empty or fully trusted (no quarantined/unverified ancestor)?
    lineage = record.get("derived_from", [])
    lineage_trusted = all(a.get("trust") == "verified" for a in lineage)

    # 4. Is the attestation still valid under current authority and time?
    authority_valid = (
        env.get("writer_authorized_for_claim_class") is True
        and now < env.get("authority_expires_at", float("inf"))
    )

    if content_bound and chain_closed and lineage_trusted and authority_valid:
        return True

    # Attested but not trusted: must re-derive before serving as verified.
    if not content_bound:
        raise UnboundAttestationError(
            f"record {record.get('id')} attestation does not bind the claim; "
            "write-time provenance cannot substitute for read-time verification"
        )
    # Otherwise: demote to 'attested', require fresh source verification.
    record["trust"] = "attested"
    return False
