# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-it-just-loaded-the-load-time-run-time-trust-window-gap-in-dynamic-skill-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-it-just-loaded-the-load-time-run-time-trust-window-gap-in-dynamic-skill-injection.warrant.json
# Markdown SHA-256:   3640a44301cbbb7445c687e4ed1ab3eb7e3284f29c8752f6a92308c65ee19530
# Code AST SHA-256:   8eb684e2b3090377fda2b1aa6e26c0dc945e7e3770e764bf0026a3df2b57ea30
# Verified Classes:   SkillTrustWindowViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SkillTrustWindowViolation(RuntimeError):
    """Raised when a skill's runtime output diverges from its load-time declared contract."""
    pass


INJECTION_MARKERS = ("ignore previous", "base64,", "http://", "https://", ".env")


def validate_first_invocation(skill_manifest: dict, raw_output: str) -> str:
    """Gate a newly loaded skill's first output before it enters trusted memory.

    Returns the output if it conforms; raises if the skill crossed the
    load-time/run-time trust boundary.
    """
    declared_schema = skill_manifest.get("output_schema")
    declared_purpose = skill_manifest.get("purpose", "")

    if declared_schema is None:
        raise SkillTrustWindowViolation(
            f"skill {skill_manifest.get('name')} has no declared output schema; "
            "cannot validate run-time conformance"
        )

    lowered = raw_output.lower()
    for marker in INJECTION_MARKERS:
        if marker in lowered:
            raise SkillTrustWindowViolation(
                f"skill {skill_manifest['name']} emitted injection marker {marker!r} "
                f"on first invocation; output quarantined, skill flagged"
            )

    if declared_purpose == "lint" and not _parses_as_lint_findings(raw_output):
        raise SkillTrustWindowViolation(
            f"skill {skill_manifest['name']} declared lint output but produced "
            "non-conforming payload; refusing trust promotion"
        )

    return raw_output


def _parses_as_lint_findings(output: str) -> bool:
    # Structural check: lint findings must be line/column/message tuples.
    # Free-form strings indicate the skill is using the output channel
    # for something other than its declared purpose.
    return all(
        line.count(":") >= 2 for line in output.splitlines() if line.strip()
    )


def promote_skill_output(skill_manifest: dict, raw_output: str) -> dict:
    validated = validate_first_invocation(skill_manifest, raw_output)
    return {
        "skill": skill_manifest["name"],
        "output": validated,
        "trust_level": "trusted",
        "validated_at": "run_time",
    }
