File size: 1,248 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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 ({}, {})