File size: 22,317 Bytes
bfb3400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Materialize an auditable Endless Terminals dataset for Jupiter Apptainer.

The upstream dataset is already Harbor-shaped and ships both Dockerfiles and
Apptainer definition files.  This derivation deliberately keeps task semantics
unchanged and applies only execution-contract fixes:

* replace the identical online verifier bootstrap (apt + curl + uvx) with the
  pytest already present in every task image;
* make one synthetic dummy Debian package architecture-independent so it can
  build on Jupiter aarch64; and
* repair one reference solution whose heredoc is followed by an invalid shell
  operator; and
* inventory runtime package/network requirements.  Python packages are served
  from Harbor's bound wheelhouse at runtime, so this script does not modify an
  image merely to add a Python package.

Without ``--apply`` the command audits the source and prints the planned
summary.  With ``--apply``, ``--output-dir`` must not exist; the source is
copied without its Git metadata and deterministic manifests are written under
``metadata/``.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shlex
import shutil
import stat
import subprocess
import tempfile
from collections import Counter
from pathlib import Path
from urllib.parse import urlparse


UPSTREAM_REPO = "obiwan96/endless-terminals"
UPSTREAM_REVISION = "26ecf78458e7f756e4d06780d5fbf3dd78e91815"
EXPECTED_TASK_COUNT = 2492
EXPECTED_TEST_SH_SHA256 = (
    "52d87e5cb768634d6a7bda203b72ea77c802fdb9e8700d3d7cdcf631080c3298"
)
VERIFIER_PATCH_ID = "offline-verifier-system-pytest-isolated-v2"
ARM_PATCH_ID = "dummy-deb-architecture-all-v1"
ARM_PATCH_TASK = "task_000000_c6317e51"
ORACLE_SYNTAX_PATCH_ID = "oracle-heredoc-chain-syntax-v1"
ORACLE_SYNTAX_PATCH_TASK = "task_000000_15619148"
REQUIRED_TASK_FILES = (
    "task.toml",
    "instruction.md",
    "environment/Dockerfile",
    "environment/container.def",
    "environment/test_initial_state.py",
    "tests/test.sh",
    "tests/test_final_state.py",
    "solution/solve.sh",
)

OFFLINE_TEST_SH = """#!/usr/bin/env bash
# harbor-endless-offline-patched-v1
set +e

mkdir -p /logs/verifier
cd /home/user || {
  echo 0 > /logs/verifier/reward.txt
  exit 0
}

# pytest is already installed in every upstream task image.  Runtime package
# installs performed by the task use Harbor's read-only wheelhouse through
# PIP_NO_INDEX/PIP_FIND_LINKS; grading itself performs no download or install.
# Remove the image's verifier-only PYTHONPATH while grading so subprocesses
# that inspect a task-created virtualenv cannot see /opt/harbor-python as if
# those packages had been installed inside the virtualenv.
env -u PYTHONPATH python3 -m pytest /tests/test_final_state.py -v
status=$?
if [ "$status" -eq 0 ]; then
  echo 1 > /logs/verifier/reward.txt
else
  echo 0 > /logs/verifier/reward.txt
fi
exit 0
"""

ARM_REPLACEMENTS = (
    ("Architecture: amd64", "Architecture: all"),
    ("curl_7.74.0-1ubuntu2.18_amd64.deb", "curl_7.74.0-1ubuntu2.18_all.deb"),
)

PIP_INSTALL_RE = re.compile(
    r"(?:(?:python\S*|/[^\s;&|]+/python\S*)\s+-m\s+)?"
    r"(?:pip3?|/[^\s;&|]+/pip)\s+install\s+([^\n;&|]+)",
    re.IGNORECASE,
)
OS_INSTALL_RE = re.compile(
    r"\b(?:apt-get|apt|yum|dnf|apk)\s+(?:install|add)\b", re.IGNORECASE
)
RAW_NETWORK_RE = re.compile(
    r"\b(?:ping|traceroute|tracepath)\b", re.IGNORECASE
)
SERVICE_RE = re.compile(r"\b(?:systemctl|service\s+\S+)\b", re.IGNORECASE)
SUDO_RE = re.compile(r"\bsudo\b", re.IGNORECASE)
URL_RE = re.compile(r"https?://[^\s\"'<>|)]+", re.IGNORECASE)
LOCAL_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0"}
PIP_OPTIONS_WITH_VALUE = {
    "-c",
    "--constraint",
    "-e",
    "--editable",
    "-f",
    "--find-links",
    "-i",
    "--index-url",
    "--extra-index-url",
    "--proxy",
    "--root",
    "--target",
    "--timeout",
    "--trusted-host",
}
LITERAL_REQUIREMENT_RE = re.compile(
    r"^[A-Za-z0-9][A-Za-z0-9._-]*"
    r"(?:\[[A-Za-z0-9._,-]+\])?"
    r"(?:(?:===|==|~=|!=|<=|>=|<|>)[^\s]+)?$"
)


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def git_revision(path: Path) -> str | None:
    try:
        return subprocess.check_output(
            ["git", "-C", str(path), "rev-parse", "HEAD"],
            text=True,
            stderr=subprocess.DEVNULL,
        ).strip()
    except (OSError, subprocess.CalledProcessError):
        return None


