# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-the-context-budget-as-a-partitioned-allocation-with-pinned-floor-reservations-rather-than-a-single-fungible-token-pool.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-the-context-budget-as-a-partitioned-allocation-with-pinned-floor-reservations-rather-than-a-single-fungible-token-pool.warrant.json
# Markdown SHA-256:   0b3f4aad822e2f8b2a3144246f2b75f0fe0d3b80b289145584c7e0ff474bef3e
# Code AST SHA-256:   abe537ac99da3a5a1fc3e8965c371da4870f4bad08167666708453e422c917f4
# Verified Classes:   ContextPartitionStarvation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ContextPartitionStarvation(RuntimeError):
    """Raised when a context partition is truncated below its reserved floor."""
    pass


PARTITION_FLOORS = {
    "system": 1_500,
    "memory": 3_000,
    "tools": 4_000,
    "evidence": 6_000,   # must cover k_required * mean_chunk * variance_margin
}
SAFETY_MARGIN = 2_000


def assemble_context(window: int, partitions: dict[str, int]) -> dict[str, int]:
    """Grant each partition its requested tokens only if every other
    partition's floor survives. Returns the granted allocation."""
    if sum(PARTITION_FLOORS.values()) + SAFETY_MARGIN > window:
        raise ContextPartitionStarvation(
            f"floors {sum(PARTITION_FLOORS.values())} + margin exceed window {window}"
        )

    granted: dict[str, int] = {}
    remaining = window - SAFETY_MARGIN

    # Reserve every floor first; growth is paid from slack only.
    for name, floor in PARTITION_FLOORS.items():
        granted[name] = floor
        remaining -= floor

    for name, requested in partitions.items():
        if name not in PARTITION_FLOORS:
            raise ContextPartitionStarvation(f"unknown partition {name!r}")
        extra = max(0, requested - PARTITION_FLOORS[name])
        grant = min(extra, remaining)
        granted[name] += grant
        remaining -= grant

    # Invariant check: no partition may fall below its floor.
    for name, floor in PARTITION_FLOORS.items():
        if granted[name] < floor:
            raise ContextPartitionStarvation(
                f"partition {name!r} granted {granted[name]} < floor {floor}"
            )

    # If evidence could not meet its floor, the turn is unsafe to run.
    if granted["evidence"] < PARTITION_FLOORS["evidence"]:
        raise ContextPartitionStarvation(
            "evidence partition starved below floor; refusing to answer"
        )
    return granted


def distill_memory(episodes: list[str], ceiling: int) -> str:
    """Distillation must emit within the memory partition's ceiling."""
    summary = " | ".join(episodes)[: ceiling * 4]  # ~4 chars/token
    if len(summary) // 4 > ceiling:
        raise ContextPartitionStarvation(
            f"distilled memory {len(summary)//4} tokens exceeds ceiling {ceiling}"
        )
    return summary
