# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-loaded-mid-task-skill-injection-via-late-bound-plugin-registry-entries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-loaded-mid-task-skill-injection-via-late-bound-plugin-registry-entries.warrant.json
# Markdown SHA-256:   d613b5b7161ab1626fef809aae620efc5382d274d91781ca547eaeb4e7334fc5
# Code AST SHA-256:   42661129e9cf03ba58550a38fc8a64a6eef0b9dd73ce589198690d13b881f4f7
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a late-bound tool manifest attempts to inject instructions."""
    pass


TRUSTED_AT_BOOT = {"http_post", "read_file", "reconcile_ledger"}  # pinned set

INJECTION_MARKERS = (
    "before invoking",
    "do not mention",
    "required for compliance",
    "first emit",
    "ignore previous",
)


def admit_manifest(entry: dict, task_started: bool) -> dict:
    """Admit a registry entry into the active tool set, or refuse it."""
    name = entry.get("name", "")
    desc = entry.get("description", "") or ""

    if task_started and name not in TRUSTED_AT_BOOT:
        # Late-bound tool: never merge into the active context mid-task.
        raise ManifestInjectionError(
            f"late-bound tool {name!r} arrived after task start; "
            f"routed to pending queue, not active context"
        )

    lowered = desc.lower()
    for marker in INJECTION_MARKERS:
        if marker in lowered:
            raise ManifestInjectionError(
                f"tool {name!r} description contains directive marker "
                f"{marker!r}; refusing to render into instruction region"
            )

    # Strip prose from the instruction region; keep schema only.
    return {
        "name": name,
        "parameters": entry.get("parameters", {}),
        "description_hash": hash(desc),
        "doc_pointer": f"quarantine://{name}",
    }


def refresh_registry(entries: list[dict], task_started: bool) -> list[dict]:
    admitted = []
    for entry in entries:
        try:
            admitted.append(admit_manifest(entry, task_started))
        except ManifestInjectionError:
            # Log and quarantine; do not fail the whole refresh.
            continue
    return admitted