def task_dirs(root: Path) -> list[Path]:
    return sorted(path for path in root.glob("task_*") if path.is_dir())


def validate_source(source: Path, allow_unpinned_source: bool) -> list[Path]:
    tasks = task_dirs(source)
    if len(tasks) != EXPECTED_TASK_COUNT:
        raise ValueError(
            f"Expected {EXPECTED_TASK_COUNT} tasks at pinned upstream revision; "
            f"found {len(tasks)}"
        )
    revision = git_revision(source)
    if not allow_unpinned_source and revision != UPSTREAM_REVISION:
        raise ValueError(
            "Source Git revision does not match the pinned upstream revision: "
            f"expected {UPSTREAM_REVISION}, got {revision!r}. Pass "
            "--allow-unpinned-source only for an explicitly reviewed materialization."
        )
    failures: list[str] = []
    for task in tasks:
        for relative in REQUIRED_TASK_FILES:
            if not (task / relative).is_file():
                failures.append(f"{task.name}/{relative}")
    if failures:
        preview = ", ".join(failures[:20])
        raise ValueError(f"Missing {len(failures)} required task files: {preview}")
    bad_verifiers = [
        task.name
        for task in tasks
        if sha256_file(task / "tests/test.sh") != EXPECTED_TEST_SH_SHA256
    ]
    if bad_verifiers:
        raise ValueError(
            f"Refusing to rewrite {len(bad_verifiers)} unrecognized test.sh files: "
            + ", ".join(bad_verifiers[:20])
        )
    return tasks


def extract_python_requirements(script: str) -> tuple[list[str], bool]:
    """Return literal pip requirements and whether dynamic inputs remain."""
    requirements: set[str] = set()
    dynamic = False
    for match in PIP_INSTALL_RE.finditer(script):
        try:
            tokens = shlex.split(match.group(1), comments=False, posix=True)
        except ValueError:
            dynamic = True
            continue
        index = 0
        while index < len(tokens):
            token = tokens[index]
            if token in {"-r", "--requirement"}:
                dynamic = True
                index += 2
                continue
            if token in PIP_OPTIONS_WITH_VALUE:
                index += 2
                continue
            if token.startswith("-"):
                index += 1
                continue
            if (
                any(char in token for char in ("$", "`", "*"))
                or token.startswith(("/", ".", ">"))
                or not LITERAL_REQUIREMENT_RE.fullmatch(token)
            ):
                dynamic = True
                index += 1
                continue
            if token in {"then", "fi", "do", "done"}:
                break
            requirements.add(token)
            index += 1
    return sorted(requirements, key=str.lower), dynamic


def external_url_hosts(script: str) -> list[str]:
    hosts: set[str] = set()
    for raw in URL_RE.findall(script):
        host = urlparse(raw.rstrip(".,;")).hostname
        if host and host not in LOCAL_HOSTS and not host.startswith("$"):
            hosts.add(host)
    return sorted(hosts)


def analyze_task(task: Path) -> dict[str, object]:
    solution = (task / "solution/solve.sh").read_text(errors="replace")
    requirements, dynamic = extract_python_requirements(solution)
    hosts = external_url_hosts(solution)
    return {
        "runtime_python_install": bool(PIP_INSTALL_RE.search(solution)),
        "runtime_python_requirements": requirements,
        "runtime_python_dynamic_requirements": dynamic,
        "runtime_os_package_install": bool(OS_INSTALL_RE.search(solution)),
        "external_url_hosts": hosts,
        "raw_network_candidate": bool(RAW_NETWORK_RE.search(solution)),
        "service_manager_candidate": bool(SERVICE_RE.search(solution)),
        "sudo_in_oracle": bool(SUDO_RE.search(solution)),
    }


