# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-tool-contract-against-a-stale-capability-advertisement-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-tool-contract-against-a-stale-capability-advertisement-mid-handoff.warrant.json
# Markdown SHA-256:   0161d15da71cf59f94d91ac052165891a4a6599999756d4756c1e869035a68d9
# Code AST SHA-256:   e7eab6551dd63b6047ebfc4c34e73ce2ae13a4527999da5699f480b775fdad50
# Verified Classes:   SchemaEpochStale, ManifestCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json


class SchemaEpochStale(RuntimeError):
    """Raised when a call is planned against a manifest epoch the callee no longer serves."""
    pass


class ManifestCache:
    def __init__(self):
        self._epoch = None
        self._tools = {}

    def load(self, manifest: dict) -> str:
        canonical = json.dumps(manifest["tools"], sort_keys=True).encode()
        self._epoch = hashlib.sha256(canonical).hexdigest()[:16]
        self._tools = {t["name"]: t for t in manifest["tools"]}
        return self._epoch

    @property
    def epoch(self):
        return self._epoch


def invoke(cache: ManifestCache, callee, tool: str, args: dict, planned_epoch: str):
    # Epoch check MUST precede field validation, or skew masquerades as a
    # retryable validation error and the caller loops.
    if planned_epoch != callee.current_epoch():
        raise SchemaEpochStale(
            f"call to {tool!r} planned under epoch {planned_epoch}, "
            f"callee serves {callee.current_epoch()}; re-fetch manifest and re-plan"
        )
    if tool not in cache._tools:
        raise SchemaEpochStale(f"tool {tool!r} absent from epoch {planned_epoch}")
    return callee.dispatch(tool, args)


def run_subtask(cache, callee, tool, args, max_replans=1):
    epoch = cache.epoch
    for attempt in range(max_replans + 1):
        try:
            return invoke(cache, callee, tool, args, epoch)
        except SchemaEpochStale:
            if attempt == max_replans:
                raise
            # Re-discovery, then re-plan under the new epoch. Do NOT resend
            # the old args: they were generated against a dead description.
            epoch = cache.load(callee.fetch_manifest())
            args = replan(tool, args, cache._tools[tool])
    raise SchemaEpochStale("unreachable")
