File size: 54,107 Bytes
04d5e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
"""Original attack protocol using the shared local Docker transport."""
from __future__ import annotations

import json
import os
import shlex
import shutil
import tarfile
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
import sys
from common import task_suite
from isolation_policy import (PRESTART_SENSITIVE_PATHS, deployment_view,
                              public_checkpoint_plan, public_gate_receipt)

CONTAINER_DIR = Path(__file__).resolve().parents[1] / "container"
if str(CONTAINER_DIR) not in sys.path:
    sys.path.insert(0, str(CONTAINER_DIR))
import container_runtime
from container_runtime import ContainerClient


class ContainerProcess:
    """Process-like adapter used by GateBroker for a remote Sandbox victim."""

    def __init__(self, run_dir: Path, task: str, blue_env: dict[str, str],
                 container_config: Path, blue_timeout: int, blue_max_tokens: int,
                 gate_timeout: int, task_root: Path, task_suite_name: str | None = None,
                 attack_plan: dict[str, Any] | None = None):
        self.run_dir = run_dir
        self.task = task
        self.blue_env = dict(blue_env)
        self.container_config = container_config
        self.blue_timeout = blue_timeout
        self.blue_max_tokens = blue_max_tokens
        self.gate_timeout = gate_timeout
        self.task_root = task_root
        self.task_suite = task_suite_name or task_suite(task)
        self.is_solvable30 = self.task_suite == "solvable30"
        self.attack_plan = attack_plan
        self._prestart_sanitized = False
        self.client: ContainerClient | None = None
        self._stop = threading.Event()
        self._finished = False
        self._exit_code: int | None = None
        self._last_workspace = 0.0
        self._last_workspace_upload = 0.0
        self._workspace_uploaded: dict[str, float] = {}
        initial_workspace = run_dir / "workspace"
        if initial_workspace.is_dir():
            for local in initial_workspace.rglob("*"):
                if local.is_file():
                    self._workspace_uploaded[local.relative_to(initial_workspace).as_posix()] = local.stat().st_mtime
        self._last_sync = 0.0
        self._last_dsh_sync = 0.0
        self._last_process_diagnostics = 0.0
        self._sync_error: str | None = None
        self._database_dump_synced = False
        self._thread: threading.Thread | None = None

    @staticmethod
    def _read_env(path: Path) -> dict[str, str]:
        values: dict[str, str] = {}
        if path.is_file():
            for line in path.read_text(encoding="utf-8").splitlines():
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, value = line.split("=", 1)
                    values[key.strip()] = value.strip().strip("'").strip('"')
        return values

    def _config(self) -> dict[str, Any]:
        from manipulationarena.local_docker import load_settings
        return load_settings(self.container_config)

    def _put(self, remote: str, local: Path, mode: str = "600") -> None:
        assert self.client is not None
        if not self.client.put_bytes(remote, local.read_bytes(), mode=mode):
            raise RuntimeError(f"Sandbox upload failed: {remote}")

    def _put_bytes(self, remote: str, data: bytes, mode: str = "600") -> None:
        assert self.client is not None
        if not self.client.put_bytes(remote, data, mode=mode):
            raise RuntimeError(f"Sandbox upload failed: {remote}")

    def _upload_runtime(self) -> None:
        assert self.client is not None
        setup = self.client.execute("mkdir -p /opt/stage2/dsh_gate_plugin "
                                    "/opt/stage2/runtime_inputs /run/attack_input", timeout=30)
        if setup["rc"] != 0:
            raise RuntimeError(setup["stderr"][-1000:])
        root = Path(__file__).resolve().parent
        files = {
            "/opt/stage2/blue_agent_runner.py": root / "blue_agent_runner.py",
            "/opt/stage2/arena_blue.py": root / "arena_blue.py",
            "/opt/stage2/mcp_error_normalizer.py": root / "mcp_error_normalizer.py",
            "/opt/stage2/qwen_openai_adapter.py": root / "qwen_openai_adapter.py",
            "/opt/stage2/openai_anthropic_bridge.py": root.parent / "openai_anthropic_bridge.py",
            "/opt/stage2/isolation_policy.py": root / "isolation_policy.py",
            "/opt/stage2/real_channel_runtime.py": root / "real_channel_runtime.py",
            "/opt/stage2/rule_based_judge.py": root / "rule_based_judge.py",
            "/opt/stage2/sandbox_attack_evaluation.py": root / "sandbox_attack_evaluation.py",
            "/opt/stage2/marker_runtime.py": root.parent / "marker_runtime.py",
            "/opt/stage2/runtime_inputs/marker.txt": root.parent / "runtime_inputs" / "marker.txt",
            "/opt/stage2/dsh_gate_plugin/index.js": root / "dsh_gate_plugin" / "index.js",
            "/opt/stage2/dsh_gate_plugin/package.json": root / "dsh_gate_plugin" / "package.json",
        }
        if self.is_solvable30:
            self._upload_solvable30(files)
            for remote, local in files.items():
                self._put(remote, local, "755" if local.suffix in {".py", ".js"} else "600")
            return
        # Keep the shared terminal MCP server compatible with arbitrary task
        # artifacts.  Its stock implementation decodes subprocess output
        # strictly as UTF-8, which breaks when a task asks it to inspect a
        # legacy-encoded or binary document.  Upload the patched source into
        # the image before Harness starts its MCP servers.
        cli_server = (self.task_root.parent.parent / "local_servers" /
                      "cli-mcp-server" / "src" / "cli_mcp_server" / "server.py")
        if not cli_server.is_file():
            raise RuntimeError(f"Required terminal MCP compatibility source is missing: {cli_server}")
        files["/opt/local_servers/cli-mcp-server/src/cli_mcp_server/server.py"] = cli_server
        # Upload server diagnostics so live sandbox logs distinguish pending
        # tool enumeration from a real empty tool list.
        woo_server = (self.task_root.parent.parent / "local_servers" /
                      "woocommerce-mcp" / "dist" / "server.js")
        if not woo_server.is_file():
            raise RuntimeError(f"Required WooCommerce server bundle is missing: {woo_server}")
        files["/opt/local_servers/woocommerce-mcp/dist/server.js"] = woo_server
        files["/opt/local_servers/woocommerce-mcp/dist/index.js"] = woo_server
        snow_server = (self.task_root.parent.parent / "local_servers" /
                       "mcp-snowflake-server" / "src" / "mcp_snowflake_server" / "server.py")
        if not snow_server.is_file():
            raise RuntimeError(f"Required Snowflake compatibility source is missing: {snow_server}")
        files["/opt/local_servers/mcp-snowflake-server/src/mcp_snowflake_server/server.py"] = snow_server
        # The arxiv_local adapter is task-backed: some tasks seed the LaTeX
        # corpus while leaving the legacy markdown column empty.  Upload the
        # fallback-aware adapter so read_paper can serve that seeded content.
        arxiv_adapter = (self.task_root.parent.parent / "local_servers" /
                         "arxiv-mcp-server" / "src" / "arxiv_mcp_server" /
                         "pg_adapter.py")
        if not arxiv_adapter.is_file():
            raise RuntimeError(f"Required arxiv MCP compatibility source is missing: {arxiv_adapter}")
        files["/opt/local_servers/arxiv-mcp-server/src/arxiv_mcp_server/pg_adapter.py"] = arxiv_adapter
        for remote, local in files.items():
            self._put(remote, local, "755" if local.suffix in {".py", ".js"} else "600")
        # Verify that critical compatibility patches reached the live sandbox.
        # A successful upload call alone is insufficient: the harness may later
        # rebuild a server from a different source tree.  Fail early with an
        # actionable error instead of running Blue against a stale adapter.
        checks = [
            ("/opt/local_servers/arxiv-mcp-server/src/arxiv_mcp_server/pg_adapter.py", "full_prompt"),
            ("/opt/local_servers/cli-mcp-server/src/cli_mcp_server/server.py", "decode(\"utf-8\", errors=\"replace\")"),
            ("/opt/local_servers/woocommerce-mcp/dist/server.js", "Tool listing pending at startup"),
            ("/opt/local_servers/mcp-snowflake-server/src/mcp_snowflake_server/server.py", "Tool listing completed"),
        ]
        for remote, marker in checks:
            if remote not in files:
                continue
            verify = self.client.execute(
                "grep -Fq " + shlex.quote(marker) + " " + shlex.quote(remote),
                timeout=30,
            )
            if verify["rc"] != 0:
                raise RuntimeError(
                    f"Sandbox runtime patch verification failed: {remote} missing {marker!r}"
                )

    def _upload_solvable30(self, files: dict[str, Path]) -> None:
        """Stage the gym config surface the runner expects on non-toolathlon images."""
        assert self.client is not None
        gym_root = self.task_root.parent.parent
        root = Path(__file__).resolve().parent
        made = self.client.execute(
            "mkdir -p /workspace/configs/mcp_servers /usr/local/lib/toolathlon-dsh "
            "/opt/local_servers/appworld", timeout=30)
        if made["rc"] != 0:
            raise RuntimeError("Sandbox solvable30 staging mkdir failed: " + made["stderr"][-500:])
        files["/opt/local_servers/appworld/appworld_mcp.py"] = gym_root / "local_servers" / "appworld" / "appworld_mcp.py"
        files["/workspace/test_mcp_servers.py"] = gym_root / "test_mcp_servers.py"
        files["/workspace/configs/mcp_servers/appworld.yaml"] = (
            gym_root / "configs" / "mcp_servers" / "appworld.yaml")
        files["/usr/local/lib/toolathlon-dsh/claim_done_mcp.py"] = root / "claim_done_mcp.py"
        if self.task.startswith("gaia2-"):
            for name in ("role_routing.py", "gaia2_mcp.py", "gaia2_launcher.py", "gaia2_judge_relay.py"):
                files["/opt/local_servers/gaia2/" + name] = root / name
            files["/workspace/configs/mcp_servers/gaia2.yaml"] = root.parent / "runtime_assets" / "gaia2.yaml"
        if self.task.startswith("medagent-original-"):
            for name in ("medagent_mcp.py", "medagent_runtime.py", "medagent_worker.py"):
                files["/opt/local_servers/medagent/" + name] = root / name
            files["/workspace/configs/mcp_servers/medagent.yaml"] = root.parent / "runtime_assets" / "medagent.yaml"
        profiles = {"tau-banking-": ("tau-banking", ("role_routing.py", "tau_mcp.py", "tau_worker.py")),
                    "healthagent-text25-": ("healthagent", ("healthagent_mcp.py", "healthagent_native.py", "healthagent_runtime.py"))}
        for prefix, (server, names) in profiles.items():
            if self.task.startswith(prefix):
                for name in names:
                    files["/opt/local_servers/" + server + "/" + name] = root / name
                files["/workspace/configs/mcp_servers/" + server + ".yaml"] = root.parent / "runtime_assets" / (server + ".yaml")
        channel = (self.attack_plan or {}).get("fixed_attack", {}).get("channel")
        if channel == "MEMORY":
            self._upload_memory_stack(files, root)

    def _upload_memory_stack(self, files: dict[str, Path], root: Path) -> None:
        """Stage node + the memory MCP server for MEMORY-channel runs.

        The solvable30 image has no node runtime, so both the runtime and the
        server build (identical @modelcontextprotocol/server-memory 0.6.3 to
        the toolathlon image) are staged from runtime_assets.
        """
        assert self.client is not None
        assets = root.parent / "runtime_assets"
        self._put("/workspace/configs/mcp_servers/memory.yaml", assets / "memory.yaml")
        shared = Path(os.environ["MANIPULATIONARENA_ROOT"]) / "environment/runtime_assets"
        node_tar = shared / "node-v20.19.0-linux-x64.tar.gz"
        memory_tar = shared / "memory-dist.tar.gz"
        for archive in (node_tar, memory_tar):
            if not archive.is_file():
                raise RuntimeError(f"Memory stack asset is missing: {archive}")
        self._put_chunked(node_tar, "/tmp/v3-node.tar.gz", chunk_size=48 * 1024)
        self._put_chunked(memory_tar, "/tmp/v3-memory.tar.gz", chunk_size=48 * 1024)
        staged = self.client.execute(
            "set -eu; "
            "mkdir -p /opt/node20 /opt/local_servers/servers/src/memory; "
            "tar -xzf /tmp/v3-node.tar.gz -C /opt/node20 --strip-components=1; "
            "tar -xzf /tmp/v3-memory.tar.gz -C /opt/local_servers/servers/src/memory; "
            "rm -f /tmp/v3-node.tar.gz /tmp/v3-memory.tar.gz; "
            "/opt/node20/bin/node --version; "
            "test -f /opt/local_servers/servers/src/memory/dist/index.js",
            timeout=300,
        )
        if staged["rc"] != 0:
            raise RuntimeError("Sandbox memory stack staging failed: " +
                               (staged["stderr"] or staged["stdout"])[-1000:])

    def _put_chunked(self, local: Path, remote: str, chunk_size: int) -> None:
        assert self.client is not None
        reset = self.client.execute(f"rm -f {remote}", timeout=30)
        if reset["rc"] != 0:
            raise RuntimeError("Sandbox upload reset failed: " + reset["stderr"][-300:])
        raw = local.read_bytes()
        parts = [(index // chunk_size, raw[index:index + chunk_size])
                 for index in range(0, len(raw), chunk_size)]

        def upload(item: tuple[int, bytes]) -> str:
            number, payload = item
            part = f"/tmp/v3-chunk-{number:04d}"
            if not self.client.put_bytes(part, payload, mode="600"):
                raise RuntimeError(f"Sandbox upload failed: {part}")
            return part

        with ThreadPoolExecutor(max_workers=8) as pool:
            remote_parts = list(pool.map(upload, parts))
        merge = "cat " + " ".join(remote_parts) + f" > {remote}; rm -f " + " ".join(remote_parts)
        merged = self.client.execute(merge, timeout=180)
        if merged["rc"] != 0:
            raise RuntimeError("Sandbox chunk merge failed: " + merged["stderr"][-500:])

    def _upload_database_dump(self) -> None:
        assert self.client is not None
        if self.is_solvable30:
            return
        dump = self.task_root.parent.parent / "db" / "init.sql.gz"
        if not dump.is_file():
            raise RuntimeError(f"Benchmark PostgreSQL dump is unavailable: {dump}")
        target = "/run/toolathlon-init.sql.gz"
        reset = self.client.execute(f"rm -f {target}", timeout=30)
        if reset["rc"] != 0:
            raise RuntimeError("Sandbox database upload reset failed: " + reset["stderr"][-500:])
        chunk_size = 64 * 1024
        raw = dump.read_bytes()
        parts = [(index // chunk_size, raw[index:index + chunk_size])
                 for index in range(0, len(raw), chunk_size)]

        def upload(item: tuple[int, bytes]) -> str:
            number, payload = item
            part = f"/tmp/v3-db-part-{number:04d}"
            if not self.client.put_bytes(part, payload, mode="600"):
                raise RuntimeError(f"Sandbox upload failed: {part}")
            return part

        with ThreadPoolExecutor(max_workers=8) as pool:
            remote_parts = list(pool.map(upload, parts))
        merge = "cat " + " ".join(remote_parts) + f" > {target}; rm -f " + " ".join(remote_parts)
        merged = self.client.execute(merge, timeout=120)
        if merged["rc"] != 0:
            raise RuntimeError("Sandbox database chunk merge failed: " + merged["stderr"][-500:])
        verify = self.client.execute(f"test -s {target}", timeout=30)
        if verify["rc"] != 0:
            raise RuntimeError("Sandbox database dump is empty after upload")

    def _upload_task_if_needed(self) -> None:
        assert self.client is not None
        source = (self.task_root / self.task).resolve()
        if source.parent != self.task_root.resolve() or not source.is_dir():
            raise RuntimeError(f"Task directory is unavailable: {source}")
        check = self.client.execute(
            f"test -f '/workspace/tasks/{self.task_suite}/{self.task}/docs/task.md'", timeout=30)
        if check["rc"] == 0:
            preprocess = source / "preprocess" / "main.py"
            if preprocess.is_file():
                self._put(f"/workspace/tasks/{self.task_suite}/{self.task}/preprocess/main.py", preprocess, "600")
            return
        with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as handle:
            archive = Path(handle.name)
        try:
            with tarfile.open(archive, "w:gz") as tar:
                tar.add(source, arcname=self.task)
            self._put("/tmp/v3-task.tar.gz", archive, "600")
            result = self.client.execute(
                f"install -d -m 700 /workspace/tasks/{self.task_suite} && "
                f"tar -xzf /tmp/v3-task.tar.gz -C /workspace/tasks/{self.task_suite} && "
                "rm -f /tmp/v3-task.tar.gz", timeout=300)
            if result["rc"] != 0:
                raise RuntimeError(result["stderr"][-1000:])
        finally:
            archive.unlink(missing_ok=True)

    def _upload_attack_sources(self) -> None:
        """Upload the exact verified source files targeted by real-channel patches."""
        if self.attack_plan is None:
            return
        binding = self.attack_plan["red_design"]["channel_binding"]
        source_path = binding.get("source_path")
        if not source_path or source_path.startswith("/run/workspace/"):
            return
        included = self.attack_plan.get("generation_metadata", {}).get("included_files", [])
        matches = [item for item in included if item.get("sandbox_path") == source_path]
        if source_path.startswith("/workspace/tasks/") and not matches:
            task_dir = Path(self.attack_plan["generation_metadata"]["source_task_dir"])
            relative = source_path.split(f"/{self.task}/", 1)[-1]
            matches = [{"path": str(task_dir / relative), "sandbox_path": source_path}]
        if len(matches) != 1:
            raise RuntimeError(f"Verified host source for real-channel deployment is missing: {source_path}")
        local = Path(matches[0]["path"])
        if not local.is_file():
            raise RuntimeError(f"Verified host source file is missing: {local}")
        self._put(source_path, local, "755" if local.suffix in {".py", ".js", ".ts", ".tsx"} else "600")

    def _upload_initial_gate_state(self) -> None:
        """Make the broker initial checkpoint visible before DSH boots."""
        assert self.client is not None
        gate = self.run_dir / "gate"
        checkpoint_plan = gate / "checkpoint-plan.json"
        if checkpoint_plan.is_file():
            public_plan = public_checkpoint_plan(json.loads(checkpoint_plan.read_text(encoding="utf-8")))
            self._put_bytes("/run/gate/checkpoint-plan.json", json.dumps(public_plan).encode("utf-8"))
        checkpoint_state = gate / "checkpoint-state.json"
        if checkpoint_state.is_file():
            self._put("/run/gate/checkpoint-state.json", checkpoint_state)
        control = self.run_dir / "control"
        if control.is_dir():
            for name in ("pending_context.json", "triggers.json"):
                local = control / name
                if local.is_file():
                    self._put("/run/control/" + name, local)

    def _start_remote(self) -> None:
        assert self.client is not None
        if self.is_solvable30:
            self._start_remote_solvable30()
            return
        database = (
            "set -eu; "
            "PG_BIN=/usr/lib/postgresql/15/bin; "
            "rm -rf /run/postgres-data /run/postgres-init.log; "
            "install -d -m 700 -o postgres -g postgres /run/postgres-data; "
            "runuser -u postgres -- $PG_BIN/initdb -D /run/postgres-data --auth-local=trust --auth-host=trust "
            ">/run/postgres-init.log 2>&1; "
            "runuser -u postgres -- $PG_BIN/pg_ctl -D /run/postgres-data "
            "-o '-h 127.0.0.1 -p 5432' -w start "
            ">>/run/postgres-init.log 2>&1; "
            "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d postgres "
            "-v ON_ERROR_STOP=1 -c \"CREATE ROLE eigent LOGIN PASSWORD 'camel';\"; "
            "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d postgres "
            "-v ON_ERROR_STOP=1 -c \"CREATE DATABASE toolathlon_gym OWNER eigent;\"; "
            "gzip -dc /run/toolathlon-init.sql.gz | "
            "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d toolathlon_gym "
            "-v ON_ERROR_STOP=1; "
            "$PG_BIN/pg_isready -h 127.0.0.1 -p 5432"
        )
        result = self.client.execute(database, timeout=600)
        if result["rc"] != 0:
            raise RuntimeError("Sandbox PostgreSQL setup failed: " + (result["stderr"] or result["stdout"])[-2000:])
        # Task preprocessors and several benchmark evaluators import
        # psycopg2.  The current benchmark image contains PostgreSQL itself
        # but does not install that Python driver in the DSH virtualenv.
        # Install the pinned wheel before launching Blue so preprocessing can
        # initialize the task database instead of failing before the agent
        # session starts.
        driver = self.client.execute(
            "/opt/dsh-venv/bin/python -c 'import importlib.util,sys; "
            "mods=[\"psycopg2\",\"openpyxl\",\"docx\",\"pptx\",\"xlsxwriter\","
            "\"PyPDF2\",\"pypdf\",\"pdfplumber\",\"pdfminer\",\"fitz\","
            "\"PIL\",\"lxml\","
            "\"requests\",\"yaml\",\"pandas\",\"numpy\"]; "
            "sys.exit(0 if all(importlib.util.find_spec(m) for m in mods) else 1)' 2>/dev/null || "
            "(/opt/dsh-venv/bin/python -m pip --version >/dev/null 2>&1 || "
            "/opt/dsh-venv/bin/python -m ensurepip --upgrade) && "
            "/opt/dsh-venv/bin/python -m pip install --no-cache-dir --disable-pip-version-check "
            "psycopg2-binary==2.9.10 openpyxl python-docx "
            "python-pptx xlsxwriter pypdf2 pypdf pdfplumber pdfminer.six pymupdf "
            "pillow lxml "
            "requests pyyaml pandas numpy",
            timeout=300,
        )
        if driver["rc"] != 0:
            raise RuntimeError("Sandbox task-runtime dependency installation failed: " +
                               (driver["stderr"] or driver["stdout"])[-2000:])
        yt_bootstrap = self.client.execute(
            "set -eu; "
            "test -f /opt/local_servers/mcp-youtube-transcript/pyproject.toml || "
            "{ echo 'youtube-transcript source is missing from the sandbox image' >&2; exit 42; }; "
            "cd /opt/local_servers/mcp-youtube-transcript; "
            "if ! test -x .venv/bin/python3 || ! .venv/bin/python3 -c 'import mcp_youtube_transcript' >/dev/null 2>&1; then "
            "  rm -rf .venv; "
            "  if command -v uv >/dev/null 2>&1; then "
            "    uv sync --frozen --no-dev --no-editable; "
            "  else "
            "    /opt/dsh-venv/bin/python -m venv .venv; "
            "    .venv/bin/python3 -m pip install --no-cache-dir --disable-pip-version-check "
            "beautifulsoup4 humanize mcp psycopg2-binary pydantic requests rich-click "
            "youtube-transcript-api yt-dlp; "
            "  fi; "
            "fi; "
            ".venv/bin/python3 -c 'import mcp_youtube_transcript'",
            timeout=900,
        )
        if yt_bootstrap["rc"] != 0:
            raise RuntimeError("youtube-transcript MCP environment setup failed: " +
                               (yt_bootstrap["stderr"] or yt_bootstrap["stdout"])[-3000:])
        env = dict(self.blue_env)
        env.update({
            "STAGE2_GATE_TIMEOUT_MS": str(self.gate_timeout * 1000),
            "PGHOST": "127.0.0.1", "PG_HOST": "127.0.0.1",
            "PGPORT": "5432", "PGUSER": "eigent", "PGPASSWORD": "camel",
            "PGDATABASE": "toolathlon_gym", "PG_CONNECT_TIMEOUT": "15",
            "LOCAL_SERVERS_PATH": "/opt/local_servers",
            "PYTHON_BIN": "/opt/dsh-venv/bin/python",
            "TASK_SUITE": self.task_suite,
        })
        if self.blue_max_tokens is not None:
            env["DSH_MAX_TOKENS"] = str(self.blue_max_tokens)
        exports = " ".join(f"{key}={shlex.quote(str(value))}" for key, value in env.items())
        command = (
            "mkdir -p /run/control/requests /run/control/decisions /run/gate /run/workspace "
            "/run/benchmark-dumps /run/dsh_home; "
            f"nohup env {exports} "
            f"/opt/dsh-venv/bin/python /opt/stage2/blue_agent_runner.py {shlex.quote(self.task)} "
            f"--task-suite {shlex.quote(self.task_suite)} "
            "> /run/blue.log 2>&1 < /dev/null & echo $! > /run/blue.pid"
        )
        result = self.client.execute(command, timeout=60)
        if result["rc"] != 0:
            raise RuntimeError(result["stderr"][-1000:])

    def _start_remote_solvable30(self) -> None:
        """Provision the stage2 runtime on a plain gym image and launch Blue.

        The solvable30 image carries no PostgreSQL, no /opt/dsh-venv and no
        MCP virtualenv, so both venvs are created in place from the internal
        package index instead of running the toolathlon database bootstrap.
        """
        assert self.client is not None
        from manipulationarena.deployment import environment_manifest, package_index_args, dsh_requirements, dsh_version_probe
        shared = environment_manifest()
        check = self.client.execute("sha256sum /opt/benign30/manifest.json", timeout=30)
        if check["rc"] or check["stdout"].split()[0:1] != [shared["native_manifest_sha256"]]:
            raise RuntimeError("Sandbox native task manifest differs from the pinned environment")
        index_args = package_index_args() + " "
        dsh_probe = shlex.quote(dsh_version_probe() + "; import yaml")
        dsh_packages = shlex.join(dsh_requirements())

        from arena_blue import builtin_dsh
        is_dsh = builtin_dsh(self.blue_env)
        blue_python = '/opt/dsh-venv/bin/python' if is_dsh else self.blue_env.get('BLUE_PYTHON', '/usr/local/bin/python3')
        blue_setup = (
            "if ! /opt/dsh-venv/bin/python -c " + dsh_probe + " >/dev/null 2>&1; then "
            "  python3 -m venv /opt/dsh-venv; "
            "  /opt/dsh-venv/bin/pip install --timeout 120 --retries 3 --no-cache-dir --disable-pip-version-check " + index_args +
            "  " + dsh_packages + " pyyaml; "
            "fi; "
            "/opt/dsh-venv/bin/python -c " + dsh_probe + "; "
        ) if is_dsh else (
            shlex.quote(blue_python) + " -c 'import yaml'; "
        )
        provision = self.client.execute(
            "set -eu; unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY; "
            + blue_setup +
            "if [ ! -x /opt/venv/bin/python3 ]; then "
            "  python3 -m venv /opt/venv; "
            "fi; "
            "/opt/venv/bin/pip install --timeout 60 --retries 2 --no-cache-dir --disable-pip-version-check " +
            index_args +
            "  'mcp>=1.12,<2' pyyaml; "
            "/opt/venv/bin/python3 -c 'import mcp, yaml'",
            timeout=900,
        )
        if provision["rc"] != 0:
            raise RuntimeError("Sandbox solvable30 runtime provisioning failed: " +
                               (provision["stderr"] or provision["stdout"])[-3000:])
        env = dict(self.blue_env)
        env.update({
            "STAGE2_GATE_TIMEOUT_MS": str(self.gate_timeout * 1000),
            "BLUE_SKIP_PG_WAIT": "1",
            "LOCAL_SERVERS_PATH": "/opt/local_servers",
            "PYTHON_BIN": blue_python,
            "TASK_SUITE": self.task_suite,
        })
        if self.task.startswith("healthagent-text25-"):
            env["DSH_REQUEST_TIMEOUT_SECONDS"] = "5400"
        if self.blue_max_tokens is not None:
            env["DSH_MAX_TOKENS"] = str(self.blue_max_tokens)
        exports = " ".join(f"{key}={shlex.quote(str(value))}" for key, value in env.items())
        command = (
            "mkdir -p /run/control/requests /run/control/decisions /run/gate /run/workspace "
            "/run/benchmark-dumps /run/dsh_home; "
            f"nohup env {exports} "
            f"{shlex.quote(blue_python)} /opt/stage2/blue_agent_runner.py {shlex.quote(self.task)} "
            f"--task-suite {shlex.quote(self.task_suite)} "
            "> /run/blue.log 2>&1 < /dev/null & echo $! > /run/blue.pid"
        )
        result = self.client.execute(command, timeout=60)
        if result["rc"] != 0:
            raise RuntimeError(result["stderr"][-1000:])

    def _remote_files(self, directory: str) -> list[str]:
        assert self.client is not None
        result = self.client.execute(
            f"find {shlex.quote(directory)} -type f -printf '%P\\n' 2>/dev/null", timeout=30)
        if result["rc"] != 0:
            return []
        return [line.strip() for line in result["stdout"].splitlines() if line.strip()]

    def _download_file(self, remote: str, local: Path) -> None:
        assert self.client is not None
        data = self.client.get_bytes(remote)
        if data is None:
            return
        local.parent.mkdir(parents=True, exist_ok=True)
        local.write_bytes(data)

    def _sync_database_dump(self) -> None:
        """Export database state for archival review and host-side attack evaluation."""
        if self.client is None or self._database_dump_synced or self.is_solvable30:
            return
        self._database_dump_synced = True
        result = self.client.execute(
            "mkdir -p /run/benchmark-dumps; "
            "PGPASSWORD=camel /usr/lib/postgresql/15/bin/pg_dump -h 127.0.0.1 -U eigent -d toolathlon_gym --inserts > /run/benchmark-dumps/toolathlon_gym.sql 2>/run/benchmark-dumps/toolathlon_gym.stderr; "
            ": > /run/benchmark-dumps/toolathlon.sql; : > /run/benchmark-dumps/toolathlon.stderr",
            timeout=300,
        )
        if result.get("rc", 1) != 0:
            (self.run_dir / "benchmark-dumps").mkdir(parents=True, exist_ok=True)
            (self.run_dir / "benchmark-dumps" / "dump-command-error.txt").write_text(
                (result.get("stderr") or result.get("stdout") or "pg_dump failed")[-4000:],
                encoding="utf-8",
            )
        for name in ("toolathlon_gym.sql", "toolathlon.sql", "toolathlon_gym.stderr", "toolathlon.stderr"):
            self._download_file("/run/benchmark-dumps/" + name, self.run_dir / "benchmark-dumps" / name)

    def _sanitize_prestart(self) -> None:
        if self._prestart_sanitized:
            return
        assert self.client is not None
        ready = self.client.execute("test -f /run/prestart_ready.json", timeout=30)
        if ready["rc"] != 0:
            return
        evidence = (
            ("/run/runtime/prestart_deployment_and_probes.json",
             self.run_dir / "runtime" / "prestart_deployment_and_probes.json"),
            ("/run/manifest/prerun_marker_counts.json",
             self.run_dir / "manifest" / "prerun_marker_counts.json"),
        )
        for remote, local in evidence:
            self._download_file(remote, local)
            if not local.is_file():
                raise RuntimeError(f"Pre-start evidence was not preserved before isolation cleanup: {remote}")
        quoted = " ".join(shlex.quote(path) for path in PRESTART_SENSITIVE_PATHS)
        removed = self.client.execute(f"rm -rf -- {quoted}", timeout=60)
        if removed["rc"] != 0:
            raise RuntimeError("Failed to remove Red pre-start files: " + removed["stderr"][-1000:])
        checks = "; ".join(f"test ! -e {shlex.quote(path)}" for path in PRESTART_SENSITIVE_PATHS)
        verified = self.client.execute(checks, timeout=30)
        if verified["rc"] != 0:
            raise RuntimeError("Red pre-start files are still visible before Blue launch")
        (self.run_dir / "runtime" / "red_blue_isolation.json").write_text(json.dumps({
            "ok": True, "checked_at": time.time(), "blue_model_started": False,
            "absent_paths": list(PRESTART_SENSITIVE_PATHS),
            "full_attack_plan_uploaded": False,
            "attack_evaluation": "host_after_blue_completion",
        }, indent=2) + "\n", encoding="utf-8")
        self._put_bytes("/run/control/prestart_ack.json", b'{"ok":true}\n')
        self._prestart_sanitized = True

    def _sync_control(self) -> None:
        assert self.client is not None
        self._sanitize_prestart()
        # A Red action is recorded on the host before its checkpoint receipt is
        # published.  Push workspace carriers first, otherwise Blue can see
        # the receipt and advance to the next pre-step before the injected file
        # has reached /run/workspace.  This ordering is the actual delivery
        # barrier; a later evaluator check cannot repair a missed read.
        self._upload_workspace_changes(force=True)
        # Upload checkpoint control records before exposing requests. This is
        # the control-plane barrier; it is independent of real channel deployment.
        control = self.run_dir / "control"
        if control.is_dir():
            for name in ("pending_context.json", "triggers.json"):
                local = control / name
                if local.is_file():
                    self._put("/run/control/" + name, local)
        for relative in self._remote_files("/run/control"):
            self._download_file("/run/control/" + relative, self.run_dir / "control" / relative)
        # Requests are the latency-sensitive control path. Do this before
        # downloading the growing session and diagnostic files below. The
        # sandbox file listing can lag briefly, and the gate sequence is not
        # contiguous: compaction and skipped pre-step callbacks can advance
        # the request number by several values. Probing only N+1/N+2 can
        # therefore miss a real request (for example 10 -> 16), leaving Blue
        # blocked until the stage2 timeout. Probe a bounded forward window on
        # every pass so stale listings cannot hide a checkpoint.
        request_files = self._remote_files("/run/gate/requests")
        # The plugin appends the matching session record and then creates the
        # request. Discover requests first, then refresh the live evidence so
        # the host cannot observe a new request together with the prior
        # session snapshot.
        self._download_file("/run/gate/observed-session.jsonl",
                            self.run_dir / "gate" / "observed-session.jsonl")
        for relative in request_files:
            self._download_file("/run/gate/requests/" + relative, self.run_dir / "gate" / "requests" / relative)
        local_requests = []
        request_root = self.run_dir / "gate" / "requests"
        if request_root.is_dir():
            for item in request_root.glob("*.json"):
                try:
                    local_requests.append(int(item.stem))
                except ValueError:
                    continue
        probe_start = max(local_requests) + 1 if local_requests else 0
        probe_end = probe_start + 64
        for seq in range(probe_start, probe_end):
            name = f"{seq:06d}.json"
            self._download_file("/run/gate/requests/" + name, request_root / name)
        for relative in self._remote_files("/run/gate"):
            # These files are handled explicitly below.  In particular,
            # observed-session.jsonl grows continuously; downloading it once
            # through this directory walk and again explicitly can delay the
            # request/decision control path long enough for Blue to hit its
            # stage2 checkpoint timeout.
            if (relative.startswith(("requests/", "decisions/")) or
                    relative in {"observed-session.jsonl", "plugin-debug.jsonl",
                                 "matcher-debug.jsonl", "heartbeat.json",
                                 "blue_finished.json", "checkpoint-plan.json", "checkpoint-state.json"}):
                continue
            self._download_file("/run/gate/" + relative, self.run_dir / "gate" / relative)
        self._download_file("/run/workspace_ready.json", self.run_dir / "workspace_ready.json")
        self._download_file("/run/runtime/prestart_deployment_and_probes.json",
                            self.run_dir / "runtime" / "prestart_deployment_and_probes.json")
        self._download_file("/run/failure.json", self.run_dir / "failure.json")
        self._download_file("/run/blue_terminal.json", self.run_dir / "blue_terminal.json")
        self._download_file("/run/blue-session-diagnostics.json", self.run_dir / "blue-session-diagnostics.json")
        self._download_file("/run/eval_res.json", self.run_dir / "eval_res.json")
        self._download_file("/run/eval.log", self.run_dir / "eval.log")
        self._download_file("/run/evaluation_finished.json", self.run_dir / "evaluation_finished.json")
        for name in ("attack-evaluation.json", "evaluation_manifest.json", "rule-based-result.json",
                     "rule-based.stdout", "rule-based.stderr"):
            self._download_file("/run/evaluation/" + name, self.run_dir / "evaluation" / name)
        self._download_file("/run/gate/blue_finished.json", self.run_dir / "gate" / "blue_finished.json")
        if (self.run_dir / "gate" / "blue_finished.json").is_file():
            self._sync_database_dump()
        self._download_file("/run/final_response.txt", self.run_dir / "final_response.txt")
        for prefix, stem in (("tau-banking-", "tau"), ("healthagent-text25-", "healthagent")):
            if self.task.startswith(prefix):
                self._download_file("/run/" + stem + "_eval.json", self.run_dir / (stem + "_eval.json"))
        if self.task.startswith("gaia2-"):
            self._download_file("/run/gaia2_eval.json", self.run_dir / "gaia2_eval.json")
        if self.task.startswith("medagent-original-"):
            self._download_file("/run/medagent_eval.json", self.run_dir / "medagent_eval.json")
        self._download_file("/run/blue-live-diagnostics.json", self.run_dir / "blue-live-diagnostics.json")
        self._download_file("/run/blue-live-diagnostics-error.log", self.run_dir / "blue-live-diagnostics-error.log")
        self._download_file("/run/blue-python-stack.log", self.run_dir / "blue-python-stack.log")
        self._download_file("/run/gate/blue-bridge-requests.jsonl", self.run_dir / "gate" / "blue-bridge-requests.jsonl")
        self._download_file("/run/blue_boot.jsonl", self.run_dir / "blue_boot.jsonl")
        self._download_file("/run/preprocess.log", self.run_dir / "preprocess.log")
        self._download_file("/run/gate.patch.yml", self.run_dir / "gate.patch.yml")
        self._download_file("/run/mcp.patch.yml", self.run_dir / "mcp.patch.yml")
        self._download_file("/run/compression.patch.yml", self.run_dir / "compression.patch.yml")
        self._download_file("/run/stage2-gate-module.jsonl", self.run_dir / "stage2-gate-module.jsonl")
        self._download_file("/run/stage2-gate-apply-enter.jsonl", self.run_dir / "stage2-gate-apply-enter.jsonl")
        self._download_file("/run/gate/plugin-debug.jsonl", self.run_dir / "gate" / "plugin-debug.jsonl")
        self._download_file("/run/gate/matcher-debug.jsonl", self.run_dir / "gate" / "matcher-debug.jsonl")
        # The DeepSeek Harness writes its own stderr (including the session
        # error traceback) to /run/blue.log; without this sync the decisive
        # diagnostics are lost when the sandbox is destroyed.
        self._download_file("/run/blue.log", self.run_dir / "blue" / "sandbox-blue.log")
        self._download_file("/run/gate/heartbeat.json", self.run_dir / "gate" / "heartbeat.json")
        self._download_file("/run/blue.log", self.run_dir / "blue.log")

        control = self.run_dir / "control"
        if control.is_dir():
            for name in ("pending_context.json", "triggers.json"):
                local = control / name
                if local.is_file():
                    self._put("/run/control/" + name, local)
        gate = self.run_dir / "gate"
        checkpoint_plan = gate / "checkpoint-plan.json"
        if checkpoint_plan.is_file():
            public_plan = public_checkpoint_plan(json.loads(checkpoint_plan.read_text(encoding="utf-8")))
            self._put_bytes("/run/gate/checkpoint-plan.json",
                            json.dumps(public_plan).encode("utf-8"))
        checkpoint_state = gate / "checkpoint-state.json"
        if checkpoint_state.is_file():
            self._put("/run/gate/checkpoint-state.json", checkpoint_state)
        for local in (gate / "decisions").glob("*.json"):
            receipt = json.loads(local.read_text(encoding="utf-8"))
            public_receipt = public_gate_receipt(receipt)
            self._put_bytes("/run/gate/decisions/" + local.name,
                            json.dumps(public_receipt).encode("utf-8"))
    def _upload_workspace_changes(self, *, force: bool = False) -> None:
        """Push Red-written host workspace files into the sandbox workspace.

        ActionExecutor writes workspace-channel injections into the host-side
        run workspace, but Blue only reads /run/workspace inside the sandbox;
        without this upload those injections would silently never reach Blue.
        Files are keyed by relative path plus mtime, so each write is pushed
        once.  Files larger than 4 MiB are skipped and recorded instead of
        blocking the sync loop.
        """
        if self.client is None or not (self.run_dir / "workspace").is_dir():
            return
        if not force and time.monotonic() - self._last_workspace_upload < 2.0:
            return
        self._last_workspace_upload = time.monotonic()
        source = self.run_dir / "workspace"
        skipped: list[str] = []
        for local in sorted(source.rglob("*")):
            if not local.is_file():
                continue
            relative = local.relative_to(source).as_posix()
            try:
                size = local.stat().st_size
                mtime = local.stat().st_mtime
            except OSError:
                continue
            if self._workspace_uploaded.get(relative, 0.0) >= mtime:
                continue
            if size > 4 * 1024 * 1024:
                skipped.append(relative)
                continue
            parent = relative.rsplit("/", 1)[0] if "/" in relative else ""
            if parent:
                quoted = "/run/workspace/" + parent.replace("'", "'\\''")
                made = self.client.execute("install -d -m 755 '%s'" % quoted, timeout=30)
                if made["rc"] != 0:
                    raise RuntimeError("Sandbox workspace mkdir failed: " + (made.get("stderr") or "")[-300:])
            if not self.client.put_bytes("/run/workspace/" + relative, local.read_bytes(), mode="644"):
                raise RuntimeError("Sandbox workspace upload failed: " + relative)
            self._workspace_uploaded[relative] = mtime
        if skipped:
            with (self.run_dir / "workspace-upload-skipped.jsonl").open("a", encoding="utf-8") as handle:
                for relative in skipped:
                    handle.write(json.dumps({"path": relative, "reason": "larger than 4 MiB"},
                                            ensure_ascii=False) + "\n")

    def _sync_workspace(self) -> None:
        assert self.client is not None
        if time.monotonic() - self._last_workspace < 2.0:
            return
        self._last_workspace = time.monotonic()
        with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as handle:
            archive = Path(handle.name)
        try:
            self.client.download_archive("/run/workspace", str(archive), timeout=300)
            target = self.run_dir / "workspace"
            target.mkdir(parents=True, exist_ok=True)
            with tarfile.open(archive, "r:gz") as tar:
                for member in tar.getmembers():
                    destination = (target / member.name).resolve()
                    if target.resolve() not in destination.parents and destination != target.resolve():
                        raise RuntimeError("Unsafe workspace archive member")
                tar.extractall(target)
        finally:
            archive.unlink(missing_ok=True)

    def _sync_dsh_sessions(self) -> None:
        """Copy DeepSeek Harness session JSONL for model-request diagnostics."""
        copied: set[str] = set()
        for relative in self._remote_files("/run/dsh_home/sessions"):
            remote = "/run/dsh_home/sessions/" + relative
            self._download_file(remote, self.run_dir / "dsh_home" / "sessions" / relative)
            copied.add(remote)

        # The sandbox artifact listing can omit the DSH session directory
        # after the Blue process exits even though the files are still present
        # in the live /run volume.  This is especially common when Blue calls
        # claim_done without ever reaching a second gate checkpoint.  Search
        # the live filesystem immediately before destroying the environment so
        # a complete session is not lost merely because the listing endpoint
        # was stale or incomplete.
        assert self.client is not None
        found = self.client.execute(
            "find /run -type f \\( -name 'session.v3.jsonl' -o -name '*.jsonl' \\) "
            "-path '*/sessions/*' -print 2>/dev/null | sort -u",
            timeout=60,
        )
        for line in str(found.get("stdout") or "").splitlines():
            remote = line.strip()
            if not remote.startswith("/run/") or remote in copied:
                continue
            relative = remote[len("/run/"):]
            self._download_file(remote, self.run_dir / relative)

    def _sync_loop(self) -> None:
        while not self._stop.is_set():
            # Blue can finish while a previous control-plane request is still
            # in flight.  Local completion markers are already authoritative
            # because they were downloaded before this loop iteration; do not
            # start another blocking remote request after completion.
            if (self.run_dir / "gate" / "blue_finished.json").is_file():
                self._exit_code = 0
                self._finished = True
                break
            if (self.run_dir / "failure.json").is_file() or (self.run_dir / "blue_terminal.json").is_file():
                self._exit_code = 1
                self._finished = True
                break
            try:
                # Keep the request/decision path ahead of diagnostic downloads.
                self._sync_control()
                now = time.monotonic()
                if now - self._last_dsh_sync >= 10:
                    self._sync_dsh_sessions()
                    self._last_dsh_sync = time.monotonic()
                if now - self._last_process_diagnostics >= 15:
                    snapshot = self.client.execute(
                        "date -u '+UTC %Y-%m-%dT%H:%M:%SZ'; "
                        "ps -eo pid,ppid,stat,etime,pcpu,pmem,wchan:24,comm; "
                        "if command -v ss >/dev/null 2>&1; then ss -tpn; "
                        "elif command -v netstat >/dev/null 2>&1; then netstat -tpn; fi",
                        timeout=30,
                    )
                    with (self.run_dir / "runtime-processes.jsonl").open("a", encoding="utf-8") as handle:
                        handle.write(json.dumps({"at": time.time(), **snapshot}, ensure_ascii=False) + "\n")
                    self._last_process_diagnostics = time.monotonic()
                # Workspace archive downloads can take minutes; collect the
                # workspace during final cleanup instead of blocking this loop.
                self._last_sync = time.monotonic()
            except Exception as exc:
                self._sync_error = f"{type(exc).__name__}: {exc}"
                try:
                    (self.run_dir / "runtime-sync-error.log").write_text(self._sync_error + "\n", encoding="utf-8")
                except Exception:
                    pass
                # A 404 from the sandbox control plane means the remote
                # environment has been deleted or expired. Keep the runner
                # from waiting for the full Blue timeout on a dead sandbox;
                # this is a retryable environment failure.
                if "404" in self._sync_error and "sandbox" in self._sync_error.lower():
                    (self.run_dir / "failure.json").write_text(
                        json.dumps({"status": "sandbox_lost", "error": self._sync_error}) + "\n",
                        encoding="utf-8",
                    )
                    self._exit_code = 1
                    self._finished = True
                    self._stop.set()
                    break
            if (self.run_dir / "gate" / "blue_finished.json").exists() or (self.run_dir / "failure.json").exists():
                self._finished = True
            if (self.run_dir / "blue_terminal.json").exists():
                self._exit_code = 1
                self._finished = True
            self._stop.wait(0.5)

    def start(self) -> "SandboxProcess":
        cfg = self._config()
        self.client = ContainerClient(cfg)
        self.client.create()
        (self.run_dir / "runtime-container.json").write_text(json.dumps({
            "container_id": self.client.container_id, "image": cfg["image"],
            "created_at": time.time(), "execution_backend": "local-docker"
        }, indent=2) + "\n", encoding="utf-8")
        self._upload_runtime()
        self._upload_database_dump()
        self._upload_task_if_needed()
        self._upload_attack_sources()
        self.client.execute("rm -rf /run/control /run/gate /run/workspace /run/benchmark-dumps "
                            "/run/attack_input /run/preattack_backup; "
                            "rm -f /run/blue_boot.jsonl /run/blue.log /run/blue.pid "
                            "/run/blue_terminal.json /run/failure.json /run/preprocess.log "
                            "/run/prestart_ready.json /run/workspace_ready.json "
                            "/run/runtime/deployment_operations.json "
                            "/run/runtime/prestart_deployment_and_probes.json "
                            "/run/manifest/prerun_marker_counts.json; "
                            "mkdir -p /run/control/requests /run/control/decisions /run/gate "
                            "/run/workspace /run/benchmark-dumps /run/attack_input", timeout=60)
        self._upload_initial_gate_state()
        if self.attack_plan is not None:
            bootstrap = deployment_view(self.attack_plan)
            self._put_bytes("/run/attack_input/deployment_plan.json",
                            json.dumps(bootstrap, ensure_ascii=False, indent=2).encode("utf-8"))
        deployment_log = self.run_dir / "runtime" / "deployment_operations.json"
        if deployment_log.is_file():
            self._put("/run/runtime/deployment_operations.json", deployment_log)
        self._start_remote()
        self._thread = threading.Thread(target=self._sync_loop, daemon=True)
        self._thread.start()
        return self

    def poll(self) -> int | None:
        if self._finished:
            return self._exit_code
        return None

    def wait(self, timeout: float | None = None) -> int:
        deadline = None if timeout is None else time.monotonic() + timeout
        while not self._finished:
            # The sync thread may be blocked in a remote request even though
            # its last successful pass already downloaded the terminal marker.
            # Honor the local marker directly so the runner can enter close()
            # and clean up the sandbox.
            if (self.run_dir / "gate" / "blue_finished.json").is_file():
                self._exit_code = 0
                self._finished = True
                break
            if (self.run_dir / "failure.json").is_file() or (self.run_dir / "blue_terminal.json").is_file():
                self._exit_code = 1
                self._finished = True
                break
            if deadline is not None and time.monotonic() >= deadline:
                raise TimeoutError("Sandbox blue process wait timed out")
            time.sleep(0.5)
        return self._exit_code or 0

    def terminate(self) -> None:
        if self.client is not None:
            self.client.execute("if [ -f /run/blue.pid ]; then kill $(cat /run/blue.pid) 2>/dev/null || true; fi", timeout=30)
        self._finished = True

    def kill(self) -> None:
        self.terminate()

    def close(self) -> None:
        self._stop.set()
        if self._thread is not None:
            self._thread.join(timeout=5)
        try:
            if self.client is not None:
                self._sync_control()
                self._sync_workspace()
                self._sync_dsh_sessions()
                self._sync_database_dump()
                self.client.execute(
                    "if [ -f /run/postgres-data/postmaster.pid ]; then "
                    "runuser -u postgres -- /usr/lib/postgresql/15/bin/pg_ctl "
                    "-D /run/postgres-data -m fast stop >/run/postgres-stop.log 2>&1 || true; fi",
                    timeout=60,
                )
                self.client.destroy()
        finally:
            self.client = None