# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-brokered-federated-task-when-policy-translation-silently-widens-its-local-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-brokered-federated-task-when-policy-translation-silently-widens-its-local-capability-envelope.warrant.json
# Markdown SHA-256:   a4dcd2a3f46039ca253ac34d353cca580c0984231758e4d089f8bce29d9f1acb
# Code AST SHA-256:   500f85bef2a23ea5e4c914327d8dbdc95a4ae8865f62e387c923570a5c996364
# Verified Classes:   CapabilityWideningError, BrokeredGrant
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

# Fields whose absence, under a permissive local default, silently widens scope.
SECURITY_RELEVANT = ("path_scope", "mode", "expiry")

# Local engine defaults: what an absent field resolves to if we proceed.
LOCAL_DEFAULTS = {
    "path_scope": "*",      # whole writable sandbox -- permissive
    "mode": "append",
    "expiry": None,         # no expiry -- permissive
}

# A sentinel the broker must emit to prove it engaged with the field.
EXPLICIT_UNSET = "<explicit-unset>"


class CapabilityWideningError(RuntimeError):
    """Raised when a brokered grant would widen scope via an absent field."""


@dataclass
class BrokeredGrant:
    capability: str
    target: str
    fields: dict = field(default_factory=dict)


def ingest_brokered_grant(grant: BrokeredGrant) -> dict:
    """Validate a broker-translated grant before the instance executes it.

    Refuses when a security-relevant field is absent AND the local default
    for that field is broader than deny-all, because the instance cannot
    distinguish a dropped field from a foreign deny-all intent.
    """
    resolved = {}
    widened = []

    for name in SECURITY_RELEVANT:
        if name in grant.fields:
            value = grant.fields[name]
            if value == EXPLICIT_UNSET:
                # Broker engaged with the field and declared it unset: deny.
                resolved[name] = None
                continue
            resolved[name] = value
            continue

        # Field is absent. Check whether the local default widens scope.
        default = LOCAL_DEFAULTS[name]
        if default not in (None, ""):
            widened.append((name, default))
        resolved[name] = default

    if widened:
        detail = ", ".join(f"{n}->{d!r}" for n, d in widened)
        raise CapabilityWideningError(
            f"grant for capability={grant.capability!r} target={grant.target!r} "
            f"is missing security-relevant fields that default permissively: {detail}. "
            f"Refusing: broker must materialize these fields or emit "
            f"{EXPLICIT_UNSET!r} to signal deny."
        )

    return resolved


def route_federated_task(grant: BrokeredGrant) -> str:
    resolved = ingest_brokered_grant(grant)
    return f"executing {grant.capability} under scope={resolved['path_scope']!r}"


# Widening case: path_scope absent, local default is the whole sandbox.
widening_grant = BrokeredGrant(
    capability="write_file",
    target="/scratch/run_4471",
    fields={"mode": "append"},  # path_scope omitted by structural copy
)

try:
    route_federated_task(widening_grant)
except CapabilityWideningError as e:
    print("REFUSED:", e)

# Safe case: broker materialized the field with an explicit sentinel.
safe_grant = BrokeredGrant(
    capability="write_file",
    target="/scratch/run_4471",
    fields={"path_scope": EXPLICIT_UNSET, "mode": "append"},
)
print(route_federated_task(safe_grant))
