# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-subagent-s-success-return-as-a-state-continuity-hazard-rather-than-a-completion-signal.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-subagent-s-success-return-as-a-state-continuity-hazard-rather-than-a-completion-signal.warrant.json
# Markdown SHA-256:   57eb5f539ea4e3d6219f70bca742588f1f1408565d796f41b1552fe0df8df34b
# Code AST SHA-256:   b844292715833501208548fa15f29a7f224a9e5c3e6ef2a8a71a0cd3e8a4657f
# Verified Classes:   HandoffContinuityError, ConstraintModel, HandoffResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class HandoffContinuityError(RuntimeError):
    """Raised when an effectful subagent returns a clean success without a
    constraint-delta, making the orchestrator's post-handoff context unsound."""
    pass


@dataclass
class ConstraintModel:
    # O's belief about the world, as a set of named constraints.
    constraints: dict[str, str] = field(default_factory=dict)

    def project(self, effect_surface: set[str]) -> dict[str, str]:
        return {k: v for k, v in self.constraints.items() if k in effect_surface}

    def apply_delta(self, mutated: dict[str, str]) -> None:
        # Atomic apply: caller holds the orchestrator lock.
        self.constraints.update(mutated)


@dataclass
class HandoffResult:
    status: str                      # "ok" | "error" | "partial"
    summary: str
    constraints_mutated: Optional[dict[str, str]] = None


def fold_handoff(
    model: ConstraintModel,
    effect_surface: set[str],
    result: HandoffResult,
) -> None:
    """Fold a subagent result into the orchestrator's constraint model.

    Invariant: for any effectful subtask (non-empty effect_surface), a clean
    success MUST carry an explicit constraints_mutated delta. A bare summary
    is treated as a continuity hazard, not a completion signal.
    """
    effectful = bool(effect_surface)

    if result.status != "ok":
        # Error/partial paths are already visible; do not silently fold.
        if result.constraints_mutated:
            model.apply_delta(result.constraints_mutated)
        return

    if effectful and result.constraints_mutated is None:
        raise HandoffContinuityError(
            f"effectful subtask over {sorted(effect_surface)} returned clean "
            f"success without constraint-delta; summary={result.summary!r} "
            f"cannot be trusted to leave orchestrator context sound"
        )

    if result.constraints_mutated is not None:
        # Validate the delta only touches the declared effect surface.
        undeclared = set(result.constraints_mutated) - effect_surface
        if undeclared:
            raise HandoffContinuityError(
                f"subagent mutated constraints outside declared effect surface: "
                f"{sorted(undeclared)}"
            )
        model.apply_delta(result.constraints_mutated)


# --- Trace of the failure above, now bounded ---

model = ConstraintModel(constraints={"namespace_readonly": "true"})
effect_surface = {"namespace_readonly"}

# S acquires an override but reports only a clean summary.
bad = HandoffResult(status="ok", summary="T1 complete; namespace updated")
try:
    fold_handoff(model, effect_surface, bad)
except HandoffContinuityError as e:
    # Orchestrator refuses to fold; re-dispatch with delta contract.
    print("rejected:", e)

# Corrected return: S reports the mutation.
good = HandoffResult(
    status="ok",
    summary="T1 complete",
    constraints_mutated={"namespace_readonly": "override-held-by-S"},
)
fold_handoff(model, effect_surface, good)
assert model.constraints["namespace_readonly"] == "override-held-by-S"
