# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-composition-score-that-aggregates-per-skill-safety-margins-across-a-shared-capability-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-composition-score-that-aggregates-per-skill-safety-margins-across-a-shared-capability-surface.warrant.json
# Markdown SHA-256:   bd7f5f42aa4cce319a5f06c80b5ae83c21cd2472f09c927096b6b6fea16f7310
# Code AST SHA-256:   902df53dc407e98c525353b977506800c0b79973d65c9b9843674b70656543ce
# Verified Classes:   CompositionScoreMisapplied, CapabilitySurface, SkillMargin, CompositionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet


class CompositionScoreMisapplied(RuntimeError):
    """Raised when a LITMUS composition score is used to gate a task whose
    capability surface is not covered by the surfaces the constituent
    per-skill margins were probed on."""


@dataclass(frozen=True)
class CapabilitySurface:
    write_prefixes: FrozenSet[str]
    read_prefixes: FrozenSet[str]
    env_keys: FrozenSet[str]
    namespaces: FrozenSet[str]  # e.g. "fs", "net", "proc"

    def overlaps(self, other: "CapabilitySurface") -> bool:
        if self.namespaces & other.namespaces:
            # shared namespace implies potential shared state
            return True
        if self.write_prefixes & other.read_prefixes:
            return True
        if other.write_prefixes & self.read_prefixes:
            return True
        if self.env_keys & other.env_keys:
            return True
        return False


@dataclass(frozen=True)
class SkillMargin:
    skill_id: str
    margin: float
    probed_surface: CapabilitySurface


@dataclass
class CompositionGate:
    margins: dict[str, SkillMargin] = field(default_factory=dict)

    def admit_task(self, skill_ids: list[str]) -> float:
        if not skill_ids:
            raise CompositionScoreMisapplied("empty task chain has no surface")
        missing = [s for s in skill_ids if s not in self.margins]
        if missing:
            raise CompositionScoreMisapplied(
                f"skills {missing} have no probed margin; cannot compose"
            )

        surfaces = [self.margins[s].probed_surface for s in skill_ids]

        # Detect capability-surface overlap across the composed chain.
        for i in range(len(surfaces)):
            for j in range(i + 1, len(surfaces)):
                if surfaces[i].overlaps(surfaces[j]):
                    raise CompositionScoreMisapplied(
                        f"skills {skill_ids[i]!r} and {skill_ids[j]!r} share a "
                        f"capability surface; additive LITMUS score is not a "
                        f"valid bound. Re-probe under union surface before "
                        f"admitting."
                    )

        # Only reachable when surfaces are pairwise disjoint.
        return sum(self.margins[s].margin for s in skill_ids) / len(skill_ids)
