# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-cross-issuer-trust-chain-in-federated-agent-capability-registries-when-manifest-re-signing-silently-voids-tr.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-cross-issuer-trust-chain-in-federated-agent-capability-registries-when-manifest-re-signing-silently-voids-tr.warrant.json
# Markdown SHA-256:   937fecbc3e91de2c2da6c6a522326e6e098c1c9e7139bde4e716c6d14995b639
# Code AST SHA-256:   71badfb100520946e14c9bfeac4f1cd0d03bdc602b5d58a6aba1b8178b316de7
# Verified Classes:   DelegationChainError, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when a manifest's signature chain cannot be reconstructed
    to match the original delegating issuer's signed semantics."""


@dataclass
class Manifest:
    issuer: str
    scope_definition_hash: str
    constraints: dict
    delegation_depth: int
    signatures: list = field(default_factory=list)  # list of issuer ids
    original_bytes_preserved: bool = False


def validate_transitive_manifest(
    manifest: Manifest,
    defining_issuer_for_scope: str,
    defining_scope_hash: str,
    parent_constraints: Optional[dict],
    trust_root: str,
) -> None:
    # (a) chain reconstruction: depth must match distinct issuer count
    distinct_issuers = list(dict.fromkeys(manifest.signatures))
    if manifest.delegation_depth > len(distinct_issuers):
        raise DelegationChainError(
            f"asserted depth {manifest.delegation_depth} exceeds "
            f"chain length {len(distinct_issuers)} for {manifest.issuer}"
        )

    # (b) scope-definition hash must match the *defining* namespace
    if manifest.scope_definition_hash != defining_scope_hash:
        raise DelegationChainError(
            f"scope hash {manifest.scope_definition_hash} does not match "
            f"defining issuer {defining_issuer_for_scope} hash {defining_scope_hash}"
        )

    # (c) constraint set must not widen relative to nearest ancestor
    if parent_constraints is not None:
        widened = {
            k: v for k, v in manifest.constraints.items()
            if k not in parent_constraints
            or parent_constraints[k] != v
        }
        if widened:
            raise DelegationChainError(
                f"constraint widening detected for {manifest.issuer}: {widened}"
            )

    # (d) re-signing must be attestation, not re-issuance
    if not manifest.original_bytes_preserved:
        raise DelegationChainError(
            f"manifest from {manifest.issuer} re-signed without preserving "
            f"original bytes; delegation chain unverifiable"
        )