def tree_hash(task: Path) -> str:
    digest = hashlib.sha256()
    for path in sorted(candidate for candidate in task.rglob("*") if candidate.is_file()):
        relative = path.relative_to(task).as_posix()
        digest.update(relative.encode())
        digest.update(b"\0")
        digest.update(bytes.fromhex(sha256_file(path)))
        digest.update(b"\n")
    return digest.hexdigest()


def patch_file(
    path: Path,
    new_content: str,
    patch_id: str,
    reason: str,
    records: list[dict[str, object]],
    *,
    executable: bool = False,
) -> None:
    old = path.read_bytes()
    old_mode = stat.S_IMODE(path.stat().st_mode)
    encoded = new_content.encode()
    path.write_bytes(encoded)
    if executable:
        path.chmod(0o755)
    new_mode = stat.S_IMODE(path.stat().st_mode)
    records.append(
        {
            "task": path.parents[1].name,
            "path": path.relative_to(path.parents[1]).as_posix(),
            "patch_id": patch_id,
            "reason": reason,
            "before_sha256": sha256_bytes(old),
            "after_sha256": sha256_bytes(encoded),
            "before_mode": oct(old_mode),
            "after_mode": oct(new_mode),
        }
    )


def apply_patches(root: Path) -> list[dict[str, object]]:
    records: list[dict[str, object]] = []
    for task in task_dirs(root):
        patch_file(
            task / "tests/test.sh",
            OFFLINE_TEST_SH,
            VERIFIER_PATCH_ID,
            "Use image-provided pytest; remove verifier-time apt, curl, uv, and uvx downloads.",
            records,
            executable=True,
        )

    arm_task = root / ARM_PATCH_TASK
    for relative in ("environment/Dockerfile", "environment/container.def"):
        path = arm_task / relative
        content = path.read_text()
        patched = content
        for old, new in ARM_REPLACEMENTS:
            patched = patched.replace(old, new)
        if patched == content:
            raise ValueError(f"Expected ARM compatibility substitutions not found in {path}")
        patch_file(
            path,
            patched,
            ARM_PATCH_ID,
            "The dummy package contains no architecture-specific payload; mark it Architecture: all for aarch64 builds.",
            records,
        )

    oracle_path = root / ORACLE_SYNTAX_PATCH_TASK / "solution/solve.sh"
    oracle_content = oracle_path.read_text()
    oracle_patched = oracle_content.replace(
        "PY\n && cat /home/user/work/output/orders_report.csv",
        "PY\ncat /home/user/work/output/orders_report.csv",
    )
    if oracle_patched == oracle_content:
        raise ValueError(f"Expected oracle syntax substitution not found in {oracle_path}")
    patch_file(
        oracle_path,
        oracle_patched,
        ORACLE_SYNTAX_PATCH_ID,
        "Remove an invalid shell operator after a heredoc; task output and grading remain unchanged.",
        records,
        executable=True,
    )
    return records


def relative_files(root: Path, *, exclude_git: bool = False) -> set[Path]:
    files: set[Path] = set()
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        relative = path.relative_to(root)
        if exclude_git and relative.parts[0] == ".git":
            continue
        if relative.parts[0] == "metadata":
            continue
        files.add(relative)
    return files


