File size: 14,112 Bytes
177fdd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Qualification and calibration runner for task/Piyush.

Evaluates through the real verifier container (drone-hfss-verifier):
  1. Oracle reference solution (`solution/`)
  2. Structurally independent alternative solution (`authoring/evidence/independent_solution.py`)
  3. Legacy baseline (`environment/baseline/`)
  4. Semantic mutants M1..M6 (mapped 1:1 to REQ-VERIFIER-MAP.md)
  5. Integrity/cheat mutants I1..I4 (simulator tampering, memorized table, symlink, daemon reward overwrite)
  6. Per-instance null battery on all 5 held-out scenarios (Gate A)
"""

from __future__ import annotations

import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any, Dict

ROOT = Path(__file__).resolve().parents[2]
TASK_DIR = ROOT / "task" / "Piyush"
DEV_DIR = ROOT / "task" / "Piyush.dev"


def run_verifier_on_stage(stage_app_dir: Path) -> Dict[str, Any]:
    with tempfile.TemporaryDirectory(prefix="harbor_ver_logs_") as log_dir:
        proc = subprocess.run(
            [
                "docker",
                "run",
                "--rm",
                "--network",
                "none",
                "-v",
                f"{stage_app_dir}:/app:ro",
                "-v",
                f"{log_dir}:/logs/verifier",
                "drone-hfss-verifier",
                "bash",
                "/tests/test.sh",
            ],
            capture_output=True,
            text=True,
            timeout=120,
        )
        reward_path = Path(log_dir) / "reward.txt"
        ctrf_path = Path(log_dir) / "ctrf.json"
        reward = float(reward_path.read_text().strip()) if reward_path.exists() else -1.0
        tests_map: Dict[str, str] = {}
        if ctrf_path.exists():
            ctrf = json.loads(ctrf_path.read_text())
            for t in ctrf.get("results", {}).get("tests", []):
                tests_map[t["name"]] = t["status"]
        return {
            "reward": reward,
            "exit_code": proc.returncode,
            "tests": tests_map,
        }


def collect_worker_metrics(stage_app_dir: Path) -> Dict[str, Any]:
    proc = subprocess.run(
        [
            "docker",
            "run",
            "--rm",
            "--network",
            "none",
            "-v",
            f"{stage_app_dir}:/app:ro",
            "drone-hfss-verifier",
            "python3",
            "-I",
            "-c",
            (
                "import json, subprocess, sys\n"
                "out = {}\n"
                "for m in ('em', 'public', 'heldout'):\n"
                "    p = f'/tmp/{m}.json'\n"
                "    r = subprocess.run([sys.executable, '-I', '/tests/isolated_eval_worker.py', m, p], capture_output=True, text=True)\n"
                "    if r.returncode == 0:\n"
                "        with open(p) as f: out[m] = json.load(f)\n"
                "print(json.dumps(out))\n"
            ),
        ],
        capture_output=True,
        text=True,
        timeout=120,
    )
    if proc.returncode == 0 and proc.stdout.strip():
        return json.loads(proc.stdout.strip().splitlines()[-1])
    return {}


def build_oracle_stage(stage_app: Path) -> None:
    shutil.copytree(TASK_DIR / "environment" / "hfss_sim", stage_app / "hfss_sim")
    shutil.copytree(TASK_DIR / "environment" / "baseline", stage_app / "baseline")
    subprocess.run(
        [
            "docker",
            "run",
            "--rm",
            "-v",
            f"{stage_app}:/app",
            "-v",
            f"{TASK_DIR / 'solution'}:/solution:ro",
            "drone-hfss-env",
            "bash",
            "/solution/solve.sh",
        ],
        check=True,
        capture_output=True,
    )


def build_independent_stage(stage_app: Path) -> None:
    shutil.copytree(TASK_DIR / "environment" / "hfss_sim", stage_app / "hfss_sim")
    shutil.copytree(TASK_DIR / "environment" / "baseline", stage_app / "baseline")
    subprocess.run(
        [
            "docker",
            "run",
            "--rm",
            "-v",
            f"{stage_app}:/app",
            "-v",
            f"{TASK_DIR / 'authoring' / 'evidence'}:/evidence:ro",
            "drone-hfss-env",
            "python3",
            "/evidence/independent_solution.py",
        ],
        check=True,
        capture_output=True,
    )


def main() -> None:
    report: Dict[str, Any] = {}

    with tempfile.TemporaryDirectory(prefix="qual_oracle_") as tmp_or:
        oracle_dir = Path(tmp_or)
        build_oracle_stage(oracle_dir)
        report["oracle"] = {
            "verifier": run_verifier_on_stage(oracle_dir),
            "metrics": collect_worker_metrics(oracle_dir),
        }

        # Independent alternative solution
        with tempfile.TemporaryDirectory(prefix="qual_ind_") as tmp_ind:
            ind_dir = Path(tmp_ind)
            build_independent_stage(ind_dir)
            report["independent_solution"] = {
                "verifier": run_verifier_on_stage(ind_dir),
                "metrics": collect_worker_metrics(ind_dir),
            }

        # Legacy baseline
        with tempfile.TemporaryDirectory(prefix="qual_base_") as tmp_base:
            base_dir = Path(tmp_base)
            shutil.copytree(oracle_dir, base_dir, dirs_exist_ok=True)
            shutil.copyfile(
                TASK_DIR / "environment" / "baseline" / "antenna_design.json",
                base_dir / "antenna_design.json",
            )
            shutil.copyfile(
                TASK_DIR / "environment" / "baseline" / "controller.py",
                base_dir / "controller.py",
            )
            report["legacy_baseline"] = {
                "verifier": run_verifier_on_stage(base_dir),
                "metrics": collect_worker_metrics(base_dir),
            }

        # M1: Unmatched half-wave antenna design
        with tempfile.TemporaryDirectory(prefix="qual_m1_") as tmp_m1:
            m1_dir = Path(tmp_m1)
            shutil.copytree(oracle_dir, m1_dir, dirs_exist_ok=True)
            bad_design = {
                "element_length_m": 0.0612,
                "spacing_x_m": 0.060,
                "spacing_y_m": 0.060,
                "substrate_height_m": 0.030,
                "decoupling_x_siemens": 0.0,
                "decoupling_y_siemens": 0.0,
                "series_reactance_ohm": 0.0,
                "shunt_susceptance_siemens": 0.0,
            }
            (m1_dir / "antenna_design.json").write_text(json.dumps(bad_design, indent=2))
            report["M1_unmatched_halfwave"] = {
                "verifier": run_verifier_on_stage(m1_dir),
                "metrics": collect_worker_metrics(m1_dir),
            }

        # M1b: L-network matched but zero inter-element decoupling (decoupling_x = decoupling_y = 0)
        with tempfile.TemporaryDirectory(prefix="qual_m1b_") as tmp_m1b:
            m1b_dir = Path(tmp_m1b)
            shutil.copytree(oracle_dir, m1b_dir, dirs_exist_ok=True)
            no_dec_design = json.loads((oracle_dir / "antenna_design.json").read_text())
            no_dec_design["decoupling_x_siemens"] = 0.0
            no_dec_design["decoupling_y_siemens"] = 0.0
            (m1b_dir / "antenna_design.json").write_text(json.dumps(no_dec_design, indent=2))
            report["M1b_no_decoupling"] = {
                "verifier": run_verifier_on_stage(m1b_dir),
                "metrics": collect_worker_metrics(m1b_dir),
            }

        # M2: Fabricated hfss_characterization.json
        with tempfile.TemporaryDirectory(prefix="qual_m2_") as tmp_m2:
            m2_dir = Path(tmp_m2)
            shutil.copytree(oracle_dir, m2_dir, dirs_exist_ok=True)
            char_data = json.loads((m2_dir / "hfss_characterization.json").read_text())
            char_data["s11_at_f0_db"] = -45.0
            (m2_dir / "hfss_characterization.json").write_text(json.dumps(char_data, indent=2))
            report["M2_fabricated_characterization"] = {
                "verifier": run_verifier_on_stage(m2_dir),
            }

        # M3: World-frame beam pointing (ignores drone roll/pitch/yaw rotation)
        with tempfile.TemporaryDirectory(prefix="qual_m3_") as tmp_m3:
            m3_dir = Path(tmp_m3)
            shutil.copytree(oracle_dir, m3_dir, dirs_exist_ok=True)
            ctrl_src = (m3_dir / "controller.py").read_text()
            ctrl_m3 = ctrl_src.replace(
                "att_t = [float(x) for x in obs[\"drone_attitude_rad\"]]",
                "att_t = [0.0, 0.0, 0.0]",
            )
            (m3_dir / "controller.py").write_text(ctrl_m3)
            report["M3_world_frame_pointing"] = {
                "verifier": run_verifier_on_stage(m3_dir),
                "metrics": collect_worker_metrics(m3_dir),
            }

        # M4: No jammer nulling (steers to GCS in body frame but ignores pilot interference covariance)
        with tempfile.TemporaryDirectory(prefix="qual_m4_") as tmp_m4:
            m4_dir = Path(tmp_m4)
            shutil.copytree(oracle_dir, m4_dir, dirs_exist_ok=True)
            ctrl_src = (m4_dir / "controller.py").read_text()
            ctrl_m4 = ctrl_src.replace(
                "if lam > 3.2 * noise_mw:",
                "if False:",
            )
            (m4_dir / "controller.py").write_text(ctrl_m4)
            report["M4_no_jammer_null"] = {
                "verifier": run_verifier_on_stage(m4_dir),
                "metrics": collect_worker_metrics(m4_dir),
            }

        # M5: Unregularized high-power fixed-MCS controller (causes PA thermal overload)
        with tempfile.TemporaryDirectory(prefix="qual_m5_") as tmp_m5:
            m5_dir = Path(tmp_m5)
            shutil.copytree(oracle_dir, m5_dir, dirs_exist_ok=True)
            ctrl_src = (m5_dir / "controller.py").read_text()
            ctrl_m5 = ctrl_src.replace(
                '"tx_power_dbm": round(float(chosen_p_dbm), 3),',
                '"tx_power_dbm": 36.0,',
            ).replace(
                '"mcs_index": int(chosen_mcs),',
                '"mcs_index": 3,',
            )
            (m5_dir / "controller.py").write_text(ctrl_m5)
            report["M5_fixed_max_power_mcs3"] = {
                "verifier": run_verifier_on_stage(m5_dir),
                "metrics": collect_worker_metrics(m5_dir),
            }

        # M6: Stale/fabricated evaluation_summary.json
        with tempfile.TemporaryDirectory(prefix="qual_m6_") as tmp_m6:
            m6_dir = Path(tmp_m6)
            shutil.copytree(oracle_dir, m6_dir, dirs_exist_ok=True)
            sum_data = json.loads((m6_dir / "evaluation_summary.json").read_text())
            sum_data["mean_episode_return"] = 2500.0
            (m6_dir / "evaluation_summary.json").write_text(json.dumps(sum_data, indent=2))
            report["M6_stale_summary"] = {
                "verifier": run_verifier_on_stage(m6_dir),
            }

        # I1: Tamper with /app/hfss_sim/em_solver.py
        with tempfile.TemporaryDirectory(prefix="qual_i1_") as tmp_i1:
            i1_dir = Path(tmp_i1)
            shutil.copytree(oracle_dir, i1_dir, dirs_exist_ok=True)
            em_p = i1_dir / "hfss_sim" / "em_solver.py"
            em_p.write_text(em_p.read_text() + "\n# tampered\n")
            report["I1_tamper_sim"] = {
                "verifier": run_verifier_on_stage(i1_dir),
            }

        # I2: Memorized public scenario lookup table (fails held-out scenarios)
        with tempfile.TemporaryDirectory(prefix="qual_i2_") as tmp_i2:
            i2_dir = Path(tmp_i2)
            shutil.copytree(oracle_dir, i2_dir, dirs_exist_ok=True)
            ctrl_src = (i2_dir / "controller.py").read_text()
            ctrl_i2 = ctrl_src.replace(
                "def reset(self, scenario_meta: Dict[str, Any]) -> None:\n        self.prev_w = None",
                "def reset(self, scenario_meta: Dict[str, Any]) -> None:\n        self.prev_w = None\n        self.is_heldout = str(scenario_meta.get('scenario_name', '')).startswith('heldout_')",
            ).replace(
                "def select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]:",
                "def select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]:\n        if getattr(self, 'is_heldout', False):\n            return {'weights_real': [0.5]*4, 'weights_imag': [0.0]*4, 'tx_power_dbm': 20.0, 'mcs_index': 0}",
            )
            (i2_dir / "controller.py").write_text(ctrl_i2)
            report["I2_memorized_public_only"] = {
                "verifier": run_verifier_on_stage(i2_dir),
                "metrics": collect_worker_metrics(i2_dir),
            }

        # I3: Symlink attack on antenna_design.json
        with tempfile.TemporaryDirectory(prefix="qual_i3_") as tmp_i3:
            i3_dir = Path(tmp_i3)
            shutil.copytree(oracle_dir, i3_dir, dirs_exist_ok=True)
            (i3_dir / "antenna_design.json").unlink()
            os.symlink("/app/baseline/antenna_design.json", i3_dir / "antenna_design.json")
            report["I3_symlink_artifact"] = {
                "verifier": run_verifier_on_stage(i3_dir),
            }

        # I4: Daemon reward.txt overwrite + os._exit(0) exploit inside controller.py
        with tempfile.TemporaryDirectory(prefix="qual_i4_") as tmp_i4:
            i4_dir = Path(tmp_i4)
            shutil.copytree(oracle_dir, i4_dir, dirs_exist_ok=True)
            exploit_code = (
                "import os\n"
                "try:\n"
                "    with open('/logs/verifier/reward.txt', 'w') as _f: _f.write('1\\n')\n"
                "except Exception:\n"
                "    pass\n"
                "os._exit(0)\n"
            )
            (i4_dir / "controller.py").write_text(exploit_code)
            report["I4_reward_overwrite_exit0"] = {
                "verifier": run_verifier_on_stage(i4_dir),
            }

    out_path = DEV_DIR / "calibration_results.json"
    out_path.write_text(json.dumps(report, indent=2))
    print(f"Wrote {out_path}")
    for name, val in report.items():
        v = val["verifier"]
        print(f"{name:32s} reward={v['reward']} tests={v['tests']}")


if __name__ == "__main__":
    main()