# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-re-issued-memory-handle-after-retention-scope-narrowing-as-a-new-provenance-epoch-not-a-resumed-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-re-issued-memory-handle-after-retention-scope-narrowing-as-a-new-provenance-epoch-not-a-resumed-write.warrant.json
# Markdown SHA-256:   d5fa6e2f37f5901f08445040530b4ba93ccd5a5632fd834633ca2919367b00b7
# Code AST SHA-256:   22b9b2a4181f573eaf8a0ccf4de1076fa1ee76ef68b6eefb57308995c6a857dd
# Verified Classes:   ProvenanceEpochMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceEpochMismatch(RuntimeError):
    """Raised when a write targets a handle whose epoch advanced since the caller last wrote."""
    pass


def guarded_append(handle, payload, caller_provenance, backend):
    current = backend.read_scope(handle)  # returns {epoch, retention, sensitivity}
    if current is None:
        # Handle vanished (forgotten or TTL-reaped); do not resurrect silently.
        raise ProvenanceEpochMismatch(
            f"handle {handle} no longer resolvable; cannot append under epoch "
            f"{caller_provenance.get('epoch')}"
        )

    if current["epoch"] != caller_provenance.get("epoch"):
        # Epoch advanced: scope was narrowed or re-partitioned between turns.
        # Refuse the append; caller must merge or fork under the new epoch.
        raise ProvenanceEpochMismatch(
            f"handle {handle}: caller epoch {caller_provenance.get('epoch')} "
            f"!= backend epoch {current['epoch']} "
            f"(retention={current['retention']}, sensitivity={current['sensitivity']})"
        )

    # Epochs match: safe resumption. Backend still owns scope; provenance is advisory.
    return backend.append(handle, payload, provenance=caller_provenance)


def merge_or_fork(handle, payload, caller_provenance, backend):
    current = backend.read_scope(handle)
    if current is None:
        raise ProvenanceEpochMismatch(f"handle {handle} unresolvable during merge")
    if current["epoch"] == caller_provenance.get("epoch"):
        return backend.append(handle, payload, provenance=caller_provenance)

    # New epoch: recompute union scope over existing fragments + new payload.
    fragments = backend.list_fragments(handle)
    union_sensitivity = max(
        [f["sensitivity"] for f in fragments] + [current["sensitivity"]],
        key=lambda s: {"public": 0, "internal": 1, "restricted": 2}[s],
    )
    union_retention = min(
        [f["retention_seconds"] for f in fragments] + [current["retention_seconds"]]
    )
    new_provenance = {
        "epoch": current["epoch"],
        "sensitivity": union_sensitivity,
        "retention_seconds": union_retention,
        "parent_epoch": caller_provenance.get("epoch"),
    }
    # Force a full re-write under the single new epoch; no partial appends.
    return backend.rewrite(handle, fragments + [payload], provenance=new_provenance)
