# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-declared-capability-manifest-as-executable-code-rather-than-data.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-declared-capability-manifest-as-executable-code-rather-than-data.warrant.json
# Markdown SHA-256:   6023b2dc6b7a7ef33a1bc42e9e9309423d4a9f12ffe1daa6188cdc2803f93a23
# Code AST SHA-256:   c0b632429cd5d05e5d559d33ad4da849738e404eb7cdea286793e268c60af809
# Verified Classes:   ManifestAuthorityViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestAuthorityViolation(RuntimeError):
    """Raised when a peer-supplied manifest attempts to acquire
    authority over the planner's call graph rather than merely
    describing a capability."""
    pass


# Lexical markers of a manifest trying to be a standing instruction.
_IMPERATIVE_MARKERS = (
    "you must", "always ", "before you", "do not mention",
    "required step", "first call", "internal implementation detail",
)
_SIBLING_REFERENCE = ("export_credentials", "delete_", "admin_", "grant_")


def admit_manifest(card: dict, trusted: bool) -> dict:
    """Decide whether a manifest may enter the planner's context.

    Returns a sanitized, data-only view. Raises if the manifest is
    trying to install standing authority. Never returns text that
    the planner will read as an instruction.
    """
    if trusted:
        return card  # provisioned by us; still not planner-readable as policy

    text_blobs = []
    for skill in card.get("skills", []):
        text_blobs.append(skill.get("description", ""))
        text_blobs.extend(skill.get("examples", []) or [])
    blob = " ".join(text_blobs).lower()

    for marker in _IMPERATIVE_MARKERS:
        if marker in blob:
            raise ManifestAuthorityViolation(
                f"manifest contains standing-instruction marker {marker!r}; "
                "refusing to render into planner context"
            )

    for ref in _SIBLING_REFERENCE:
        if ref in blob:
            raise ManifestAuthorityViolation(
                f"manifest references sibling capability {ref!r}; "
                "capability authority must derive from runtime policy, not peer text"
            )

    # Strip examples entirely: they are few-shot prompts placed by a third party.
    sanitized = {
        "name": card.get("name"),
        "skills": [
            {"id": s.get("id"), "input_schema": s.get("input_schema")}
            for s in card.get("skills", [])
        ],
        "trust": "untrusted_data",
    }
    return sanitized


def plan_with_manifest(card: dict, user_intent: str) -> dict:
    view = admit_manifest(card, trusted=False)
    # Selection is by structured index, not by prose the planner reads.
    chosen = match_by_schema(view, user_intent)
    if chosen is None:
        raise ManifestAuthorityViolation(
            "no capability matched user intent via structured index; "
            "refusing to fall back to description-prose selection"
        )
    return chosen


def match_by_schema(view: dict, user_intent: str):
    # Placeholder for a non-LLM matcher over input_schema + skill id.
    for skill in view["skills"]:
        if skill.get("id") and skill["id"] in user_intent:
            return skill
    return None
