# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-privacy-budget-exhaustion-is-silently-corrupting-cross-org-anomaly-correlation-in-federated-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-privacy-budget-exhaustion-is-silently-corrupting-cross-org-anomaly-correlation-in-federated-agent-traces.warrant.json
# Markdown SHA-256:   245d5c33b23523f27961ae7c92923f12874a901fbef5ba35303696b31b39bdb3
# Code AST SHA-256:   09a01a16ecdc32cd09e3fa81a51535a05d87bc7c9f39d83fee190d814ded1deb
# Verified Classes:   NoiseRegimeMismatchError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class NoiseRegimeMismatchError(RuntimeError):
    """Raised when a cross-org correlation spans a change in a producer's
    DP noise regime or feature schema, making the aggregates incomparable."""
    pass


def correlate_across_orgs(
    detection: dict,   # {"org": ..., "metric": ..., "value": ..., "regime_bit": bool, "schema_ver": int}
    baseline: dict,    # same shape, drawn from trailing window
    confidence_threshold: float,
) -> dict:
    # Schema must match exactly; coarsening changes bin semantics, not just noise.
    if detection["schema_ver"] != baseline["schema_ver"]:
        raise NoiseRegimeMismatchError(
            f"schema_ver {baseline['schema_ver']} -> {detection['schema_ver']} "
            f"for {detection['org']}/{detection['metric']}: bins incomparable"
        )

    # Regime bit flipped => noise scale changed inside the span.
    if detection["regime_bit"] != baseline["regime_bit"]:
        # Do NOT silently compute a difference-of-means across regimes.
        return {
            "state": "UNVERIFIED",
            "reason": "noise_regime_changed",
            "org": detection["org"],
            "metric": detection["metric"],
            # Unverified is unknown, never clear.
            "escalate": False,
            "treat_as_healthy": False,
        }

    delta = detection["value"] - baseline["value"]
    # ... normalized deviation, confidence scoring against stationary noise ...
    confidence = abs(delta)  # placeholder for real scoring
    if confidence < confidence_threshold:
        return {"state": "CLEAR", "escalate": False, "treat_as_healthy": True}

    return {"state": "CONFIRMED", "escalate": True, "treat_as_healthy": False}
