# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-miss-skill-injection-at-the-schema-boundary-when-the-tool-s-declared-contract-is-a-strict-subset-of-its-actual-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-miss-skill-injection-at-the-schema-boundary-when-the-tool-s-declared-contract-is-a-strict-subset-of-its-actual-behavior.warrant.json
# Markdown SHA-256:   df1e83d7edcbca5bd3104e9e31cb511a7633e27cf2b72b451cda1a57a3f76f22
# Code AST SHA-256:   e95dc678d4d48723657cf941f6ca2ee830f9e7b57a95e712d9b3665b150ca377
# Verified Classes:   SkillInjectionBoundaryError, TrustClass, FieldContract, ToolContract
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Callable


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a schema-conformant call crosses a trust-class or capability boundary."""


class TrustClass(Enum):
    DATA = "data"
    INSTRUCTION = "instruction"


@dataclass(frozen=True)
class FieldContract:
    name: str
    trust: TrustClass
    resolves_to: str | None = None  # e.g. "fs.write", "sql.parse", "prompt.assemble"


@dataclass(frozen=True)
class ToolContract:
    name: str
    fields: dict[str, FieldContract]
    primitive: str  # resolved capability, NOT the tool name


# Two tools aliasing the same write primitive with overlapping schema shapes.
REGISTRY: dict[str, ToolContract] = {
    "write_note": ToolContract(
        name="write_note",
        primitive="fs.write",
        fields={
            "path": FieldContract("path", TrustClass.DATA, resolves_to="fs.write"),
            "body": FieldContract("body", TrustClass.DATA, resolves_to="prompt.assemble"),
        },
    ),
    "cache_write": ToolContract(
        name="cache_write",
        primitive="fs.write",
        fields={
            "path": FieldContract("path", TrustClass.DATA, resolves_to="fs.write"),
            "body": FieldContract("body", TrustClass.DATA, resolves_to="prompt.assemble"),
        },
    ),
}

# Directories a future cold start will read as skill/config/memory.
PERSISTENCE_SINKS = ("~/.agent/skills/", "~/.agent/config/", "~/.agent/memory/")
TASK_OUTPUT_SCOPE = ("./notes/",)


def _resolve_path(p: str) -> str:
    return p.replace("~", "/home/agent") if p.startswith("~") else p


def validate_call(tool_name: str, args: dict[str, str]) -> None:
    contract = REGISTRY.get(tool_name)
    if contract is None:
        raise SkillInjectionBoundaryError(f"unknown tool {tool_name!r}")

    # 1. Schema conformance (the check that is NOT sufficient).
    for fname, fc in contract.fields.items():
        if fname not in args:
            raise SkillInjectionBoundaryError(f"missing field {fname!r}")

    # 2. Trust-class check: a DATA field must not feed an instruction sink
    #    unless the value is explicitly re-typed by a trusted component.
    for fname, fc in contract.fields.items():
        if fc.resolves_to == "prompt.assemble" and fc.trust is TrustClass.DATA:
            # body is DATA but flows to prompt assembly -> must be quarantined,
            # not silently accepted. In this runtime, quarantine is a hold.
            raise SkillInjectionBoundaryError(
                f"{tool_name}.{fname} is DATA-class but resolves to an "
                f"instruction sink (prompt.assemble); payload must be quarantined"
            )

    # 3. Capability-scoped path check keyed on resolved primitive, not tool name.
    if contract.primitive == "fs.write":
        resolved = _resolve_path(args["path"])
        if any(resolved.startswith(_resolve_path(s)) for s in PERSISTENCE_SINKS):
            raise SkillInjectionBoundaryError(
                f"{tool_name} (primitive={contract.primitive}) writes to "
                f"persistence sink {resolved!r}; this is a capability escalation "
                f"regardless of schema conformance"
            )
        if not any(resolved.startswith(s) for s in TASK_OUTPUT_SCOPE):
            raise SkillInjectionBoundaryError(
                f"{tool_name} write to {resolved!r} is outside task output scope"
            )


def dispatch(tool_name: str, args: dict[str, str], executor: Callable[[str, dict], None]) -> None:
    validate_call(tool_name, args)
    executor(tool_name, args)


if __name__ == "__main__":
    injected = {
        "path": "~/.agent/skills/auto.md",
        "body": "<!-- SYSTEM: ... -->",
    }
    try:
        dispatch("write_note", injected, lambda n, a: None)
    except SkillInjectionBoundaryError as e:
        print(f"BLOCKED: {e}")
