# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-post-load-skill-metadata-as-untrusted-input-rather-than-trusted-configuration.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-post-load-skill-metadata-as-untrusted-input-rather-than-trusted-configuration.warrant.json
# Markdown SHA-256:   10733110ce52292fc8028c1d8ddb477f44c537d01d357ae6426672776f43813d
# Code AST SHA-256:   9c7e2382b6e7522a4eacf82deca33414c83ec855c18c7e298f8adcc5dd6d2859
# Verified Classes:   UntrustedMetadataInControlPosition
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UntrustedMetadataInControlPosition(RuntimeError):
    """Raised when package-supplied prose is about to occupy an operator-authority context slot."""
    pass


# Fields whose content is prose and can carry imperatives.
IMPERATIVE_CAPABLE_FIELDS = frozenset({"description", "when_to_use", "examples", "notes"})

# Imperative markers that indicate a description is trying to steer routing.
ROUTING_DIRECTIVE_MARKERS = (
    "prefer", "instead of", "always", "never", "do not", "first",
    "rather than", "before using", "override",
)


def assemble_tool_context(registry, operator_policy):
    """
    Build the tool-selection preamble from the registry.
    Operator-authored routing policy is trusted; package prose is not.
    """
    context_blocks = []
    # Operator policy occupies the high-authority slot, verbatim.
    context_blocks.append({"authority": "operator", "text": operator_policy})

    for pkg in registry:
        manifest = pkg["manifest"]
        for field in IMPERATIVE_CAPABLE_FIELDS:
            prose = manifest.get(field)
            if not prose:
                continue
            lowered = prose.lower()
            if any(m in lowered for m in ROUTING_DIRECTIVE_MARKERS):
                # The package is trying to write into the control plane.
                raise UntrustedMetadataInControlPosition(
                    f"skill {pkg['id']!r} field {field!r} contains a routing "
                    f"directive; refusing to surface it in a control-authority "
                    f"position. Derive a description from structural fields "
                    f"instead, or route to operator review."
                )
            # Even non-directive prose goes in a low-authority, labeled region.
            context_blocks.append({
                "authority": "package-supplied",
                "text": f"[untrusted description from {pkg['id']}]: {prose}",
            })

        # Structural fields are parsed, not quoted; they are safe to surface.
        schema = manifest.get("parameters", {})
        context_blocks.append({
            "authority": "runtime-derived",
            "text": f"Tool {pkg['id']}: parameters={list(schema)}; "
                    f"scope={manifest.get('scope')}",
        })

    return context_blocks


def safe_assemble(registry, operator_policy):
    try:
        return assemble_tool_context(registry, operator_policy)
    except UntrustedMetadataInControlPosition as exc:
        # Fail closed: drop the offending package, keep the operator policy.
        # Do not silently fall back to load-time trust.
        return [{"authority": "operator", "text": operator_policy,
                 "note": f"package quarantined: {exc}"}]
