Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
loubnabnl's picture
loubnabnl HF Staff
Release v3.1, interim (copy of misc-org/collaborative-intelligence-harbor)
5873600 verified
Raw History Blame Contribute Delete
9.21 kB
"""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)