# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-delegated-capability-scope-but-the-downstream-tool-cache-replays-a-pre-attenuation-result.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-a-delegated-capability-scope-but-the-downstream-tool-cache-replays-a-pre-attenuation-result.warrant.json
# Markdown SHA-256:   decabfaef50911326b59a13b217fa2aaf87db841cd75748ead022a989c58c67a
# Code AST SHA-256:   60d205b391cbd789f6624c3e4daeb52b144124d108374cbaf17e3a238942fbec
# Verified Classes:   ScopeReplayViolation, CachedResult, ScopeAwareCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeReplayViolation(RuntimeError):
    """Raised when a cached tool result would be admitted under a scope
    broader than the one it was produced under, or when canonicalization
    is not idempotent across the cache/auth boundary."""
    pass


def canonicalize_path(p: str) -> str:
    # Single canonicalization shared by cache keyer AND scope gate.
    parts = []
    for seg in p.split("/"):
        if seg in ("", "."):
            continue
        if seg == "..":
            if parts:
                parts.pop()
            continue
        parts.append(seg)
    return "/" + "/".join(parts)


def scope_covers(scope: str, canonical_path: str) -> bool:
    # scope like "/workspace/public/**"
    prefix = scope.rstrip("*").rstrip("/")
    return canonical_path == prefix or canonical_path.startswith(prefix + "/")


@dataclass(frozen=True)
class CachedResult:
    tool: str
    canonical_args: str
    writer_scope: str
    payload: str


class ScopeAwareCache:
    def __init__(self):
        self._store: dict[tuple[str, str], CachedResult] = {}

    def put(self, tool: str, raw_args: str, writer_scope: str, payload: str) -> None:
        canon = canonicalize_path(raw_args)
        # Idempotence invariant: re-canonicalizing must be a no-op.
        if canonicalize_path(canon) != canon:
            raise ScopeReplayViolation(
                f"non-idempotent canonicalization for {raw_args!r} -> {canon!r}"
            )
        self._store[(tool, canon)] = CachedResult(tool, canon, writer_scope, payload)

    def get(self, tool: str, raw_args: str, reader_scope: str) -> str | None:
        canon = canonicalize_path(raw_args)
        entry = self._store.get((tool, canon))
        if entry is None:
            return None
        # Admission check: writer scope must be a subset of reader scope.
        # We approximate subset by requiring reader_scope to cover the
        # canonical target AND the writer scope to be no broader than reader.
        if not scope_covers(reader_scope, entry.canonical_args):
            raise ScopeReplayViolation(
                f"cache hit for {canon!r} denied: entry written under "
                f"{entry.writer_scope!r}, reader scope {reader_scope!r}"
            )
        if entry.writer_scope != reader_scope and not _scope_subset(
            entry.writer_scope, reader_scope
        ):
            raise ScopeReplayViolation(
                f"scope-tag mismatch: writer {entry.writer_scope!r} not "
                f"subset of reader {reader_scope!r}"
            )
        return entry.payload


def _scope_subset(a: str, b: str) -> bool:
    a_prefix = a.rstrip("*").rstrip("/")
    b_prefix = b.rstrip("*").rstrip("/")
    return a_prefix == b_prefix or a_prefix.startswith(b_prefix + "/")


def child_read(cache: ScopeAwareCache, path: str, child_scope: str) -> str:
    hit = cache.get("fs.read", path, child_scope)
    if hit is not None:
        return hit
    if not scope_covers(child_scope, canonicalize_path(path)):
        raise ScopeReplayViolation(
            f"live dispatch denied: {canonicalize_path(path)!r} "
            f"outside {child_scope!r}"
        )
    return f"<fresh read of {canonicalize_path(path)}>"


if __name__ == "__main__":
    c = ScopeAwareCache()
    c.put("fs.read", "/workspace/secret/keys.env", "/workspace/**", "SECRET")
    try:
        child_read(c, "/workspace/secret/keys.env", "/workspace/public/**")
    except ScopeReplayViolation as e:
        print("blocked:", e)
