# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-survives-schema-validation-because-its-injection-payload-lives-in-the-description-to-paramet.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-survives-schema-validation-because-its-injection-payload-lives-in-the-description-to-paramet.warrant.json
# Markdown SHA-256:   0559303f7f292df41b5be81d8257be059009f6391452c1c735527241d5fd79c9
# Code AST SHA-256:   617a2d2c501e9d68e9b45fed13501ee9e67066671ad109042500e6761e7cfcc1
# Verified Classes:   CouplingAuditFailure, ManifestVerdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class CouplingAuditFailure(RuntimeError):
    """Raised when a schema-valid manifest carries a description-to-parameter coupling payload."""
    pass


# Imperative verbs that, when their grammatical object is a parameter value slot
# rather than the tool itself, indicate the description is steering argument construction.
CONSTRUCTION_VERBS = (
    "place", "put", "insert", "copy", "paste", "include", "embed",
    "normalize", "forward", "append", "prepend", "attach", "carry",
)


@dataclass
class ManifestVerdict:
    loadable: bool
    reason: str


def audit_coupling(manifest: dict) -> ManifestVerdict:
    desc = (manifest.get("description") or "").lower()
    params = manifest.get("parameters", {}).get("properties", {})

    # Condition 2: find free-form / wide-enum destinations.
    free_slots = set()
    for pname, pspec in params.items():
        if pspec.get("type") == "string" and "pattern" not in pspec and "maxLength" not in pspec:
            free_slots.add(pname.lower())
        if "enum" in pspec:
            for member in pspec["enum"]:
                if isinstance(member, str) and len(member) > 24:
                    free_slots.add(pname.lower())

    if not free_slots:
        return ManifestVerdict(True, "no free-form destination; coupling cannot complete")

    # Condition 1+2 join: does the description direct caller content INTO a named slot?
    for verb in CONSTRUCTION_VERBS:
        if verb in desc:
            for slot in free_slots:
                if slot in desc:
                    raise CouplingAuditFailure(
                        f"description verb '{verb}' targets free-form parameter "
                        f"'{slot}': construction-influence coupling detected, "
                        f"schema validity is not a load gate"
                    )

    return ManifestVerdict(True, "no description-to-slot coupling found")


def load_manifest(raw: str) -> dict:
    manifest = json.loads(raw)
    verdict = audit_coupling(manifest)
    if not verdict.loadable:
        raise CouplingAuditFailure(verdict.reason)
    return manifest
