# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-credentials-when-a-cross-org-attestation-chain-re-signs-a-sub-delegation-with-a-narrower-scope-than-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-credentials-when-a-cross-org-attestation-chain-re-signs-a-sub-delegation-with-a-narrower-scope-than-it.warrant.json
# Markdown SHA-256:   e77f3122e40822f78609746a7edaebc932944ab92e9d4755ce95949f7296e318
# Code AST SHA-256:   e05ba5a58c951f7a31903acc98435baa7c61c270ac4f6412fd5d18e9606f5ca8
# Verified Classes:   UnprovenScopeEdge, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnprovenScopeEdge(RuntimeError):
    """Raised when a cross-org re-signed edge cannot be witnessed as a narrowing."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: dict            # namespace-local capability claims
    namespace: str         # e.g. "orgA.files.v1" vs "orgB.report.v1"
    residual_claims: dict = field(default_factory=dict)  # claims of parent not representable here
    signature_valid: bool = True


def verify_edge(parent: Warrant, child: Warrant, shared_algebra: Optional[dict] = None) -> None:
    if not (parent.signature_valid and child.signature_valid):
        raise UnprovenScopeEdge("signature chain broken; cannot evaluate scope")

    # Path (a): shared-algebra containment proof
    if shared_algebra is not None and parent.namespace == child.namespace:
        for k, v in child.scope.items():
            if shared_algebra.get(k, {}).get("top") != v and parent.scope.get(k) != v:
                raise UnprovenScopeEdge(
                    f"child claim {k}={v!r} not contained in parent {parent.scope.get(k)!r}"
                )
        return

    # Path (b): cross-namespace requires explicit residual claims
    # and an issuer-signed non-requirement assertion for the child's operation.
    if parent.namespace != child.namespace:
        if not child.residual_claims:
            raise UnprovenScopeEdge(
                f"cross-namespace edge {parent.namespace}->{child.namespace} "
                f"has no residual_claims; normalization is lossy and cannot witness containment"
            )
        # The child's declared operation must not depend on any residual claim.
        required = child.scope.get("_requires", set())
        dropped = set(child.residual_claims.keys())
        overlap = required & dropped
        if overlap:
            raise UnprovenScopeEdge(
                f"child operation requires residual claims {sorted(overlap)} "
                f"that were dropped at the {parent.namespace}->{child.namespace} boundary"
            )
        return

    raise UnprovenScopeEdge("unreachable: namespace comparison failed")


# --- reproduction of the observed failure ---
W0 = Warrant(
    issuer="orgA.root", subject="a1",
    namespace="orgA.files.v1",
    scope={"files:read": "/data/tenant-*/reports", "tenant_allowlist": {"tenant-42"}},
)
# Re-signing at A->B boundary drops tenant_allowlist and emits NO residual set.
W1_lossy = Warrant(
    issuer="orgB.attestor", subject="b1",
    namespace="orgB.report.v1",
    scope={"report.read": "tenant-42/reports"},
    residual_claims={},   # <-- the bug: lossy projection with no residual
)
try:
    verify_edge(W0, W1_lossy)
except UnprovenScopeEdge as e:
    print("DENIED (correct):", e)

# Correct form: residual set names the dropped claim.
W1_safe = Warrant(
    issuer="orgB.attestor", subject="b1",
    namespace="orgB.report.v1",
    scope={"report.read": "tenant-42/reports", "_requires": {"tenant_allowlist"}},
    residual_claims={"tenant_allowlist": {"tenant-42"}},
)
try:
    verify_edge(W0, W1_safe)
except UnprovenScopeEdge as e:
    print("DENIED (operation depends on dropped claim):", e)
