# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-capability-grant-rather-than-a-data-payload-and-how-does-the-skil.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-capability-grant-rather-than-a-data-payload-and-how-does-the-skil.warrant.json
# Markdown SHA-256:   27b9a1ec7fc6adba4c1b8fcc58b4e685e369cf2aca2c90f64c153d805abd888a
# Code AST SHA-256:   d65a215333ccfd816fa9fd0cc4f6178f161d1c6efc0f5a6592f47226d1583b7a
# Verified Classes:   ManifestRedirectError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ManifestRedirectError(RuntimeError):
    """Raised when an untrusted manifest's text could steer a privileged call."""
    pass


FIRST_PARTY = "first_party"


def admit_manifest(manifest: dict, ambient_capabilities: set[str]) -> dict:
    """
    Decide whether a dynamically loaded manifest may enter the model context.
    Returns an admission record. Raises ManifestRedirectError on redirect risk
    that cannot be quarantined.
    """
    declared = set(manifest.get("declared_capabilities", []))
    trust = manifest.get("trust", "unvetted")
    prose = manifest.get("description", "")

    # Clause 2: capability closure over the invocation graph.
    if trust != FIRST_PARTY and not ambient_capabilities.issubset(declared):
        # The manifest cannot grant upward, but it can redirect an ambient
        # capability. Admit only under quarantine.
        if _contains_imperative_reference(prose):
            raise ManifestRedirectError(
                f"manifest {manifest['name']!r} (trust={trust}) contains prose "
                f"that references tools outside its declared delta "
                f"{sorted(declared)}; ambient={sorted(ambient_capabilities)}. "
                f"Migrate references to structured 'requires' declarations."
            )
        return {"name": manifest["name"], "admitted": True, "quarantined": True}

    # Clause 1: provenance binding survives into the model view.
    return {"name": manifest["name"], "admitted": True, "quarantined": False,
            "provenance": trust}


def _contains_imperative_reference(prose: str) -> bool:
    """
    Heuristic: prose that names another tool or an executable verb in an
    imperative frame. False negatives are the residual risk; false positives
    are cheap (they force structured declarations).
    """
    lowered = prose.lower()
    imperative_markers = ("always call", "must call", "invoke ", "execute ",
                          "run `", "call `")
    return any(marker in lowered for marker in imperative_markers)
