Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 9,790 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
"""Private full-workspace evidence without changing upstream checker inputs.

The pinned Sandbox.snapshot remains Python-only. This process-local scope reads
the complete bounded text workspace immediately before the primary Sandbox is
cleaned up. No submitted code is imported or executed here.
"""
from __future__ import annotations

import copy
import hashlib
import threading
from contextlib import contextmanager
from pathlib import Path

from .coding import ExecutionError, snapshot, validate_files

_CAPTURE_LOCK = threading.Lock()


def _text_hashes(files: dict[str, str]) -> dict[str, str]:
    return {name: hashlib.sha256(content.encode()).hexdigest() for name, content in files.items()}


def _native_text(text: str) -> str:
    return text.replace("\r\n", "\n").replace("\r", "\n")


def validate_workspace(sidecar: dict, transcript: dict, record: dict) -> dict[str, str]:
    """Validate private full files against pinned source and native evidence.

    The caller supplies the already selected source version's record. No agent
    path, verdict or declared file hash is trusted without recomputation. This
    validates text evidence only and never imports or executes workspace code.
    """
    required = {"schema_version", "state", "final_files", "text_hashes", "raw_hashes", "initial_text_hashes",
                "test_files", "hashes_before", "hashes_after", "test_files_before"}
    if (not isinstance(sidecar, dict) or set(sidecar) != required
            or type(sidecar.get("schema_version")) is not int or sidecar["schema_version"] != 1
            or sidecar.get("state") != "complete"):
        raise ExecutionError("Invalid or incomplete trusted workspace sidecar")
    if not isinstance(transcript, dict) or not isinstance(record, dict):
        raise ExecutionError("Invalid workspace source binding")
    native = transcript.get("sandbox")
    if not isinstance(native, dict):
        raise ExecutionError("Trusted workspace requires a native sandbox")
    try:
        files = validate_files(sidecar["final_files"])
        originals = validate_files(record.get("sandbox_files"))
        hashes = _text_hashes(files)
        initial_hashes = _text_hashes(originals)
    except (UnicodeError, TypeError, ValueError) as error:
        raise ExecutionError("Invalid UTF-8 workspace content") from error
    if sidecar["text_hashes"] != hashes or sidecar["raw_hashes"] != hashes:
        raise ExecutionError("Trusted workspace content hash mismatch")
    if sidecar["initial_text_hashes"] != initial_hashes:
        raise ExecutionError("Trusted workspace initial source hash mismatch")
    protected = record.get("test_files")
    if (not isinstance(protected, list) or any(not isinstance(name, str) for name in protected)
            or len(set(protected)) != len(protected) or any(name not in originals for name in protected)):
        raise ExecutionError("Invalid protected workspace source files")
    expected_before = {name: initial_hashes[name] for name in protected}
    expected_contents = {name: _native_text(originals[name]) for name in protected}
    expected_after = {name: hashes.get(name) for name in protected}
    expected = {"test_files": protected, "hashes_before": expected_before, "hashes_after": expected_after,
                "test_files_before": expected_contents}
    for name, value in expected.items():
        if sidecar[name] != value or native.get(name) != value:
            raise ExecutionError(f"Trusted workspace differs from native/source {name}")
    expected_python = {name: _native_text(content) for name, content in files.items() if name.endswith(".py")}
    if native.get("final_files") != expected_python:
        raise ExecutionError("Trusted workspace differs from native Python-only snapshot")
    return copy.deepcopy(files)