def validate_materialization(
    source: Path,
    output: Path,
    patch_records: list[dict[str, object]],
) -> dict[str, object]:
    """Prove that only the declared execution-contract files changed."""
    expected_changes = {
        Path(task.name) / "tests/test.sh" for task in task_dirs(source)
    }
    expected_changes.update(
        {
            Path(ARM_PATCH_TASK) / "environment/Dockerfile",
            Path(ARM_PATCH_TASK) / "environment/container.def",
            Path(ORACLE_SYNTAX_PATCH_TASK) / "solution/solve.sh",
        }
    )
    source_files = relative_files(source, exclude_git=True)
    output_files = relative_files(output)
    if source_files != output_files:
        missing = sorted(str(path) for path in source_files - output_files)
        extra = sorted(str(path) for path in output_files - source_files)
        raise ValueError(
            "Materialized file set differs from source outside metadata: "
            f"missing={missing[:10]}, extra={extra[:10]}"
        )

    changed: set[Path] = set()
    for relative in sorted(source_files):
        if sha256_file(source / relative) != sha256_file(output / relative):
            changed.add(relative)
    if changed != expected_changes:
        unexpected = sorted(str(path) for path in changed - expected_changes)
        absent = sorted(str(path) for path in expected_changes - changed)
        raise ValueError(
            "Materialized content changes do not match the patch contract: "
            f"unexpected={unexpected[:10]}, absent={absent[:10]}"
        )
    if len(patch_records) != len(expected_changes):
        raise ValueError(
            f"Expected {len(expected_changes)} patch records, got {len(patch_records)}"
        )

    offline_sha = sha256_bytes(OFFLINE_TEST_SH.encode())
    for task in task_dirs(output):
        verifier = task / "tests/test.sh"
        if sha256_file(verifier) != offline_sha or not (verifier.stat().st_mode & 0o111):
            raise ValueError(f"Offline verifier validation failed: {verifier}")
    return {
        "status": "passed",
        "source_file_count": len(source_files),
        "declared_changed_file_count": len(changed),
        "unchanged_file_count": len(source_files) - len(changed),
    }


def copy_source(source: Path, output: Path) -> None:
    if output.exists():
        raise FileExistsError(f"Refusing to replace existing output directory: {output}")
    output.parent.mkdir(parents=True, exist_ok=True)
    staging = Path(
        tempfile.mkdtemp(prefix=f".{output.name}.tmp-", dir=str(output.parent))
    )
    try:
        for child in source.iterdir():
            if child.name == ".git":
                continue
            target = staging / child.name
            if child.is_dir():
                shutil.copytree(child, target, copy_function=shutil.copy2)
            else:
                shutil.copy2(child, target)
        staging.rename(output)
    except Exception:
        shutil.rmtree(staging, ignore_errors=True)
        raise


def write_json(path: Path, value: object) -> None:
    path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n")


def write_jsonl(path: Path, rows: list[dict[str, object]]) -> None:
    with path.open("w") as stream:
        for row in rows:
            stream.write(json.dumps(row, sort_keys=True) + "\n")


