# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-ttl-expiry-as-a-silent-read-miss-versus-a-hard-authorization-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-ttl-expiry-as-a-silent-read-miss-versus-a-hard-authorization-fault.warrant.json
# Markdown SHA-256:   047192cf230134ae8d3383f3a820437cf5f49defd0a1cbddc8804e6b26cd3b32
# Code AST SHA-256:   6e22f2b532dc830511283d5e2f2be7d91fbc426a5ca42c5240aab5b96172a28d
# Verified Classes:   MemoryBoundaryViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class MemoryBoundaryViolation(RuntimeError):
    """Raised when a read-miss is repaired by a write without proving the miss was an expiry."""
    pass


def resolve_miss(tool, key: str, caller: str, rederive_fn) -> dict:
    """
    Resolve a read-miss on `key` without laundering an ACL denial into a freshness event.

    Invariant: a write under `caller` is permitted only if the capability probe
    proves `read` is allowed on the key's namespace. Otherwise we refuse.
    """
    probe = tool.capability(namespace_of(key), principal=caller)
    read_allowed = bool(probe.get("read", False))
    write_allowed = bool(probe.get("write", False))

    if not read_allowed:
        # Denial, not expiry. The record may be alive and invisible to us.
        # Never re-derive, never write: that would launder the boundary.
        raise MemoryBoundaryViolation(
            f"read-miss on {key!r} for {caller!r} is an authorization fault, "
            f"not an expiry; refusing to re-derive or overwrite"
        )

    if not write_allowed:
        # Expiry confirmed, but we cannot persist the rebuild. Surface it.
        raise MemoryBoundaryViolation(
            f"read-miss on {key!r} is an expiry, but {caller!r} lacks write; "
            f"cannot checkpoint the re-derived value"
        )

    value, provenance_ok = rederive_fn()
    if not provenance_ok:
        # Rebuild succeeded but provenance was lost: mark it, do not silently overwrite.
        tool.write(key, value, principal=caller, meta={"provenance": "reconstructed"})
        return {"status": "reconstructed", "key": key}

    tool.write(key, value, principal=caller, meta={"provenance": "reobserved"})
    return {"status": "reobserved", "key": key}
