# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-validly-signed-skill-manifest-as-insufficient-evidence-of-behavioral-safety.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-validly-signed-skill-manifest-as-insufficient-evidence-of-behavioral-safety.warrant.json
# Markdown SHA-256:   049fe624d3ebd6c7a85743f6442fc009a25f111ee05a2fb4b438f1469325bbdb
# Code AST SHA-256:   8e0c376918a5903c8c485ff3e9ae1ea4aefa71c98acabe25abf6958a724327c1
# Verified Classes:   UnsafeSkillAdmission, Manifest, RuntimeState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional, FrozenSet


class UnsafeSkillAdmission(RuntimeError):
    """Raised when a skill is admitted on signature alone despite flow capabilities
    or an unseeded (cold-start) behavioral baseline."""
    pass


FLOW_CAPABILITIES = frozenset({"net:egress", "exec", "cross_skill_channel", "persist:write"})


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    version: str
    declared_scopes: FrozenSet[str]
    entrypoint_hash: str
    signature_valid: bool
    publisher_key_trusted: bool


@dataclass
class RuntimeState:
    loaded_artifact_hash: str
    drift_baseline_seeded: bool          # True only if seeded from signed reference corpus
    drift_score: Optional[float]         # None == cold start, NOT "safe"
    co_resident_egress: bool             # any co-resident skill holds net:egress


def admit_skill(m: Manifest, rt: RuntimeState, drift_threshold: float = 0.35) -> str:
    # 1. Provenance precondition.
    if not (m.signature_valid and m.publisher_key_trusted):
        raise UnsafeSkillAdmission(f"{m.skill_id}: signature/trust precondition failed")

    # 4. TOCTOU: runtime must verify the loaded artifact matches the signed hash.
    if rt.loaded_artifact_hash != m.entrypoint_hash:
        raise UnsafeSkillAdmission(
            f"{m.skill_id}: loaded artifact hash {rt.loaded_artifact_hash} "
            f"!= signed {m.entrypoint_hash}"
        )

    has_flow = bool(m.declared_scopes & FLOW_CAPABILITIES)

    # Statically-safe class: signature is sufficient.
    if not has_flow:
        return "admit:signed-safe-class"

    # Above the flow boundary, signature is necessary but not sufficient.
    # 2. Cold-start must be fail-closed, not permissive.
    if rt.drift_score is None or not rt.drift_baseline_seeded:
        raise UnsafeSkillAdmission(
            f"{m.skill_id}: flow-capable skill with unseeded/absent baseline; "
            f"cold-start is not evidence of conformance — quarantine required"
        )

    # 3. Composition scope: egress via a co-resident skill is still egress.
    if "net:egress" not in m.declared_scopes and rt.co_resident_egress:
        raise UnsafeSkillAdmission(
            f"{m.skill_id}: declares no egress but co-resident egress channel exists; "
            f"composition scope violation"
        )

    if rt.drift_score >= drift_threshold:
        raise UnsafeSkillAdmission(
            f"{m.skill_id}: drift {rt.drift_score:.2f} >= {drift_threshold}"
        )

    return "admit:signed+seeded+composition-checked"


# Poisoned-baseline trace: malicious behavior present from invocation 1,
# so drift against self-baseline stays ~0. Gate must catch it via seeding,
# not via the (useless) low score.
poisoned = Manifest(
    skill_id="summarize_doc", version="2.3.1",
    declared_scopes=frozenset({"read:workspace"}),
    entrypoint_hash="a1b2", signature_valid=True, publisher_key_trusted=True,
)
state = RuntimeState(
    loaded_artifact_hash="a1b2",
    drift_baseline_seeded=False,   # first execution: no signed reference seed
    drift_score=0.01,              # self-consistent malicious baseline
    co_resident_egress=True,       # side channel to an egress-capable peer
)
admit_skill(poisoned, state)       # raises UnsafeSkillAdmission — cold start, fail-closed