def materialize_metadata(
    output: Path,
    patch_records: list[dict[str, object]],
    validation: dict[str, object],
) -> dict[str, object]:
    metadata = output / "metadata"
    metadata.mkdir()
    tasks_rows: list[dict[str, object]] = []
    requirements: set[str] = set()
    risk_counts: Counter[str] = Counter()
    for task in task_dirs(output):
        analysis = analyze_task(task)
        for requirement in analysis["runtime_python_requirements"]:
            requirements.add(str(requirement))
        for key in (
            "runtime_python_install",
            "runtime_python_dynamic_requirements",
            "runtime_os_package_install",
            "raw_network_candidate",
            "service_manager_candidate",
            "sudo_in_oracle",
        ):
            if analysis[key]:
                risk_counts[key] += 1
        if analysis["external_url_hosts"]:
            risk_counts["external_url_reference"] += 1
        tasks_rows.append(
            {
                "task": task.name,
                "tree_sha256": tree_hash(task),
                "patch_ids": [
                    VERIFIER_PATCH_ID,
                    *([ARM_PATCH_ID] if task.name == ARM_PATCH_TASK else []),
                    *(
                        [ORACLE_SYNTAX_PATCH_ID]
                        if task.name == ORACLE_SYNTAX_PATCH_TASK
                        else []
                    ),
                ],
                **analysis,
            }
        )

    write_jsonl(metadata / "tasks.jsonl", tasks_rows)
    write_jsonl(metadata / "patches.jsonl", patch_records)
    (metadata / "runtime-python-requirements.txt").write_text(
        "\n".join(sorted(requirements, key=str.lower))
        + ("\n" if requirements else "")
    )
    patch_definitions = {
        "schema_version": 1,
        "patches": [
            {
                "id": VERIFIER_PATCH_ID,
                "scope": "all tasks",
                "expected_before_sha256": EXPECTED_TEST_SH_SHA256,
                "after_sha256": sha256_bytes(OFFLINE_TEST_SH.encode()),
                "semantics": "Reward and final-state tests unchanged; only dependency acquisition is removed.",
            },
            {
                "id": ARM_PATCH_ID,
                "scope": ARM_PATCH_TASK,
                "replacements": [list(item) for item in ARM_REPLACEMENTS],
                "semantics": "Dummy package payload and tested version remain unchanged.",
            },
            {
                "id": ORACLE_SYNTAX_PATCH_ID,
                "scope": ORACLE_SYNTAX_PATCH_TASK,
                "replacement": [
                    "PY\\n && cat /home/user/work/output/orders_report.csv",
                    "PY\\ncat /home/user/work/output/orders_report.csv",
                ],
                "semantics": "Fix shell parsing only; generated report and final-state tests are unchanged.",
            },
        ],
    }
    write_json(metadata / "patch-definitions.json", patch_definitions)
    provenance = {
        "schema_version": 1,
        "kind": "derived_dataset_provenance",
        "upstream_repo": UPSTREAM_REPO,
        "upstream_revision": UPSTREAM_REVISION,
        "task_count": len(tasks_rows),
        "execution_profiles": [
            "jupiter-aarch64-rootless-apptainer-wheelhouse-v1",
            "jupiter-aarch64-rootless-apptainer-proxy-v1",
        ],
    }
    write_json(metadata / "provenance.json", provenance)

    summary: dict[str, object] = {
        "schema_version": 1,
        "kind": "endless_terminals_offline_patch_summary",
        "upstream_repo": UPSTREAM_REPO,
        "upstream_revision": UPSTREAM_REVISION,
        "task_count": len(tasks_rows),
        "patched_verifiers": sum(
            record["patch_id"] == VERIFIER_PATCH_ID for record in patch_records
        ),
        "patched_environment_files": sum(
            record["patch_id"] == ARM_PATCH_ID for record in patch_records
        ),
        "patched_oracle_files": sum(
            record["patch_id"] == ORACLE_SYNTAX_PATCH_ID
            for record in patch_records
        ),
        "unique_runtime_python_requirements": len(requirements),
        "risk_counts": dict(sorted(risk_counts.items())),
        "validation": validation,
    }
    write_json(metadata / "summary.json", summary)

    checksummed = [
        metadata / "patch-definitions.json",
        metadata / "patches.jsonl",
        metadata / "provenance.json",
        metadata / "runtime-python-requirements.txt",
        metadata / "summary.json",
        metadata / "tasks.jsonl",
    ]
    with (metadata / "SHA256SUMS").open("w") as stream:
        for path in checksummed:
            stream.write(f"{sha256_file(path)}  {path.name}\n")
    return summary


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("--output-dir", type=Path)
    parser.add_argument("--apply", action="store_true")
    parser.add_argument(
        "--allow-unpinned-source",
        action="store_true",
        help="Accept a source without the pinned Git revision (recorded as a deviation).",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    source = args.source.expanduser().resolve()
    if not source.is_dir():
        raise SystemExit(f"Source directory does not exist: {source}")
    try:
        tasks = validate_source(source, args.allow_unpinned_source)
    except (OSError, ValueError) as error:
        raise SystemExit(f"Invalid source: {error}") from error

    analyses = [analyze_task(task) for task in tasks]
    planned = {
        "mode": "apply" if args.apply else "dry-run",
        "upstream_revision": git_revision(source),
        "tasks": len(tasks),
        "verifiers_to_patch": len(tasks),
        "environment_files_to_patch": 2,
        "oracle_files_to_patch": 1,
        "runtime_python_install_tasks": sum(
            bool(row["runtime_python_install"]) for row in analyses
        ),
        "runtime_os_package_install_tasks": sum(
            bool(row["runtime_os_package_install"]) for row in analyses
        ),
        "external_url_reference_tasks": sum(
            bool(row["external_url_hosts"]) for row in analyses
        ),
        "raw_network_candidate_tasks": sum(
            bool(row["raw_network_candidate"]) for row in analyses
        ),
    }
    print(json.dumps(planned, indent=2, sort_keys=True))
    if not args.apply:
        return 0
    if args.output_dir is None:
        raise SystemExit("--output-dir is required with --apply")

    output = args.output_dir.expanduser().resolve()
    copy_source(source, output)
    patch_records = apply_patches(output)
    validation = validate_materialization(source, output, patch_records)
    summary = materialize_metadata(output, patch_records, validation)
    print(json.dumps(summary, indent=2, sort_keys=True))
    print(f"output={output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())