class WorkspaceCapture:
    """A single native episode's trusted private sidecar, never public input."""

    def __init__(self):
        self.state = "waiting"
        self._primary = None
        self._files = None
        self._integrity = None
        self._raw_hashes = None
        self._initial_hashes = None
        self._closed = False

    @property
    def final_files(self) -> dict[str, str] | None:
        return copy.deepcopy(self._files) if self.state == "complete" else None

    def bind(self, transcript: dict) -> dict:
        """Bind complete private evidence to the original native integrity data.

        Full file content preserves UTF-8 bytes including CRLF. raw_hashes bind
        the protected bytes the upstream integrity method hashed; text_hashes
        bind serialized UTF-8 content. Both therefore agree for valid captures.
        """
        if self.state == "not_applicable":
            if transcript.get("sandbox") is not None:
                raise ExecutionError("Native sandbox is missing its trusted workspace capture")
            return {"schema_version": 1, "state": self.state}
        if self.state != "complete" or self._files is None or self._integrity is None:
            raise ExecutionError(f"Workspace capture is not complete: {self.state}")
        native = transcript.get("sandbox")
        if not isinstance(native, dict):
            raise ExecutionError("Workspace capture has no native sandbox binding")
        for key in ("test_files", "hashes_before", "hashes_after", "test_files_before"):
            if native.get(key) != self._integrity.get(key):
                raise ExecutionError(f"Workspace capture differs from native {key}")
        python_files = {name: _native_text(text)
                        for name, text in self._files.items() if name.endswith(".py")}
        if native.get("final_files") != python_files:
            raise ExecutionError("Workspace capture differs from native Python-only snapshot")
        for name, expected in native["hashes_before"].items():
            if self._initial_hashes.get(name) != expected:
                raise ExecutionError("Workspace capture differs from protected initial bytes")
        for name, expected in native["hashes_after"].items():
            if self._raw_hashes.get(name) != expected:
                raise ExecutionError("Workspace capture differs from protected final bytes")
        return {"schema_version": 1, "state": "complete", "final_files": copy.deepcopy(self._files),
                "text_hashes": _text_hashes(self._files), "raw_hashes": dict(self._raw_hashes),
                "initial_text_hashes": dict(self._initial_hashes),
                "test_files": copy.deepcopy(native["test_files"]),
                "hashes_before": copy.deepcopy(native["hashes_before"]),
                "hashes_after": copy.deepcopy(native["hashes_after"]),
                "test_files_before": copy.deepcopy(native["test_files_before"])}


@contextmanager
def capture_workspace():
    """Capture exactly one primary Sandbox across a complete native episode.

    Overlapping scopes and additional Sandbox instances fail closed. Scratch
    directories created by the original checkers are not Sandbox instances.
    Cleanup failures or exceptional episode exits never produce complete data.
    """
    from collab_intel.harness.sandbox import Sandbox

    if not _CAPTURE_LOCK.acquire(blocking=False):
        raise ExecutionError("Overlapping workspace capture scopes are unsupported")
    original_init, original_cleanup = Sandbox.__init__, Sandbox.cleanup
    capture = WorkspaceCapture()

    def initialize(instance, *args, **kwargs):
        if capture._primary is not None:
            capture.state = "ambiguous"
            raise ExecutionError("An episode created multiple primary Sandbox instances")
        capture._primary = instance
        capture.state = "initializing"
        try:
            original_init(instance, *args, **kwargs)
            capture._initial_hashes = _text_hashes(snapshot(instance.dir))
            capture.state = "active"
        except BaseException:
            capture.state = "initialization_failed"
            raise

    def cleanup(instance):
        if instance is not capture._primary:
            capture.state = "ambiguous"
            raise ExecutionError("Cleanup does not belong to the primary Sandbox")
        if capture._closed:
            return original_cleanup(instance)
        try:
            capture._files = snapshot(instance.dir)
            capture._raw_hashes = {name: hashlib.sha256((instance.dir / name).read_bytes()).hexdigest()
                                   for name in capture._files}
            capture._integrity = copy.deepcopy(instance.integrity())
        except BaseException:
            capture.state = "capture_failed"
            raise
        finally:
            try:
                original_cleanup(instance)
            except BaseException:
                capture.state = "cleanup_failed"
                raise
        if Path(instance.dir).exists():
            capture.state = "cleanup_failed"
            raise ExecutionError("Primary Sandbox cleanup did not remove its workspace")
        capture._closed = True
        if capture.state == "active":
            capture.state = "captured"

    Sandbox.__init__, Sandbox.cleanup = initialize, cleanup
    try:
        yield capture
    except BaseException:
        if capture.state not in {"initialization_failed", "capture_failed", "cleanup_failed", "ambiguous"}:
            capture.state = "episode_failed"
        raise
    else:
        if capture._primary is None:
            capture.state = "not_applicable"
        elif capture.state == "captured":
            capture.state = "complete"
        elif capture.state == "active":
            capture.state = "abandoned"
    finally:
        Sandbox.__init__, Sandbox.cleanup = original_init, original_cleanup
        _CAPTURE_LOCK.release()