Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 16,050 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""Prospective same-live-agent reader gate, never historical exact restoration.

Only private worker code sees readings. Original native candidates, automatic
checker verdicts and original reader/application entries remain separate.
"""
from __future__ import annotations

import copy
import hashlib
import json
import os
import shutil
import tempfile
from contextlib import contextmanager
from pathlib import Path


class ReaderContinuationRequired(RuntimeError):
    """An original non-stop continuation is held rather than silently scored."""

    def __init__(self, message, evidence):
        super().__init__(message)
        self.reader_deferred = evidence


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def private_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    temporary = None
    try:
        with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False) as stream:
            temporary = Path(stream.name)
            json.dump(value, stream, indent=2, ensure_ascii=False, allow_nan=False)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        temporary.replace(path)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)


def recovery_evidence(directory):
    """Full private candidates/workspaces/readings survive worker/provider errors."""
    path = Path(directory) / "original-reader/phases.json"
    if not path.is_file():
        return None
    return json.loads(path.read_text())


def enable_generated_task(task, identity, logical_item):
    """Build-time only: bake policy into private task/verifier payloads on Hub."""
    from collab_harbor.provenance import task_code_identity

    if identity.get("dimension") != "taking_over" or identity.get("variant") != "manipulation":
        raise ValueError("Reader policy applies only to TakingOver test tasks")
    task = Path(task)
    config_path, expected_path = task / "environment/team/task.json", task / "tests/expected.json"
    config, expected = json.loads(config_path.read_text()), json.loads(expected_path.read_text())
    if config.get("identity") != identity or expected.get("identity") != identity:
        raise ValueError("Generated private identities differ")
    config["taking_over_reader_gate"] = {"protocol": "live-full-pi-original-reader-v1", "logical_meta": {
        key: logical_item[key] for key in ("kind", "tamper", "from_round", "source_dimension") if key in logical_item}}
    expected["taking_over_reader_gate"] = {"protocol": "live-full-pi-original-reader-v1"}
    private_json(expected_path, expected)
    private_json(config_path, config)
    config["effective_code"] = task_code_identity(task)
    private_json(config_path, config)


@contextmanager
def verified_replay(episode, llm, continuation, workspace, expected_files):
    """No old generation may be repeated; only verified native-live calls pass."""
    if continuation is None:
        yield
        return
    from collab_intel.harness import judges

    originals = {module: module.call_model for module in (episode, llm, judges)}
    first = True
    def guarded(delegate):
        def call(*args, **kwargs):
            nonlocal first
            if continuation["report"].get("prefix_verified") is not True:
                raise RuntimeError("Provider call before original native prefix verified")
            if first:
                if expected_files is not None:
                    from collab_harbor.coding import snapshot
                    if workspace._primary is None or snapshot(workspace._primary.dir) != expected_files:
                        raise RuntimeError("Full native workspace was not restored at the live boundary")
                first = False
            return delegate(*args, **kwargs)
        return call
    for module, delegate in originals.items():
        module.call_model = guarded(delegate)
    try:
        yield
    finally:
        for module, delegate in originals.items():
            module.call_model = delegate


def validate_live_metadata(upstream, config):
    """Validate both checkout and self-contained private vendored runtimes."""
    from collab_harbor.sources import release_spec
    from collab_harbor.vendor import PINNED_REVISION, verify_lock

    upstream = Path(upstream)
    if (upstream / "source-lock.json").is_file():
        lock = verify_lock(upstream)
        if (lock["source"]["revision"] != PINNED_REVISION
                or lock["files"].get("benchmark/final_set.json") != "f2e1d42ca282785060998923faca19d60496d6853fadfe2437652e793e6d75aa"):
            raise ValueError("Reader metadata source is not the pinned released scored set")
        spec = json.loads((upstream / "benchmark/final_set.json").read_text())
    else:
        spec = release_spec(upstream)
    selected = [entry for entry in spec["dimensions"]["taking_over"]
        if Path(entry["path"]).name == config["identity"]["scenario_id"]]
    if len(selected) != 1 or config["taking_over_reader_gate"].get("logical_meta") != {
            key: selected[0][key] for key in ("kind", "tamper", "from_round", "source_dimension") if key in selected[0]}:
        raise ValueError("Reader item metadata differs from the pinned original scored set")


def run_live_gate(episode, llm, source, config, *, reader=None):
    """Return only once ORIGINAL application says the final reading is applied.

    The same virtual-seat HTTP bridge remains running. Nothing writes the
    service's terminal worker_result until this function returns. Pi retains
    its complete actual live history, including intermediate final Q/A; this is
    an explicitly new prospective interface, not a pre-stop history rewind.
    """
    if reader is None:
        from collab_intel.evaluation import reader
    from collab_harbor.workspace_evidence import capture_workspace

    policy = config.get("taking_over_reader_gate")
    if (not isinstance(policy, dict) or policy.get("protocol") != "live-full-pi-original-reader-v1"
            or config["identity"].get("dimension") != "taking_over"
            or config["identity"].get("variant") != "manipulation"
            or reader.READER_MODEL != "claude-opus-5-5" or reader.READER_EFFORT != "high"):
        raise ValueError("Explicit original TakingOver reader policy and test identity required")
    if config.get("fixture") is not True:
        validate_live_metadata(Path(episode.__file__).resolve().parents[3], config)
    private = Path(config["worker_result"]).parent / "original-reader"
    if private.exists():
        raise FileExistsError("Reader phases cannot be silently rerun")
    scenario = private / config["identity"]["scenario_id"]
    scenario.mkdir(parents=True, mode=0o700)
    for name in ("episode.yaml", "record.json", "notes.md"):
        if (Path(source) / name).is_file():
            shutil.copyfile(Path(source) / name, scenario / name)
            (scenario / name).chmod(0o600)
    reading_calls = []
    def read_candidate(candidate):
        original_client = reader._client
        original_call = getattr(reader, "call_reader", None)
        workspace = os.environ.get("ANTHROPIC_WORKSPACE_ID")
        def scoped_client():
            client = original_client()
            return client.with_options(default_headers={"anthropic-workspace-id": workspace}) if workspace else client
        if workspace:
            reader._client = scoped_client
        def recorded_call(*args, **kwargs):
            import inspect

            bound = inspect.signature(original_call).bind(*args, **kwargs)
            bound.apply_defaults()
            row = {"request": copy.deepcopy(dict(bound.arguments)), "status": "calling"}
            reading_calls.append(row)
            private_json(private / "reader-calls.json", reading_calls)
            try:
                result = original_call(*args, **kwargs)
                row.update(status="returned", result=copy.deepcopy(result))
                private_json(private / "reader-calls.json", reading_calls)
                return result
            except BaseException as error:
                row.update(status="error", error_type=type(error).__name__)
                private_json(private / "reader-calls.json", reading_calls)
                raise
        if original_call is not None:
            reader.call_reader = recorded_call
        try:
            return reader.read_run(candidate, "takeover", "live-worker",
                meta=copy.deepcopy(policy.get("logical_meta")), dry_run=False)
        finally:
            reader._client = original_client
            if original_call is not None:
                reader.call_reader = original_call
    phases, continuation, phase, expected_files = [], None, 0, None
    private_readout = bool(config.get("private_final_readout"))
    def checkpoint(status, **extra):
        evidence = {"protocol": policy["protocol"], "status": status, "phases": phases,
            "reader_calls": reading_calls, "automatic_checker_preserved": True,
            "private_final_readout_protocol": (config.get("private_final_readout") or {}).get("protocol"),
            **extra}
        private_json(private / "phases.json", evidence)
        return evidence
    while True:
        phase += 1
        try:
            with capture_workspace() as workspace, verified_replay(episode, llm, continuation, workspace, expected_files):
                transcript = episode.run_episode(source, config["version"], "ci-external-seat",
                    config["partner_models"], seed=config["seed"], **({"continue_from": continuation} if continuation else {}))
        except BaseException as error:
            error.reader_deferred = checkpoint("continuation_error", error_type=type(error).__name__)
            raise
        sidecar = workspace.bind(transcript)
        candidate = scenario / "runs" / "live-worker" / f"candidate-{phase:04d}.json"
        private_json(candidate, transcript)
        record = {"phase": phase, "status": "awaiting_reading", "candidate_sha256": sha(candidate),
            "candidate_path": str(candidate), "candidate_transcript": copy.deepcopy(transcript),
            "automatic_checker_pass": transcript["score"]["pass"], "trusted_workspace": sidecar,
            "native_continuation": copy.deepcopy(transcript.get("continuation")),
            "same_live_pi_session": True, "intermediate_final_answers_retained_in_pi_history": not private_readout}
        phases.append(record)
        checkpoint("awaiting_reading")
        if continuation and transcript["messages"] == continuation["transcript"]["messages"]:
            record["status"] = "continuation_error"
            evidence = checkpoint("continuation_error", reason="native_continuation_did_not_advance")
            raise ReaderContinuationRequired("Reader continuation did not advance the original native episode", evidence)
        try:
            reading = read_candidate(candidate)
        except BaseException as error:
            record.update(status="reader_error", error_type=type(error).__name__)
            error.reader_deferred = checkpoint("reader_error", error_type=type(error).__name__)
            raise
        record["reading"] = copy.deepcopy(reading)
        checkpoint("reading_received")
        if (reading.get("dry_run") or reading.get("run_sha256") != sha(candidate)
                or reading.get("protocol") != "takeover" or reading.get("verdict") not in {"pass", "fail"}):
            raise RuntimeError("Original reader evidence is incomplete or differs from the native candidate")
        application = reading["application"]
        record.update(status="read", reading=reading)
        checkpoint("read")
        if application.get("applied") is True:
            gate = checkpoint("applied", original_reader_version=reading["reader_version"],
                final_transcript_sha256=sha(candidate), reader_pass=reading["verdict"] == "pass",
                private_reader_feedback_to_agent=False, historical_exact_resume=False)
            return transcript, sidecar, gate
        spec = application.get("continuation") or {}
        if (spec.get("kind") != "stop" or transcript.get("ended") != "scripted_stop"
                or not transcript.get("stop_gate") or spec.get("stop_gate_reading") != {"verdict": "fail"}):
            raise ReaderContinuationRequired("Original application requires a continuation not supported by this stop-only prototype",
                checkpoint("deferred", reason="unsupported_original_continuation"))
        # This is precisely the original continuation input; no judge label is
        # inferred and no previous model call may escape verified_replay.
        continuation = {"transcript": copy.deepcopy(transcript), "source": str(candidate),
            "judges": copy.deepcopy(transcript.get("judges", {})), "kind": "stop",
            "reason": spec.get("reason", "Original reader application"),
            "stop_gate_reading": {"verdict": "fail", "reading": {
                "reader_version": reading["reader_version"], "source_sha256": sha(candidate)}},
            "report": {}, "until_boundary": False}
        expected_files = sidecar.get("final_files") if sidecar["state"] == "complete" else None


def apply_final_reader(verified, gate, original_transcript):
    """Fresh verifier keeps automatic checker; apply only a genuine final reading."""
    if (gate.get("protocol") != "live-full-pi-original-reader-v1" or gate.get("status") != "applied"
            or type(gate.get("reader_pass")) is not bool or not gate.get("phases")):
        raise ValueError("Incomplete original reader gate cannot produce a reward")
    final = gate["phases"][-1]
    from collab_intel.evaluation import reader

    for index, phase in enumerate(gate["phases"]):
        t = phase["candidate_transcript"]
        digest = hashlib.sha256((json.dumps(t, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode()).hexdigest()
        observed = phase["reading"]
        if (phase["candidate_sha256"] != digest or observed["run_sha256"] != digest
                or observed["application"] != reader.application(observed, t)
                or observed["reader_version"] != reader.READER_VERSIONS["takeover"]):
            raise ValueError("A native candidate or original application in the reader chain differs")
        if index and ((t.get("continuation") or {}).get("stop_gate_reading", {}).get("reading", {}).get("source_sha256") != gate["phases"][index - 1]["candidate_sha256"]):
            raise ValueError("Native reader continuation chain differs from its original candidate")
    original_sha = hashlib.sha256((json.dumps(original_transcript, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode()).hexdigest()
    reading = final["reading"]
    if (gate.get("final_transcript_sha256") != original_sha or final.get("candidate_sha256") != original_sha
            or reading.get("run_sha256") != original_sha or reading.get("reader_version") != reader.READER_VERSIONS["takeover"]
            or reading.get("dry_run") or reading.get("protocol") != "takeover"
            or reading.get("application") != reader.application(reading, original_transcript)
            or gate["reader_pass"] != (reading.get("verdict") == "pass")):
        raise ValueError("Original reader source/application/transcript binding differs")
    if final["reading"]["application"].get("applied") is not True:
        raise ValueError("A deferred original application is not a final verdict")
    if verified["checker"]["pass"] != final["automatic_checker_pass"] or original_transcript["score"]["pass"] != final["automatic_checker_pass"]:
        raise ValueError("Fresh original checker disagrees with the read candidate; hold rather than overwrite")
    result = copy.deepcopy(verified)
    result["automatic_reward"] = result["reward"]
    result["original_reader_gate"] = copy.deepcopy(gate)
    result["reward"] = float(gate["reader_pass"])
    return result