# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-delegated-subtask-s-return-value-to-prevent-prompt-injection-propagation-across-the-delegation-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-delegated-subtask-s-return-value-to-prevent-prompt-injection-propagation-across-the-delegation-boundar.warrant.json
# Markdown SHA-256:   027735396859a682500634f586f5f35e75afe26ac393d5b5541ee72a44d48fd9
# Code AST SHA-256:   f26473a66f0ea9d01430e48b73e94523c1caa625148d4ec08f3227553a4426c1
# Verified Classes:   InjectionPropagationError, TrustLabel, SubtaskResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class InjectionPropagationError(RuntimeError):
    """Raised when a delegated subtask result would cross the delegation
    boundary into the orchestrator's action-selection context without
    passing quarantine."""


class TrustLabel(Enum):
    INTERNAL_WORKER = "internal_worker"  # provenance only, NOT content trust
    QUARANTINED = "quarantined"
    VERIFIED_FACTS = "verified_facts"


@dataclass
class SubtaskResult:
    agent_id: str
    raw_text: str
    trust: TrustLabel = TrustLabel.INTERNAL_WORKER
    declared_fields: dict[str, str] = field(default_factory=dict)


# Directives addressed to the parent, credential-shaped tokens, and
# action-sink references that were not in the original delegation request.
_DIRECTIVE_PATTERNS = (
    re.compile(r"\b(?:orchestrator|assistant|parent)\b[^.\n]{0,40}\b(?:should|must|please)\b", re.I),
    re.compile(r"\b(?:POST|GET|PUT)\b\s+https?://", re.I),
    re.compile(r"\b(?:HANDOFF_TOKEN|SESSION_TOKEN|API_KEY)\s*=", re.I),
    re.compile(r"\bcallback(?:\s+url)?\b", re.I),
)


def _scan(text: str) -> list[str]:
    hits: list[str] = []
    for pat in _DIRECTIVE_PATTERNS:
        for m in pat.finditer(text):
            hits.append(m.group(0))
    return hits


def _recombine(results: Iterable[SubtaskResult]) -> str:
    return "\n".join(r.raw_text for r in results)


def admit_result(
    result: SubtaskResult,
    *,
    prior_results: Iterable[SubtaskResult] = (),
    action_tools_available: bool,
) -> SubtaskResult:
    """Gate a delegated result before it enters the parent's action context.

    Invariant: a result whose content contains directives may only enter the
    action-selection context after quarantine + tool-free re-derivation.
    Recombination of individually-benign results is checked jointly.
    """
    if result.trust is TrustLabel.VERIFIED_FACTS:
        return result

    own_hits = _scan(result.raw_text)
    joint_hits = _scan(_recombine([*prior_results, result]))

    # Recombination: neither fragment is actionable alone, but together they
    # complete an injection. Per-result scanning misses this; joint scanning
    # catches it.
    if joint_hits and not own_hits:
        raise InjectionPropagationError(
            f"recombination injection across subtask boundary: fragments from "
            f"{[r.agent_id for r in prior_results]} + {result.agent_id} "
            f"jointly match {joint_hits!r}; per-result scan was clean"
        )

    if not own_hits:
        return result

    if action_tools_available:
        raise InjectionPropagationError(
            f"result from {result.agent_id} contains directive-shaped content "
            f"{own_hits!r} and parent has action tools reachable; must quarantine "
            f"and re-derive facts in a tool-free context before admission"
        )

    # No action tools: content may influence reasoning but not action.
    # Downgrade trust so downstream assembly cannot promote it.
    return SubtaskResult(
        agent_id=result.agent_id,
        raw_text=result.raw_text,
        trust=TrustLabel.QUARANTINED,
        declared_fields=result.declared_fields,
    )


def rederive_facts_in_sandbox(result: SubtaskResult, schema: dict[str, str]) -> SubtaskResult:
    """Tool-free re-derivation. Only schema-declared fields survive; prose
    (and therefore any embedded directive) is dropped."""
    if result.trust is not TrustLabel.QUARANTINED:
        raise InjectionPropagationError(
            f"re-derivation requires QUARANTINED input, got {result.trust}"
        )
    facts = {k: result.declared_fields.get(k, "") for k in schema}
    return SubtaskResult(
        agent_id=result.agent_id,
        raw_text="",
        trust=TrustLabel.VERIFIED_FACTS,
        declared_fields=facts,
    )
