# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-context-budget-is-arbitrated-by-wall-clock-timeouts-rather-than-token-accounting-in-a-shared-subagent-workspace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-context-budget-is-arbitrated-by-wall-clock-timeouts-rather-than-token-accounting-in-a-shared-subagent-workspace.warrant.json
# Markdown SHA-256:   8d24ffeb864b5921689d0b1d040b6e9aeb09de78bce105efbfe1eff2668b7ece
# Code AST SHA-256:   adbfaa51978e40bbe7e8d19646f04ffe007e0a8cf05b1ce5728e4bf87c482430
# Verified Classes:   TruncationDetected, CompletionWitness, StagedArtifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class TruncationDetected(RuntimeError):
    """Raised when a shared-workspace artifact's observed content does not
    match the completion witness declared by its producer's task spec."""


@dataclass(frozen=True)
class CompletionWitness:
    expected_count: int
    expected_hash: str  # hash over the canonical serialization of items


@dataclass(frozen=True)
class StagedArtifact:
    items: list
    witness: CompletionWitness | None  # None == writer was killed before writing witness
    aborted_by_reaper: bool


def _hash_items(items: list) -> str:
    canonical = json.dumps(items, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def promote_to_shared_workspace(staged: StagedArtifact) -> list:
    """Atomic promote step. Rejects any artifact lacking a verifiable
    completion witness, regardless of whether it parses as valid JSON."""
    if staged.aborted_by_reaper:
        raise TruncationDetected(
            "writer was reclaimed by wall-clock reaper before promote; "
            "artifact must not enter shared namespace"
        )
    if staged.witness is None:
        raise TruncationDetected(
            "no completion witness written; artifact is a prefix of unknown length"
        )
    observed_count = len(staged.items)
    if observed_count != staged.witness.expected_count:
        raise TruncationDetected(
            f"count mismatch: witness declared {staged.witness.expected_count}, "
            f"artifact contains {observed_count}; truncation laundered as completeness"
        )
    observed_hash = _hash_items(staged.items)
    if observed_hash != staged.witness.expected_hash:
        raise TruncationDetected(
            "hash mismatch: artifact content diverges from producer's declared output"
        )
    return staged.items


def verify_against_task_spec(items: list, expected_count: int) -> None:
    """Verifier path: the completeness oracle comes from the task spec,
    never from the artifact under verification."""
    if len(items) != expected_count:
        raise TruncationDetected(
            f"verifier expected {expected_count} findings from task spec, "
            f"received {len(items)}; upstream truncation not caught at promote"
        )
