# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-every-litmus-sub-skill-probe-yet-fail-composition-scoring-at-the-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-every-litmus-sub-skill-probe-yet-fail-composition-scoring-at-the-seam.warrant.json
# Markdown SHA-256:   a2a348f4a666ef4e30ef5b35c9a7431eb6cc76c2769e7b2f1cefe9e86ca74173
# Code AST SHA-256:   6800c690ddb39476e68a4a20b896f040ee6ada12caf0127e1b4d1c8dcf2e3874
# Verified Classes:   UntypedSeamError, Skill, Chain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Sequence


class UntypedSeamError(RuntimeError):
    """Raised when a composition score is requested across an untyped handoff."""


@dataclass
class Skill:
    name: str
    predicate: Callable[[dict, dict], bool]   # (inherited_context, output) -> ok
    output_typed: bool                        # False if any free-text channel exists
    output_fields: Sequence[str] = field(default_factory=tuple)


@dataclass
class Chain:
    skills: Sequence[Skill]

    def seam_is_typed(self, i: int) -> bool:
        # A seam is typed only if the upstream skill has no untyped channel
        # AND no downstream predicate reads a field the upstream wrote.
        upstream, downstream = self.skills[i], self.skills[i + 1]
        if not upstream.output_typed:
            return False
        # Conservative: if downstream predicate references any upstream field
        # by name, the seam is semantic and must be probed jointly.
        return not set(upstream.output_fields) & set(downstream.output_fields)


def score_composition(chain: Chain, traces: Sequence[dict]) -> float:
    if len(chain.skills) < 2:
        raise UntypedSeamError("composition requires >= 2 skills")

    # Refuse the product-of-marginals shortcut across any untyped seam.
    for i in range(len(chain.skills) - 1):
        if not chain.seam_is_typed(i):
            raise UntypedSeamError(
                f"seam {chain.skills[i].name}->{chain.skills[i+1].name} is untyped; "
                f"product-of-marginals is an upper bound, not an estimate"
            )

    # Only reachable when every seam is typed: evaluate joint predicate on
    # the actual inherited context of each trace.
    passed = 0
    for trace in traces:
        ctx = trace["initial_context"]
        ok = True
        for skill in chain.skills:
            out = trace["outputs"][skill.name]
            if not skill.predicate(ctx, out):
                ok = False
                break
            ctx = {**ctx, **out}
        passed += int(ok)
    return passed / len(traces)
