# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-auto-compaction-rewrites-the-transcript-mid-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-auto-compaction-rewrites-the-transcript-mid-horizon.warrant.json
# Markdown SHA-256:   fb83b41c272b17a8a4b5d0062d07a2c00a634287bd35b771c854f568c5e37760
# Code AST SHA-256:   a7a872471028f3a70c1de651b0f7c52a7f430cfd294e0af066955834cdbcb3f5
# Verified Classes:   ProvenanceCompactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceCompactionError(RuntimeError):
    """Raised when compaction would sever a retained assertion from its authorizing tool call."""
    pass


MUTATING_TOOLS = frozenset({"write_file", "edit_file", "apply_patch", "delete_file", "run_shell_mutate"})


def compact_transcript(records, boundary_step, summarizer):
    """
    records: list of dicts with keys: step, kind ('tool'|'assistant'), tool, args, result, text
    boundary_step: exclusive upper bound of the slice being compacted
    summarizer: callable(list_of_records) -> str
    """
    slice_ = [r for r in records if r["step"] < boundary_step]
    tail = [r for r in records if r["step"] >= boundary_step]

    # 1. Pin mutating tool calls; they are never summarized into prose.
    pinned = [r for r in slice_ if r["kind"] == "tool" and r["tool"] in MUTATING_TOOLS]
    if not pinned and any(r["kind"] == "tool" for r in slice_):
        # No mutations in window: safe to summarize reads.
        pass

    # 2. Compute invalidations: any assertion about a resource touched by a pinned mutation
    #    that occurred after the assertion's origin step is superseded.
    invalidations = {}
    for p in pinned:
        resource = p["args"].get("path") or p["args"].get("target")
        if resource is None:
            continue
        invalidations.setdefault(resource, []).append(p["step"])

    # 3. Summarize only non-pinned, non-invalidated spans.
    summarizable = [
        r for r in slice_
        if r not in pinned
        and not _is_superseded(r, invalidations)
    ]

    summary = summarizer(summarizable)

    # 4. Verify every provenance edge referenced by the summary resolves.
    referenced_ids = _extract_tool_ids(summary)
    live_ids = {r["tool_call_id"] for r in pinned} | {
        r["tool_call_id"] for r in tail if r["kind"] == "tool"
    }
    dangling = referenced_ids - live_ids
    if dangling:
        raise ProvenanceCompactionError(
            f"Compaction at step {boundary_step} produced summary referencing "
            f"tool calls {sorted(dangling)} that are neither pinned nor in the live tail. "
            f"Retained assertions would be unverifiable; refusing to compact. "
            f"Mitigation: pin these calls or demote their claims to 'unverified'."
        )

    # 5. Snapshot alignment check: summarizer input must equal boundary slice.
    covered = {r["step"] for r in summarizable} | {r["step"] for r in pinned}
    expected = {r["step"] for r in slice_}
    if covered != expected:
        raise ProvenanceCompactionError(
            f"Snapshot skew at step {boundary_step}: summarizer input covers "
            f"{sorted(expected - covered)} steps outside the boundary slice."
        )

    return {
        "summary": summary,
        "pinned_mutations": [
            {"tool": p["tool"], "args_hash": hash(str(p["args"])), "step": p["step"]}
            for p in pinned
        ],
        "invalidations": invalidations,
        "tail": tail,
    }


def _is_superseded(record, invalidations):
    resource = record.get("args", {}).get("path") or record.get("args", {}).get("target")
    if resource is None:
        return False
    return any(s > record["step"] for s in invalidations.get(resource, []))


def _extract_tool_ids(summary_text):
    import re
    return set(re.findall(r"tool_call_id=([a-f0-9\-]+)", summary_text))
