# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-advertisement-forgery-in-cross-org-agent-federation-and-where-trust-brokering-silently-accepts-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-advertisement-forgery-in-cross-org-agent-federation-and-where-trust-brokering-silently-accepts-it.warrant.json
# Markdown SHA-256:   312234b2276b9bd69fbb4e8c229e00a33adca978167d76e88096954bc2f1322d
# Code AST SHA-256:   d05df16c0ca4ba1f0c8230aa0257b5227e1438ba32ac90fdf7dfc2d24f1701cd
# Verified Classes:   StructuralForgeryError, CapabilityAdvertisement
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StructuralForgeryError(RuntimeError):
    """Raised when an advertised capability set is schema-valid but structurally unrealizable."""
    pass


# Closed side-effect vocabulary that imply external I/O.
EXTERNAL_SIDE_EFFECTS = {"read:external", "write:external", "net:egress", "net:ingress"}


@dataclass
class CapabilityAdvertisement:
    capability: str
    side_effects: list[str]
    max_external_calls: Optional[int]
    max_wall_clock_s: int
    attestation_scope: list[str]
    terminal: bool = False
    output_types: list[str] = field(default_factory=list)


def assert_structurally_realizable(adv: CapabilityAdvertisement) -> None:
    """
    Enforce the structural-realizability invariant on an admitted advertisement.
    Runs AFTER signature verification, BEFORE trust scoring.
    A structurally impossible advertisement is never a false positive.
    """
    # Signal 1: side-effect / envelope contradiction.
    declares_external = bool(set(adv.side_effects) & EXTERNAL_SIDE_EFFECTS)
    if declares_external and adv.max_external_calls == 0:
        raise StructuralForgeryError(
            f"capability {adv.capability!r} declares external side-effects "
            f"{sorted(set(adv.side_effects) & EXTERNAL_SIDE_EFFECTS)} but envelope "
            f"forbids external calls (max_external_calls=0). Structurally impossible."
        )

    # Signal 4: attestation-scope mismatch (valid signature, wrong subject).
    if adv.capability not in adv.attestation_scope:
        raise StructuralForgeryError(
            f"capability {adv.capability!r} is not covered by attestation scope "
            f"{adv.attestation_scope}. Signature may verify but signs a different claim."
        )

    # Signal 2: terminal sink emitting unconsumable / empty output set.
    if adv.terminal and not adv.output_types:
        raise StructuralForgeryError(
            f"capability {adv.capability!r} claims terminal=true but declares no "
            f"output types; a real graph sink emits a terminal type."
        )

    # Signal 3: envelope monotonicity is checked by the caller against the parent
    # capability; here we only assert the local envelope is non-degenerate.
    if adv.max_wall_clock_s <= 0:
        raise StructuralForgeryError(
            f"capability {adv.capability!r} declares non-positive wall clock envelope."
        )


def admit(adv: CapabilityAdvertisement, trust_score: float, threshold: float = 0.70) -> bool:
    # Structural check precedes trust scoring so a high score cannot mask impossibility.
    assert_structurally_realizable(adv)
    return trust_score >= threshold


if __name__ == "__main__":
    forged = CapabilityAdvertisement(
        capability="document.summarize",
        side_effects=["read:external"],
        max_external_calls=0,          # contradicts read:external
        max_wall_clock_s=30,
        attestation_scope=["document.summarize"],
    )
    try:
        admit(forged, trust_score=0.81)  # high trust must NOT rescue it
    except StructuralForgeryError as e:
        print(f"REJECTED at admission: {e}")
