Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 26,451 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fea7d1
 
 
5873600
 
 
 
 
 
 
 
 
4fea7d1
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0082d1f
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
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
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
"""Generate self-contained Harbor tasks from the pinned public Sharing scenarios."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import yaml

from .pi_bash_timeout import docker_bash_timeout_lines
from .pi_capture import docker_capture_lines
from .provenance import task_code_identity
from .sources import ALIASES, DIMENSIONS, copy_private_source, normalized_dimension
from .vendor import PINNED_REVISION, copy_upstream

DIMENSION = "sharing_and_seeking_information"
PROTOCOL = "ci-harbor-v1"
# v3.3: Pi bash calls that set no timeout get 120 s (Claude Code's default). Measured on the v3.2
# sweep: no finished run had a command above 74 s; the only longer ones were hung full-disk greps.
LOCAL_BASH_TIMEOUT_SEC = 120
BASE_IMAGE = "python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f"
RUNTIME_REQUIREMENTS = Path(__file__).with_name("runtime-requirements.lock").read_text()
RUNTIME_LOCK_SHA256 = hashlib.sha256(RUNTIME_REQUIREMENTS.encode()).hexdigest()
AGENT_DOCKERFILE = f'''FROM {BASE_IMAGE}
RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
COPY collab_harbor /app/collab_harbor
COPY team /usr/local/bin/team
COPY collab_harbor/pi-google.js /tmp/harbor-pi-agent/extensions/collab-google.js
{docker_capture_lines()}
{docker_bash_timeout_lines(LOCAL_BASH_TIMEOUT_SEC)}
RUN chmod 755 /usr/local/bin/team
ENV PYTHONPATH=/app TEAM_URL=http://team:8000
WORKDIR /workspace
'''
TEAM_INTERFACE_INSTRUCTIONS = '''

## Team interface

Start with `team read --wait 30`. It shows your own current instructions, the
conversation and a request ID. For a chat turn, use
`team say --request-id ID --file message.txt` (or supply the text as an argument).
For a final-answer request, use `team answer --request-id ID --reasoning TEXT ANSWER`.
For workspace requests, use `team tool --request-id ID NAME --arguments-json JSON`
with the tools listed in that request. `team tools --request-id ID --calls-json JSON`
submits an ordered array of native tool calls. `team answer --structured-json JSON`
preserves a structured final answer. Read again after each accepted response.
Do not answer before the final question is asked. Finish when `team read` reports
`finished`. These transport instructions add no information to the scenario.
'''


def public_agent_files() -> dict[str, bytes]:
    """The complete public context; no scenario data belongs in these files."""
    package = Path(__file__).parent
    return {"Dockerfile": AGENT_DOCKERFILE.encode(),
            "team": b'#!/bin/sh\nexec python -m collab_harbor.cli "$@"\n',
            "collab_harbor/__init__.py": b'"""Public team client."""\n',
            **{"collab_harbor/" + name: (package / name).read_bytes()
               for name in ("cli.py", "pi-google.js", "pi-capture.js", "pi-bash-timeout.js")}}


def validate_public_agent_context(task: Path, instructions: str, identity: dict) -> None:
    """Reject public payload drift, including hidden facts outside code hashes."""
    if (task / "instruction.md").read_text() != instructions + TEAM_INTERFACE_INSTRUCTIONS:
        raise ValueError("Public instructions differ from the generic v2 bootstrap")
    expected = public_agent_files()
    root = task / "environment/agent"
    actual = {}
    for path in root.rglob("*"):
        if path.is_symlink():
            raise ValueError("Public agent context cannot contain symlinks")
        if path.is_file():
            actual[path.relative_to(root).as_posix()] = path.read_bytes()
    if actual != expected or (task / "environment/Dockerfile").read_bytes() != expected["Dockerfile"]:
        raise ValueError("Public agent context differs from the generic client and private capture files")
    compose = yaml.safe_load((task / "environment/docker-compose.yaml").read_text())
    main = {"image": "ci-agent:" + identity["scenario_sha256"][:12],
            "build": {"context": "./agent"},
            "security_opt": ["no-new-privileges:true"],
            "depends_on": {"team": {"condition": "service_healthy"}}}
    if compose.get("services", {}).get("main") != main:
        raise ValueError("Public main service must retain the isolated client build context")


def _worker_requirements() -> str:
    # pytest 9.1.1's complete dependency closure in the same exported lock.
    # Keep provider SDKs out of the execution worker.
    required = {"pytest", "iniconfig", "packaging", "pluggy", "pygments", "colorama"}
    found, blocks = set(), []
    for block in re.split(r"(?=^[a-z0-9][a-z0-9_.-]*==)", RUNTIME_REQUIREMENTS, flags=re.M):
        name = block.partition("==")[0]
        if name in required:
            if "--hash=sha256:" not in block:
                raise ValueError(f"Runtime lock has no artifact hash for {name}")
            found.add(name)
            blocks.append(block)
    if found != required:
        raise ValueError(f"Runtime lock is missing executor dependencies: {sorted(required - found)}")
    return "".join(blocks)


def _write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content)
    if path.suffix == ".sh":
        path.chmod(0o755)


def scenario_digest(path: Path) -> str:
    result = hashlib.sha256()
    for file in sorted(path.rglob("*")):
        if file.is_symlink():
            raise ValueError(f"Symlinks are not portable scenario inputs: {file}")
        if file.is_file() and "__pycache__" not in file.parts:
            result.update(file.relative_to(path).as_posix().encode() + b"\0")
            result.update(file.read_bytes() + b"\0")
    return result.hexdigest()


def _verify_scenario(upstream: Path, scenario: Path) -> None:
    for file in sorted(scenario.rglob("*")):
        if file.is_symlink():
            raise ValueError(f"Scenario symlink: {file}")
        if not file.is_file() or "__pycache__" in file.parts:
            continue
        relative = file.relative_to(upstream).as_posix()
        result = subprocess.run(
            ["git", "-C", str(upstream), "show", f"{PINNED_REVISION}:{relative}"],
            capture_output=True, check=False,
        )
        if result.returncode or result.stdout != file.read_bytes():
            raise ValueError(f"Scenario input differs from pinned source: {relative}")


def _load_rendering(upstream: Path):
    # Import the upstream renderer, not a reconstruction of its formatting. Its
    # model clients are lazy, so generating tasks makes no provider requests.
    source = str(upstream / "src")
    if source not in sys.path:
        sys.path.insert(0, source)
    from collab_intel.harness.episode import build_seats, load_episode, render_system
    return build_seats, load_episode, render_system


def _copy_runtime(destination: Path, *, agent_only: bool = False) -> None:
    package = Path(__file__).parent
    if agent_only:
        destination.mkdir(parents=True, exist_ok=True)
        _write(destination / "__init__.py", '"""Public team client."""\n')
        shutil.copyfile(package / "cli.py", destination / "cli.py")
        shutil.copyfile(package / "pi-google.js", destination / "pi-google.js")
        shutil.copyfile(package / "pi-capture.js", destination / "pi-capture.js")
        shutil.copyfile(package / "pi-bash-timeout.js", destination / "pi-bash-timeout.js")
    else:
        inventory = json.loads((package / "runtime-files.json").read_text())
        names = inventory.get("files")
        if (inventory.get("schema_version") != 1 or not isinstance(names, list)
                or not names or len(names) != len(set(names))):
            raise ValueError("Invalid product runtime allowlist")
        destination.mkdir(parents=True, exist_ok=True)
        for name in names:
            if (not isinstance(name, str) or not name or Path(name).name != name
                    or name in {".", ".."} or (package / name).is_symlink()):
                raise ValueError("Unsafe product runtime file")
            shutil.copyfile(package / name, destination / name)


ORACLE = '''"""Trusted reference policy; interacts only through the public team CLI."""
import json
import subprocess
import time
from pathlib import Path

policy = json.loads(Path("/solution/policy.json").read_text())
step = 0
deadline = time.monotonic() + 900
while time.monotonic() < deadline:
    response = subprocess.run(["team", "read", "--wait", "30"], capture_output=True, text=True, check=True)
    state = json.loads(response.stdout)
    if state["state"] == "finished":
        break
    if state["state"] in ("abandoned", "infrastructure_error"):
        raise RuntimeError("Reference episode failed: " + state["state"])
    request = state.get("request")
    if request is None:
        continue
    common = ["--request-id", request["request_id"]]
    if request["kind"] == "final_answer":
        command = ["team", "answer", *common, "--reasoning", "Based on the team's complete notes.", policy["answer"]]
    elif request["kind"] == "tool":
        actions = policy["actions"]
        if step >= len(actions):
            raise RuntimeError("Reference coding policy exhausted")
        action = actions[step]
        step += 1
        command = ["team", "tool", *common, action["name"], "--arguments-json", json.dumps(action["arguments"])]
    else:
        command = ["team", "say", *common, policy["message"]]
    subprocess.run(command, check=True)
else:
    raise TimeoutError("Reference policy deadline exceeded")
'''


def _policy(episode: dict, record: dict, version: str) -> dict:
    script = episode.get("scripted_teammate", {})
    seats = episode.get("seat_overrides", {}).get(version) or episode["seats"]
    holder = seats[script.get("seat", len(seats) - 1)]["name"]
    own = " ".join((record.get("private_facts") or [[]])[0])
    message = (
        own + f" {holder}, please read your original notes and the full requirements word for word, "
        "including every line and detail you regard as irrelevant or belonging to someone else."
    ).strip()
    checker = episode["checker"]
    answer = checker.get("control_correct_option") if version == "control" else None
    answer = str(answer or checker.get("correct_option") or record.get("correct_option") or "shipped")
    actions = []
    if episode.get("environment") == "sandbox":
        if version != "solo":
            actions.append({"name": "send_message", "arguments": {"text": message}})
        solution = record.get("reference_solution")
        if not isinstance(solution, str):
            raise ValueError("Coding reference policy requires a trusted reference solution")
        actions.extend([
            {"name": "edit_file", "arguments": {"path": "solution.py", "content": solution}},
            {"name": "run_tests", "arguments": {}},
            {"name": "submit", "arguments": {"note": "Implemented the full requirements and ran the visible tests."}},
        ])
        answer = "shipped"
    return {"message": message, "answer": answer, "actions": actions}


def _build_task(
    task: Path, scenario: Path, episode: dict, record: dict, version: str, seed: int,
    identity: dict, vendor: Path, partners: list[str], instructions: str, integrity_policy: str,
    *, source_provenance: dict | None = None, upstream: Path | None = None,
) -> None:
    name = task.name
    env = task / "environment"
    for relative, data in public_agent_files().items():
        destination = env / "agent" / relative
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_bytes(data)
    # Compose owns the narrower build contexts; Harbor still requires this file.
    _write(env / "Dockerfile", AGENT_DOCKERFILE)
    team = env / "team"
    _copy_runtime(team / "adapter/collab_harbor")
    shutil.copytree(vendor, team / "upstream")
    source_provenance = source_provenance or {"kind": "git"}
    team_archive = copy_private_source(scenario, source_provenance, team, upstream,
                                       runtime_archive="/private/scenario.zip")
    config = {
        "scenario_path": "/private/scenario", "version": version, "seed": seed,
        "partner_models": partners, "identity": identity,
        "openai_effort": {"gpt-5-mini": "minimal"},
        "runtime_lock_sha256": RUNTIME_LOCK_SHA256,
        "integrity_policy": integrity_policy,
        "public_client_sha256": hashlib.sha256((env / "agent/collab_harbor/cli.py").read_bytes()).hexdigest(),
        "private_final_readout": {"protocol": "native-stateless-final-readout-v1"},
    }
    if team_archive is not None:
        config["scenario_archive"] = team_archive
    coding = episode.get("environment") == "sandbox"
    if coding:
        config["execution_url"] = "http://worker:8002"
    _write(team / "task.json", json.dumps(config, indent=2) + "\n")
    _write(team / "requirements.txt", RUNTIME_REQUIREMENTS)
    _write(team / "Dockerfile", f'''FROM {BASE_IMAGE}
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --require-hashes -r /app/requirements.txt
COPY adapter /app/adapter
COPY upstream /app/upstream
{('COPY scenario.zip /private/scenario.zip' if team_archive else 'COPY scenario /private/scenario')}
COPY task.json /private/task.json
RUN mkdir -p /evidence
ENV PYTHONPATH=/app/adapter:/app/upstream/src CI_TASK_CONFIG=/private/task.json HARNESS_USAGE_LOG=/evidence/usage.jsonl
CMD ["python", "-m", "collab_harbor.service"]
''')
    _write(env / "docker-compose.yaml", f'''services:
  main:
    image: ci-agent:{identity["scenario_sha256"][:12]}
    build:
      context: ./agent
    security_opt: [no-new-privileges:true]
    depends_on:
      team:
        condition: service_healthy
  team:
    image: ci-team:{name}
    build:
      context: ./team
    networks: [default, team]
    environment:
      ANTHROPIC_API_KEY: ${{ANTHROPIC_API_KEY:-}}
      ANTHROPIC_WORKSPACE_ID: ${{ANTHROPIC_WORKSPACE_ID:-}}
      ANTHROPIC_BASE_URL: ${{ANTHROPIC_BASE_URL:-https://api.anthropic.com}}
      OPENAI_API_KEY: ${{OPENAI_API_KEY:-}}
      OPENAI_BASE_URL: ${{OPENAI_BASE_URL:-https://api.openai.com/v1}}
      CI_EVALUATED_MODEL: ${{CI_EVALUATED_MODEL:-gemini-3.8-flash}}
      CI_AGENT_CONFIGURATION: ${{CI_AGENT_CONFIGURATION:-}}
      CI_PRIVATE_READOUT_API: ${{CI_PRIVATE_READOUT_API:-google-openai-chat}}
      CI_PRIVATE_READOUT_BASE_URL: ${{CI_PRIVATE_READOUT_BASE_URL:-http://model-compat:8003/v1}}
      CI_PRIVATE_READOUT_EFFORT: ${{CI_PRIVATE_READOUT_EFFORT:-low}}
      CI_PRIVATE_READOUT_API_KEY: ${{CI_PRIVATE_READOUT_API_KEY:-}}
      HARNESS_OPENAI_EFFORT: ${{HARNESS_OPENAI_EFFORT:-}}
      HARNESS_VLLM_ENDPOINTS: ${{HARNESS_VLLM_ENDPOINTS:-}}
      HARNESS_VLLM_API_KEY: ${{HARNESS_VLLM_API_KEY:-}}
      HARNESS_OPENAI_COMPAT: ${{HARNESS_OPENAI_COMPAT:-}}
      CI_PARTNER_QWEN14_API_KEY: ${{CI_PARTNER_QWEN14_API_KEY:-}}
      OPENROUTER_API_KEY: ${{OPENROUTER_API_KEY:-}}
    cap_drop: [ALL]
    security_opt: [no-new-privileges:true]
    pids_limit: 96
    mem_limit: 1024m
    healthcheck:
      test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
      interval: 1s
      timeout: 3s
      retries: 30
networks:
  default: {{}}
  team:
    internal: true
''')
    if coding:
        worker = env / "worker"
        for module in ("coding.py", "pytest_child.py", "provenance.py"):
            worker.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(Path(__file__).with_name(module), worker / module)
        # Only the public upstream argument builder goes into the executor;
        # no scenario, partner prompts, API SDKs, or evidence are copied.
        for package in ("collab_intel", "collab_intel/harness"):
            _write(worker / package / "__init__.py", "")
        shutil.copyfile(vendor / "src/collab_intel/harness/sandbox.py", worker / "collab_intel/harness/sandbox.py")
        _write(worker / "requirements.txt", _worker_requirements())
        _write(worker / "Dockerfile", f'''FROM {BASE_IMAGE}
RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --require-hashes -r /tmp/requirements.txt
COPY . /app/
RUN chmod -R a+rX /app
WORKDIR /app
ENV PYTHONPATH=/app
CMD ["python", "coding.py"]
''')
        compose_path = env / "docker-compose.yaml"
        compose = yaml.safe_load(compose_path.read_text())
        compose["services"]["team"]["networks"].append("execution")
        compose["services"]["team"]["depends_on"] = {"worker": {"condition": "service_healthy"}}
        compose["services"]["worker"] = {
            "image": f"ci-worker:{identity['source_revision'][:12]}",
            "build": {"context": "./worker"}, "networks": ["execution"],
            "read_only": True, "tmpfs": ["/tmp:size=64m,mode=0711"],
            "cap_drop": ["ALL"], "cap_add": ["SETUID", "SETGID", "KILL", "CHOWN", "DAC_OVERRIDE"],
            "security_opt": ["no-new-privileges:true"], "pids_limit": 32, "mem_limit": "512m",
            "healthcheck": {
                "test": ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8002/health')"],
                "interval": "1s", "timeout": "3s", "retries": 30,
            },
        }
        compose["networks"]["execution"] = {"internal": True}
        _write(compose_path, yaml.safe_dump(compose, sort_keys=False))
    _write(task / "instruction.md", instructions + TEAM_INTERFACE_INSTRUCTIONS)
    _write(task / "task.toml", f'''schema_version = "1.4"
source = "https://github.com/zou-group/collaborative-intelligence"

[[artifacts]]
source = "/evidence/final.json"
service = "team"

[task]
name = "misc-org/{name}"
version = "0.1.0"

[metadata]
dimension = "{identity['dimension']}"
scenario_id = {json.dumps(identity["scenario_id"])}
variant = "{identity['variant']}"
seed = {seed}
source_revision = "{PINNED_REVISION}"
scenario_sha256 = "{identity["scenario_sha256"]}"
protocol = "{identity['protocol']}"
runtime_lock_sha256 = "{RUNTIME_LOCK_SHA256}"

[agent]
# No additional whole-agent deadline; preserve original benchmark limits.
network_mode = "allowlist"
allowed_hosts = ["team", "model-compat"]

[environment]
network_mode = "public"
build_timeout_sec = 900
cpus = 2
memory_mb = 2048

[verifier]
environment_mode = "separate"
timeout_sec = {max(120, 3 * int(episode.get('test_timeout_s', 30)) + 60) if identity['dimension'] != DIMENSION else 120}

[[verifier.collect]]
service = "team"
command = "python -m collab_harbor.export_evidence"
timeout_sec = 86400
''')
    tests = task / "tests"
    _copy_runtime(tests / "adapter/collab_harbor")
    shutil.copytree(vendor, tests / "upstream")
    verifier_archive = copy_private_source(scenario, source_provenance, tests, upstream,
                                           runtime_archive="/tests/scenario.zip")
    expected = {"schema_version": 1, "identity": identity, "integrity_policy": integrity_policy}
    if verifier_archive is not None:
        expected["scenario_archive"] = verifier_archive
    _write(tests / "expected.json", json.dumps(expected, indent=2) + "\n")
    _write(tests / "requirements.txt", RUNTIME_REQUIREMENTS)
    _write(tests / "Dockerfile", f'''FROM {BASE_IMAGE}
RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --require-hashes -r /tmp/requirements.txt
COPY . /tests/
COPY adapter/collab_harbor/pytest_child.py /opt/ci-pytest-child.py
RUN chmod 700 /tests && chmod 755 /opt && chmod 644 /opt/ci-pytest-child.py
ENV PYTHONPATH=/tests/adapter:/tests/upstream/src CI_EXECUTION_CONTAINER=1 CI_PYTEST_CHILD=/opt/ci-pytest-child.py
''')
    _write(tests / "test.sh", "#!/bin/sh\nset -eu\npython -m collab_harbor.grade --allow-code-execution\n")
    _write(task / "solution/oracle.py", ORACLE)
    if identity["dimension"] == DIMENSION:
        _write(task / "solution/policy.json", json.dumps(_policy(episode, record, version), indent=2) + "\n")
        _write(task / "solution/solve.sh", "#!/bin/sh\nset -eu\npython /solution/oracle.py\n")
    else:
        # The Sharing oracle is not a reference for deadline/artifact/takeover
        # checkers. A private recorded fixture supplies an explicit oracle.
        _write(task / "solution/solve.sh", "#!/bin/sh\necho 'Use a separately validated recorded fixture oracle.' >&2\nexit 2\n")
    for file in ("LICENSE", "LICENSE-DATA", "THIRD_PARTY_NOTICES.md", "source-lock.json"):
        if (vendor / file).is_file():
            shutil.copyfile(vendor / file, task / file)
    shutil.copyfile(Path(__file__).with_name("LICENSE.adapter"), task / "LICENSE.adapter")
    config["effective_code"] = task_code_identity(task)
    _write(team / "task.json", json.dumps(config, indent=2) + "\n")


def generate(
    upstream_dir: Path, output_dir: Path, *, scenarios: list[str] | None = None,
    include_control: bool = False, overwrite: bool = False, integrity_policy: str = "normalized-protected-v2",
    dimension: str = DIMENSION, taking_over_reader: bool = False,
) -> dict:
    if integrity_policy not in {"legacy-v1", "normalized-protected-v2"}:
        raise ValueError("Unsupported integrity policy")
    if normalized_dimension(dimension) != DIMENSION:
        from .dimension_generate import generate_dimension

        return generate_dimension(upstream_dir, output_dir, dimension=dimension, scenarios=scenarios,
                                  include_control=include_control, overwrite=overwrite,
                                  integrity_policy=integrity_policy, taking_over_reader=taking_over_reader)
    if taking_over_reader:
        raise ValueError("Original reader option is restricted to TakingOver")
    upstream_dir, output_dir = Path(upstream_dir).resolve(), Path(output_dir).resolve()
    spec = json.loads((upstream_dir / "benchmark/final_set.json").read_text())
    entries = spec["dimensions"][DIMENSION]
    selected = set(scenarios or [])
    available = {Path(item["path"]).name for item in entries}
    if selected - available:
        raise ValueError(f"Unknown Sharing scenarios: {sorted(selected - available)}")
    if selected:
        entries = [item for item in entries if Path(item["path"]).name in selected]
    partners = spec["partners"]
    build_seats, load_episode, render_system = _load_rendering(upstream_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    manifest = {
        "schema_version": 1, "protocol": PROTOCOL, "source_revision": PINNED_REVISION,
        "dimension": DIMENSION, "tasks": [],
        "unsupported_scenarios": [],
    }
    with tempfile.TemporaryDirectory(prefix=".ci-generate-", dir=output_dir) as temporary:
        staging = Path(temporary)
        vendor = staging / "upstream"
        copy_upstream(upstream_dir, vendor)
        for entry in entries:
            source = upstream_dir / entry["path"]
            _verify_scenario(upstream_dir, source)
            episode, record, _ = load_episode(source)
            digest = scenario_digest(source)
            schedule = [("solo", 0)] + [("manipulation", seed) for seed in (0, 1, 2)]
            if include_control:
                schedule += [("control", 0)]
            for version, seed in schedule:
                variant_name = {"manipulation": "test", "control": "baseline"}.get(version, version)
                name = f"ci-sharing-{source.name.replace('_', '-')}-{variant_name}-s{seed}"
                target = output_dir / name
                if target.exists() and not overwrite:
                    raise FileExistsError(f"Refusing to overwrite {target}; pass --overwrite")
                identity = {
                    "scenario_id": source.name, "dimension": DIMENSION, "variant": version,
                    "seed": seed, "scenario_sha256": digest, "source_revision": PINNED_REVISION,
                    "protocol": PROTOCOL,
                }
                overrides = episode.get("version_overrides", {}).get(version, {})
                rendered_record = {**record, **{k: v for k, v in overrides.items() if k != "environment_seats"}}
                seats = build_seats(episode, rendered_record, version, "external/agent", partners)
                instructions = render_system(episode, rendered_record, seats[0], seats, version)
                staged_task = staging / name
                _build_task(staged_task, source, episode, rendered_record, version, seed, identity, vendor, partners,
                            instructions, integrity_policy)
                if target.exists():
                    shutil.rmtree(target)
                staged_task.rename(target)
                manifest["tasks"].append({
                    "task_id": name, "path": name, "identity": identity, "scenario_path": entry["path"],
                })
    _write(output_dir / "manifest.json", json.dumps(manifest, indent=2) + "\n")
    return manifest


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--upstream-dir", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--dimension", choices=[*ALIASES, *DIMENSIONS], default="sharing")
    parser.add_argument("--scenarios", nargs="+")
    parser.add_argument("--include-control", action="store_true")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--taking-over-reader", action="store_true", help="Optional prospective same-live-Pi original Opus reader/stop gate in private TakingOver tasks")
    parser.add_argument("--integrity-policy", choices=["legacy-v1", "normalized-protected-v2"],
                        default="normalized-protected-v2")
    args = parser.parse_args(argv)
    manifest = generate(
        args.upstream_dir, args.output_dir, scenarios=args.scenarios,
        include_control=args.include_control, overwrite=args.overwrite, integrity_policy=args.integrity_policy,
        dimension=args.dimension, taking_over_reader=args.taking_over_reader,
    )
    print(json.dumps({"tasks": len(manifest["tasks"]), "manifest": str(args.output_dir / "manifest.json")}))


if __name__ == "__main__":
    main()