# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-a-write-audit-diff-because-the-trust-weighted-baseline-itself-was-poisoned-by-an-earlier-legitimate-write.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-a-write-audit-diff-because-the-trust-weighted-baseline-itself-was-poisoned-by-an-earlier-legitimate-write.warrant.json
# Markdown SHA-256:   45f78a8645d8a7a0feff2eec3a00b4da58d0585ce02ca4c006773f62a92d9e15
# Code AST SHA-256:   ad93cc53713f726536b63603828c79582885aa872126988731e7dc786c97c281
# Verified Classes:   FrameDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class FrameDriftError(RuntimeError):
    """Raised when incremental consolidation would move the baseline's
    detection region along an axis with insufficient margin, without
    independent provenance to justify the shift."""


def consolidate_write(
    write_vector: dict[str, float],
    baseline: dict[str, float],
    margin: dict[str, float],
    provenance_attested: bool,
    negligible_threshold: float = 1e-3,
) -> dict[str, float]:
    """Fold a write into the trust-weighted baseline, or refuse.

    Refusal is not rejection: the caller should quarantine the write
    (accept into working set, exclude from centroid) and re-derive the
    baseline from provenance-checked entries on the next reconciliation.
    """
    if provenance_attested:
        return _fold(write_vector, baseline)

    for axis, value in write_vector.items():
        slack = margin.get(axis, 0.0)
        if slack <= 0.0:
            raise FrameDriftError(
                f"baseline has no detection margin on axis {axis!r}; "
                f"cannot consolidate without provenance attestation"
            )
        projection = abs(value - baseline.get(axis, 0.0))
        if projection > negligible_threshold and projection > slack:
            raise FrameDriftError(
                f"write projection {projection:.4f} on axis {axis!r} "
                f"exceeds margin {slack:.4f} and is not negligible; "
                f"incremental consolidation would poison the frame"
            )

    return _fold(write_vector, baseline)


def _fold(write_vector: dict[str, float], baseline: dict[str, float]) -> dict[str, float]:
    merged = dict(baseline)
    for axis, value in write_vector.items():
        merged[axis] = 0.5 * merged.get(axis, 0.0) + 0.5 * value
    return merged
