# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-load-time-skill-injection-from-widening-an-agent-s-effective-authority-beyond-its-declared-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-load-time-skill-injection-from-widening-an-agent-s-effective-authority-beyond-its-declared-warrant.warrant.json
# Markdown SHA-256:   9f04cb824166ff64469ffcf15d13d4739e121ee6e723b76f36c0a1c4d0d05159
# Code AST SHA-256:   28a8638f1b5a42bde1aec188ff3ccc01b53736a3be1269017a78fd37d82d98ed
# Verified Classes:   ScopeClosureViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeClosureViolation(RuntimeError):
    """Raised when a skill's realized authority would exceed its declared,
    warrant-bounded scope at activation time."""
    pass


def mint_derived_token(skill_manifest: dict, agent_warrant: dict) -> dict:
    declared = skill_manifest.get("scopes", {})
    # Fail-closed: empty declared scope means empty authority, never unrestricted.
    if not declared:
        return {"scopes": {}, "allowlist": []}

    # Binding isolation: derived token is the intersection of declared and warrant,
    # never a union, never ambient.
    derived = {}
    for scope, spec in declared.items():
        if scope not in agent_warrant:
            raise ScopeClosureViolation(
                f"skill {skill_manifest['name']!r} declares scope {scope!r} "
                f"absent from agent warrant"
            )
        w = agent_warrant[scope]
        d = spec
        if scope == "call:http":
            allow = sorted(set(d.get("allowlist", [])) & set(w.get("allowlist", [])))
            if not allow:
                raise ScopeClosureViolation(
                    f"skill {skill_manifest['name']!r} http allowlist "
                    f"{d.get('allowlist')} disjoint from warrant allowlist "
                    f"{w.get('allowlist')}; refusing to mint unrestricted token"
                )
            derived[scope] = {"allowlist": allow}
        else:
            derived[scope] = dict(d)

    # Closure gate: any dependency not pinned in the manifest is a lazy-resolution
    # hazard and must be rejected before activation.
    pinned = set(skill_manifest.get("dependencies", []))
    for dep in skill_manifest.get("imports_seen", []):
        if dep not in pinned:
            raise ScopeClosureViolation(
                f"skill {skill_manifest['name']!r} imports {dep!r} not in pinned "
                f"dependency set; lazy resolution would bind against ambient capabilities"
            )

    return {"scopes": derived, "allowlist": derived.get("call:http", {}).get("allowlist", [])}
