# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-task-handoff-when-a-trust-broker-s-capability-attestation-is-valid-but-scope-narrowed-relative-t.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-task-handoff-when-a-trust-broker-s-capability-attestation-is-valid-but-scope-narrowed-relative-t.warrant.json
# Markdown SHA-256:   2159811a0635c4110bbb6e6c82e34f02dd1c834ad17f81187604917f93d5ed44
# Code AST SHA-256:   bda27cd61d4524e2a06f30f8d20da3c70db067aa6d9a98fba0cbaa9e5a2301d9
# Verified Classes:   ScopeNarrowedHandoffError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ScopeNarrowedHandoffError(RuntimeError):
    """Raised when a federated handoff is dispatched despite the executor's
    attested capability scope not covering the payload's tool invocations."""
    pass


def verify_handoff_admissible(attestation: dict, payload: dict) -> None:
    """Pre-handoff conjunctive scope check. Must be evaluated by the requester
    before committing state transfer, and re-evaluated by the executor at admission.
    Fails closed on any constraint the caller cannot interpret."""
    constraints = attestation.get("constraints", {})
    invocations = payload.get("invocations", [])

    if attestation.get("schema_version") not in ("1.2", "1.3"):
        raise ScopeNarrowedHandoffError(
            f"unparseable attestation schema {attestation.get('schema_version')!r}; "
            "refusing handoff rather than assuming unconstrained"
        )

    for inv in invocations:
        cap = inv["capability"]
        if cap not in constraints:
            continue  # capability attested without narrowing
        c = constraints[cap]
        if cap == "fs.write":
            target = inv["args"]["path"]
            prefix = c.get("prefix")
            if prefix is None or not target.startswith(prefix):
                raise ScopeNarrowedHandoffError(
                    f"fs.write target {target!r} outside attested prefix {prefix!r}"
                )
        elif cap == "shell.exec":
            cmd = inv["args"]["command"].split()[0]
            allow = c.get("allowlist", [])
            if cmd not in allow:
                raise ScopeNarrowedHandoffError(
                    f"shell.exec command {cmd!r} not in attested allowlist {allow!r}"
                )
        elif cap == "http.fetch":
            host = inv["args"]["url"].split("/")[2]
            domains = c.get("domains", [])
            if not any(host == d or host.endswith("." + d.lstrip("*.")) for d in domains):
                raise ScopeNarrowedHandoffError(
                    f"http.fetch host {host!r} outside attested domains {domains!r}"
                )
        else:
            raise ScopeNarrowedHandoffError(
                f"unknown constraint type for capability {cap!r}; fail closed"
            )


def route_subtask(candidates: list[dict], payload: dict) -> dict:
    """Scope-aware routing: only dispatch to an executor whose attestation
    provably covers the payload. Terminal on ScopeNarrowedHandoffError."""
    for cand in candidates:
        try:
            verify_handoff_admissible(cand["attestation"], payload)
        except ScopeNarrowedHandoffError:
            continue  # narrow executor; skip, do NOT retry same payload here
        return cand
    raise ScopeNarrowedHandoffError(
        "no candidate in federation attests scope covering payload; "
        "escalate for re-attestation or contract narrowing — do not rewrite subtask"
    )
