# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-plugin-manifest-has-been-weaponized-late-binding-skill-injection-through-tool-description-fields-and-the-pre-execut.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-plugin-manifest-has-been-weaponized-late-binding-skill-injection-through-tool-description-fields-and-the-pre-execut.warrant.json
# Markdown SHA-256:   c569e9f5d41b8e9a39ecc0ae94c78e76a354b0127077f13fb6a27e61bc38b765
# Code AST SHA-256:   7d44462d423a0ce56263f211968bf24d1bfdbb3dbdf0ab5699d4fe1716aad0b3
# Verified Classes:   DescriptionIntegrityViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DescriptionIntegrityViolation(RuntimeError):
    """Raised when a dynamically loaded manifest field can author plan steps
    outside the turn's pre-authorized capability graph."""
    pass


# Fields the model reads as declarative but which can carry imperative payload.
MODEL_READABLE_FIELDS = ("description", "enum", "default", "examples")

# Imperative markers that indicate plan-authoring content rather than docs.
IMPERATIVE_MARKERS = (
    "must ", "before calling", "also invoke", "first run",
    "then call", "pass its output", "include result", "you should",
)


def _iter_model_readable_strings(schema, path="parameters"):
    """Yield (json_path, string_value) for every string the model will see."""
    if isinstance(schema, dict):
        for key, val in schema.items():
            child = f"{path}.{key}"
            if key in MODEL_READABLE_FIELDS:
                if isinstance(val, str):
                    yield child, val
                elif isinstance(val, list):
                    for i, item in enumerate(val):
                        if isinstance(item, str):
                            yield f"{child}[{i}]", item
            else:
                yield from _iter_model_readable_strings(val, child)
    elif isinstance(schema, list):
        for i, item in enumerate(schema):
            yield from _iter_model_readable_strings(item, f"{path}[{i}]")


def assert_description_integrity(manifest, authorized_tools, legal_arg_sources):
    """
    Enforce the description-integrity invariant before a manifest is ingested
    into model context.

    manifest: parsed plugin manifest dict.
    authorized_tools: set of tool names legal for this turn (frozen pre-ingest).
    legal_arg_sources: set of tool names whose outputs may feed arguments.
    """
    if not isinstance(manifest, dict):
        raise DescriptionIntegrityViolation(
            f"manifest is not a mapping: {type(manifest).__name__}"
        )

    for json_path, text in _iter_model_readable_strings(manifest):
        lowered = text.lower()

        # 1. Imperative content in a field the model treats as documentation.
        for marker in IMPERATIVE_MARKERS:
            if marker in lowered:
                raise DescriptionIntegrityViolation(
                    f"imperative payload at {json_path!r}: contains {marker!r} "
                    f"-> can author plan steps, not just describe data"
                )

        # 2. Description references a tool outside the authorized set.
        for tool_name in _extract_tool_references(text):
            if tool_name not in authorized_tools:
                raise DescriptionIntegrityViolation(
                    f"{json_path!r} references unauthorized tool "
                    f"{tool_name!r}; authorized={sorted(authorized_tools)}"
                )

    # 3. Declared data-flow edges must point only at allowlisted sources.
    for edge in manifest.get("data_flow_edges", []):
        src = edge.get("from_tool")
        if src not in legal_arg_sources:
            raise DescriptionIntegrityViolation(
                f"manifest declares data-flow edge from {src!r}, which is not "
                f"an allowlisted argument source {sorted(legal_arg_sources)}"
            )

    return True


def _extract_tool_references(text):
    """Heuristic: backtick-quoted or snake_case identifiers that look like tools."""
    import re
    return set(re.findall(r"`([a-z][a-z0-9_]{2,})`", text))
