# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """Forked-environment replay. The world is a pure Python state machine, so a counterfactual is exact: deep copy, apply one intervention, read the state. There is no learned simulator in this path, which is what keeps the L_cf labels honest. """ from __future__ import annotations from clsa.envs.sandbox import SandboxEnv def fork_outcome(env: SandboxEnv, action: dict) -> dict: """Counterfactual outcome of do(action) from the current state.""" return env.fork(action) def paired_fork(env: SandboxEnv, action: dict, alternatives: list[dict]) -> dict: """Outcome of do(a) plus the consequences of each do(a') from the same state.""" base = fork_outcome(env, action) alts = [(alt, fork_outcome(env, alt)) for alt in alternatives] return {"do_a": base, "alternatives": alts} def worst_alternative(env: SandboxEnv, alternatives: list[dict]) -> tuple[dict, dict]: """The highest-harm alternative, used as a' for the certificate fork.""" scored = [(alt, fork_outcome(env, alt)) for alt in alternatives] scored.sort(key=lambda pair: (pair[1]["harm"], pair[1]["irreversible_harm"]), reverse=True) return scored[0] if scored else ({}, {})