# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-to-subgoals-when-parallel-agents-share-a-mutable-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-to-subgoals-when-parallel-agents-share-a-mutable-context-window.warrant.json
# Markdown SHA-256:   02d2c15b0fbd2952c4bd4b76f6d1a262e84c8e76f4b8ed020bb5e9ca1641f7d7
# Code AST SHA-256:   74cc7333ddeed2ea0e70617fedc0c2d81a979755ed0bffe7226d068cca91b73b
# Verified Classes:   AttributionOrderViolation, SubgoalLedger, WindowEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import List, Optional


class AttributionOrderViolation(RuntimeError):
    """Raised when per-subgoal token attribution cannot be reconstructed
    because the shared-window mutation order was not recorded or was
    reordered relative to the ledger."""
    pass


@dataclass
class SubgoalLedger:
    subgoal_id: str
    allocated_tokens: int
    attributed_tokens: int
    mutation_order_id: Optional[int] = None
    regime: str = "hybrid"  # "serialized" | "forked" | "hybrid"


@dataclass
class WindowEvent:
    order_id: int
    subgoal_id: str
    appended_tokens: int


def reconcile_ledger(
    prefix_tokens: int,
    events: List[WindowEvent],
    ledgers: List[SubgoalLedger],
    window_peak: int,
) -> dict:
    if any(lg.regime == "hybrid" for lg in ledgers):
        # Hybrid regime: attribution is order-dependent and must not be
        # used as an accounting artifact. Only window_peak is trustworthy.
        return {
            "attribution": "approximate",
            "window_peak": window_peak,
            "allocated_sum": sum(lg.allocated_tokens for lg in ledgers),
        }

    # Serialized or forked: attribution must match the recorded order.
    order_ids = [ev.order_id for ev in events]
    if order_ids != sorted(order_ids):
        raise AttributionOrderViolation(
            f"Window mutation order {order_ids} is not monotonic; "
            f"attribution cannot be reconstructed from the ledger."
        )

    attributed = sum(lg.attributed_tokens for lg in ledgers)
    expected = sum(ev.appended_tokens for ev in events)
    if attributed != expected:
        raise AttributionOrderViolation(
            f"Ledger attributed {attributed} tokens but event log records "
            f"{expected} appended tokens; discrepancy is unauditable."
        )

    total = prefix_tokens + expected
    if total > window_peak:
        raise AttributionOrderViolation(
            f"Reconstructed window total {total} exceeds recorded peak "
            f"{window_peak}; a mutation was not logged."
        )

    return {
        "attribution": "exact",
        "window_peak": window_peak,
        "attributed_sum": attributed,
        "reconstructed_total": total,
    }
