File size: 7,107 Bytes
7aae553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Materialize a gold-free filesystem root for GeoDisaster test execution."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import shutil
from collections import defaultdict
from pathlib import Path
from typing import Any

from eval_isolation import (
    DEFAULT_OUTPUT,
    ROOT,
    agent_input_surface,
    audit_agent_rows,
    path_entries,
    private_path,
    read_jsonl,
)


def sha256(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 inside(path: Path, parent: Path) -> bool:
    try:
        path.relative_to(parent)
        return True
    except ValueError:
        return False


def safe_relative(path_value: str) -> Path:
    relative = Path(path_value)
    if relative.is_absolute() or ".." in relative.parts:
        raise ValueError(f"unsafe declared path: {path_value}")
    if private_path(path_value):
        raise ValueError(f"private path reached bundle builder: {path_value}")
    return relative


def validate_public_question_json(path: Path, relative: Path) -> None:
    """Reject legacy private hints in a question sidecar before packaging."""
    if path.suffix.lower() != ".json" or "questions" not in relative.parts:
        return
    payload = json.loads(path.read_text(encoding="utf-8"))
    forbidden = {
        "aoi_type_hidden",
        "gt_path_hidden",
        "gt_link",
        "oracle_trajectory_link",
        "expected_final_answer",
        "final_answer",
    }

    def walk(value: Any, prefix: str = "") -> list[str]:
        found: list[str] = []
        if isinstance(value, dict):
            for key, child in value.items():
                field = f"{prefix}.{key}" if prefix else str(key)
                if key in forbidden:
                    found.append(field)
                found.extend(walk(child, field))
        elif isinstance(value, list):
            for index, child in enumerate(value):
                found.extend(walk(child, f"{prefix}[{index}]"))
        return found

    violations = walk(payload)
    if violations:
        raise ValueError(f"private fields in public question sidecar {relative}: {violations}")


def declared_files(source_root: Path, rows: list[dict[str, Any]]) -> tuple[dict[Path, set[str]], list[str]]:
    selected: dict[Path, set[str]] = defaultdict(set)
    missing_optional: set[str] = set()
    missing_required: set[str] = set()
    for row in rows:
        record_id = str(row["id"])
        for entry in path_entries(agent_input_surface(row)):
            relative = safe_relative(str(entry["path"]))
            source = source_root / relative
            optional = bool(entry.get("optional"))
            if not source.exists():
                (missing_optional if optional else missing_required).add(relative.as_posix())
                continue
            if source.is_symlink():
                raise ValueError(f"symlinks are not allowed in an isolated bundle: {relative}")
            if source.is_file():
                validate_public_question_json(source, relative)
                selected[relative].add(record_id)
                continue
            if not source.is_dir():
                raise ValueError(f"unsupported declared input type: {relative}")
            for candidate in source.rglob("*"):
                if not candidate.is_file():
                    continue
                child = candidate.relative_to(source_root)
                if candidate.is_symlink():
                    raise ValueError(f"symlinks are not allowed in an isolated bundle: {child}")
                if private_path(child.as_posix()):
                    continue
                selected[child].add(record_id)
    if missing_required:
        raise RuntimeError(f"required inputs missing: {sorted(missing_required)[:10]}")
    return dict(selected), sorted(missing_optional)


def install_file(source: Path, destination: Path, mode: str) -> None:
    destination.parent.mkdir(parents=True, exist_ok=True)
    if mode == "hardlink":
        os.link(source, destination)
    else:
        shutil.copy2(source, destination)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-root", type=Path, default=ROOT)
    parser.add_argument("--inputs", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--mode", choices=("copy", "hardlink"), default="copy")
    args = parser.parse_args()

    source_root = args.source_root.resolve()
    output = args.output.resolve()
    if output == source_root or inside(output, source_root) or inside(source_root, output):
        raise ValueError("--output must be separate from, and not contain, the source repository")
    if output.exists() and any(output.iterdir()):
        raise ValueError("--output must not exist or must be empty")
    output.mkdir(parents=True, exist_ok=True)

    rows = read_jsonl(args.inputs.resolve())
    audit = audit_agent_rows(rows)
    if not audit["ready"]:
        raise RuntimeError(f"agent-visible input audit failed: {audit}")
    files, missing_optional = declared_files(source_root, rows)

    manifest_entries = []
    for relative in sorted(files, key=lambda item: item.as_posix()):
        source = source_root / relative
        destination = output / relative
        install_file(source, destination, args.mode)
        manifest_entries.append(
            {
                "path": relative.as_posix(),
                "bytes": source.stat().st_size,
                "sha256": sha256(source),
                "declared_by": sorted(files[relative]),
            }
        )

    input_destination = output / "data/core/geodisaster_2921_test_inputs.jsonl"
    install_file(args.inputs.resolve(), input_destination, args.mode)
    manifest = {
        "schema_version": "geodisaster_isolated_test_bundle_v1",
        "records": len(rows),
        "files": len(manifest_entries),
        "bytes": sum(entry["bytes"] for entry in manifest_entries),
        "missing_optional_paths": missing_optional,
        "strict_runtime_environment": {
            "GEODISASTER_DATASET_ROOT": str(output),
            "GEODISASTER_STRICT_DATA_ROOT": "1",
        },
        "input_audit": audit,
        "entries": manifest_entries,
    }
    manifest_path = output / "evaluation_bundle_manifest.json"
    manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
    print(
        json.dumps(
            {
                "output": str(output),
                "records": len(rows),
                "files": len(manifest_entries),
                "bytes": manifest["bytes"],
                "missing_optional": len(missing_optional),
                "private_paths": len(audit["private_declared_paths"]),
                "ready": True,
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()