File size: 6,042 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
#!/usr/bin/env python3
"""Build and validate the agent-visible GeoDisaster test projection.

Reference/gold records remain evaluator-only.  This module owns the narrower
record contract passed to an evaluated agent and its tools.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any, Iterable


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_REFERENCE = ROOT / "data/core/geodisaster_2921_test_source.jsonl"
DEFAULT_OUTPUT = ROOT / "data/core/geodisaster_2921_test_inputs.jsonl"

REFERENCE_ONLY_TOP_LEVEL_KEYS = {
    "correction_provenance",
    "executions",
    "expected_final_answer",
    "final_answer",
    "gt_chain",
    "multiagentic_gt_chain",
    "source_replay",
    "tool_sequence",
}

AGENT_VISIBLE_TOP_LEVEL_KEYS = {
    "available_initial_handles",
    "id",
    "initial_artifacts",
    "question",
    "question_type",
    "sample_id",
    "split",
    "split_group_id",
    "split_seed",
}

PRIVATE_PATH_SEGMENTS = {"gt", "ground_truth", "hidden", "trajectories"}
PRIVATE_NAME_MARKERS = {
    "canonical_answer",
    "expected_answer",
    "expected_final_answer",
    "gt_report",
    "hidden_gt",
    "selected_routes.json",
}


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()]


def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as stream:
        for row in rows:
            stream.write(json.dumps(row, separators=(",", ":"), ensure_ascii=False) + "\n")
    temporary.replace(path)


def private_path(path_value: str) -> bool:
    path = Path(path_value)
    lowered_parts = {part.lower() for part in path.parts}
    lowered_name = path.name.lower()
    return bool(lowered_parts & PRIVATE_PATH_SEGMENTS) or any(
        marker in lowered_name for marker in PRIVATE_NAME_MARKERS
    )


def scrub_private_paths(value: Any) -> Any:
    """Remove only explicit private path cards; retain legitimate input cards."""

    if isinstance(value, dict):
        path_value = value.get("path")
        if isinstance(path_value, str) and path_value and private_path(path_value):
            return None
        cleaned: dict[str, Any] = {}
        for key, child in value.items():
            scrubbed = scrub_private_paths(child)
            if scrubbed is not None:
                cleaned[key] = scrubbed
        return cleaned
    if isinstance(value, list):
        return [cleaned for child in value if (cleaned := scrub_private_paths(child)) is not None]
    return value


def agent_visible_record(reference: dict[str, Any]) -> dict[str, Any]:
    record = {
        key: reference[key]
        for key in AGENT_VISIBLE_TOP_LEVEL_KEYS
        if key in reference
    }
    record["initial_artifacts"] = scrub_private_paths(record.get("initial_artifacts") or {})
    return record


def path_entries(value: Any) -> Iterable[dict[str, Any]]:
    if isinstance(value, dict):
        if isinstance(value.get("path"), str) and value["path"]:
            yield value
        for child in value.values():
            yield from path_entries(child)
    elif isinstance(value, list):
        for child in value:
            yield from path_entries(child)


def agent_input_surface(row: dict[str, Any]) -> dict[str, Any]:
    return {
        "question": row.get("question") or {},
        "initial_artifacts": row.get("initial_artifacts") or {},
    }


def audit_agent_rows(
    rows: list[dict[str, Any]], reference_rows: list[dict[str, Any]] | None = None
) -> dict[str, Any]:
    ids = [str(row.get("id") or "") for row in rows]
    forbidden_keys = sorted(
        {
            key
            for row in rows
            for key in row
            if key in REFERENCE_ONLY_TOP_LEVEL_KEYS
        }
    )
    unexpected_keys = sorted({key for row in rows for key in row} - AGENT_VISIBLE_TOP_LEVEL_KEYS)
    declared = [
        entry
        for row in rows
        for entry in path_entries(agent_input_surface(row))
    ]
    private = sorted(
        {
            str(entry["path"])
            for entry in declared
            if private_path(str(entry["path"]))
        }
    )
    reference_ids = [str(row.get("id") or "") for row in reference_rows or []]
    result = {
        "records": len(rows),
        "unique_ids": len(set(ids)),
        "duplicate_ids": len(ids) - len(set(ids)),
        "all_test_split": all(row.get("split") == "test" for row in rows),
        "ids_match_reference_in_order": reference_rows is None or ids == reference_ids,
        "reference_only_top_level_keys": forbidden_keys,
        "unexpected_top_level_keys": unexpected_keys,
        "declared_path_references": len(declared),
        "unique_declared_paths": len({str(entry["path"]) for entry in declared}),
        "private_declared_paths": private,
    }
    result["ready"] = (
        result["records"] == 292
        and result["unique_ids"] == 292
        and result["duplicate_ids"] == 0
        and result["all_test_split"]
        and result["ids_match_reference_in_order"]
        and not forbidden_keys
        and not unexpected_keys
        and not private
    )
    return result


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--reference", type=Path, default=DEFAULT_REFERENCE)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--check-only", action="store_true")
    args = parser.parse_args()

    reference = read_jsonl(args.reference.resolve())
    if args.check_only:
        rows = read_jsonl(args.output.resolve())
    else:
        rows = [agent_visible_record(row) for row in reference]
        write_jsonl(args.output.resolve(), rows)
    report = audit_agent_rows(rows, reference)
    print(json.dumps(report, indent=2))
    if not report["ready"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()