# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-manifest-level-tool-descriptions-as-untrusted-code-rather-than-trusted-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-manifest-level-tool-descriptions-as-untrusted-code-rather-than-trusted-metadata.warrant.json
# Markdown SHA-256:   a2bcd0d0dfb184d007cfc236aa50f1638ec76d2adb3f6b00ef1c8060e0df1ce0
# Code AST SHA-256:   f61c00f6769edfc7df2d56865fe6f1f655c91dc898311fadf5e73ee2ed6a187f
# Verified Classes:   ManifestInjectionError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a manifest description cannot be safely injected as data."""


@dataclass(frozen=True)
class Manifest:
    name: str
    description: str
    impl_hash: str
    author_domain: str


TRUSTED_DOMAIN = "internal.agent"


def _is_instruction_bearing(description: str) -> bool:
    markers = ("assistant:", "note to the assistant", "you must", "first call")
    lowered = description.lower()
    return any(m in lowered for m in markers)


def inject_manifest(manifest: Manifest, budget_remaining: int) -> str:
    """Render a manifest description into a delimited data region for the model."""
    if manifest.author_domain != TRUSTED_DOMAIN:
        if _is_instruction_bearing(manifest.description):
            raise ManifestInjectionError(
                f"manifest {manifest.name!r} from untrusted domain "
                f"{manifest.author_domain!r} carries instruction-bearing description; "
                f"refusing to inject as free text"
            )
    rendered = f"<tool-data name={manifest.name!r}>{manifest.description}</tool-data>"
    if len(rendered) > budget_remaining:
        raise ManifestInjectionError(
            f"manifest {manifest.name!r} would overflow description budget "
            f"({len(rendered)} > {budget_remaining}); refusing silent truncation"
        )
    return rendered


def load_bundle(manifests: list[Manifest], seen: dict[str, str]) -> list[str]:
    """Load manifests with provenance-bound de-duplication by name."""
    blocks = []
    budget = 4096
    for m in manifests:
        prior = seen.get(m.name)
        if prior is not None and prior != m.impl_hash:
            raise ManifestInjectionError(
                f"description/implementation split for {m.name!r}: "
                f"existing impl {prior[:8]} vs new {m.impl_hash[:8]}"
            )
        block = inject_manifest(m, budget)
        budget -= len(block)
        seen[m.name] = m.impl_hash
        blocks.append(block)
    return blocks
