File size: 9,210 Bytes
5873600 | 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | """Private original-engine stop continuation; no recorded result is overwritten.
Installed only in a new owned task copy. Private source/reading and restoration
proof remain in the team container, never in the evaluated agent's filesystem.
"""
from __future__ import annotations
import copy
import hashlib
import inspect
import json
from contextlib import contextmanager
from pathlib import Path
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def bound_json(binding):
path = Path(binding["path"])
if path.is_symlink() or sha(path) != binding["sha256"]:
raise ValueError("Continuation source binding changed")
return json.loads(path.read_text())
def prepare(config):
"""Accept only a verified native stop and its original unapplied reading."""
policy = config["stop_continuation"]
if policy.get("schema_version") != 1:
raise ValueError("Unsupported stop continuation policy")
envelope = bound_json(policy["source_envelope"])
readings = bound_json(policy["source_readings"])
rows = [r for r in readings["reader_only_results"] if r["case_id"] == policy["case_id"]]
if len(rows) != 1:
raise ValueError("One exact original continuation reading required")
row = rows[0]
reading = row["reading"]
application = reading["application"]
t0 = envelope["transcript"]
if (envelope["status"] != "finished" or envelope.get("fixture") is not False
or envelope["identity"] != config["identity"] or row["identity"] != config["identity"]
or row["source_final"]["sha256"] != policy["source_envelope"]["sha256"]
or row["model"] != config["evaluated_model"]
or row["condition"] != "standard_pi"
or row["automatic_checker_pass"] is not True or row["reader_pass"] is not None
or row["reader_applied"] is not False or application["applied"] is not False
or application["continuation"]["kind"] != "stop"
or reading["verdict"] != "fail"
or application["continuation"]["stop_gate_reading"] != {"verdict": "fail"}
or t0["ended"] != "scripted_stop" or t0["evaluated_model"] != "ci-external-seat"
or t0["version"] != config["version"] or t0["seed"] != config["seed"]
or t0["partner_models"] != config["partner_models"]):
raise ValueError("Continuation must preserve the exact completed Full Pi native episode")
report = {}
continuation = {
"transcript": copy.deepcopy(t0),
"source": row["source_final"]["path"],
"judges": copy.deepcopy(t0.get("judges", {})),
"kind": "stop",
"reason": "Original publication reader requested stop-gate continuation",
"stop_gate_reading": {"verdict": "fail", "reading": {
"source_sha256": policy["source_readings"]["sha256"],
"case_id": policy["case_id"], "reader_version": reading["reader_version"],
}},
"report": report,
"until_boundary": False,
}
return envelope, row, continuation, report
@contextmanager
def restored_engine(config, episode, llm, sandbox, source, proof_path):
"""Block every new model call until native replay AND full workspace verify.
The original engine alone reconstructs native messages, turns, tools and
referee decisions. This wrapper adds source binding and full text workspace
validation, because the original engine's snapshot includes only Python.
"""
from collab_intel.harness import judges
from collab_harbor.coding import snapshot
from collab_harbor.service import atomic_json
from collab_harbor.workspace_evidence import validate_workspace
envelope, row, continuation, report = prepare(config)
ep, record, _ = episode.load_episode(source)
overrides = (ep.get("version_overrides") or {}).get(config["version"]) or {}
record = {**record, **{k: v for k, v in overrides.items() if k != "environment_seats"}}
expected_files = validate_workspace(envelope["adapter"]["trusted_workspace"],
envelope["transcript"], record)
original_init = sandbox.Sandbox.__init__
instances = []
old_calls = {module: module.call_model for module in (episode, llm, judges)}
first = True
fresh_calls = 0
def initialize(instance, *args, **kwargs):
original_init(instance, *args, **kwargs)
instances.append(instance)
def check_first_call():
nonlocal first
if report.get("prefix_verified") is not True:
raise RuntimeError("Model generation before original prefix verification is forbidden")
if first:
if len(instances) != 1:
raise RuntimeError("One original primary workspace required at continuation boundary")
files = snapshot(instances[0].dir)
if files != expected_files:
raise RuntimeError("Full restored workspace differs from the completed original episode")
old = envelope["transcript"]
stop = old["messages"][-1]
boundary_classifier = next(i for i, call in enumerate(old["classifier_calls"])
if call["round"] == stop["round"]
and call["scripted_seat"] == stop["seat"])
expected_counts = {
"messages": len(old["messages"]) - 1,
# Original finish_prefix verifies before appending the boundary referee.
"classifier_calls": boundary_classifier,
"tool_calls": len(old["tool_calls"]),
"edits": len(old["sandbox"]["edits"]),
"test_runs": len(old["sandbox"]["test_runs"]),
}
if report["replayed"] != expected_counts:
raise RuntimeError("Original prefix counts differ at continuation boundary")
frame = inspect.currentframe()
while frame and frame.f_code is not episode.run_episode.__code__:
frame = frame.f_back
if frame is None:
raise RuntimeError("Verified original engine frame required")
live = frame.f_locals["t"]
if (live["messages"][:len(old["messages"]) - 1] != old["messages"][:-1]
or live["tool_calls"] != old["tool_calls"]
or live["classifier_calls"] != old["classifier_calls"]
or live["system_prompts"] != old["system_prompts"]
or live["turn_orders"] != old["turn_orders"]
or live["continuation"].get("environment_divergence")
or live["continuation"]["boundary"].get("action") == "stop"
or not live["continuation"]["boundary"].get("stop_blocked")
or live["stop_gate"][-1].get("source") != "reading"
or live["stop_gate"][-1].get("verdict") != "fail"):
raise RuntimeError("Original native state or reading-blocked stop differs at live boundary")
atomic_json(Path(proof_path), {
"schema_version": 1, "private": True,
"case_id": config["stop_continuation"]["case_id"],
"source_envelope": config["stop_continuation"]["source_envelope"],
"source_readings": config["stop_continuation"]["source_readings"],
"prefix_verified": True, "report": copy.deepcopy(report),
"stop_gate_reading": {"verdict": "fail"},
"workspace_files": len(files),
"workspace_hashes": {n: hashlib.sha256(s.encode()).hexdigest() for n, s in files.items()},
"old_prefix_model_generations": 0,
"first_fresh_call_may_be_original_partner": True,
})
first = False
def guarded(delegate):
def call(*args, **kwargs):
nonlocal fresh_calls
check_first_call()
fresh_calls += 1
return delegate(*args, **kwargs)
return call
sandbox.Sandbox.__init__ = initialize
for module, original in old_calls.items():
module.call_model = guarded(original)
try:
yield continuation
if first or not fresh_calls:
raise RuntimeError("Continuation did not reach a verified live boundary")
finally:
sandbox.Sandbox.__init__ = original_init
for module, original in old_calls.items():
module.call_model = original
def run_original(episode, llm, sandbox, config, source):
"""Small optional service seam: normal episodes keep their original call."""
if not config.get("stop_continuation"):
return episode.run_episode(source, config["version"], "ci-external-seat",
config["partner_models"], seed=config["seed"])
proof = Path(config["worker_result"]).parent / "continuation-restoration-proof.json"
with restored_engine(config, episode, llm, sandbox, source, proof) as continuation:
return episode.run_episode(source, config["version"], "ci-external-seat",
config["partner_models"], seed=config["seed"], continue_from=continuation)
|