diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..eb25eaf90087c566e48462ded3b1cfcc2dfc3b70 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.avro filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.lz4 filter=lfs diff=lfs merge=lfs -text +*.mds filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +# Audio files - uncompressed +*.pcm filter=lfs diff=lfs merge=lfs -text +*.sam filter=lfs diff=lfs merge=lfs -text +*.raw filter=lfs diff=lfs merge=lfs -text +# Audio files - compressed +*.aac filter=lfs diff=lfs merge=lfs -text +*.flac filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.ogg filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +# Image files - uncompressed +*.bmp filter=lfs diff=lfs merge=lfs -text +*.gif filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.tiff filter=lfs diff=lfs merge=lfs -text +# Image files - compressed +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +# Video files - compressed +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text +sample/scorer/bin/sample_verifier-linux-amd64 filter=lfs diff=lfs merge=lfs -text +sample/scorer/bin/sample_verifier-macos-arm64 filter=lfs diff=lfs merge=lfs -text +sample/scorer/bin/sample_verifier-linux-arm64 filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..8a8364d9007df82ecb86e0c43058fb6199499b22 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,3 @@ +Evaluation only. This free sample is for evaluating the tasks. It grants no licence to train on them or pass them on. Licensed use: https://zerotrustphysics.com/offers/fast-start/ + +Protocol Company diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..72dd1ec75ec8f6dac1555ed1238ccceb20e917b6 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +--- +pretty_name: "Zero-Trust Physics free sample: Nuclear and Fusion" +license: other +license_name: evaluation-only +license_link: LICENSE.md +language: [en] +tags: [physics, rl-environment, rlvr, harbor, hud, mcp, evaluation, zero-trust-physics] +task_categories: [reinforcement-learning, question-answering] +size_categories: [n<1K] +viewer: true +configs: + - config_name: default + data_files: + - split: test + path: sample_tasks.jsonl +--- + +# Free sample: Nuclear and Fusion + + +**Five free tasks from the nuclear and fusion pack.** + +An agent works with fusion plasmas: vertical displacement events on the MAST tokamak, JET’s deuterium-tritium pulses and proton-boron fuel. Every answer is graded by rerunning the physics, with no AI judge. + +- **Run it:** clone this repository and run `sh sample/verify_sample.sh`. It works offline. +- **What’s inside:** the 5 tasks, the scorer, the reference answers, the cheat suite and a quality report for each task. +- **Beyond the sample:** Flagship task pack, Exclusive batches, Custom environments, Runtime & private infrastructure: scoped and invoiced, https://zerotrustphysics.com/offers/ + +Every number is below. + +--- + + +> **Protocol Company** · [zerotrustphysics.com](https://zerotrustphysics.com) · **The Foundry:** physics environments of real systems ([free runnable preview](https://huggingface.co/datasets/zero-trust-physics/zero-trust-physics-foundry-preview)) · Flagship task pack, Exclusive batches, Custom environments, Runtime & private infrastructure: scoped and invoiced, https://zerotrustphysics.com/offers/ · free open-engine samples: [sample groups 1–5](https://huggingface.co/collections/zero-trust-physics/zero-trust-physics-6ad3b6ef5195b706ac6d041e) · [kruze@zerotrustphysics.com](mailto:kruze@zerotrustphysics.com) + +Protocol Company · Zero-Trust Physics · release v0.15.3 · 13 November 2026 + +Five calibrated multi-step physics RLVR tasks scored by deterministic recomputation on the Zero-Trust Physics verifier; the reward is computed, never judged by a model. + +**Domain & slice coverage.** These 5 free evaluation tasks exercise measured MAST spherical-tokamak vertical displacement events (`energy/tokamak_vde_mast`), JET DTE1 deuterium-tritium hot-ion plasmas (`energy/tokamak_jet_dte1`), coupled JET plasma transport-to-beam-target reactivity (`tokamak_jet_dte1` -> `tokamak_dt_beam_target`), and p-B11 magnetic confinement (`fusion_pb11_thermal`): two budgeted searches, two designs to a limit, and a two-model chained design. The full 30-task paid Domain Pack and 100,000-run SFT corpus add calibrated reactivity-insertion, pump-coastdown, pulse, and coupled core-to-fuel-pin tasks across all measured nuclear fission reactors — SPERT III E-core (`reactor_spert3`), SPERT III pressurized C-core (`reactor_spert3_ccore`), ORNL MSRE molten-salt fuel pump (`reactor_msre_pump`), and JSI TRIGA Mark II core and instrumented fuel element (`reactor_triga_jsi`, `fuel_rod_triga_jsi`) — alongside TFTR supershot plasmas. + +**Evaluation only.** This free sample is for evaluating the tasks. It grants no licence to train on them or pass them on. + +| Task (kind) | pass@1 (solved / n) | pass@8 | Mean graded | Cheat suite | +|---|---|---|---|---| +| `g5r8-bs-mast-2seg-drift-down-wall-b4` (budgeted search) | 50% (4 of 8) | 100% (n=8) | 0.579 | 0 of 16 above 0; honest 3 of 3 at 1 | +| `g5r10-ch-jet-dt3-least-tbeam-power-c12-b7` (chained design) | 37.5% (3 of 8) | 100% (n=8) | 0.820 | 0 of 19 above 0; honest 3 of 3 at 1 | +| `g5r10-dl-dt4-core-te-fastshare-pion` (design to a limit) | 37.5% (3 of 8) | 100% (n=8) | 0.837 | 0 of 17 above 0; honest 3 of 3 at 1 | +| `g5r8-dl-jet-tritium-rich-dome-hotion` (design to a limit) | 37.5% (3 of 8) | 100% (n=8) | 0.719 | 0 of 17 above 0; honest 3 of 3 at 1 | +| `g5-bs-pb11-weakest-field-that-holds-b4` (budgeted search) | 62.5% (5 of 8) | 100% (n=8) | 0.728 | 0 of 16 above 0; honest 3 of 3 at 1 | + +Calibrated on a frontier model (tool variant, 8 attempts per task): sample `pass@1` spans 37.5%–62.5% (median 37.5%), with `pass@8` and continuous `graded` reward (scoring bracket or design tightness against task tolerance) reported beside binary `pass/fail`. Across all 5 tasks, 85 adversarial cheat attempts scored `0` above `0` and all 15 honest controls scored `1`. Per-task quality reports (HTML and JSON) are in `reports/`. + +**Attempting a task.** The Harbor, HUD, Inspect, and native MCP variants shipped in this free sample connect to https://mcp.zerotrustphysics.com/mcp/open (`Too many concurrent physics tasks.` triggers automatic retry in the bundled bridge). The public MCP preview endpoint serves 1 concurrent physics call per IP for interactive evaluation; parallel RL rollouts use the zero-dependency offline binary. + +> **`https://mcp.zerotrustphysics.com/mcp`** now serves the Vivarium: four closed physical systems to read, fork, drive and be graded on. The open library (`v0.15.3`) used here is at `https://mcp.zerotrustphysics.com/mcp/open`, unchanged. + +**For rollouts at scale,** the Flagship task pack and the runtime licence ship compiled offline binaries for Linux amd64, Linux arm64 and macOS arm64, so Harbor rollouts and grading run `--network none` with zero external dependencies and no rate limit. Managed private deployment is available under an enterprise agreement. + +**Scoring.** `scorer/` scores offline: `bin/` holds a sample-only verifier (macOS arm64, Linux amd64, Linux arm64) that computes these 5 tasks' requests, and refuses everything else by name. It holds no signing key, and its answers matched the served engine byte for byte on all 2,352 calls compared. The 5-crate Rust physics and proof-verification engine source is public, archived read-only at tag `v0.15.3` (https://github.com/johnkruze/zero-trust-physics-engine/tree/v0.15.3); read-only source audit of the pack verifier build is available under NDA for qualified buyers (https://zerotrustphysics.com/offers/fast-start/#runtime). Harbor's own grader runs in the task image and reaches the address. + +**HUD.** `tasks/hud/tasks/` packages these tasks for HUD's Harbor adapter (`hud.integrations.harbor.adapt`). Verifier calls route through an HTTP logging sidecar while the agent's sandbox has no network, and the grader reads the call log from the sidecar's container so the call budget holds without a Harbor trajectory (an edited or missing log scores `0`). Validated on HUD adapter 0.6.21 (5/5 tasks) and local Docker runtime; reach out for assisted HUD cloud onboarding. + +| Folder | What it holds | +|---|---| +| `tasks/` | `harbor/`, `hud/`, `inspect/`, `mcp/`: the 5 tasks in each format. | +| `scorer/`, `harness/` | The scorer, cheat suite, sample verifier, bridge to the address, call-logging proxy. | +| `reference/`, `reports/`, `calibration/` | Reference answers with SHA-384 proofs; a quality report per task; `passk_summary.json` and `cheat_suite.jsonl`. | +| `VERIFY.md`, `verify_sample.sh`, `SHA384SUMS` | One command: every hash, the 5 references, the cheat suite. | + +**Commercial work:** this group's withheld tasks are not in this archive, and this sample verifier does not compute them. Flagship task pack, Exclusive batches, Custom environments, Runtime & private infrastructure: scoped and invoiced, https://zerotrustphysics.com/offers/ + +Protocol Company · zerotrustphysics.com + +**In this repository:** `sample_tasks.jsonl` powers the Dataset Viewer above; `sample/` is the archive unpacked, unchanged (run `sh sample/verify_sample.sh`); `archive/` holds the `.tar.gz` archive, the Raw Data `.zip`, and their SHA-384 files. The Foundry (free preview: https://huggingface.co/datasets/zero-trust-physics/zero-trust-physics-foundry-preview) and its four offers: https://zerotrustphysics.com/offers/fast-start/ diff --git a/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip b/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip new file mode 100644 index 0000000000000000000000000000000000000000..6b2f9bcaf8768a51469f22a50d6ddc20612cd5b7 --- /dev/null +++ b/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5e05d426670ee3bbc012a6710da87f0d1f0f9d545f396fefc7da491d5655422 +size 121089 diff --git a/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip.sha384 b/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip.sha384 new file mode 100644 index 0000000000000000000000000000000000000000..ed90867b71418e5754158a36d6c014d5927cc55f --- /dev/null +++ b/archive/zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip.sha384 @@ -0,0 +1 @@ +dcac89622a11c0428a7151d201feaf55692bae05b23de41f6b465d561cbc40b1a1cfef5551e0c7207892cdf3a80a5ccd zero-trust-physics-sample-raw-data_nuclear-fusion_2026-11-13.zip diff --git a/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz b/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..c7aa9671049bd7af6605b766d3bf97cda8e533b7 --- /dev/null +++ b/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afe03837b777fb391a779b2befc3e96a9daf5803c66302e4c7f172c17342b319 +size 3097543 diff --git a/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz.sha384 b/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz.sha384 new file mode 100644 index 0000000000000000000000000000000000000000..4a000b7ef538462aa7376d2d84b6b1f3cf892af8 --- /dev/null +++ b/archive/zero-trust-physics-sample_nuclear-fusion_2026-11-13.tar.gz.sha384 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:352213f2ad9a1de01693cdfc7731f79b711142d5aaa1f89a09147faa9fe8ae5d +size 157 diff --git a/sample/README.md b/sample/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a3863ee9a458c1f50b937a2a2ed5f916439dcd5 --- /dev/null +++ b/sample/README.md @@ -0,0 +1,40 @@ +# Free sample: Nuclear and Fusion + +Protocol Company · Zero-Trust Physics · release v0.15.3 · 13 November 2026 + +Five calibrated multi-step physics RLVR tasks scored by deterministic recomputation on the Zero-Trust Physics verifier; the reward is computed, never judged by a model. + +**Domain & slice coverage.** These 5 free evaluation tasks exercise measured MAST spherical-tokamak vertical displacement events (`energy/tokamak_vde_mast`), JET DTE1 deuterium-tritium hot-ion plasmas (`energy/tokamak_jet_dte1`), coupled JET plasma transport-to-beam-target reactivity (`tokamak_jet_dte1` -> `tokamak_dt_beam_target`), and p-B11 magnetic confinement (`fusion_pb11_thermal`): two budgeted searches, two designs to a limit, and a two-model chained design. The full 30-task paid Domain Pack and 100,000-run SFT corpus add calibrated reactivity-insertion, pump-coastdown, pulse, and coupled core-to-fuel-pin tasks across all measured nuclear fission reactors — SPERT III E-core (`reactor_spert3`), SPERT III pressurized C-core (`reactor_spert3_ccore`), ORNL MSRE molten-salt fuel pump (`reactor_msre_pump`), and JSI TRIGA Mark II core and instrumented fuel element (`reactor_triga_jsi`, `fuel_rod_triga_jsi`) — alongside TFTR supershot plasmas. + +**Evaluation only.** This free sample is for evaluating the tasks. It grants no licence to train on them or pass them on. + +| Task (kind) | pass@1 (solved / n) | pass@8 | Mean graded | Cheat suite | +|---|---|---|---|---| +| `g5r8-bs-mast-2seg-drift-down-wall-b4` (budgeted search) | 50% (4 of 8) | 100% (n=8) | 0.579 | 0 of 16 above 0; honest 3 of 3 at 1 | +| `g5r10-ch-jet-dt3-least-tbeam-power-c12-b7` (chained design) | 37.5% (3 of 8) | 100% (n=8) | 0.820 | 0 of 19 above 0; honest 3 of 3 at 1 | +| `g5r10-dl-dt4-core-te-fastshare-pion` (design to a limit) | 37.5% (3 of 8) | 100% (n=8) | 0.837 | 0 of 17 above 0; honest 3 of 3 at 1 | +| `g5r8-dl-jet-tritium-rich-dome-hotion` (design to a limit) | 37.5% (3 of 8) | 100% (n=8) | 0.719 | 0 of 17 above 0; honest 3 of 3 at 1 | +| `g5-bs-pb11-weakest-field-that-holds-b4` (budgeted search) | 62.5% (5 of 8) | 100% (n=8) | 0.728 | 0 of 16 above 0; honest 3 of 3 at 1 | + +Calibrated on a frontier model (tool variant, 8 attempts per task): sample `pass@1` spans 37.5%–62.5% (median 37.5%), with `pass@8` and continuous `graded` reward (scoring bracket or design tightness against task tolerance) reported beside binary `pass/fail`. Across all 5 tasks, 85 adversarial cheat attempts scored `0` above `0` and all 15 honest controls scored `1`. Per-task quality reports (HTML and JSON) are in `reports/`. + +**Attempting a task.** The Harbor, HUD, Inspect, and native MCP variants shipped in this free sample connect to https://mcp.zerotrustphysics.com/mcp/open (`Too many concurrent physics tasks.` triggers automatic retry in the bundled bridge). The public MCP preview endpoint serves 1 concurrent physics call per IP for interactive evaluation; parallel RL rollouts use the zero-dependency offline binary. + +> **`https://mcp.zerotrustphysics.com/mcp`** now serves the Vivarium: four closed physical systems to read, fork, drive and be graded on. The open library (`v0.15.3`) used here is at `https://mcp.zerotrustphysics.com/mcp/open`, unchanged. + +**For rollouts at scale:** Domain Pack, scoped and invoiced, https://zerotrustphysics.com/offers/ + +**Scoring.** `scorer/` scores offline: `bin/` holds a sample-only verifier (macOS arm64, Linux amd64, Linux arm64) that computes these 5 tasks' requests, and refuses everything else by name. It holds no signing key, and its answers matched the served engine byte for byte on all 2,352 calls compared. The 5-crate Rust physics and proof-verification engine source is public at https://github.com/johnkruze/zero-trust-physics-engine (tag `v0.15.2`); read-only source audit of the pack verifier build is available under NDA for qualified buyers (https://zerotrustphysics.com/offers/#licence). Harbor's own grader runs in the task image and reaches the address. + +**HUD.** `tasks/hud/tasks/` packages these tasks for HUD's Harbor adapter (`hud.integrations.harbor.adapt`). Verifier calls route through an HTTP logging sidecar while the agent's sandbox has no network, and the grader reads the call log from the sidecar's container so the call budget holds without a Harbor trajectory (an edited or missing log scores `0`). Validated on HUD adapter 0.6.21 (5/5 tasks) and local Docker runtime; reach out for assisted HUD cloud onboarding. + +| Folder | What it holds | +|---|---| +| `tasks/` | `harbor/`, `hud/`, `inspect/`, `mcp/`: the 5 tasks in each format. | +| `scorer/`, `harness/` | The scorer, cheat suite, sample verifier, bridge to the address, call-logging proxy. | +| `reference/`, `reports/`, `calibration/` | Reference answers with SHA-384 proofs; a quality report per task; `passk_summary.json` and `cheat_suite.jsonl`. | +| `VERIFY.md`, `verify_sample.sh`, `SHA384SUMS` | One command: every hash, the 5 references, the cheat suite. | + +**Commercial packs and licensing:** Domain Pack, scoped and invoiced, https://zerotrustphysics.com/offers/. None of the withheld tasks is in this archive, and this sample verifier does not compute them. + +Protocol Company · zerotrustphysics.com diff --git a/sample/SHA384SUMS b/sample/SHA384SUMS new file mode 100644 index 0000000000000000000000000000000000000000..cdf0ff1e7c314d4eac75c6739c1dbdb8d5a3681c --- /dev/null +++ b/sample/SHA384SUMS @@ -0,0 +1,271 @@ +4a7d1bb7e79161159b0a3bcee518b93f475c1214591ac30594971e3336eaa3fc30d370113b4e127df70ded932a1f3ddd ./README.md +1e071fae1d71e92b776c89137452631b1a37a46f8de033135b91bf133e49a56a5257b4fea4fbbfeddd2c6dbe27fb6734 ./VERIFY.md +eeceb643b867a48ccd6e134df7915a999ded62b44ba6b07cfde3ebc0fffc3b618f177f3a6686a81ce574e0adec266d0e ./calibration/cheat_suite.jsonl +251a217f06a3e4264dfdf1451e0bec509647165c16b79fcef83eb064b88c964d8be1f44d48f60e5dc94399b3371d6b5e ./calibration/passk_summary.json +87779703ea62613cc92343c13c470bfb394ba1688426eb4809d4f0dbf264fec2e96ab604b9ca2e49580060b99097deb4 ./harness/mcp_log_proxy.py +be966b3249d0d2cdda05f96e92cdedc8a5b08361ec533274d13055bbf4aed93cd9160e2ed989b7b08d03161eee4b232f ./reference/g5-bs-pb11-weakest-field-that-holds-b4.calls.jsonl +d1c548d307e38cfb80b4604b1c5ddb723524f7ae56661d97bd0d20eeb48a3f3165a2c64b467ea8bd929b1474f5541e4c ./reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl +eabaf80b9a6b438fb94e9a4b96506e6f3856bc222471d6c43529cb6cd03083c745ae8dbf27d040e486acbaf5d2d29fff ./reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl.status.json +dbbdaf86283f521059b6e1a6d278c07aed56bf78401081dd06825a13eb7cf0efd2b1bb9da105e40d739f04650a039600 ./reference/g5-bs-pb11-weakest-field-that-holds-b4.txt +d00a2ca5ce9e0816b1b91ae3c4b0251693bc9e3ccef1198985653aecc1231c8e056e2901486e8e5d9cdb1bbe7f5cfb92 ./reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.calls.jsonl +5a0ad98bc7e640fe3cfbd91917da1c2d9659765527250b284c28a6e9cc88aa2f0b9943352233c06e4952128154a66953 ./reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl +e67a030b5567a2d3c293dc62f460bc9443d1243d05ac2970c1399d9d8c20078f8f89414915e8c53540a6595e2aacedc7 ./reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl.status.json +8f6359a2d7e5070fed0de69a9b930f9e62b4bbcf9ed51578d6c575efb2419fbc1cd75483f014270fb5365c52fe069956 ./reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt +10c871301baea56ca042247e2dca5cf6c43ec670f2e3c14f39f02f3c70b27ce7a016297c9c17017ac13a3367570ca2c8 ./reference/g5r10-dl-dt4-core-te-fastshare-pion.calls.jsonl +ad0febe967f3624207ac3174300f806ea1911daadec43ec859c59c55822cb9cd822aed79774c40daa51dea737a2e4368 ./reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl +e88e243d03b9c662700859a95c9f9d6b08b6c154fdca3d907ee18cc80a2a04c0d82ff76374497f242d967f696f8fa2e1 ./reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl.status.json +62d77475c2c57d1dded4de96a1d660bc9bf724697b0e375f44fb121b911875d280e5e9735ad0026bedda9bc184d0d238 ./reference/g5r10-dl-dt4-core-te-fastshare-pion.txt +3530b7baa14104ef246d9561fca51744aba6419189d4a6a2b25a6d4742437f03ad70781d71ec74195462fab50cc9ec99 ./reference/g5r8-bs-mast-2seg-drift-down-wall-b4.calls.jsonl +70db0c114f1becdcee1d0f23b47347d6ecc0329a050729008862d5711f3a24c87bb8f454b0182078e0c99581b48e0f41 ./reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl +53394e6ecc6fca8dfbcea6d992408107431e7145e7b3f17e34bdcc9ea31953073af5b938547fbc15c096b31aeb67aa52 ./reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl.status.json +2877acc719c806211c9811d10b73ba5891fb52d525dec609c5c47ac2806a6c2c6a574549de03cbd11c00b86117a8c034 ./reference/g5r8-bs-mast-2seg-drift-down-wall-b4.txt +bb4292b463a9192cce2f34e9410b12d2e9a837da586914c65a4a5c452cae81d263919bd780b5cef8f4a00033a11231de ./reference/g5r8-dl-jet-tritium-rich-dome-hotion.calls.jsonl +0a7a5443e09e863cf3f599195fd72073e5950df98b5e5da67a96e19b589237c4da0438f2e833761a3523b127154c8f21 ./reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl +97d99a34b98e9c071951e28a6831f3c6223f2a2d135dad0420e2b3ec4bffb0199ec4a6ed3e0530524092ba5f07bfd79f ./reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl.status.json +c17088c32bc6b4a75276729927ee0de54f1628c864feeee152b4a3cfdb6d9247d4ee59247c7ffbba891dde8ff1489b8e ./reference/g5r8-dl-jet-tritium-rich-dome-hotion.txt +a36223cb9f53b9c1fefdf5973ed1af0e7a89b6e5e27e37f15ffdad9d8824c64f0935937bdbf6de8789a4eba59503173e ./reference/naive_scores.jsonl +94feaf54979e094befb7a20248a032dea92bbc26669140b63c47d5ed5444dc326f34170c8a5c3a58cbd2008c4f82e71b ./reference/reference_scores.jsonl +c058b0442fe58a84b139b447c762df992fe39886d084d6f61864cb47f0d6e3d0a158b59adfc1c93eb0a51907d9c4aea9 ./reports/describe_short.json +2b8e884092b7cb12d9686a172dd8fa98143d3e20183ba722e4aabe965efb57f652b229261802d7e5db86c3bc810fc21f ./reports/g5-bs-pb11-weakest-field-that-holds-b4.html +a3c0d94ce73b19b8c796fc2c7dc18dc39ca3048e1bfd31536fe1dbd5c7e0a84374a7e09605d87d4496effe6e69a256ed ./reports/g5-bs-pb11-weakest-field-that-holds-b4.json +f39db6a48e4bb36c8d7013a48ad230afaab54300aefe0914db9c2253a67b2ad0c798cddf4174fca1e92b666a33cac4f7 ./reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.html +dfdc6a68f8bfa8b1e00f41975bd7b9018ac512a9f4ee738a9edb93c15d6960f8f489aca93f6e1f5503e7ec31120bcb58 ./reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.json +acf1b5419222a49ae6fe87165fa048436a6964a91d68325f8b3b24646e0f9cf869f9704d92e0365026e3f70a103b36e8 ./reports/g5r10-dl-dt4-core-te-fastshare-pion.html +a7d65633eb1c996e18fc054451b27e18ef4af0a8320e7412fb37f9e66cdec72052fac32e716fa06dc4e9a99ac08b72d6 ./reports/g5r10-dl-dt4-core-te-fastshare-pion.json +202f8c8156d7eb479b03fa8a8880cbc471f4cbb321d5496ccf363abffd70491f2b2744f4530f49a20aedb57c6be01659 ./reports/g5r8-bs-mast-2seg-drift-down-wall-b4.html +d8759dbc30c0715c889dc8262a3c7ef62776db45c5627059f88fab2d0d480cf3ec470889b94eeee37c66788ebd89c07e ./reports/g5r8-bs-mast-2seg-drift-down-wall-b4.json +eacfa11ec5abb84aae0d65b3813a192171d9461bd9f952feec955f0fbf35d27d60f6f841de60a0a1c0d5f65cb50c7215 ./reports/g5r8-dl-jet-tritium-rich-dome-hotion.html +66a6e4067fc8725e35a4a06d720f9e21aaec639e28969a452e62de52f0e5dc7e1fb69a5fcadcfd25b9d7153a883dc56b ./reports/g5r8-dl-jet-tritium-rich-dome-hotion.json +3cb67b3c3ea200ceabc70d371e9b2eaf9a64857d242064381dfeee555259fe438768cc09c065b7fe8f2ed0cdc9a63896 ./reports/index.html +cf918811eaa560fa8c08e2cf70319c2d2a81da710cf61ce82d06fe05c7935cfa0eaa90ca765a672b66d5939b24920fe7 ./reports/live_scores.jsonl +7174523593ce4af05a777e3f0c892aa1ed7bd65f020bf2020d4b136be4fda153dadf5b66f404b4994dee834ed1f03f35 ./reports/live_verify.json +4ee5ef58badae202e330aad33fdae81f62040b95f97f44f6609635f6d83759009ea613abebbc4a09718bdbbff64a3b69 ./reports/vault_proof.json +14f4151399c899aa56f9b8536ef2dc813f32a58a9b016efea561132a65cfcaa959782b9be12a6b24db14db737741c000 ./scorer/bin/sample_verifier-linux-amd64 +9adf8fb8be9bcd690f34de44b19699aa554717272098ac8630dbb5608548f619d2c875f92d7c4d480c80b2cae3c139d9 ./scorer/bin/sample_verifier-linux-arm64 +2975f9c8351febe264e4dcf209914d13598461d61473e15995088b15ac92d6048ccda26fad4c935fc66242747e4855b8 ./scorer/bin/sample_verifier-macos-arm64 +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./scorer/chainlib.py +5cec621f6aabd8cb982584285ac725fe85a5fc0ae95b6142f8f3e3edec49318f8e0adcfd305a85534fa2a13fc48f890e ./scorer/data/environments.jsonl +4420b16dd05d4ff3b21d421c6d48afbb9d163187db62e28024e3e99f78a9c6ef6b22621451dcf165581f94552c307715 ./scorer/mcp_stdio_open +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./scorer/pack_score.py +d851c6838b15bcb7c96c4d1d75b6c59a905e9a3ee54b393a8f098ff768ae04fd2976cb7b00f949eb068b329392141bbb ./scorer/prompt.py +f6fa72af84d02c0c72cd6866eb2c0fab9875fb8d5be40f1b74aca9066e58ab5fcc252943876ed5d3e7a69cd47606ebf1 ./scorer/run_cheat_suite.py +4af2040470af799b1a4f3d4711207bb872b7bcd52323a7d28386f702fdc0142411ee5c1275775166a563362786f4d5ef ./scorer/run_naive.py +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./scorer/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./scorer/score.py +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./scorer/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./scorer/ztp_open_bridge.py +fa944099e65223ac2d70dedaab7efc08279d6ecb0ee1afd213ebbcfc5d1e3a56b4ad7e78f96d572b026929c3f456df36 ./tasks/harbor/hud_taskset.json +5de8192d506c82d32faae5ef5126823ba3c505c65a30a7d65e171ed7924901f4ae77360db93372a973e4e63a8bc9b89a ./tasks/harbor/registry.json +8c5f12bc78c1f36ee2f7a579751b7a64a33fc09df24baf1bf3e41826486c0f5c98156a014addae8c4178d190b7dfbdf8 ./tasks/harbor/task_checksums.json +2386b4e1fb3c389c2c74cc1ea810252a7cd1231cabf14511c1d7994747f6894b26b12ba3b2db27021bc5a223db8a4269 ./tasks/harbor/task_checksums.sha256 +8d29e0b753c89d8d5e47a306dd088deb5c8c9e5446bf27e9a39583e39575038d41b436385c27f787a51acaa35aaedc92 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/ztp_open_bridge.py +2ce52725e56645053492fb27e2f0cd89b4685423db8c86b528b582b7697c4363394966beed647a3f69be428b1799d926 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/chainlib.py +affef3645fb8f1e7f8ca1f178f340bf6a6c0080636065bd78946b3f2cc0f4898ff002bd3b5014a41e1a2e5ac85157e7b ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/data/environments.jsonl +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/score.py +e88d0861f12a7c032719d720796a4277892a3d5446474497981b52bf92f4b8ac95f34abe656c156d3f51f13612cd232e ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/solve.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/ztp_mcp.py +4a295fc3ae28620658e59d28741fb4b65d81526d6cbbb869eab79be7cb4a50ee7048b0671d0ba5e93e4cfb25ad218f21 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml +ec0982aa0762934fd944bf10e9256d32417e88f2e0a01a252d068f113680356a90efe6ea82a401e8c50e935ca7328ed8 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile +affef3645fb8f1e7f8ca1f178f340bf6a6c0080636065bd78946b3f2cc0f4898ff002bd3b5014a41e1a2e5ac85157e7b ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py +4dd13c251fda485f3e112a6d32563cb72dfa1acfdb47f501ff475eb950ee0a7f9108ed987607210a6855154cf59671fc ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py +8d29e0b753c89d8d5e47a306dd088deb5c8c9e5446bf27e9a39583e39575038d41b436385c27f787a51acaa35aaedc92 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/ztp_open_bridge.py +7e4a1d7e81c48c5b13d850cbfad4e7efcb6e4a96b38c81e0387c71c82d18bc4d348814d926d35c5644227093d25ccbd5 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/chainlib.py +2e19bc31c5a0bbaaf3bb95e56ea1a487e44697ea0a4147471b6842f30979de38206b35e0d5dddfb19e9d9c5834cc255b ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/data/environments.jsonl +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/score.py +e88d0861f12a7c032719d720796a4277892a3d5446474497981b52bf92f4b8ac95f34abe656c156d3f51f13612cd232e ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/solve.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/ztp_mcp.py +49f9a94d047a2a1bf69a70a0e2e0140ae3493e8b913e7b4e5f1a2727bb1aee7039980107ab878312c4e188aa60a35be0 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml +ec0982aa0762934fd944bf10e9256d32417e88f2e0a01a252d068f113680356a90efe6ea82a401e8c50e935ca7328ed8 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile +2e19bc31c5a0bbaaf3bb95e56ea1a487e44697ea0a4147471b6842f30979de38206b35e0d5dddfb19e9d9c5834cc255b ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py +4dd13c251fda485f3e112a6d32563cb72dfa1acfdb47f501ff475eb950ee0a7f9108ed987607210a6855154cf59671fc ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py +8d29e0b753c89d8d5e47a306dd088deb5c8c9e5446bf27e9a39583e39575038d41b436385c27f787a51acaa35aaedc92 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/ztp_open_bridge.py +aa55a0fda1fc0e2789a12f37041abb7a53b1e591f89a45faaf4cf9002244835886c433adc86952d412a22f1ad356762c ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/chainlib.py +6be9e98688402220094efac8fa59e8007b41e8d5872f530d29495cea938f4e4854847de3f2630918869883309901a436 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/data/environments.jsonl +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/score.py +e88d0861f12a7c032719d720796a4277892a3d5446474497981b52bf92f4b8ac95f34abe656c156d3f51f13612cd232e ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/solve.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/ztp_mcp.py +58b76643a62a1be0732a18217d0c29a27769f3378d49716c0af1058a9058bf8d2f1f7d97a470bafda7bdb42f1abc6ef8 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml +ec0982aa0762934fd944bf10e9256d32417e88f2e0a01a252d068f113680356a90efe6ea82a401e8c50e935ca7328ed8 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile +6be9e98688402220094efac8fa59e8007b41e8d5872f530d29495cea938f4e4854847de3f2630918869883309901a436 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py +4dd13c251fda485f3e112a6d32563cb72dfa1acfdb47f501ff475eb950ee0a7f9108ed987607210a6855154cf59671fc ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py +8d29e0b753c89d8d5e47a306dd088deb5c8c9e5446bf27e9a39583e39575038d41b436385c27f787a51acaa35aaedc92 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/ztp_open_bridge.py +9ab45a00edd9ca4ae31ee874e4d0647939fe8a769e05f36df090af0f8560d9afa278604a684dae2cac19a942fbf4ea1f ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/chainlib.py +945cff01131d8f654bdd6f652af7f6a37eaace70987c25516326c1b78e5d3e8d4ac91732faebd25d0f4ed7e1fcd611fe ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/data/environments.jsonl +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/score.py +e88d0861f12a7c032719d720796a4277892a3d5446474497981b52bf92f4b8ac95f34abe656c156d3f51f13612cd232e ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/solve.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/ztp_mcp.py +bc090bd2e6533b2bea16e5593f2626871fb2bf8706ada499edea50b1649c88208f96f51b03339508bdd2234a042337b5 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml +ec0982aa0762934fd944bf10e9256d32417e88f2e0a01a252d068f113680356a90efe6ea82a401e8c50e935ca7328ed8 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile +945cff01131d8f654bdd6f652af7f6a37eaace70987c25516326c1b78e5d3e8d4ac91732faebd25d0f4ed7e1fcd611fe ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py +4dd13c251fda485f3e112a6d32563cb72dfa1acfdb47f501ff475eb950ee0a7f9108ed987607210a6855154cf59671fc ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py +8d29e0b753c89d8d5e47a306dd088deb5c8c9e5446bf27e9a39583e39575038d41b436385c27f787a51acaa35aaedc92 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/ztp_open_bridge.py +6c4cb66104096d80d7bdd22dcdd71498f89f368fa0e40748f3ff91a3d8db648881624d9c4a94ab0c813aa69e4febff98 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/chainlib.py +67be84f8d874efea9686d1df70157a9cb1af5ee1380244d87f5c188cde494065875b4e5eaa8bb7e9e1058fdb129e4dd0 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/data/environments.jsonl +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/score.py +e88d0861f12a7c032719d720796a4277892a3d5446474497981b52bf92f4b8ac95f34abe656c156d3f51f13612cd232e ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/solve.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/ztp_mcp.py +a34eb717d1e78750f434ed4d8005f042b85421b534050e9d7c24fbf029e30d8ba29c02272f62fff9cf369a3bfd0bf643 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml +ec0982aa0762934fd944bf10e9256d32417e88f2e0a01a252d068f113680356a90efe6ea82a401e8c50e935ca7328ed8 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile +67be84f8d874efea9686d1df70157a9cb1af5ee1380244d87f5c188cde494065875b4e5eaa8bb7e9e1058fdb129e4dd0 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py +4dd13c251fda485f3e112a6d32563cb72dfa1acfdb47f501ff475eb950ee0a7f9108ed987607210a6855154cf59671fc ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py +236b5c4bb6d6f42e6b0a2c9713ee0a026f76152d7b1411370fa8891f54a6b9aa1d08a1d9fb84e9ceadef1af355c3954a ./tasks/hud/set_door.py +d328525c6601ee613064882f1f252c64a7fa59ca80a180585b52b4db1268d1163700b21c57885f8c9f8f491a0f30cd30 ./tasks/hud/task_checksums.json +610493a1947f6d178c4813d64563bb07e8c287080e632874b166a76f012117e477dc5883ad81e6eacec3557c4503cd35 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile +020c36ea94bfa603abc8db6113e54bc6b5682259b8861edaaf9f32de756bedee4dfc2ec0ed4334eaccc0df75cc0dc852 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/docker-compose.yaml +5828695fdb24c01062ce07464e5ea65f3f723131f4dcda51deee2e8235ef02fc890b5810ab347faa82da25d16714619b ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/Dockerfile +827ab325681d02d5d6ad0664b0cd51c179bc561989e498d670899118e1004c50a66cd611077728336c36c266b4b0b6de ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_log_proxy.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_open_bridge.py +2ce52725e56645053492fb27e2f0cd89b4685423db8c86b528b582b7697c4363394966beed647a3f69be428b1799d926 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md +e739dbe7d6602a72884e970d6229c940258f2951fe35a2e5de7200b02b1f929878212e277caef391575a0d2e676be7c8 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml +2acd843a5600d97a0c67da00a878bd3bc5cde306848d8f4bbc59cba9f41db5af8ce43da17e38713f69c8b51450e08785 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile +affef3645fb8f1e7f8ca1f178f340bf6a6c0080636065bd78946b3f2cc0f4898ff002bd3b5014a41e1a2e5ac85157e7b ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py +37cf818d736fb6c2c071a0398fea1ff1d48598e7032b36ab6fac7cd6d732f714430b671ecf65cbba00344f6db3dc20a4 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/hud_grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py +cd2ecdac7e3ca0cc456221b05dd86c656974d5894104a7480882386d46343d274b6eae4e5cdfcaf3420512b315fb206d ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py +610493a1947f6d178c4813d64563bb07e8c287080e632874b166a76f012117e477dc5883ad81e6eacec3557c4503cd35 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile +020c36ea94bfa603abc8db6113e54bc6b5682259b8861edaaf9f32de756bedee4dfc2ec0ed4334eaccc0df75cc0dc852 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/docker-compose.yaml +5828695fdb24c01062ce07464e5ea65f3f723131f4dcda51deee2e8235ef02fc890b5810ab347faa82da25d16714619b ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/Dockerfile +827ab325681d02d5d6ad0664b0cd51c179bc561989e498d670899118e1004c50a66cd611077728336c36c266b4b0b6de ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_log_proxy.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_open_bridge.py +7e4a1d7e81c48c5b13d850cbfad4e7efcb6e4a96b38c81e0387c71c82d18bc4d348814d926d35c5644227093d25ccbd5 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md +6342a870cf314e95e412aaee59d66696b0d32c11b00789f8ba09a8da4e7e76416788e247eb1158547cc8af6a9e709d17 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml +2acd843a5600d97a0c67da00a878bd3bc5cde306848d8f4bbc59cba9f41db5af8ce43da17e38713f69c8b51450e08785 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile +2e19bc31c5a0bbaaf3bb95e56ea1a487e44697ea0a4147471b6842f30979de38206b35e0d5dddfb19e9d9c5834cc255b ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py +37cf818d736fb6c2c071a0398fea1ff1d48598e7032b36ab6fac7cd6d732f714430b671ecf65cbba00344f6db3dc20a4 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/hud_grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py +cd2ecdac7e3ca0cc456221b05dd86c656974d5894104a7480882386d46343d274b6eae4e5cdfcaf3420512b315fb206d ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py +610493a1947f6d178c4813d64563bb07e8c287080e632874b166a76f012117e477dc5883ad81e6eacec3557c4503cd35 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile +020c36ea94bfa603abc8db6113e54bc6b5682259b8861edaaf9f32de756bedee4dfc2ec0ed4334eaccc0df75cc0dc852 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/docker-compose.yaml +5828695fdb24c01062ce07464e5ea65f3f723131f4dcda51deee2e8235ef02fc890b5810ab347faa82da25d16714619b ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/Dockerfile +827ab325681d02d5d6ad0664b0cd51c179bc561989e498d670899118e1004c50a66cd611077728336c36c266b4b0b6de ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_log_proxy.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_open_bridge.py +aa55a0fda1fc0e2789a12f37041abb7a53b1e591f89a45faaf4cf9002244835886c433adc86952d412a22f1ad356762c ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md +25794e83dd27d57e53ee2258d5411a29916425c1dd5ef412deb45bdbc6ae2b5606fd38c93b838c572b5a39d98f8e8a8d ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml +2acd843a5600d97a0c67da00a878bd3bc5cde306848d8f4bbc59cba9f41db5af8ce43da17e38713f69c8b51450e08785 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile +6be9e98688402220094efac8fa59e8007b41e8d5872f530d29495cea938f4e4854847de3f2630918869883309901a436 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py +37cf818d736fb6c2c071a0398fea1ff1d48598e7032b36ab6fac7cd6d732f714430b671ecf65cbba00344f6db3dc20a4 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/hud_grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py +cd2ecdac7e3ca0cc456221b05dd86c656974d5894104a7480882386d46343d274b6eae4e5cdfcaf3420512b315fb206d ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py +610493a1947f6d178c4813d64563bb07e8c287080e632874b166a76f012117e477dc5883ad81e6eacec3557c4503cd35 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile +020c36ea94bfa603abc8db6113e54bc6b5682259b8861edaaf9f32de756bedee4dfc2ec0ed4334eaccc0df75cc0dc852 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/docker-compose.yaml +5828695fdb24c01062ce07464e5ea65f3f723131f4dcda51deee2e8235ef02fc890b5810ab347faa82da25d16714619b ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/Dockerfile +827ab325681d02d5d6ad0664b0cd51c179bc561989e498d670899118e1004c50a66cd611077728336c36c266b4b0b6de ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_log_proxy.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_open_bridge.py +9ab45a00edd9ca4ae31ee874e4d0647939fe8a769e05f36df090af0f8560d9afa278604a684dae2cac19a942fbf4ea1f ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md +24812c8703147cdbd6a747d0e5f841fdedb3ffe562a0982208db20de5375bf367a491347bdef750175cf06a9f3cd2cae ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml +2acd843a5600d97a0c67da00a878bd3bc5cde306848d8f4bbc59cba9f41db5af8ce43da17e38713f69c8b51450e08785 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile +945cff01131d8f654bdd6f652af7f6a37eaace70987c25516326c1b78e5d3e8d4ac91732faebd25d0f4ed7e1fcd611fe ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py +37cf818d736fb6c2c071a0398fea1ff1d48598e7032b36ab6fac7cd6d732f714430b671ecf65cbba00344f6db3dc20a4 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/hud_grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py +cd2ecdac7e3ca0cc456221b05dd86c656974d5894104a7480882386d46343d274b6eae4e5cdfcaf3420512b315fb206d ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py +610493a1947f6d178c4813d64563bb07e8c287080e632874b166a76f012117e477dc5883ad81e6eacec3557c4503cd35 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile +020c36ea94bfa603abc8db6113e54bc6b5682259b8861edaaf9f32de756bedee4dfc2ec0ed4334eaccc0df75cc0dc852 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/docker-compose.yaml +5828695fdb24c01062ce07464e5ea65f3f723131f4dcda51deee2e8235ef02fc890b5810ab347faa82da25d16714619b ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/Dockerfile +827ab325681d02d5d6ad0664b0cd51c179bc561989e498d670899118e1004c50a66cd611077728336c36c266b4b0b6de ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_log_proxy.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_open_bridge.py +6c4cb66104096d80d7bdd22dcdd71498f89f368fa0e40748f3ff91a3d8db648881624d9c4a94ab0c813aa69e4febff98 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md +3e0025e170f8dfed5f37bc646ef9206192624d62f4c8de9105597adcceed29cfde7208b1fefd581981d04a24b056a375 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml +2acd843a5600d97a0c67da00a878bd3bc5cde306848d8f4bbc59cba9f41db5af8ce43da17e38713f69c8b51450e08785 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile +67be84f8d874efea9686d1df70157a9cb1af5ee1380244d87f5c188cde494065875b4e5eaa8bb7e9e1058fdb129e4dd0 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl +b42707c4c2044e7f66439f20a446dabe48bbbc75e4392f320230ed2743129f680f3d469c7a18ba295453f78c1fa7c85d ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py +37cf818d736fb6c2c071a0398fea1ff1d48598e7032b36ab6fac7cd6d732f714430b671ecf65cbba00344f6db3dc20a4 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/hud_grade.py +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py +cd2ecdac7e3ca0cc456221b05dd86c656974d5894104a7480882386d46343d274b6eae4e5cdfcaf3420512b315fb206d ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/inspect/chainlib.py +5cec621f6aabd8cb982584285ac725fe85a5fc0ae95b6142f8f3e3edec49318f8e0adcfd305a85534fa2a13fc48f890e ./tasks/inspect/data/environments.jsonl +b36ffd89cb42467f54cedfccc924e89c35bf048ec0e5cf4d429a563cffb39cb55de20d9657972d370c2140517161418e ./tasks/inspect/inspect_task.py +4420b16dd05d4ff3b21d421c6d48afbb9d163187db62e28024e3e99f78a9c6ef6b22621451dcf165581f94552c307715 ./tasks/inspect/mcp_stdio_open +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/inspect/pack_score.py +d851c6838b15bcb7c96c4d1d75b6c59a905e9a3ee54b393a8f098ff768ae04fd2976cb7b00f949eb068b329392141bbb ./tasks/inspect/prompt.py +38a991195690215d491627d069e86ea47303d186cfba1a3de9848d7a57a87f31b21f18c6382112c2107b7f847f40fc7f ./tasks/inspect/sandbox/compose.yaml +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/inspect/score.py +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/inspect/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/inspect/ztp_open_bridge.py +266422579d937776408d9cf560404ec7af34dd996c2740875dd163f1a9e2a1f8b66d903829201f83d682cab7d09ff490 ./tasks/mcp/README.md +fb129e40bace09eafcc73199859d6ab9c06d95ae2a1c25492db27cf36ebaf349c09c34be9982dd150dde90b18db1391d ./tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/grade.sh +a4fd969bf25e91994139da7b0d6fa7e792d1d4aeac7e048453e238745fd4f35166310f194d121a76e1ae2a967e59db39 ./tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/mcp.json +36b173aae8f21a771847a5d97c37a10cc2840e5addbcbf98ee1c889917f23792b8c9b9aee9680736dc201ad686c19a08 ./tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/prompt.md +fb129e40bace09eafcc73199859d6ab9c06d95ae2a1c25492db27cf36ebaf349c09c34be9982dd150dde90b18db1391d ./tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/grade.sh +c7eaea875ae8c2fa544e7f30a27ab7ed4f42744727b015f0f9a45ccc89809927179b9cec4caee0cbc1e1dcdcc7ac72c2 ./tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/mcp.json +d7c14633b7ce75fadf5d861a6e27b661979407706a9186419840b21b721b0cec8eeaa83adf987bd0d2601e6e7e0ff795 ./tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/prompt.md +fb129e40bace09eafcc73199859d6ab9c06d95ae2a1c25492db27cf36ebaf349c09c34be9982dd150dde90b18db1391d ./tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/grade.sh +a242021922486aecb05ed06ec5182bc24ccf822d004d3994e32ad2ff03e57a43d8f95801ed88993b3d5b81d96b6e8264 ./tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/mcp.json +d013a0c9b23199a49ea8a17d38bf1e0a1bf3fd9ae0b1dff9b4d4fedd2622e8afd07af9d9f1479158947005291b049259 ./tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/prompt.md +fb129e40bace09eafcc73199859d6ab9c06d95ae2a1c25492db27cf36ebaf349c09c34be9982dd150dde90b18db1391d ./tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/grade.sh +c60083573893a392779d049fa17983af0436a600fd33a44afa8826291aec427dcf6f5bc31afc1a10bb3eac9c0dc66426 ./tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/mcp.json +756b784084e29153fafca22d885380e88f68a573c4170068a36b92d35f83bddf1f64a1e109c56c028d592541cc776ce4 ./tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/prompt.md +fb129e40bace09eafcc73199859d6ab9c06d95ae2a1c25492db27cf36ebaf349c09c34be9982dd150dde90b18db1391d ./tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/grade.sh +c0ec5e835856fd6ccf085c8c7c33dce645a7c6aee2e1ddbff4ca0271e60256c532d551dc3b98729c3071370bf1faace1 ./tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/mcp.json +2d54b31252bd8ac70c6add9853c5152f0ca19825159efbe1fc156cceec5b89b95b67d5f1749e30249f490c1bf540efd9 ./tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/prompt.md +0b4254f74fd12013bc5af575f0a260922a1c5888c60e65cfbdaa6f0e2a184d88267bd1226133134880037d9440cbef83 ./tasks/mcp/scorer/bind.py +4ab72c5978af483ef7a99096b99e9c20ecd746152f3bfcfdb0fe24e6c61b2463830d4c28f046472f7be308a367f8f858 ./tasks/mcp/scorer/chainlib.py +5cec621f6aabd8cb982584285ac725fe85a5fc0ae95b6142f8f3e3edec49318f8e0adcfd305a85534fa2a13fc48f890e ./tasks/mcp/scorer/data/environments.jsonl +df6cd1ed60eb0f654c6c6eb8f4323fb28a6dda73089c77e1b199ac70a0515d871ba1f2c6d5de809824c2ea721af5293a ./tasks/mcp/scorer/grade_mcp.py +87779703ea62613cc92343c13c470bfb394ba1688426eb4809d4f0dbf264fec2e96ab604b9ca2e49580060b99097deb4 ./tasks/mcp/scorer/mcp_log_proxy.py +4420b16dd05d4ff3b21d421c6d48afbb9d163187db62e28024e3e99f78a9c6ef6b22621451dcf165581f94552c307715 ./tasks/mcp/scorer/mcp_stdio_open +88aa869521c90682583fbef41fd0d8ca3d52ae37207f7fccdf394f02183393ab92b3e722efea6fda08c30fe98abf8523 ./tasks/mcp/scorer/pack_score.py +d851c6838b15bcb7c96c4d1d75b6c59a905e9a3ee54b393a8f098ff768ae04fd2976cb7b00f949eb068b329392141bbb ./tasks/mcp/scorer/prompt.py +a960c3d64cd1ba7bf9decc16fef45e2779b9fe5001ed15720ed9cdce7d8164a959b5fef3f77924f051fca12441f82235 ./tasks/mcp/scorer/run_reference.py +ba7a7c9ea95d22e25555e497c385b45a703db9e62c39fb61a4ae4d06a6fc3532d0888c39695e157d1537fe52ee510c82 ./tasks/mcp/scorer/score.py +be1dc2f239841f5ad366c0c19d979fa2fd4f33f5f070d9f4b5e84f7d68a5310bf8416cc7b6baa5fdc1ff1b389d26221f ./tasks/mcp/scorer/ztp_mcp.py +45d88b8eb4d6632791490b842350e656c3ed1666ccce6d2a46d68371068650ab440a920b634ecb13594b82fc3fbf0431 ./tasks/mcp/scorer/ztp_open_bridge.py +fd1b53535e0a3b7a706629cc481781dbbf94f800f712c6b1d2f369d3b4c52b21120fdb5bdbfff3ecaea1cd161019370a ./verify_sample.sh diff --git a/sample/VERIFY.md b/sample/VERIFY.md new file mode 100644 index 0000000000000000000000000000000000000000..13936ee75a02e4779cffeda51e5fcc60fd3a6900 --- /dev/null +++ b/sample/VERIFY.md @@ -0,0 +1,25 @@ +# Verify the sample + +Python 3 and nothing else. In the unpacked folder: + + sh verify_sample.sh + +It verifies every SHA-384 in `SHA384SUMS`, scores the 5 reference answers on the bundled verifier (reward 1 on 5 of 5) and runs the cheat suite (every cheat 0, every honest control 1). It ends `SAMPLE HOLDS`, or names what did not hold, and exits non-zero. + +**With the network denied.** macOS: `sandbox-exec -p '(version 1)(allow default)(deny network*)' sh verify_sample.sh`. Linux: `sudo unshare -n sh verify_sample.sh` (or `docker run --network none ... sh verify_sample.sh`). + +**macOS browser downloads.** `git clone` and `curl` require no extra step; if you downloaded an archive through a macOS web browser or mail client, clear Gatekeeper quarantine once with `xattr -dr com.apple.quarantine scorer/bin`. + +**Linux.** `scorer/bin/sample_verifier-linux-amd64` and `sample_verifier-linux-arm64` are static binaries; `verify_sample.sh` selects the binary matching the host CPU (`x86_64` or `aarch64`/`arm64`) and runs with `--network none`. Any other platform can score against `https://mcp.zerotrustphysics.com/mcp/open`. + +**Harbor.** `harbor run -p tasks/harbor/tasks -a oracle` runs each reference answer in Harbor's containers and grades it with the task's `tests/grade.py`. Each image's `/usr/local/bin/mcp_stdio` connects to the public MCP preview endpoint (1 concurrent physics call per IP). + +**Inspect.** `tasks/inspect/inspect_task.py`, one Inspect task for the set. + +**HUD.** `tasks/hud/tasks/` for HUD's Harbor adapter (`hud.integrations.harbor.adapt`, hud 0.6.21). Your adapter run needs Docker. The Compose project's main service needs user namespaces for HUD's sandbox. + +**Native MCP.** `tasks/mcp/README.md`: per task a prompt, an `mcp.json` and a one-line grader. + +**A proof by hand.** Every run proof is a SHA-384 seal over the request and answer. `verify_tape` with the request and its `run_seal`, on the bundled verifier or at the address, computes it again. The bundled verifier signs nothing; the address signs its answers ML-DSA-87. + +Protocol Company · zerotrustphysics.com diff --git a/sample/calibration/cheat_suite.jsonl b/sample/calibration/cheat_suite.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5fb847438a0f112848503a348bd9c09cabd58721 --- /dev/null +++ b/sample/calibration/cheat_suite.jsonl @@ -0,0 +1,150 @@ +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "honest", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "honest_reply_log_matches", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "honest_numbers_respelled", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "no_request_behind", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a solve request on the card is not among the calls in the log", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "edited_call_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the call log beside the reply differs from the harness log", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "over_budget", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "5 computing calls; the budget is 4", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "forbidden_tool", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the log holds calls of find_flip, which the task rules out", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "no_harness_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "no harness call log: every attempt is scored with the calls the harness recorded", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "harness_log_edited", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the harness log's chain breaks at line 2", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "stale_engine_tag", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "copied_proof_other_task", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "nudged_figure", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "figure_plus_10_percent", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "card_request_not_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a solve request on the card is not among the calls in the log", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "swapped_sides", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the holds request comes back refused (PressureExceedsField)", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "stop_misnamed", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the card names the stop 'SomeOtherStop'; the verifier names PressureExceedsField", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "proof_from_other_design", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "proof_uppercase", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds seal: the proof is not a SHA-384 seal of 96 hex digits", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "extra_argument", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds request differs from the task's at note", "ok": true} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "binding_misnamed", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "failing_given_as_passing", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "step_misnamed", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "missing_solve", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "solve_handed_other_run", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "every_row_genuine", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "every_row_false", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "every_row_false_true_reasons", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "next_start_rounded", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "next_proof_copied", "applies": false, "why": "not a budget card"} +{"task": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "vector": "next_request_edited", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "honest", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "honest_reply_log_matches", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "honest_numbers_respelled", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "no_request_behind", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "edited_call_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the call log beside the reply differs from the harness log", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "over_budget", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "5 computing calls; the budget is 4", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "forbidden_tool", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the log holds calls of find_flip, which the task rules out", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "no_harness_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "no harness call log: every attempt is scored with the calls the harness recorded", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "harness_log_edited", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the harness log's chain breaks at line 2", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "stale_engine_tag", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "copied_proof_other_task", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "nudged_figure", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "figure_plus_10_percent", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "card_request_not_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "swapped_sides", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the holds request comes back ended (PlasmaAtWall)", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "stop_misnamed", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the card names the stop 'SomeOtherStop'; the verifier names PlasmaAtWall", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "proof_from_other_design", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "proof_uppercase", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds seal: the proof is not a SHA-384 seal of 96 hex digits", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "extra_argument", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the holds request differs from the task's at note", "ok": true} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "binding_misnamed", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "failing_given_as_passing", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "step_misnamed", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "missing_solve", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "solve_handed_other_run", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "every_row_genuine", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "every_row_false", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "every_row_false_true_reasons", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "next_start_rounded", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "next_proof_copied", "applies": false, "why": "not a budget card"} +{"task": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "vector": "next_request_edited", "applies": false, "why": "not a budget card"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "honest", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "honest_reply_log_matches", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "honest_numbers_respelled", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "no_request_behind", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "edited_call_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the call log beside the reply differs from the harness log", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "over_budget", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "8 computing calls; the budget is 7", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "forbidden_tool", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the log holds calls of find_flip, which the task rules out", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "no_harness_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "no harness call log: every attempt is scored with the calls the harness recorded", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "harness_log_edited", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the harness log's chain breaks at line 4", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "stale_engine_tag", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "copied_proof_other_task", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "nudged_figure", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "figure_plus_10_percent", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "card_request_not_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "swapped_sides", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks dt_power", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "binding_misnamed", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "binding names 'j_beta'; the constraint that binds is another", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "proof_from_other_design", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the failing design's jet proof: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "failing_given_as_passing", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks dt_power", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "proof_uppercase", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's jet proof: the proof is not a SHA-384 seal of 96 hex digits", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "extra_argument", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's jet differs from the task's at note", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "missing_solve", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's slice is missing", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "solve_handed_other_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's slice does not carry jet's ion_temperature_kev at parameters.ion_temperature_kev[0], bit for bit", "ok": true} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "stop_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "step_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "next_start_rounded", "applies": false, "why": "not a continued design"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "next_proof_copied", "applies": false, "why": "not a continued design"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "next_request_edited", "applies": false, "why": "not a continued design"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "every_row_genuine", "applies": false, "why": "forensics only"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "every_row_false", "applies": false, "why": "forensics only"} +{"task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "vector": "every_row_false_true_reasons", "applies": false, "why": "forensics only"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "honest", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "honest_reply_log_matches", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "honest_numbers_respelled", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "no_request_behind", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a solve request on the card is not among the calls in the log", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "edited_call_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the call log beside the reply differs from the harness log", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "over_budget", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "5 computing calls; the budget is 4", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "forbidden_tool", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the log holds calls of find_flip, which the task rules out", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "no_harness_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "no harness call log: every attempt is scored with the calls the harness recorded", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "harness_log_edited", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the harness log's chain breaks at line 2", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "stale_engine_tag", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "copied_proof_other_task", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "nudged_figure", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "figure_plus_10_percent", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "card_request_not_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a solve request on the card is not among the calls in the log", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "swapped_sides", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks dt_fast_e", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "binding_misnamed", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "binding names 'dt_pion'; the constraint that binds is another", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "proof_from_other_design", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the failing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "failing_given_as_passing", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks dt_fast_e", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "proof_uppercase", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's solution_seal: the proof is not a SHA-384 seal of 96 hex digits", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "extra_argument", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's solve differs from the task's at note", "ok": true} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "stop_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "step_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "missing_solve", "applies": false, "why": "a design of one request"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "solve_handed_other_run", "applies": false, "why": "a design of one request"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "next_start_rounded", "applies": false, "why": "not a continued design"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "next_proof_copied", "applies": false, "why": "not a continued design"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "next_request_edited", "applies": false, "why": "not a continued design"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "every_row_genuine", "applies": false, "why": "forensics only"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "every_row_false", "applies": false, "why": "forensics only"} +{"task": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "vector": "every_row_false_true_reasons", "applies": false, "why": "forensics only"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "honest", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "honest_reply_log_matches", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "honest_numbers_respelled", "applies": true, "expect": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "no_request_behind", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "edited_call_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the call log beside the reply differs from the harness log", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "over_budget", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "5 computing calls; the budget is 4", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "forbidden_tool", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the log holds calls of find_flip, which the task rules out", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "no_harness_log", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "no harness call log: every attempt is scored with the calls the harness recorded", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "harness_log_edited", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the harness log's chain breaks at line 2", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "stale_engine_tag", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "copied_proof_other_task", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "nudged_figure", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "figure_plus_10_percent", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "card_request_not_run", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "a run_trajectory request on the card is not among the calls in the log", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "swapped_sides", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks j_fusion", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "binding_misnamed", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "binding names 'j_fusion_energy'; the constraint that binds is another", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "proof_from_other_design", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the failing design's run_seal: the verifier says the seal does not hold (cause run_seal)", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "failing_given_as_passing", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the passing design breaks j_fusion", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "proof_uppercase", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's run_seal: the proof is not a SHA-384 seal of 96 hex digits", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "extra_argument", "applies": true, "expect": 0, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's run differs from the task's at note", "ok": true} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "stop_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "step_misnamed", "applies": false, "why": "no stop binds"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "missing_solve", "applies": false, "why": "a design of one request"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "solve_handed_other_run", "applies": false, "why": "a design of one request"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "next_start_rounded", "applies": false, "why": "not a continued design"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "next_proof_copied", "applies": false, "why": "not a continued design"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "next_request_edited", "applies": false, "why": "not a continued design"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "every_row_genuine", "applies": false, "why": "forensics only"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "every_row_false", "applies": false, "why": "forensics only"} +{"task": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "vector": "every_row_false_true_reasons", "applies": false, "why": "forensics only"} diff --git a/sample/calibration/passk_summary.json b/sample/calibration/passk_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..424853837cae089d937e4f65a3cf172a2f2476e5 --- /dev/null +++ b/sample/calibration/passk_summary.json @@ -0,0 +1,75 @@ +{ + "note": "pass@k of this sample's tasks: pass@k = 1 - C(n-c, k) / C(n, k), n attempts with no harness error, c with reward 1", + "per_task": [ + { + "variant": "tool", + "model": "Frontier model", + "task": "g5-bs-pb11-weakest-field-that-holds-b4", + "attempts": 8, + "n": 8, + "correct": 5, + "harness_errors": 0, + "harness_error_rate": 0.0, + "mean_graded": 0.72753225, + "pass@1": 0.625, + "pass@8": 1.0, + "in_band": true + }, + { + "variant": "tool", + "model": "Frontier model", + "task": "g5r8-bs-mast-2seg-drift-down-wall-b4", + "attempts": 8, + "n": 8, + "correct": 4, + "harness_errors": 0, + "harness_error_rate": 0.0, + "mean_graded": 0.5785515, + "pass@1": 0.5, + "pass@8": 1.0, + "in_band": true + }, + { + "variant": "tool", + "model": "Frontier model", + "task": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "attempts": 8, + "n": 8, + "correct": 3, + "harness_errors": 0, + "harness_error_rate": 0.0, + "mean_graded": 0.820310875, + "pass@1": 0.375, + "pass@8": 1.0, + "in_band": true + }, + { + "variant": "tool", + "model": "Frontier model", + "task": "g5r10-dl-dt4-core-te-fastshare-pion", + "attempts": 8, + "n": 8, + "correct": 3, + "harness_errors": 0, + "harness_error_rate": 0.0, + "mean_graded": 0.8368211249999999, + "pass@1": 0.375, + "pass@8": 1.0, + "in_band": true + }, + { + "variant": "tool", + "model": "Frontier model", + "task": "g5r8-dl-jet-tritium-rich-dome-hotion", + "attempts": 8, + "n": 8, + "correct": 3, + "harness_errors": 0, + "harness_error_rate": 0.0, + "mean_graded": 0.718861875, + "pass@1": 0.375, + "pass@8": 1.0, + "in_band": true + } + ] +} \ No newline at end of file diff --git a/sample/harness/mcp_log_proxy.py b/sample/harness/mcp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..0172d4963b39b33786a5d07ab7e2c9de50879123 --- /dev/null +++ b/sample/harness/mcp_log_proxy.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""A stdio MCP proxy that records every tool call and changes no byte of any message. + + python3 mcp_log_proxy.py --log LOG [--forbid-under DIR ...] [--trace FILE] -- ENGINE [ENGINE ARGS ...] + +It starts ENGINE (an MCP server over stdio, one JSON-RPC message a line, such as the Zero-Trust +Physics mcp_stdio), hands every line the client writes to ENGINE's stdin, and every line ENGINE +writes back to the client's stdout, byte for byte. It reads a copy of each message and, for every +tools/call, appends one JSON line to LOG when the answer comes back: + + {"seq", "jsonrpc_id", "tool", "arguments", "ts_request", "ts_response", "duration_s", + "response_sha384", "text_sha384", "is_error", "chain"} + +response_sha384 is the SHA-384 of the answer line exactly as forwarded (without its newline); +text_sha384 is the SHA-384 of the answer's text content. chain is the SHA-384 of the previous +line's chain followed by this line's JSON without its chain (sorted keys, no spaces): an edit to +any line, or a line taken out, breaks every chain after it. A call still unanswered when the +client closes is written with "unanswered": true. + +LOG must lie outside the solver's working directory: the proxy refuses to start when LOG is +under its own working directory (where an agent's CLI starts it) or under any --forbid-under. +Beside LOG it keeps LOG.status.json: the engine command, the handshake (initialize, or +server/discover under MCP 2026-07-28), the call count, the engine's exit code. --trace FILE also keeps every line both ways, for diagnosing a client. + +Standard library only. Licence: Apache-2.0. +""" +import hashlib +import json +import os +import signal +import subprocess +import sys +import threading +import time + + +# initialize (MCP 2025-06-18 and before) or server/discover (MCP 2026-07-28, which newer clients send first) +HANDSHAKES = ("initialize", "server/discover") + + +def now(): + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + ".%03dZ" % (int(time.time() * 1000) % 1000) + + +def sha384(data): + return hashlib.sha384(data).hexdigest() + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return sha384(((previous or "") + payload).encode("utf-8")) + + +def under(path, folder): + path, folder = os.path.realpath(path), os.path.realpath(folder) + return path == folder or path.startswith(folder.rstrip(os.sep) + os.sep) + + +class Recorder: + def __init__(self, log_path, engine): + self.log_path = log_path + self.lock = threading.Lock() + self.pending = {} + self.seq = 0 + self.chain = None + self.status = {"engine": engine, "proxy_pid": os.getpid(), "started": now(), "handshake": None, + "tools_list": False, "calls": 0, "unanswered": 0, "engine_exit": None, "ended": None, + "problems": []} + open(log_path, "a").close() + self.write_status() + + def write_status(self): + tmp = self.log_path + ".status.json.tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(self.status, f, indent=1) + os.replace(tmp, self.log_path + ".status.json") + + def append(self, entry): + """One log line, chained to the one before. Called with the lock held.""" + self.seq += 1 + entry = dict(entry, seq=self.seq) + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.log_path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + self.status["calls"] += 1 + + @staticmethod + def messages(line): + try: + found = json.loads(line) + except ValueError: + return [] + if isinstance(found, list): + return [m for m in found if isinstance(m, dict)] + return [found] if isinstance(found, dict) else [] + + def from_client(self, line): + for message in self.messages(line): + if "id" in message and message.get("method"): + key = json.dumps(message["id"]) + with self.lock: + self.pending[key] = {"method": message["method"], "params": message.get("params"), + "ts": now(), "t0": time.time(), "id": message["id"]} + + def from_engine(self, line): + raw = line.rstrip(b"\r\n") + for message in self.messages(line): + if "id" not in message or message.get("method"): + continue + key = json.dumps(message["id"]) + with self.lock: + asked = self.pending.pop(key, None) + if asked is None: + continue + if asked["method"] in HANDSHAKES: + result = message.get("result") if isinstance(message.get("result"), dict) else {} + if not (self.status["handshake"] or {}).get("ok"): + srv = result.get("serverInfo") + if isinstance(srv, dict) and str(srv.get("title") or "").startswith("Zero-Trust Physics"): + desc = str(srv.get("description") or "") + if ": " in desc: + desc = "Deterministic physics of real objects: " + desc.split(": ", 1)[1] + srv = dict(srv, title="Zero-Trust Physics Verifier", description=desc) + self.status["handshake"] = {"method": asked["method"], "ok": "result" in message, + "server": srv} + self.write_status() + elif asked["method"] == "tools/list": + if not self.status["tools_list"]: + self.status["tools_list"] = "result" in message + self.write_status() + elif asked["method"] == "tools/call": + params = asked["params"] if isinstance(asked["params"], dict) else {} + result = message.get("result") if isinstance(message.get("result"), dict) else {} + text = "".join(c.get("text", "") for c in result.get("content", []) or [] if isinstance(c, dict)) + self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"), + "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": asked["ts"], "ts_response": now(), + "duration_s": round(time.time() - asked["t0"], 6), + "response_sha384": sha384(raw), "text_sha384": sha384(text.encode("utf-8")), + "is_error": bool(result.get("isError")) or "error" in message}) + + def close(self, engine_exit): + with self.lock: + for asked in self.pending.values(): + if asked["method"] != "tools/call": + continue + params = asked["params"] if isinstance(asked["params"], dict) else {} + self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"), + "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": asked["ts"], "ts_response": None, "duration_s": None, + "response_sha384": None, "text_sha384": None, "is_error": None, "unanswered": True}) + self.status["unanswered"] += 1 + self.pending.clear() + self.status["engine_exit"] = engine_exit + self.status["ended"] = now() + self.write_status() + + +def main(argv): + log, forbid, engine, trace = None, [], None, None + i = 0 + while i < len(argv): + if argv[i] == "--": + engine = argv[i + 1:] + break + if argv[i] == "--log" and i + 1 < len(argv): + log = argv[i + 1] + i += 2 + continue + if argv[i] == "--trace" and i + 1 < len(argv): + trace = open(argv[i + 1], "ab") + i += 2 + continue + if argv[i] == "--forbid-under" and i + 1 < len(argv): + forbid.append(argv[i + 1]) + i += 2 + continue + sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]") + if not log or not engine: + sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]") + log = os.path.abspath(log) + for folder in [os.getcwd()] + forbid: + if under(log, folder): + sys.exit("mcp_log_proxy: the log %s lies inside %s, where the solver works; put it outside" % (log, folder)) + os.makedirs(os.path.dirname(log), exist_ok=True) + recorder = Recorder(log, engine) + try: + proc = subprocess.Popen(engine, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr.fileno(), bufsize=0) + except OSError as problem: + recorder.status["problems"].append("the engine did not start: %s" % problem) + recorder.close(None) + sys.exit("mcp_log_proxy: the engine did not start: %s" % problem) + out = sys.stdout.buffer + + def engine_to_client(): + try: + for line in iter(proc.stdout.readline, b""): + if trace: + trace.write(b"< " + line) + trace.flush() + try: + recorder.from_engine(line) + except Exception as problem: # the log must never stop an answer + recorder.status["problems"].append("log: %s" % problem) + out.write(line) + out.flush() + except (BrokenPipeError, OSError) as problem: + recorder.status["problems"].append("client output closed: %s" % problem) + + finished = threading.Lock() + + def finish(): + """Once: close the engine, log what is unanswered, close the client's output, and leave.""" + if not finished.acquire(blocking=False): + return + try: + proc.stdin.close() + except OSError: + pass + try: + code = proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + code = proc.wait() + recorder.close(code) + try: + out.flush() + except OSError: + pass + os._exit(0) + + reader_done = threading.Event() + client_closed = threading.Event() + + def engine_to_client_then_finish(): + engine_to_client() + reader_done.set() + if proc.poll() is None: + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + if proc.poll() is not None and not client_closed.is_set(): + # the engine has gone: the client must see its output close rather than wait for an answer + recorder.status["problems"].append("the engine closed its output (exit %s)" % proc.returncode) + finish() + + reader = threading.Thread(target=engine_to_client_then_finish, daemon=True) + reader.start() + + def stop(signum, frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGHUP, stop) + source = sys.stdin.buffer + try: + for line in iter(source.readline, b""): + if trace: + trace.write(b"> " + line) + trace.flush() + try: + recorder.from_client(line) + except Exception as problem: + recorder.status["problems"].append("log: %s" % problem) + try: + proc.stdin.write(line) + proc.stdin.flush() + except (BrokenPipeError, OSError) as problem: + recorder.status["problems"].append("engine input closed: %s" % problem) + break + except KeyboardInterrupt: + pass + client_closed.set() + try: + proc.stdin.close() + except OSError: + pass + reader.join(timeout=30) + finish() + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.calls.jsonl b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.calls.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69e106f9d8686630e20bbb9e759069384ccce89e --- /dev/null +++ b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.calls.jsonl @@ -0,0 +1,2 @@ +{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}} +{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}} diff --git a/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2a0dca680d6fbcbaff8d6d3bfbcb97b49700c74a --- /dev/null +++ b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl @@ -0,0 +1,2 @@ +{"arguments": {"parameters": {"ash_fraction": 0.01, "boron_fraction": 0.128, "electron_density_per_m3": 2.2e+20, "energy_confinement_time_s": 45.0, "ion_temperature_kev": 310.0, "kinetic_enhancement": false, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96}, "solver": "fusion_pb11_thermal"}, "chain": "d94dc9f724f6f53b18907b4125612d4bffd7d2894aa1e15a4e86757f0488e5f62bf4d4553df5d51b99bb3b451f6ee08a", "duration_s": 0.072083, "is_error": false, "jsonrpc_id": 2, "response_sha384": "1ca58e633c5a103a9607cbfdc2b54fbb5a1590fe7102d6c4f5b9b260936926d4c7e1d1a5b3fd00939059834fe4a2162a", "seq": 1, "text_sha384": "caa4cfde802b4d2afa081f64447bdeac2c9d8b11aa33118398e31d5c283a99424716c3593645bbccae9b501299c3bfe2", "tool": "solve", "ts_request": "2026-11-14T01:37:12.471Z", "ts_response": "2026-11-14T01:37:12.543Z"} +{"arguments": {"parameters": {"ash_fraction": 0.01, "boron_fraction": 0.128, "electron_density_per_m3": 2.2e+20, "energy_confinement_time_s": 45.0, "ion_temperature_kev": 310.0, "kinetic_enhancement": false, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96}, "solver": "fusion_pb11_thermal"}, "chain": "e11f200d7ae219f037da76468aff3dc0096edad32861dcd7a04ebb52c7b50fd071c84a6f3dc82e4e5433ecee74b7fc7c", "duration_s": 0.066913, "is_error": false, "jsonrpc_id": 3, "response_sha384": "9a3397aab485eeddfc19b83016c4896e87b119608599c85c8e014e14da2bd8bd224e2c6507cade4d3350ded2c2477875", "seq": 2, "text_sha384": "54037ec0877fe58f080f3339249296ac69c068eee0fd0e4b274b8f4bf82a655a9d8160d130fc51875379019d4c637882", "tool": "solve", "ts_request": "2026-11-14T01:37:12.544Z", "ts_response": "2026-11-14T01:37:12.611Z"} diff --git a/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl.status.json b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl.status.json new file mode 100644 index 0000000000000000000000000000000000000000..1fd974cebf2fea3cc43e1195d025a67f4b0c9100 --- /dev/null +++ b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl.status.json @@ -0,0 +1,24 @@ +{ + "engine": [ + ".../engine_0.15.3_served/mcp_stdio" + ], + "proxy_pid": 5504, + "started": "2026-11-14T01:37:12.466Z", + "handshake": { + "method": "initialize", + "ok": true, + "server": { + "name": "Zero-Trust Physics", + "title": "Zero-Trust Physics Verifier", + "version": "0.15.3", + "description": "Deterministic physics of real objects: each model compared with measurement or held to a reference calculation, a conservation ledger on every step, a SHA-384 proof on every answer, and a refusal by name where its equations, constants or tables no longer hold. Cards: genesis_kernel_v0.13.1", + "websiteUrl": "https://zerotrustphysics.com" + } + }, + "tools_list": false, + "calls": 2, + "unanswered": 0, + "engine_exit": 0, + "ended": "2026-11-14T01:37:12.612Z", + "problems": [] +} \ No newline at end of file diff --git a/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.txt b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.txt new file mode 100644 index 0000000000000000000000000000000000000000..e82ac4ef0ee25ff440fd0100888f6b6aeda8c39a --- /dev/null +++ b/sample/reference/g5-bs-pb11-weakest-field-that-holds-b4.txt @@ -0,0 +1,3 @@ +The stop PressureExceedsField lies between the two requests below. + +{"holds": {"request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793"}, "stops": {"request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "stopped": "PressureExceedsField"}} diff --git a/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.calls.jsonl b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.calls.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d8821341f08b2d83861e55467ff03298feccf28a --- /dev/null +++ b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.calls.jsonl @@ -0,0 +1,4 @@ +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}} +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}} +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}} +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}} diff --git a/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c2fd094f003687f5bc793c4528d436164e8465f --- /dev/null +++ b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl @@ -0,0 +1,4 @@ +{"arguments": {"card": "tokamak_jet_dte1", "domain": "energy", "dt_s": 0.001, "initial": {"deuterium_beam_ion_energy_j": 415000.0, "elapsed_time_s": 0.0, "tail_ion_energy_j": 215000.0, "thermal_energy_j": 4950000.0, "tritium_beam_ion_energy_j": 545000.0}, "record_every": 1800, "segments": [{"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 8400000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 0.0, "icrh_power_w": 4800000.0, "line_density_per_m3": 4.2e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 5200000.0, "tritium_fraction": 0.5}, "steps": 700}, {"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 8400000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 0.0, "icrh_power_w": 4800000.0, "line_density_per_m3": 4.2e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 9739916.12958908, "tritium_fraction": 0.5}, "steps": 1100}]}, "chain": "59c67d644b84b4b5705df653aa2e2be13190639d9a814e3b7323d39eaa3fb5e5c7aa60a64e584d506a48b108fa223f79", "duration_s": 0.015192, "is_error": false, "jsonrpc_id": 2, "response_sha384": "69d00fb22ebc0fa507680dc72dfa9dcb81abe8dd35536a3f662966347e98fd1992ae1b4d363146861f25b5d1f49b7aa2", "seq": 1, "text_sha384": "44d2d1ae3fbb0ed3490b275678911107c7dd9b3d35cdb42037df515b3a939fcd8bb575e544f7adedb689808461a8ebbc", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:12.250Z", "ts_response": "2026-11-14T01:37:12.265Z"} +{"arguments": {"parameters": {"beam_energy_kev": [99.0, 136.0], "beam_mass_number": [2.0, 3.0], "beam_power_share": [0.56, 0.44], "beam_power_w": [980000.0, 600000.0, 260000.0], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "electron_temperature_kev": [8.6, 5.4, 3.0], "impurity_charge": 6.0, "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_mass_u": 12.0, "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "shell_volume_m3": [1.52, 2.92, 5.18], "time_since_beam_change_s": 2.5, "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18]}, "solver": "tokamak_dt_beam_target"}, "chain": "83b8189cec2565e8efb55cb5d287dbbab588b67c4d616355299cd3aacf0e83c41a7e7a22a8f8ad4ac9dee50665267389", "duration_s": 0.013088, "is_error": false, "jsonrpc_id": 3, "response_sha384": "42ff062e752821df1fdd920faf6fadaccbd0633e7ad5348015ce6697eb3dc6ac369f8893d4db5d7fef68b7d830bc4309", "seq": 2, "text_sha384": "b3de9272e026c8c3746366c69386906e9efc80d9b96f2cbe5c6d2df0b7f15960e55ce7e1599315a4206cec346fb96fb6", "tool": "solve", "ts_request": "2026-11-14T01:37:12.265Z", "ts_response": "2026-11-14T01:37:12.278Z"} +{"arguments": {"card": "tokamak_jet_dte1", "domain": "energy", "dt_s": 0.001, "initial": {"deuterium_beam_ion_energy_j": 415000.0, "elapsed_time_s": 0.0, "tail_ion_energy_j": 215000.0, "thermal_energy_j": 4950000.0, "tritium_beam_ion_energy_j": 545000.0}, "record_every": 1800, "segments": [{"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 8400000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 0.0, "icrh_power_w": 4800000.0, "line_density_per_m3": 4.2e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 5200000.0, "tritium_fraction": 0.5}, "steps": 700}, {"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 8400000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 0.0, "icrh_power_w": 4800000.0, "line_density_per_m3": 4.2e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 9223916.12958908, "tritium_fraction": 0.5}, "steps": 1100}]}, "chain": "9b6505b390711f480684d15ea2a3ee0c38825986b0849eddb0445cbad30d060832e84778ab58ff5d78d01797ad7ab223", "duration_s": 0.01388, "is_error": false, "jsonrpc_id": 4, "response_sha384": "9858bd73970b7740992bb9bd828062df4f08e239127261994f5f6c0fa811ef5a43edcd2d53eb8540040b50b84a694103", "seq": 3, "text_sha384": "02fd4f27b1ce5dd4aeaf168c5dda50ea574ad12b0eecb04b367c6000c6a686605a674d5e8d5a788b2ba0b89f73605c6d", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:12.279Z", "ts_response": "2026-11-14T01:37:12.293Z"} +{"arguments": {"parameters": {"beam_energy_kev": [99.0, 136.0], "beam_mass_number": [2.0, 3.0], "beam_power_share": [0.56, 0.44], "beam_power_w": [980000.0, 600000.0, 260000.0], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "electron_temperature_kev": [8.6, 5.4, 3.0], "impurity_charge": 6.0, "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_mass_u": 12.0, "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "shell_volume_m3": [1.52, 2.92, 5.18], "time_since_beam_change_s": 2.5, "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18]}, "solver": "tokamak_dt_beam_target"}, "chain": "8a4f2a65d7f59dfd0b20655bf686eeeab9af8cc6d6acf1f980d5abef3488019b52674aeae2115a96befc220bbfb380e9", "duration_s": 0.012673, "is_error": false, "jsonrpc_id": 5, "response_sha384": "1517b408a3f26e05a5fb5228ff6ba642381c32c9aa72d823850c7e7bf2921ffaa6500a36917c7c110d1e511a0cc5a57f", "seq": 4, "text_sha384": "ac0377c1e6fcd354e9235390b3dad3a0535f086e37e8c0de156eb88b76017875a8bea7f826c5cdfe48e0d466fdaaea1f", "tool": "solve", "ts_request": "2026-11-14T01:37:12.293Z", "ts_response": "2026-11-14T01:37:12.306Z"} diff --git a/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl.status.json b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl.status.json new file mode 100644 index 0000000000000000000000000000000000000000..2b34006e13cd4da99044b5180c87a07f42752854 --- /dev/null +++ b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl.status.json @@ -0,0 +1,24 @@ +{ + "engine": [ + ".../engine_0.15.3_served/mcp_stdio" + ], + "proxy_pid": 5498, + "started": "2026-11-14T01:37:12.245Z", + "handshake": { + "method": "initialize", + "ok": true, + "server": { + "name": "Zero-Trust Physics", + "title": "Zero-Trust Physics Verifier", + "version": "0.15.3", + "description": "Deterministic physics of real objects: each model compared with measurement or held to a reference calculation, a conservation ledger on every step, a SHA-384 proof on every answer, and a refusal by name where its equations, constants or tables no longer hold. Cards: genesis_kernel_v0.13.1", + "websiteUrl": "https://zerotrustphysics.com" + } + }, + "tools_list": false, + "calls": 4, + "unanswered": 0, + "engine_exit": 0, + "ended": "2026-11-14T01:37:12.307Z", + "problems": [] +} \ No newline at end of file diff --git a/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c23b024e2cce9f375b922c3d53527640a3da714 --- /dev/null +++ b/sample/reference/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt @@ -0,0 +1,3 @@ +The boundary lies between the two designs below; dt_power binds. + +{"passing": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}, "failing": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}, "binding": "dt_power"} diff --git a/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.calls.jsonl b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.calls.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bfc7cf24a05e910cdf3bffbc995cf12877908fea --- /dev/null +++ b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.calls.jsonl @@ -0,0 +1,2 @@ +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}} +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}} diff --git a/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..892519f0a972beb2eda08d8913562bc05bbc13b1 --- /dev/null +++ b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl @@ -0,0 +1,2 @@ +{"arguments": {"parameters": {"beam_energy_kev": [98.0, 138.0], "beam_mass_number": [2.0, 3.0], "beam_power_share": [0.54, 0.46], "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "impurity_charge": 8.0, "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_mass_u": 16.0, "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "time_since_beam_change_s": 2.9, "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18]}, "solver": "tokamak_dt_beam_target"}, "chain": "9ad73e47763f447cc0a339fa7f1ecb6d948415f1b7b30fe883ee4ac851a3e90478534a641e65c507084fc192add478df", "duration_s": 0.015328, "is_error": false, "jsonrpc_id": 2, "response_sha384": "aeb6e11bb77bc0483319d0081786461b47cc550d74b27426265d1486eab61b7ea72c0ff74a8113467f628e71a3767be7", "seq": 1, "text_sha384": "55c8bf5233f6878e85d3493e3c87d74e5c5232e02c1a20b54128530807827f78a54bf8c5d47eabe1ac0e270121e4efed", "tool": "solve", "ts_request": "2026-11-14T01:37:12.341Z", "ts_response": "2026-11-14T01:37:12.357Z"} +{"arguments": {"parameters": {"beam_energy_kev": [98.0, 138.0], "beam_mass_number": [2.0, 3.0], "beam_power_share": [0.54, 0.46], "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "impurity_charge": 8.0, "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_mass_u": 16.0, "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "time_since_beam_change_s": 2.9, "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18]}, "solver": "tokamak_dt_beam_target"}, "chain": "2bed0010d730bd670163b85cfcca45dfd03ab210bab98a24797b63bae8681a18da4c3a1cce91bd589f1fe37d7e265552", "duration_s": 0.015074, "is_error": false, "jsonrpc_id": 3, "response_sha384": "95efb0823a3fb3ffd9eec7fb636af5a7b47afe54dadee3f02b0fb4d2448160b6a178f6c3d9a295a637c5c1a5d8bb5e8e", "seq": 2, "text_sha384": "783779e72075be4eac9cdf68e230439bda71166f0a3e1eae00a140794af7e3cb356eab0bd75d32a56fc3f81d3e8ac757", "tool": "solve", "ts_request": "2026-11-14T01:37:12.357Z", "ts_response": "2026-11-14T01:37:12.372Z"} diff --git a/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl.status.json b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl.status.json new file mode 100644 index 0000000000000000000000000000000000000000..4127491f943cb955beb06291b88b1d9311f1e332 --- /dev/null +++ b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl.status.json @@ -0,0 +1,24 @@ +{ + "engine": [ + ".../engine_0.15.3_served/mcp_stdio" + ], + "proxy_pid": 5500, + "started": "2026-11-14T01:37:12.337Z", + "handshake": { + "method": "initialize", + "ok": true, + "server": { + "name": "Zero-Trust Physics", + "title": "Zero-Trust Physics Verifier", + "version": "0.15.3", + "description": "Deterministic physics of real objects: each model compared with measurement or held to a reference calculation, a conservation ledger on every step, a SHA-384 proof on every answer, and a refusal by name where its equations, constants or tables no longer hold. Cards: genesis_kernel_v0.13.1", + "websiteUrl": "https://zerotrustphysics.com" + } + }, + "tools_list": false, + "calls": 2, + "unanswered": 0, + "engine_exit": 0, + "ended": "2026-11-14T01:37:12.373Z", + "problems": [] +} \ No newline at end of file diff --git a/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.txt b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.txt new file mode 100644 index 0000000000000000000000000000000000000000..f568d5c445c702cc857b91ec97ddd76173f2e8af --- /dev/null +++ b/sample/reference/g5r10-dl-dt4-core-te-fastshare-pion.txt @@ -0,0 +1,3 @@ +The boundary lies between the two designs below; dt_fast_e binds. + +{"passing": {"solve": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}}, "proof": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949"}}, "failing": {"solve": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}}, "proof": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e"}}, "binding": "dt_fast_e"} diff --git a/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.calls.jsonl b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.calls.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a55d2ea580b5584dfe76d55b27aa1dd27c452738 --- /dev/null +++ b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.calls.jsonl @@ -0,0 +1,2 @@ +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}} +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}} diff --git a/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69f97253f8fa115ecf17b02c61f884ee27b5e532 --- /dev/null +++ b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl @@ -0,0 +1,2 @@ +{"arguments": {"card": "tokamak_vde_mast", "domain": "energy", "dt_s": 0.001, "initial": {"displacement_m": 0.0038, "p6_current_a": -31.0, "velocity_m_s": 0.0249, "wall_current_a": -83.4}, "record_every": 56, "segments": [{"load": {"p6_voltage_v": 0.0}, "steps": 18}, {"load": {"p6_voltage_v": -6.9444887558793384}, "steps": 38}]}, "chain": "098d5eec709709e1a492bdb3cc70c5adc4bba669443de7ae8052c69f6c7b6b5d55eed74a1d4efbe136a462a7dc7f48d0", "duration_s": 1.205544, "is_error": false, "jsonrpc_id": 2, "response_sha384": "26dff476f74452976609a83b2a5ddbbb406871ef6f342b18e34e4e0b5341be7ac3078a37633ea45a3e7f9700eacb05e7", "seq": 1, "text_sha384": "662bad386646cd682c5195ee689f9b72e28f6769c27dfbf2f5f28c6d9217e601104ca55b4bd1a273545b52d1cfc8cd58", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:09.811Z", "ts_response": "2026-11-14T01:37:11.017Z"} +{"arguments": {"card": "tokamak_vde_mast", "domain": "energy", "dt_s": 0.001, "initial": {"displacement_m": 0.0038, "p6_current_a": -31.0, "velocity_m_s": 0.0249, "wall_current_a": -83.4}, "record_every": 56, "segments": [{"load": {"p6_voltage_v": 0.0}, "steps": 18}, {"load": {"p6_voltage_v": -6.945322144533363}, "steps": 38}]}, "chain": "2349e141479ebfad646e123a41bcb994516304c3c9be4b74f162c1c28b691fc0b71afedb79123b0a815643a1a4643002", "duration_s": 1.196244, "is_error": false, "jsonrpc_id": 3, "response_sha384": "ba0e5fa867f395935156158e356ce53aa7e2b5536c0e28b0343383eb19a4793f6244582c0f37168db0774306caa0e0b8", "seq": 2, "text_sha384": "0df9ec42ce3139944c0abe17d3e47c21533852038dbb49200612c92df91247803867ad779ab7e2719dd7c28244fcf6db", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:11.017Z", "ts_response": "2026-11-14T01:37:12.213Z"} diff --git a/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl.status.json b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl.status.json new file mode 100644 index 0000000000000000000000000000000000000000..afc9a79d8c2ec1a3aaf513e11012ba300b15ec97 --- /dev/null +++ b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl.status.json @@ -0,0 +1,24 @@ +{ + "engine": [ + ".../engine_0.15.3_served/mcp_stdio" + ], + "proxy_pid": 5496, + "started": "2026-11-14T01:37:09.804Z", + "handshake": { + "method": "initialize", + "ok": true, + "server": { + "name": "Zero-Trust Physics", + "title": "Zero-Trust Physics Verifier", + "version": "0.15.3", + "description": "Deterministic physics of real objects: each model compared with measurement or held to a reference calculation, a conservation ledger on every step, a SHA-384 proof on every answer, and a refusal by name where its equations, constants or tables no longer hold. Cards: genesis_kernel_v0.13.1", + "websiteUrl": "https://zerotrustphysics.com" + } + }, + "tools_list": false, + "calls": 2, + "unanswered": 0, + "engine_exit": 0, + "ended": "2026-11-14T01:37:12.215Z", + "problems": [] +} \ No newline at end of file diff --git a/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.txt b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.txt new file mode 100644 index 0000000000000000000000000000000000000000..194f034e32534fd5c2b767655a4a8e060a760632 --- /dev/null +++ b/sample/reference/g5r8-bs-mast-2seg-drift-down-wall-b4.txt @@ -0,0 +1,3 @@ +The stop PlasmaAtWall lies between the two requests below. + +{"holds": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969"}, "stops": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "stopped": "PlasmaAtWall"}} diff --git a/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.calls.jsonl b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.calls.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a5a0442261a75803117ff47697ab6df32ec06dfa --- /dev/null +++ b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.calls.jsonl @@ -0,0 +1,2 @@ +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}} +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}} diff --git a/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..acd9e8f4ce2ea03623a539db32a0c9c8318d36ce --- /dev/null +++ b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl @@ -0,0 +1,2 @@ +{"arguments": {"card": "tokamak_jet_dte1", "domain": "energy", "dt_s": 0.001, "initial": {"deuterium_beam_ion_energy_j": 455000.0, "elapsed_time_s": 0.0, "tail_ion_energy_j": 235000.0, "thermal_energy_j": 5350000.0, "tritium_beam_ion_energy_j": 515000.0}, "record_every": 1700, "segments": [{"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 5800000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 1.0, "icrh_power_w": 2800000.0, "line_density_per_m3": 3.6e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 6200000.0, "tritium_fraction": 0.52}, "steps": 600}, {"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 5800000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 1.0, "icrh_power_w": 2800000.0, "line_density_per_m3": 3.6e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 6200000.0, "tritium_fraction": 0.7461228712236883}, "steps": 1100}]}, "chain": "e7425d56acb3f047c1ae2177e3da293fd2a0ed7b57846a325720ef9de358ba8207156d9ad92241e0efaeca0f9c715fe6", "duration_s": 0.014402, "is_error": false, "jsonrpc_id": 2, "response_sha384": "83315430c4eb8a7e1fb6266d0fa115ad0d074e379d431e82fae99de6462d9ba087de46f08daa4004c86fc1306c4d97b2", "seq": 1, "text_sha384": "61f4700be7d81c381497698c31c678f1c01141c3cad26321a22e5e355ee7655f8d87c3802bf7aade3c48461bc703c419", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:12.408Z", "ts_response": "2026-11-14T01:37:12.422Z"} +{"arguments": {"card": "tokamak_jet_dte1", "domain": "energy", "dt_s": 0.001, "initial": {"deuterium_beam_ion_energy_j": 455000.0, "elapsed_time_s": 0.0, "tail_ion_energy_j": 235000.0, "thermal_energy_j": 5350000.0, "tritium_beam_ion_energy_j": 515000.0}, "record_every": 1700, "segments": [{"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 5800000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 1.0, "icrh_power_w": 2800000.0, "line_density_per_m3": 3.6e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 6200000.0, "tritium_fraction": 0.52}, "steps": 600}, {"load": {"deuterium_beam_energy_kev": 93.0, "deuterium_beam_power_w": 5800000.0, "effective_charge": 1.95, "electron_temperature_kev": 7.6, "hot_ion_regime": 1.0, "icrh_power_w": 2800000.0, "line_density_per_m3": 3.6e+19, "ohmic_power_w": 540000.0, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_beam_energy_kev": 131.0, "tritium_beam_power_w": 6200000.0, "tritium_fraction": 0.7463028712236883}, "steps": 1100}]}, "chain": "34845743fb07db64b6e80d30b6288cac413520849e0e1ba350aa6f2033b418ecc91dadca5398770420147faf305d7adb", "duration_s": 0.013234, "is_error": false, "jsonrpc_id": 3, "response_sha384": "9924199c768f18a625e40d9cd0a17aab46d282f4c9490536d8ab1cc44783858af39223478d38024683adf35bd66e0ee4", "seq": 2, "text_sha384": "3c9e56d2eb0a0847d75053ffa736079136f331e78156abebf8e831580d6823285b69e1453596eb805de974563d4eb568", "tool": "run_trajectory", "ts_request": "2026-11-14T01:37:12.422Z", "ts_response": "2026-11-14T01:37:12.436Z"} diff --git a/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl.status.json b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl.status.json new file mode 100644 index 0000000000000000000000000000000000000000..cecb59c4a8a44742c14cb1a73fb39a5c0f6036ab --- /dev/null +++ b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl.status.json @@ -0,0 +1,24 @@ +{ + "engine": [ + ".../engine_0.15.3_served/mcp_stdio" + ], + "proxy_pid": 5502, + "started": "2026-11-14T01:37:12.403Z", + "handshake": { + "method": "initialize", + "ok": true, + "server": { + "name": "Zero-Trust Physics", + "title": "Zero-Trust Physics Verifier", + "version": "0.15.3", + "description": "Deterministic physics of real objects: each model compared with measurement or held to a reference calculation, a conservation ledger on every step, a SHA-384 proof on every answer, and a refusal by name where its equations, constants or tables no longer hold. Cards: genesis_kernel_v0.13.1", + "websiteUrl": "https://zerotrustphysics.com" + } + }, + "tools_list": false, + "calls": 2, + "unanswered": 0, + "engine_exit": 0, + "ended": "2026-11-14T01:37:12.437Z", + "problems": [] +} \ No newline at end of file diff --git a/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.txt b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f2f47218cac2b13a56ef9b82fea5766fc075d68 --- /dev/null +++ b/sample/reference/g5r8-dl-jet-tritium-rich-dome-hotion.txt @@ -0,0 +1,3 @@ +The boundary lies between the two designs below; j_fusion binds. + +{"passing": {"run": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}}, "proof": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153"}}, "failing": {"run": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}}, "proof": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3"}}, "binding": "j_fusion"} diff --git a/sample/reference/naive_scores.jsonl b/sample/reference/naive_scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..28c6c78d4d91b8d3d7b0a823cb8fb84b1673afa0 --- /dev/null +++ b/sample/reference/naive_scores.jsonl @@ -0,0 +1,5 @@ +{"id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 0, "proofs_hold": 1, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the holds request comes back ended (PlasmaAtWall)", "computing_calls": 1, "holds_outcome": "ended", "stops_outcome": "ended (PlasmaAtWall)", "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "calls_from": "harness", "correct": 0, "proofs_hold": 1, "reward": 0, "graded": 0.0, "verdict": "integrity", "reason": "the passing design's slice is missing", "computing_calls": 1, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 0, "proofs_hold": 1, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the failing design meets every constraint", "computing_calls": 1, "passing": {"x": 9.5, "met": {"dt_fast_e": true, "dt_pion": true}, "values": {"dt_fast_e": 283615.47396580724, "dt_pion": 1398100.9167303161}}, "failing": {"x": 9.5, "met": {"dt_fast_e": true, "dt_pion": true}, "values": {"dt_fast_e": 283615.47396580724, "dt_pion": 1398100.9167303161}}, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 0, "proofs_hold": 1, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the failing design meets every constraint", "computing_calls": 1, "passing": {"x": 0.7, "met": {"j_fusion": true, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 15075905.132957283, "j_fusion_energy": 16652213.649129007, "completes": "completed"}}, "failing": {"x": 0.7, "met": {"j_fusion": true, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 15075905.132957283, "j_fusion_energy": 16652213.649129007, "completes": "completed"}}, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 0, "proofs_hold": 1, "reward": 0, "graded": 0.0, "verdict": "wrong", "reason": "the stops request comes back converged (None), not the stop PressureExceedsField", "computing_calls": 1, "holds_outcome": "converged", "stops_outcome": "converged (None)", "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} diff --git a/sample/reference/reference_scores.jsonl b/sample/reference/reference_scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24349473b6821483d7b81d1808bf7783c0ce122a --- /dev/null +++ b/sample/reference/reference_scores.jsonl @@ -0,0 +1,5 @@ +{"id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "holds_outcome": "completed", "stops_outcome": "ended (PlasmaAtWall)", "holds_value": -6.9444887558793384, "stops_value": -6.945322144533363, "width": 0.0008333886540246027, "width_ratio": 0.5999999999998852, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 4, "passing": {"x": 9739916.12958908, "met": {"dt_power": true, "j_beta": true, "jet_completes": true}, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}}, "failing": {"x": 9223916.12958908, "met": {"dt_power": false, "j_beta": true, "jet_completes": true}, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}}, "width": 516000.0, "width_ratio": 0.6, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "passing": {"x": 10.73913080971837, "met": {"dt_fast_e": true, "dt_pion": true}, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}}, "failing": {"x": 10.744830809718371, "met": {"dt_fast_e": false, "dt_pion": true}, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}}, "width": 0.0057000000000009265, "width_ratio": 0.6000000000000976, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "passing": {"x": 0.7461228712236883, "met": {"j_fusion": true, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}}, "failing": {"x": 0.7463028712236883, "met": {"j_fusion": false, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}}, "width": 0.000180000000000069, "width_ratio": 0.60000000000023, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "holds_outcome": "converged", "stops_outcome": "refused (PressureExceedsField)", "holds_value": 5.695798204932004, "stops_value": 5.695456467291837, "width": 0.0003417376401664285, "width_ratio": 0.5999999999994965, "engine_binary_sha256_seen": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076", "engine_binary_is_reference": true} diff --git a/sample/reports/describe_short.json b/sample/reports/describe_short.json new file mode 100644 index 0000000000000000000000000000000000000000..ae3929cf95310437fbb14c43f4a1897cb14339e8 --- /dev/null +++ b/sample/reports/describe_short.json @@ -0,0 +1,682 @@ +{ + "energy/tokamak_jet_dte1": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "form": "short", + "specimen": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step.", + "against_measurement": "compared with measurement", + "accuracy_against_measurement": "Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", + "phase_fields": [ + { + "name": "thermal_energy_j", + "unit": "J", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": null + }, + { + "name": "deuterium_beam_ion_energy_j", + "unit": "J", + "minimum": 0.0, + "maximum": null + }, + { + "name": "tritium_beam_ion_energy_j", + "unit": "J", + "minimum": 0.0, + "maximum": null + }, + { + "name": "tail_ion_energy_j", + "unit": "J", + "minimum": 0.0, + "maximum": null + }, + { + "name": "elapsed_time_s", + "unit": "s", + "minimum": 0.0, + "maximum": null + } + ], + "load_fields": [ + { + "name": "deuterium_beam_power_w", + "unit": "W", + "minimum": 0.0, + "maximum": null + }, + { + "name": "tritium_beam_power_w", + "unit": "W", + "minimum": 0.0, + "maximum": null + }, + { + "name": "deuterium_beam_energy_kev", + "unit": "keV", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": 917.2538563990214 + }, + { + "name": "tritium_beam_energy_kev", + "unit": "keV", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": 1373.6809354871243 + }, + { + "name": "icrh_power_w", + "unit": "W", + "minimum": 0.0, + "maximum": null + }, + { + "name": "ohmic_power_w", + "unit": "W", + "minimum": 0.0, + "maximum": null + }, + { + "name": "line_density_per_m3", + "unit": "1/m^3", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": null + }, + { + "name": "plasma_current_a", + "unit": "A", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": null + }, + { + "name": "toroidal_field_t", + "unit": "T", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": null + }, + { + "name": "tritium_fraction", + "unit": "1", + "minimum": 0.0, + "maximum": 1.0 + }, + { + "name": "electron_temperature_kev", + "unit": "keV", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": null + }, + { + "name": "effective_charge", + "unit": "1", + "minimum": 1.0, + "maximum": 6.0, + "maximum_exclusive": true + }, + { + "name": "hot_ion_regime", + "unit": "1", + "minimum": 0.0, + "maximum": 1.0 + } + ], + "dt_s": { + "unit": "s", + "floor_s": 1e-06, + "ceiling_s": 0.001 + }, + "stops": [ + "NonFiniteInput", + "NonFiniteState", + "NonPositiveDt", + "InvalidCard", + "HeatingPowerNegative", + "NoHeatingPower", + "BeamEnergyOutsideCrossSection", + "PlasmaCurrentNotPositive", + "ToroidalFieldNotPositive", + "FuelMixOutsideCard", + "EffectiveChargeOutsideCard", + "DensityNotPositive", + "DensityAboveGreenwald", + "SafetyFactorBelowLimit", + "ElectronTemperatureOutsideCard", + "RegimeNotNamed", + "EnergyOutsideCard", + "TemperatureAboveReactivityFit", + "BetaAboveTroyon", + "NegativeTime", + "StepBelowClockResolution", + "DtAboveStateCeiling", + "SpontaneousGeneration", + "FirstLawBreach", + "DtBelowFloor", + "DtAboveCeiling", + "ContinuationWithoutUpstream" + ], + "declared_ends": [], + "continues_with_from": true, + "example_run_trajectory": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "initial": { + "thermal_energy_j": 9000000.0, + "deuterium_beam_ion_energy_j": 500000.0, + "tritium_beam_ion_energy_j": 700000.0, + "tail_ion_energy_j": 400000.0, + "elapsed_time_s": 0.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 1000, + "load": { + "deuterium_beam_power_w": 10500000.0, + "tritium_beam_power_w": 9500000.0, + "deuterium_beam_energy_kev": 80.0, + "tritium_beam_energy_kev": 150.0, + "icrh_power_w": 2400000.0, + "ohmic_power_w": 500000.0, + "line_density_per_m3": 6.4e+19, + "plasma_current_a": 3800000.0, + "toroidal_field_t": 3.9, + "tritium_fraction": 0.451, + "electron_temperature_kev": 7.4, + "effective_charge": 2.4, + "hot_ion_regime": 0.0 + } + } + ], + "record_every": 25 + }, + "full_form": "Short form: phase_fields are initial's keys, load_fields each segment's load keys, a null bound is given in words in full, stops are refusal names. describe_card with form \"full\" or none has each bound's reason, the validation record, the frame layout and each stop's meaning." + }, + "energy/tokamak_vde_mast": { + "domain": "energy", + "card": "tokamak_vde_mast", + "form": "short", + "specimen": "Vertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep.", + "against_measurement": "compared with measurement", + "accuracy_against_measurement": "Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.", + "phase_fields": [ + { + "name": "displacement_m", + "unit": "m", + "minimum": -0.3910649269819259, + "minimum_exclusive": true, + "maximum": 0.38888768851757044, + "maximum_exclusive": true + }, + { + "name": "velocity_m_s", + "unit": "m/s", + "minimum": -1779348.1301704806, + "minimum_exclusive": true, + "maximum": 1779348.1301704806, + "maximum_exclusive": true + }, + { + "name": "wall_current_a", + "unit": "A", + "minimum": null, + "maximum": null + }, + { + "name": "p6_current_a", + "unit": "A", + "minimum": null, + "maximum": null + } + ], + "load_fields": [ + { + "name": "p6_voltage_v", + "unit": "V", + "minimum": null, + "maximum": null + } + ], + "dt_s": { + "unit": "s", + "floor_s": 9.5367431640625e-10, + "ceiling_s": 0.001 + }, + "stops": [ + "NonFiniteInput", + "NonFiniteState", + "NonPositiveDt", + "InvalidCard", + "StartOutsideVessel", + "SpeedAtAlfvenSpeed", + "PlasmaAtWall", + "SubstepsAboveBudget", + "SpontaneousGeneration", + "FirstLawBreach", + "DtBelowFloor", + "DtAboveCeiling" + ], + "declared_ends": [ + "PlasmaAtWall" + ], + "continues_with_from": true, + "example_run_trajectory": { + "domain": "energy", + "card": "tokamak_vde_mast", + "initial": { + "displacement_m": 0.001, + "velocity_m_s": 0.006546503766672119, + "wall_current_a": -21.946577663159488, + "p6_current_a": -8.150423262860404 + }, + "dt_s": 0.0001, + "segments": [ + { + "steps": 100, + "load": { + "p6_voltage_v": 0.0 + } + } + ], + "record_every": 10 + }, + "full_form": "Short form: phase_fields are initial's keys, load_fields each segment's load keys, a null bound is given in words in full, stops are refusal names. describe_card with form \"full\" or none has each bound's reason, the validation record, the frame layout and each stop's meaning." + }, + "fusion_pb11_thermal": { + "solver": "fusion_pb11_thermal", + "form": "short", + "summary": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", + "against_measurement": "held to a reference calculation", + "accuracy_against_measurement": "Held to a reference calculation: the published calculations of Ochs et al. (2022) and Putvinski et al. (2019) and the research's own plain model, ion temperatures 200 to 450 keV: 7 of 8 compared quantities within their targets, synchrotron over fusion power 7.9 percent off against a 5 percent target; at 300 keV the electron temperature 159.33 keV against a published 163.0.", + "inputs": [ + { + "name": "ion_temperature_kev", + "type": "number", + "minimum": 1.0, + "maximum": 1000.0, + "unit": "keV" + }, + { + "name": "electron_density_per_m3", + "type": "number", + "minimum": 1e+18, + "maximum": 1e+22, + "unit": "m^-3" + }, + { + "name": "boron_fraction", + "type": "number", + "minimum": 0.01, + "maximum": 0.9, + "unit": "" + }, + { + "name": "ash_fraction", + "type": "number", + "minimum": 0.0, + "maximum": 1.0, + "unit": "" + }, + { + "name": "magnetic_field_t", + "type": "number", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": 1000000.0, + "unit": "T" + }, + { + "name": "minor_radius_m", + "type": "number", + "minimum": 0.1, + "maximum": 10.0, + "unit": "m" + }, + { + "name": "wall_reflectivity", + "type": "number", + "minimum": 0.0, + "maximum": 1.0, + "unit": "" + }, + { + "name": "energy_confinement_time_s", + "type": "number", + "minimum": 0.0, + "minimum_exclusive": true, + "maximum": 1e+300, + "unit": "s" + }, + { + "name": "kinetic_enhancement", + "type": "true or false" + } + ], + "returns": { + "result": [ + "electron_temperature_kev", + "reactivity_m3_per_s", + "fusion_power_w_per_m3", + "bremsstrahlung_power_w_per_m3", + "bremsstrahlung_power_xie_w_per_m3", + "synchrotron_power_w_per_m3", + "ion_electron_power_w_per_m3", + "alpha_energy_fraction_to_electrons", + "auxiliary_power_w_per_m3", + "ignition_margin", + "ignition_loss_rate_per_s", + "pressure_pa", + "beta", + "internal_field_t", + "effective_charge" + ], + "invariants": [ + "electron_energy_residual", + "total_energy_residual", + "charge_residual" + ] + }, + "refusals": [ + "IonTemperatureOutOfRange", + "ElectronDensityOutOfRange", + "BoronFractionOutOfRange", + "AshFractionOutOfRange", + "MagneticFieldOutOfRange", + "MinorRadiusOutOfRange", + "WallReflectivityOutOfRange", + "ConfinementTimeOutOfRange", + "NonFiniteValue", + "ChargeNotNeutral", + "PressureExceedsField", + "ElectronTemperatureOutOfRange", + "SynchrotronAboveUnabsorbedEmission", + "AlphaSharesBroken", + "NotSettled", + "EnergyBalanceBroken" + ], + "examples": [ + "example_solve" + ], + "example_solve": { + "solver": "fusion_pb11_thermal", + "parameters": { + "ion_temperature_kev": 300, + "electron_density_per_m3": 1.6e+20, + "boron_fraction": 0.15, + "ash_fraction": 0, + "magnetic_field_t": 6.661098700751347, + "minor_radius_m": 2, + "wall_reflectivity": 0.95, + "energy_confinement_time_s": 100, + "kinetic_enhancement": false + } + }, + "full_form": "This is the short form: inputs are the keys of parameters, and solve takes a name under examples as example in place of parameters. describe_solver with form \"full\", or with no form, has each input's bound in words, what each returned name holds and its unit, the invariants and their tolerances, each refusal's meaning, the validation record or the reference, and every worked example." + }, + "tokamak_dt_beam_target": { + "solver": "tokamak_dt_beam_target", + "form": "short", + "summary": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", + "against_measurement": "held to a reference calculation", + "accuracy_against_measurement": "Held to a reference calculation: TRANSP's fusion power from the measured profiles of 34 TFTR slices outside any fit: as served, 27 answered and 7 refused by name, the median ratio 1.011 and 25 of the 27 within 0.75 to 1.25 (25 of 34 counting each refusal outside, against a target of 0.90 of them); the run of 9 October, before those limits, 1.022 and 30 of 34 (0.882); against four measured values +7, +21, -11 and about +8 percent.", + "inputs": [ + { + "name": "shell_volume_m3", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 1e-06, + "maximum": 1e+300, + "unit": "m^3" + }, + { + "name": "electron_temperature_kev", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.05, + "maximum": 100.0, + "unit": "keV" + }, + { + "name": "ion_temperature_kev", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.2, + "maximum": 100.0, + "unit": "keV" + }, + { + "name": "electron_density_per_m3", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 1e+18, + "maximum": 1e+21, + "unit": "m^-3" + }, + { + "name": "deuterium_density_per_m3", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.0, + "maximum": 1e+21, + "unit": "m^-3" + }, + { + "name": "tritium_density_per_m3", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.0, + "maximum": 1e+21, + "unit": "m^-3" + }, + { + "name": "impurity_density_per_m3", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.0, + "maximum": 1e+21, + "unit": "m^-3" + }, + { + "name": "impurity_charge", + "type": "number", + "minimum": 1.0, + "maximum": 8.0, + "unit": "1" + }, + { + "name": "impurity_mass_u", + "type": "number", + "minimum": 1.0, + "maximum": 20.0, + "unit": "u" + }, + { + "name": "beam_power_w", + "type": "array of numbers", + "fewest": 1, + "most": 128, + "minimum": 0.0, + "maximum": 1e+300, + "unit": "W" + }, + { + "name": "beam_mass_number", + "type": "array of numbers", + "fewest": 1, + "most": 12, + "minimum": 2.0, + "maximum": 3.0, + "unit": "u" + }, + { + "name": "beam_energy_kev", + "type": "array of numbers", + "fewest": 1, + "most": 12, + "minimum": 0.0, + "maximum": 1000.0, + "unit": "keV" + }, + { + "name": "beam_power_share", + "type": "array of numbers", + "fewest": 1, + "most": 12, + "minimum": 0.0, + "maximum": 1.0, + "unit": "1" + }, + { + "name": "time_since_beam_change_s", + "type": "number", + "minimum": 0.0, + "maximum": 1e+300, + "unit": "s" + } + ], + "returns": { + "result": [ + "thermal_dt_rate_per_s", + "beam_target_dt_rate_per_s", + "beam_beam_dt_rate_per_s", + "dt_rate_per_s", + "dt_fusion_power_w", + "dd_neutron_rate_per_s", + "dd_fusion_power_w", + "neutron_rate_per_s", + "fast_ion_count", + "fast_ion_energy_j", + "fast_ion_energy_time_s", + "slowing_down_time_max_s", + "beam_power_to_electrons_w", + "beam_power_to_ions_w", + "beam_power_thermalised_w", + "beam_target_fused_fraction", + "beam_beam_fused_fraction", + "fast_ion_fraction_max", + "charge_excess_max", + "charge_excess_min", + "dt_rate_density_per_m3_s" + ], + "invariants": [ + "particle_ledger_residual", + "energy_ledger_residual", + "power_ledger_residual" + ] + }, + "refusals": [ + "ShellCountOutOfRange", + "ProfileLengthsDiffer", + "BeamComponentCountOutOfRange", + "ShellVolumeOutOfRange", + "ElectronTemperatureOutOfRange", + "IonTemperatureOutOfRange", + "ElectronDensityOutOfRange", + "IonDensityNegative", + "ImpurityChargeOutOfRange", + "ImpurityMassOutOfRange", + "ImpurityMassBelowCharge", + "ThermalChargeExceedsElectrons", + "BeamPowerOutOfRange", + "BeamSpeciesUnknown", + "BeamEnergyOutOfRange", + "BeamPowerShareOutOfRange", + "TimeSinceBeamChangeOutOfRange", + "NonFiniteValue", + "SlowingRateNotPositive", + "NotSettled", + "ParticleLedgerBroken", + "EnergyLedgerBroken", + "PowerLedgerBroken", + "BeamBeamShareTooLarge", + "FastIonShareTooLarge", + "BeamChangeTooRecent", + "IonChargeExceedsElectrons", + "IonChargeBelowElectrons" + ], + "examples": [ + "example_solve" + ], + "example_solve": { + "solver": "tokamak_dt_beam_target", + "parameters": { + "shell_volume_m3": [ + 0.185232, + 1.13996, + 2.13983, + 2.78539 + ], + "electron_temperature_kev": [ + 10.9616, + 10.2851, + 7.36622, + 4.37061 + ], + "ion_temperature_kev": [ + 19.2543, + 18.2776, + 8.04433, + 4.37061 + ], + "electron_density_per_m3": [ + 4.06983e+19, + 4.47374e+19, + 5.06836e+19, + 4.15438e+19 + ], + "deuterium_density_per_m3": [ + 1.69228e+19, + 2.04297e+19, + 1.82594e+19, + 1.18337e+19 + ], + "tritium_density_per_m3": [ + 1.37276e+19, + 1.62253e+19, + 1.76105e+19, + 1.52491e+19 + ], + "impurity_density_per_m3": [ + 8.09588e+17, + 7.77101e+17, + 1.92707e+18, + 2.19865e+18 + ], + "impurity_charge": 6.0, + "impurity_mass_u": 12.0, + "beam_power_w": [ + 77277.5, + 319378.0, + 593792.0, + 150108.0 + ], + "beam_mass_number": [ + 2.0, + 3.0 + ], + "beam_energy_kev": [ + 80.0, + 152.0 + ], + "beam_power_share": [ + 0.5, + 0.5 + ], + "time_since_beam_change_s": 0.5503 + } + }, + "full_form": "This is the short form: inputs are the keys of parameters, and solve takes a name under examples as example in place of parameters. describe_solver with form \"full\", or with no form, has each input's bound in words, what each returned name holds and its unit, the invariants and their tolerances, each refusal's meaning, the validation record or the reference, and every worked example." + } +} diff --git a/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.html b/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.html new file mode 100644 index 0000000000000000000000000000000000000000..b828037c3b7f74d6f4403ccf2dd7a4531452c379 --- /dev/null +++ b/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.html @@ -0,0 +1,98 @@ + +Task report: g5-bs-pb11-weakest-field-that-holds-b4 +

g5-bs-pb11-weakest-field-that-holds-b4

+

Multi-step physics RLVR task scored by deterministic recomputation on the Zero-Trust Physics verifier.

+

Budgeted search · models fusion_pb11_thermal · Zero-Trust Physics v0.15.3 · Protocol Company

+

Checksums

+ + +
Whatsha256SHA-384
Task row32598bba76e342a660ec16c538a8ecc71dd2fda8135d777220482c3cae71664504f0b6af4e7588711ebed7a19b4ff9e4a6aa8425cb3562f8c5afaac7b30adc21e271535779d16aa2feba65dd629dfe39
Harbor directory48138b19251be5ea4e2bfe91e12eeb1885ca03583a3227484aec658e1657bc090489ffa0e2b0a652d347e1dcbce71c0ed595337de8b95297f5399150051cbcb0d485dbb0a29e6008ec49d3c212d3f382
+

Instruction

A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.
+
+Find it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.
+
+The request, with <x> the one input you change:
+{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": "<x>", "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}
+
+Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.
+
+You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.
+
+End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "<the tool's name as the verifier names it, without any prefix your own program adds>", "arguments": {<the arguments exactly as you sent them>}}, and a proof is the run_seal or solution_seal the verifier gave for that request.
+
+The card:
+{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": "<the stop's name exactly as the verifier gives it>"}}
+
+holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.
+

Reference solution

+

From the reference agent's reply (g5-bs-pb11-weakest-field-that-holds-b4.txt). Built on engine v0.15.3 at commit 664d68f426cc. Open address: a record exists.

+
On the cardToolProofOpen address
holdssolve1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793verified
stopssolve97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880verified
+
{
+ "holds": {
+  "request": {
+   "tool": "solve",
+   "arguments": {
+    "solver": "fusion_pb11_thermal",
+    "parameters": {
+     "ion_temperature_kev": 310.0,
+     "electron_density_per_m3": 2.2e+20,
+     "boron_fraction": 0.128,
+     "ash_fraction": 0.01,
+     "magnetic_field_t": 5.695798204932004,
+     "minor_radius_m": 2.1,
+     "wall_reflectivity": 0.96,
+     "energy_confinement_time_s": 45.0,
+     "kinetic_enhancement": false
+    }
+   }
+  },
+  "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793"
+ },
+ "stops": {
+  "request": {
+   "tool": "solve",
+   "arguments": {
+    "solver": "fusion_pb11_thermal",
+    "parameters": {
+     "ion_temperature_kev": 310.0,
+     "electron_density_per_m3": 2.2e+20,
+     "boron_fraction": 0.128,
+     "ash_fraction": 0.01,
+     "magnetic_field_t": 5.695456467291837,
+     "minor_radius_m": 2.1,
+     "wall_reflectivity": 0.96,
+     "energy_confinement_time_s": 45.0,
+     "kinetic_enhancement": false
+    }
+   }
+  },
+  "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880",
+  "stopped": "PressureExceedsField"
+ }
+}
+

What the models were compared with

+
ModelAgainstSpecimenAccuracy against measurement
fusion_pb11_thermalheld to a reference calculationEnergy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).Held to a reference calculation: the published calculations of Ochs et al. (2022) and Putvinski et al. (2019) and the research's own plain model, ion temperatures 200 to 450 keV: 7 of 8 compared quantities within their targets, synchrotron over fusion power 7.9 percent off against a 5 percent target; at 300 keV the electron temperature 159.33 keV against a published 163.0.
+

Cheat suite

0 cheat attempt(s) scored above 0. 19 vectors applied; 11 do not apply to this kind.

VectorExpectedRewardGradedResultScorer's reason
honesthonest control (1)11.000holds
honest_reply_log_matcheshonest control (1)11.000holds
honest_numbers_respelledhonest control (1)11.000holds
no_request_behindcheat (0)00.000holdsa solve request on the card is not among the calls in the log
edited_call_logcheat (0)00.000holdsthe call log beside the reply differs from the harness log
over_budgetcheat (0)00.000holds5 computing calls; the budget is 4
forbidden_toolcheat (0)00.000holdsthe log holds calls of find_flip, which the task rules out
no_harness_logcheat (0)00.000holdsno harness call log: every attempt is scored with the calls the harness recorded
harness_log_editedcheat (0)00.000holdsthe harness log's chain breaks at line 2
stale_engine_tagcheat (0)00.000holdsthe task was built on engine 0.15.0; the verifier is 0.15.3
copied_proof_other_taskcheat (0)00.000holdsthe holds seal: the verifier says the seal does not hold (cause solution_seal)
nudged_figurecheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause solution_seal)
figure_plus_10_percentcheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause solution_seal)
card_request_not_runcheat (0)00.000holdsa solve request on the card is not among the calls in the log
swapped_sidescheat (0)00.000holdsthe holds request comes back refused (PressureExceedsField)
stop_misnamedcheat (0)00.000holdsthe card names the stop 'SomeOtherStop'; the verifier names PressureExceedsField
proof_from_other_designcheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause solution_seal)
proof_uppercasecheat (0)00.000holdsthe holds seal: the proof is not a SHA-384 seal of 96 hex digits
extra_argumentcheat (0)00.000holdsthe holds request differs from the task's at note
+

Solver runs

+
AgentRewardGradedComputing callsScorer's reason
Reference agent11.0002
One-call agent00.0001the stops request comes back converged (None), not the stop PressureExceedsField
+

Pass@k by model family

+
FamilyVariantModelSolvedpass@1pass@8Mean gradedHarness errors
Frontier modeltoolFrontier model5 of 862%100%0.7280%
+

Measured calibration: Frontier model, tool variant, n=8.

+

Calibrated on pass@1 in [2%, 70%] on a frontier model's tool variant, with pass@8 and continuous graded reward reported beside pass/fail.

+ +

Written 2026-11-14T01:37:52Z.

+ \ No newline at end of file diff --git a/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.json b/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.json new file mode 100644 index 0000000000000000000000000000000000000000..46ea8b15c68c5c327c5cd8f78ee0d6bae7cf9cfe --- /dev/null +++ b/sample/reports/g5-bs-pb11-weakest-field-that-holds-b4.json @@ -0,0 +1,329 @@ +{ + "id": "g5-bs-pb11-weakest-field-that-holds-b4", + "family": "budget", + "kind": "budgeted_search", + "models": [ + "fusion_pb11_thermal" + ], + "checksums": { + "row_sha256": "32598bba76e342a660ec16c538a8ecc71dd2fda8135d777220482c3cae716645", + "row_sha384": "04f0b6af4e7588711ebed7a19b4ff9e4a6aa8425cb3562f8c5afaac7b30adc21e271535779d16aa2feba65dd629dfe39", + "harbor_dir_sha256": "48138b19251be5ea4e2bfe91e12eeb1885ca03583a3227484aec658e1657bc09", + "harbor_dir_sha384": "0489ffa0e2b0a652d347e1dcbce71c0ed595337de8b95297f5399150051cbcb0d485dbb0a29e6008ec49d3c212d3f382" + }, + "instruction": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"holds\": {\"request\": ..., \"proof\": ...}, \"stops\": {\"request\": ..., \"proof\": ..., \"stopped\": \"\"}}\n\nholds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.", + "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", + "reference": { + "from": "the reference agent's reply (g5-bs-pb11-weakest-field-that-holds-b4.txt)", + "card": { + "holds": { + "request": { + "tool": "solve", + "arguments": { + "solver": "fusion_pb11_thermal", + "parameters": { + "ion_temperature_kev": 310.0, + "electron_density_per_m3": 2.2e+20, + "boron_fraction": 0.128, + "ash_fraction": 0.01, + "magnetic_field_t": 5.695798204932004, + "minor_radius_m": 2.1, + "wall_reflectivity": 0.96, + "energy_confinement_time_s": 45.0, + "kinetic_enhancement": false + } + } + }, + "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793" + }, + "stops": { + "request": { + "tool": "solve", + "arguments": { + "solver": "fusion_pb11_thermal", + "parameters": { + "ion_temperature_kev": 310.0, + "electron_density_per_m3": 2.2e+20, + "boron_fraction": 0.128, + "ash_fraction": 0.01, + "magnetic_field_t": 5.695456467291837, + "minor_radius_m": 2.1, + "wall_reflectivity": 0.96, + "energy_confinement_time_s": 45.0, + "kinetic_enhancement": false + } + } + }, + "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", + "stopped": "PressureExceedsField" + } + }, + "proofs": [ + { + "where": "holds", + "tool": "solve", + "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", + "open_address": "verified" + }, + { + "where": "stops", + "tool": "solve", + "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", + "open_address": "verified" + } + ], + "open_address_record": true, + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "measurement": [ + { + "model": "fusion_pb11_thermal", + "against_measurement": "held to a reference calculation", + "accuracy_against_measurement": "Held to a reference calculation: the published calculations of Ochs et al. (2022) and Putvinski et al. (2019) and the research's own plain model, ion temperatures 200 to 450 keV: 7 of 8 compared quantities within their targets, synchrotron over fusion power 7.9 percent off against a 5 percent target; at 300 keV the electron temperature 159.33 keV against a published 163.0.", + "specimen": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", + "error": null + } + ], + "cheat_suite": { + "vectors": [ + { + "vector": "honest", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_reply_log_matches", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_numbers_respelled", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "no_request_behind", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a solve request on the card is not among the calls in the log" + }, + { + "vector": "edited_call_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the call log beside the reply differs from the harness log" + }, + { + "vector": "over_budget", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "5 computing calls; the budget is 4" + }, + { + "vector": "forbidden_tool", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the log holds calls of find_flip, which the task rules out" + }, + { + "vector": "no_harness_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "no harness call log: every attempt is scored with the calls the harness recorded" + }, + { + "vector": "harness_log_edited", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the harness log's chain breaks at line 2" + }, + { + "vector": "stale_engine_tag", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3" + }, + { + "vector": "copied_proof_other_task", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "nudged_figure", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "figure_plus_10_percent", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "card_request_not_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a solve request on the card is not among the calls in the log" + }, + { + "vector": "swapped_sides", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds request comes back refused (PressureExceedsField)" + }, + { + "vector": "stop_misnamed", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the card names the stop 'SomeOtherStop'; the verifier names PressureExceedsField" + }, + { + "vector": "proof_from_other_design", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "proof_uppercase", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds seal: the proof is not a SHA-384 seal of 96 hex digits" + }, + { + "vector": "extra_argument", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds request differs from the task's at note" + } + ], + "not_applicable": [ + { + "vector": "binding_misnamed", + "why": "not a budget card" + }, + { + "vector": "failing_given_as_passing", + "why": "not a budget card" + }, + { + "vector": "step_misnamed", + "why": "not a budget card" + }, + { + "vector": "missing_solve", + "why": "not a budget card" + }, + { + "vector": "solve_handed_other_run", + "why": "not a budget card" + }, + { + "vector": "every_row_genuine", + "why": "not a budget card" + }, + { + "vector": "every_row_false", + "why": "not a budget card" + }, + { + "vector": "every_row_false_true_reasons", + "why": "not a budget card" + }, + { + "vector": "next_start_rounded", + "why": "not a budget card" + }, + { + "vector": "next_proof_copied", + "why": "not a budget card" + }, + { + "vector": "next_request_edited", + "why": "not a budget card" + } + ], + "cheats_scoring_above_0": 0, + "run": true + }, + "solver_runs": { + "reference": { + "reward": 1, + "graded": 1.0, + "correct": 1, + "proofs_hold": 1, + "computing_calls": 2, + "verdict": "pass", + "reason": null + }, + "naive": { + "reward": 0, + "graded": 0.0, + "correct": 0, + "proofs_hold": 1, + "computing_calls": 1, + "verdict": "wrong", + "reason": "the stops request comes back converged (None), not the stop PressureExceedsField" + } + }, + "passk": [ + { + "family": "Frontier model", + "model": "Frontier model", + "variant": "tool", + "n": 8, + "correct": 5, + "pass@1": 0.625, + "pass@8": 1.0, + "mean_graded": 0.72753225, + "harness_error_rate": 0.0 + } + ], + "no_tool_question": false, + "physics_forensics": false, + "blind_baseline": null, + "written_utc": "2026-11-14T01:37:52Z" +} diff --git a/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.html b/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.html new file mode 100644 index 0000000000000000000000000000000000000000..e97b31f61848114a71f96710cafaa3abaed6f320 --- /dev/null +++ b/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.html @@ -0,0 +1,315 @@ + +Task report: g5r10-ch-jet-dt3-least-tbeam-power-c12-b7 +

g5r10-ch-jet-dt3-least-tbeam-power-c12-b7

+

Multi-step physics RLVR task scored by deterministic recomputation on the Zero-Trust Physics verifier.

+

Chained design · models energy/tokamak_jet_dte1, tokamak_dt_beam_target · Zero-Trust Physics v0.15.3 · Protocol Company

+

Checksums

+ + +
Whatsha256SHA-384
Task rowd194f40019bd8b080b87f1395255cc1e50051d0c74184a54a7321a1d342b856e8b17f526b9a5a7e10c7b8e0f188d914d6edf1700c7e7774384f27ffaef202fdf02a8c8f0eb348ba95d5774536e9d16d6
Harbor directory38166ae374f84840ffe9ec105a7057b5e9feeeda363963c710537fee479134927aa9908c0a110151c76853a2fcd2f7df606d30f6dd5203c17ceec25703e0bd3aa17e7f85f2abecfcef87e9664791d80c
+

Instruction

JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.
+
+Find the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.
+
+Constraints (id (the request it is read from): what, limit):
+- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W
+- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182
+- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)
+Each design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.
+jet:
+{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": "<your value>", "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}
+slice (it must converge):
+{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": ["<the jet's final_state.ion_temperature_kev, bit for bit>", 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}
+
+Budget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.
+
+You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.
+
+End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "<the tool's name as the verifier names it, without any prefix your own program adds>", "arguments": {<the arguments exactly as you sent them>}}, and a proof is the run_seal or solution_seal the verifier gave for that request.
+
+The card:
+{"passing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "failing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "binding": "<constraint id>"}
+
+Each design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.
+

Reference solution

+

From the reference agent's reply (g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt). Built on engine v0.15.3 at commit 664d68f426cc. Open address: a record exists.

+
On the cardToolProofOpen address
passing.jetrun_trajectory71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345verified
passing.slicesolve9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695everified
failing.jetrun_trajectoryb9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8everified
failing.slicesolve8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3cverified
+
{
+ "passing": {
+  "jet": {
+   "request": {
+    "tool": "run_trajectory",
+    "arguments": {
+     "domain": "energy",
+     "card": "tokamak_jet_dte1",
+     "initial": {
+      "thermal_energy_j": 4950000.0,
+      "deuterium_beam_ion_energy_j": 415000.0,
+      "tritium_beam_ion_energy_j": 545000.0,
+      "tail_ion_energy_j": 215000.0,
+      "elapsed_time_s": 0.0
+     },
+     "dt_s": 0.001,
+     "segments": [
+      {
+       "steps": 700,
+       "load": {
+        "deuterium_beam_power_w": 8400000.0,
+        "tritium_beam_power_w": 5200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 4800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 4.2e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.5,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 0.0
+       }
+      },
+      {
+       "steps": 1100,
+       "load": {
+        "deuterium_beam_power_w": 8400000.0,
+        "tritium_beam_power_w": 9739916.12958908,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 4800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 4.2e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.5,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 0.0
+       }
+      }
+     ],
+     "record_every": 1800
+    }
+   },
+   "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"
+  },
+  "slice": {
+   "request": {
+    "tool": "solve",
+    "arguments": {
+     "solver": "tokamak_dt_beam_target",
+     "parameters": {
+      "shell_volume_m3": [
+       1.52,
+       2.92,
+       5.18
+      ],
+      "electron_temperature_kev": [
+       8.6,
+       5.4,
+       3.0
+      ],
+      "ion_temperature_kev": [
+       8.687979018530239,
+       6.9,
+       3.6
+      ],
+      "electron_density_per_m3": [
+       4.55e+19,
+       3.55e+19,
+       2.45e+19
+      ],
+      "deuterium_density_per_m3": [
+       1.77e+19,
+       1.38e+19,
+       9.5e+18
+      ],
+      "tritium_density_per_m3": [
+       1.77e+19,
+       1.38e+19,
+       9.5e+18
+      ],
+      "impurity_density_per_m3": [
+       2.8e+17,
+       2.2e+17,
+       1.5e+17
+      ],
+      "impurity_charge": 6.0,
+      "impurity_mass_u": 12.0,
+      "beam_power_w": [
+       980000.0,
+       600000.0,
+       260000.0
+      ],
+      "beam_mass_number": [
+       2.0,
+       3.0
+      ],
+      "beam_energy_kev": [
+       99.0,
+       136.0
+      ],
+      "beam_power_share": [
+       0.56,
+       0.44
+      ],
+      "time_since_beam_change_s": 2.5
+     }
+    }
+   },
+   "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"
+  }
+ },
+ "failing": {
+  "jet": {
+   "request": {
+    "tool": "run_trajectory",
+    "arguments": {
+     "domain": "energy",
+     "card": "tokamak_jet_dte1",
+     "initial": {
+      "thermal_energy_j": 4950000.0,
+      "deuterium_beam_ion_energy_j": 415000.0,
+      "tritium_beam_ion_energy_j": 545000.0,
+      "tail_ion_energy_j": 215000.0,
+      "elapsed_time_s": 0.0
+     },
+     "dt_s": 0.001,
+     "segments": [
+      {
+       "steps": 700,
+       "load": {
+        "deuterium_beam_power_w": 8400000.0,
+        "tritium_beam_power_w": 5200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 4800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 4.2e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.5,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 0.0
+       }
+      },
+      {
+       "steps": 1100,
+       "load": {
+        "deuterium_beam_power_w": 8400000.0,
+        "tritium_beam_power_w": 9223916.12958908,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 4800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 4.2e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.5,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 0.0
+       }
+      }
+     ],
+     "record_every": 1800
+    }
+   },
+   "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"
+  },
+  "slice": {
+   "request": {
+    "tool": "solve",
+    "arguments": {
+     "solver": "tokamak_dt_beam_target",
+     "parameters": {
+      "shell_volume_m3": [
+       1.52,
+       2.92,
+       5.18
+      ],
+      "electron_temperature_kev": [
+       8.6,
+       5.4,
+       3.0
+      ],
+      "ion_temperature_kev": [
+       8.553608273716595,
+       6.9,
+       3.6
+      ],
+      "electron_density_per_m3": [
+       4.55e+19,
+       3.55e+19,
+       2.45e+19
+      ],
+      "deuterium_density_per_m3": [
+       1.77e+19,
+       1.38e+19,
+       9.5e+18
+      ],
+      "tritium_density_per_m3": [
+       1.77e+19,
+       1.38e+19,
+       9.5e+18
+      ],
+      "impurity_density_per_m3": [
+       2.8e+17,
+       2.2e+17,
+       1.5e+17
+      ],
+      "impurity_charge": 6.0,
+      "impurity_mass_u": 12.0,
+      "beam_power_w": [
+       980000.0,
+       600000.0,
+       260000.0
+      ],
+      "beam_mass_number": [
+       2.0,
+       3.0
+      ],
+      "beam_energy_kev": [
+       99.0,
+       136.0
+      ],
+      "beam_power_share": [
+       0.56,
+       0.44
+      ],
+      "time_since_beam_change_s": 2.5
+     }
+    }
+   },
+   "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"
+  }
+ },
+ "binding": "dt_power"
+}
+

What the models were compared with

+
ModelAgainstSpecimenAccuracy against measurement
energy/tokamak_jet_dte1compared with measurementHeated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step.Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).
tokamak_dt_beam_targetheld to a reference calculationThe deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.Held to a reference calculation: TRANSP's fusion power from the measured profiles of 34 TFTR slices outside any fit: as served, 27 answered and 7 refused by name, the median ratio 1.011 and 25 of the 27 within 0.75 to 1.25 (25 of 34 counting each refusal outside, against a target of 0.90 of them); the run of 9 October, before those limits, 1.022 and 30 of 34 (0.882); against four measured values +7, +21, -11 and about +8 percent.
+

Cheat suite

0 cheat attempt(s) scored above 0. 22 vectors applied; 8 do not apply to this kind.

VectorExpectedRewardGradedResultScorer's reason
honesthonest control (1)11.000holds
honest_reply_log_matcheshonest control (1)11.000holds
honest_numbers_respelledhonest control (1)11.000holds
no_request_behindcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
edited_call_logcheat (0)00.000holdsthe call log beside the reply differs from the harness log
over_budgetcheat (0)00.000holds8 computing calls; the budget is 7
forbidden_toolcheat (0)00.000holdsthe log holds calls of find_flip, which the task rules out
no_harness_logcheat (0)00.000holdsno harness call log: every attempt is scored with the calls the harness recorded
harness_log_editedcheat (0)00.000holdsthe harness log's chain breaks at line 4
stale_engine_tagcheat (0)00.000holdsthe task was built on engine 0.15.0; the verifier is 0.15.3
copied_proof_other_taskcheat (0)00.000holdsthe passing design's jet proof: the verifier says the seal does not hold (cause run_seal)
nudged_figurecheat (0)00.000holdsthe passing design's jet proof: the verifier says the seal does not hold (cause run_seal)
figure_plus_10_percentcheat (0)00.000holdsthe passing design's jet proof: the verifier says the seal does not hold (cause run_seal)
card_request_not_runcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
swapped_sidescheat (0)00.000holdsthe passing design breaks dt_power
binding_misnamedcheat (0)00.000holdsbinding names 'j_beta'; the constraint that binds is another
proof_from_other_designcheat (0)00.000holdsthe failing design's jet proof: the verifier says the seal does not hold (cause run_seal)
failing_given_as_passingcheat (0)00.000holdsthe passing design breaks dt_power
proof_uppercasecheat (0)00.000holdsthe passing design's jet proof: the proof is not a SHA-384 seal of 96 hex digits
extra_argumentcheat (0)00.000holdsthe passing design's jet differs from the task's at note
missing_solvecheat (0)00.000holdsthe passing design's slice is missing
solve_handed_other_runcheat (0)00.000holdsthe passing design's slice does not carry jet's ion_temperature_kev at parameters.ion_temperature_kev[0], bit for bit
+

Solver runs

+
AgentRewardGradedComputing callsScorer's reason
Reference agent11.0004
One-call agent00.0001the passing design's slice is missing
+

Pass@k by model family

+
FamilyVariantModelSolvedpass@1pass@8Mean gradedHarness errors
Frontier modeltoolFrontier model3 of 838%100%0.8200%
+

Measured calibration: Frontier model, tool variant, n=8.

+

Calibrated on pass@1 in [2%, 70%] on a frontier model's tool variant, with pass@8 and continuous graded reward reported beside pass/fail.

+ +

Written 2026-11-14T01:37:52Z.

+ \ No newline at end of file diff --git a/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.json b/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.json new file mode 100644 index 0000000000000000000000000000000000000000..e28d66243dce79fb9c7d55ceec5e8299113a1c57 --- /dev/null +++ b/sample/reports/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.json @@ -0,0 +1,571 @@ +{ + "id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "family": "chain_design", + "kind": "chained_design", + "models": [ + "energy/tokamak_jet_dte1", + "tokamak_dt_beam_target" + ], + "checksums": { + "row_sha256": "d194f40019bd8b080b87f1395255cc1e50051d0c74184a54a7321a1d342b856e", + "row_sha384": "8b17f526b9a5a7e10c7b8e0f188d914d6edf1700c7e7774384f27ffaef202fdf02a8c8f0eb348ba95d5774536e9d16d6", + "harbor_dir_sha256": "38166ae374f84840ffe9ec105a7057b5e9feeeda363963c710537fee47913492", + "harbor_dir_sha384": "7aa9908c0a110151c76853a2fcd2f7df606d30f6dd5203c17ceec25703e0bd3aa17e7f85f2abecfcef87e9664791d80c" + }, + "instruction": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"jet\": {\"request\": ..., \"proof\": ...}, \"slice\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"jet\": {\"request\": ..., \"proof\": ...}, \"slice\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\nEach design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries \"stopped\": the stop's name exactly as the verifier gives it, and, for a run, \"step\": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.", + "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", + "reference": { + "from": "the reference agent's reply (g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.txt)", + "card": { + "passing": { + "jet": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "initial": { + "thermal_energy_j": 4950000.0, + "deuterium_beam_ion_energy_j": 415000.0, + "tritium_beam_ion_energy_j": 545000.0, + "tail_ion_energy_j": 215000.0, + "elapsed_time_s": 0.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 700, + "load": { + "deuterium_beam_power_w": 8400000.0, + "tritium_beam_power_w": 5200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 4800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 4.2e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.5, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 0.0 + } + }, + { + "steps": 1100, + "load": { + "deuterium_beam_power_w": 8400000.0, + "tritium_beam_power_w": 9739916.12958908, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 4800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 4.2e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.5, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 0.0 + } + } + ], + "record_every": 1800 + } + }, + "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345" + }, + "slice": { + "request": { + "tool": "solve", + "arguments": { + "solver": "tokamak_dt_beam_target", + "parameters": { + "shell_volume_m3": [ + 1.52, + 2.92, + 5.18 + ], + "electron_temperature_kev": [ + 8.6, + 5.4, + 3.0 + ], + "ion_temperature_kev": [ + 8.687979018530239, + 6.9, + 3.6 + ], + "electron_density_per_m3": [ + 4.55e+19, + 3.55e+19, + 2.45e+19 + ], + "deuterium_density_per_m3": [ + 1.77e+19, + 1.38e+19, + 9.5e+18 + ], + "tritium_density_per_m3": [ + 1.77e+19, + 1.38e+19, + 9.5e+18 + ], + "impurity_density_per_m3": [ + 2.8e+17, + 2.2e+17, + 1.5e+17 + ], + "impurity_charge": 6.0, + "impurity_mass_u": 12.0, + "beam_power_w": [ + 980000.0, + 600000.0, + 260000.0 + ], + "beam_mass_number": [ + 2.0, + 3.0 + ], + "beam_energy_kev": [ + 99.0, + 136.0 + ], + "beam_power_share": [ + 0.56, + 0.44 + ], + "time_since_beam_change_s": 2.5 + } + } + }, + "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e" + } + }, + "failing": { + "jet": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "initial": { + "thermal_energy_j": 4950000.0, + "deuterium_beam_ion_energy_j": 415000.0, + "tritium_beam_ion_energy_j": 545000.0, + "tail_ion_energy_j": 215000.0, + "elapsed_time_s": 0.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 700, + "load": { + "deuterium_beam_power_w": 8400000.0, + "tritium_beam_power_w": 5200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 4800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 4.2e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.5, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 0.0 + } + }, + { + "steps": 1100, + "load": { + "deuterium_beam_power_w": 8400000.0, + "tritium_beam_power_w": 9223916.12958908, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 4800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 4.2e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.5, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 0.0 + } + } + ], + "record_every": 1800 + } + }, + "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e" + }, + "slice": { + "request": { + "tool": "solve", + "arguments": { + "solver": "tokamak_dt_beam_target", + "parameters": { + "shell_volume_m3": [ + 1.52, + 2.92, + 5.18 + ], + "electron_temperature_kev": [ + 8.6, + 5.4, + 3.0 + ], + "ion_temperature_kev": [ + 8.553608273716595, + 6.9, + 3.6 + ], + "electron_density_per_m3": [ + 4.55e+19, + 3.55e+19, + 2.45e+19 + ], + "deuterium_density_per_m3": [ + 1.77e+19, + 1.38e+19, + 9.5e+18 + ], + "tritium_density_per_m3": [ + 1.77e+19, + 1.38e+19, + 9.5e+18 + ], + "impurity_density_per_m3": [ + 2.8e+17, + 2.2e+17, + 1.5e+17 + ], + "impurity_charge": 6.0, + "impurity_mass_u": 12.0, + "beam_power_w": [ + 980000.0, + 600000.0, + 260000.0 + ], + "beam_mass_number": [ + 2.0, + 3.0 + ], + "beam_energy_kev": [ + 99.0, + 136.0 + ], + "beam_power_share": [ + 0.56, + 0.44 + ], + "time_since_beam_change_s": 2.5 + } + } + }, + "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c" + } + }, + "binding": "dt_power" + }, + "proofs": [ + { + "where": "passing.jet", + "tool": "run_trajectory", + "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345", + "open_address": "verified" + }, + { + "where": "passing.slice", + "tool": "solve", + "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e", + "open_address": "verified" + }, + { + "where": "failing.jet", + "tool": "run_trajectory", + "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e", + "open_address": "verified" + }, + { + "where": "failing.slice", + "tool": "solve", + "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c", + "open_address": "verified" + } + ], + "open_address_record": true, + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "measurement": [ + { + "model": "energy/tokamak_jet_dte1", + "against_measurement": "compared with measurement", + "accuracy_against_measurement": "Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", + "specimen": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step.", + "error": null + }, + { + "model": "tokamak_dt_beam_target", + "against_measurement": "held to a reference calculation", + "accuracy_against_measurement": "Held to a reference calculation: TRANSP's fusion power from the measured profiles of 34 TFTR slices outside any fit: as served, 27 answered and 7 refused by name, the median ratio 1.011 and 25 of the 27 within 0.75 to 1.25 (25 of 34 counting each refusal outside, against a target of 0.90 of them); the run of 9 October, before those limits, 1.022 and 30 of 34 (0.882); against four measured values +7, +21, -11 and about +8 percent.", + "specimen": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", + "error": null + } + ], + "cheat_suite": { + "vectors": [ + { + "vector": "honest", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_reply_log_matches", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_numbers_respelled", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "no_request_behind", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "edited_call_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the call log beside the reply differs from the harness log" + }, + { + "vector": "over_budget", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "8 computing calls; the budget is 7" + }, + { + "vector": "forbidden_tool", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the log holds calls of find_flip, which the task rules out" + }, + { + "vector": "no_harness_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "no harness call log: every attempt is scored with the calls the harness recorded" + }, + { + "vector": "harness_log_edited", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the harness log's chain breaks at line 4" + }, + { + "vector": "stale_engine_tag", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3" + }, + { + "vector": "copied_proof_other_task", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "nudged_figure", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "figure_plus_10_percent", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's jet proof: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "card_request_not_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "swapped_sides", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks dt_power" + }, + { + "vector": "binding_misnamed", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "binding names 'j_beta'; the constraint that binds is another" + }, + { + "vector": "proof_from_other_design", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the failing design's jet proof: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "failing_given_as_passing", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks dt_power" + }, + { + "vector": "proof_uppercase", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's jet proof: the proof is not a SHA-384 seal of 96 hex digits" + }, + { + "vector": "extra_argument", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's jet differs from the task's at note" + }, + { + "vector": "missing_solve", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's slice is missing" + }, + { + "vector": "solve_handed_other_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's slice does not carry jet's ion_temperature_kev at parameters.ion_temperature_kev[0], bit for bit" + } + ], + "not_applicable": [ + { + "vector": "stop_misnamed", + "why": "no stop binds" + }, + { + "vector": "step_misnamed", + "why": "no stop binds" + }, + { + "vector": "next_start_rounded", + "why": "not a continued design" + }, + { + "vector": "next_proof_copied", + "why": "not a continued design" + }, + { + "vector": "next_request_edited", + "why": "not a continued design" + }, + { + "vector": "every_row_genuine", + "why": "forensics only" + }, + { + "vector": "every_row_false", + "why": "forensics only" + }, + { + "vector": "every_row_false_true_reasons", + "why": "forensics only" + } + ], + "cheats_scoring_above_0": 0, + "run": true + }, + "solver_runs": { + "reference": { + "reward": 1, + "graded": 1.0, + "correct": 1, + "proofs_hold": 1, + "computing_calls": 4, + "verdict": "pass", + "reason": null + }, + "naive": { + "reward": 0, + "graded": 0.0, + "correct": 0, + "proofs_hold": 1, + "computing_calls": 1, + "verdict": "integrity", + "reason": "the passing design's slice is missing" + } + }, + "passk": [ + { + "family": "Frontier model", + "model": "Frontier model", + "variant": "tool", + "n": 8, + "correct": 3, + "pass@1": 0.375, + "pass@8": 1.0, + "mean_graded": 0.820310875, + "harness_error_rate": 0.0 + } + ], + "no_tool_question": false, + "physics_forensics": false, + "blind_baseline": null, + "written_utc": "2026-11-14T01:37:52Z" +} diff --git a/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.html b/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.html new file mode 100644 index 0000000000000000000000000000000000000000..09d5e2a817c89df6582c2fc5a4c1e90614279211 --- /dev/null +++ b/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.html @@ -0,0 +1,213 @@ + +Task report: g5r10-dl-dt4-core-te-fastshare-pion +

g5r10-dl-dt4-core-te-fastshare-pion

+

Multi-step physics RLVR task scored by deterministic recomputation on the Zero-Trust Physics verifier.

+

Design to a limit · models tokamak_dt_beam_target · Zero-Trust Physics v0.15.3 · Protocol Company

+

Checksums

+ + +
Whatsha256SHA-384
Task row2a4ff9b2937f6ddda4826fbe69acd059c81f0f8479b302f764276546077a3578dff38389b003fd44aa38b910cfbc0e7a15dec6f90a93dacf47a7bfaaf61f52ff9165884b85d98f10a1b29d1ba3b5abad
Harbor directoryb6676a75309f43c17408adbc9c99c3c293c2f4815860e2f604b10565b383b9110943d2fb563f5bbe43655b122b8716cf33ce4ba2d83ad90b0e1052a9193fe230e5960510067c1af7af2498e21017f090
+

Instruction

A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).
+
+Find the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.
+
+Constraints (id, what, limit):
+- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J
+- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W
+Each design is one solve (leave out "run"):
+{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": ["<your value>", 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}}
+
+Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.
+
+You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.
+
+End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "<the tool's name as the verifier names it, without any prefix your own program adds>", "arguments": {<the arguments exactly as you sent them>}}, and a proof is the run_seal or solution_seal the verifier gave for that request.
+
+The card:
+{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": "<constraint id>"}
+
+Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.
+

Reference solution

+

From the reference agent's reply (g5r10-dl-dt4-core-te-fastshare-pion.txt). Built on engine v0.15.3 at commit 664d68f426cc. Open address: a record exists.

+
On the cardToolProofOpen address
passing.solvesolvec7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949verified
failing.solvesolve9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97everified
+
{
+ "passing": {
+  "solve": {
+   "request": {
+    "tool": "solve",
+    "arguments": {
+     "solver": "tokamak_dt_beam_target",
+     "parameters": {
+      "shell_volume_m3": [
+       1.02,
+       1.92,
+       3.22,
+       5.18
+      ],
+      "electron_temperature_kev": [
+       10.73913080971837,
+       6.4,
+       4.2,
+       2.5
+      ],
+      "ion_temperature_kev": [
+       13.2,
+       8.2,
+       5.1,
+       3.0
+      ],
+      "electron_density_per_m3": [
+       4.72e+19,
+       3.88e+19,
+       2.98e+19,
+       2.08e+19
+      ],
+      "deuterium_density_per_m3": [
+       1.84e+19,
+       1.51e+19,
+       1.16e+19,
+       8.1e+18
+      ],
+      "tritium_density_per_m3": [
+       1.84e+19,
+       1.51e+19,
+       1.16e+19,
+       8.1e+18
+      ],
+      "impurity_density_per_m3": [
+       2.4e+17,
+       1.9e+17,
+       1.5e+17,
+       1e+17
+      ],
+      "impurity_charge": 8.0,
+      "impurity_mass_u": 16.0,
+      "beam_power_w": [
+       920000.0,
+       620000.0,
+       380000.0,
+       160000.0
+      ],
+      "beam_mass_number": [
+       2.0,
+       3.0
+      ],
+      "beam_energy_kev": [
+       98.0,
+       138.0
+      ],
+      "beam_power_share": [
+       0.54,
+       0.46
+      ],
+      "time_since_beam_change_s": 2.9
+     }
+    }
+   },
+   "proof": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949"
+  }
+ },
+ "failing": {
+  "solve": {
+   "request": {
+    "tool": "solve",
+    "arguments": {
+     "solver": "tokamak_dt_beam_target",
+     "parameters": {
+      "shell_volume_m3": [
+       1.02,
+       1.92,
+       3.22,
+       5.18
+      ],
+      "electron_temperature_kev": [
+       10.744830809718371,
+       6.4,
+       4.2,
+       2.5
+      ],
+      "ion_temperature_kev": [
+       13.2,
+       8.2,
+       5.1,
+       3.0
+      ],
+      "electron_density_per_m3": [
+       4.72e+19,
+       3.88e+19,
+       2.98e+19,
+       2.08e+19
+      ],
+      "deuterium_density_per_m3": [
+       1.84e+19,
+       1.51e+19,
+       1.16e+19,
+       8.1e+18
+      ],
+      "tritium_density_per_m3": [
+       1.84e+19,
+       1.51e+19,
+       1.16e+19,
+       8.1e+18
+      ],
+      "impurity_density_per_m3": [
+       2.4e+17,
+       1.9e+17,
+       1.5e+17,
+       1e+17
+      ],
+      "impurity_charge": 8.0,
+      "impurity_mass_u": 16.0,
+      "beam_power_w": [
+       920000.0,
+       620000.0,
+       380000.0,
+       160000.0
+      ],
+      "beam_mass_number": [
+       2.0,
+       3.0
+      ],
+      "beam_energy_kev": [
+       98.0,
+       138.0
+      ],
+      "beam_power_share": [
+       0.54,
+       0.46
+      ],
+      "time_since_beam_change_s": 2.9
+     }
+    }
+   },
+   "proof": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e"
+  }
+ },
+ "binding": "dt_fast_e"
+}
+

What the models were compared with

+
ModelAgainstSpecimenAccuracy against measurement
tokamak_dt_beam_targetheld to a reference calculationThe deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.Held to a reference calculation: TRANSP's fusion power from the measured profiles of 34 TFTR slices outside any fit: as served, 27 answered and 7 refused by name, the median ratio 1.011 and 25 of the 27 within 0.75 to 1.25 (25 of 34 counting each refusal outside, against a target of 0.90 of them); the run of 9 October, before those limits, 1.022 and 30 of 34 (0.882); against four measured values +7, +21, -11 and about +8 percent.
+

Cheat suite

0 cheat attempt(s) scored above 0. 20 vectors applied; 10 do not apply to this kind.

VectorExpectedRewardGradedResultScorer's reason
honesthonest control (1)11.000holds
honest_reply_log_matcheshonest control (1)11.000holds
honest_numbers_respelledhonest control (1)11.000holds
no_request_behindcheat (0)00.000holdsa solve request on the card is not among the calls in the log
edited_call_logcheat (0)00.000holdsthe call log beside the reply differs from the harness log
over_budgetcheat (0)00.000holds5 computing calls; the budget is 4
forbidden_toolcheat (0)00.000holdsthe log holds calls of find_flip, which the task rules out
no_harness_logcheat (0)00.000holdsno harness call log: every attempt is scored with the calls the harness recorded
harness_log_editedcheat (0)00.000holdsthe harness log's chain breaks at line 2
stale_engine_tagcheat (0)00.000holdsthe task was built on engine 0.15.0; the verifier is 0.15.3
copied_proof_other_taskcheat (0)00.000holdsthe passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)
nudged_figurecheat (0)00.000holdsthe passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)
figure_plus_10_percentcheat (0)00.000holdsthe passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)
card_request_not_runcheat (0)00.000holdsa solve request on the card is not among the calls in the log
swapped_sidescheat (0)00.000holdsthe passing design breaks dt_fast_e
binding_misnamedcheat (0)00.000holdsbinding names 'dt_pion'; the constraint that binds is another
proof_from_other_designcheat (0)00.000holdsthe failing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)
failing_given_as_passingcheat (0)00.000holdsthe passing design breaks dt_fast_e
proof_uppercasecheat (0)00.000holdsthe passing design's solution_seal: the proof is not a SHA-384 seal of 96 hex digits
extra_argumentcheat (0)00.000holdsthe passing design's solve differs from the task's at note
+

Solver runs

+
AgentRewardGradedComputing callsScorer's reason
Reference agent11.0002
One-call agent00.0001the failing design meets every constraint
+

Pass@k by model family

+
FamilyVariantModelSolvedpass@1pass@8Mean gradedHarness errors
Frontier modeltoolFrontier model3 of 838%100%0.8370%
+

Measured calibration: Frontier model, tool variant, n=8.

+

Calibrated on pass@1 in [2%, 70%] on a frontier model's tool variant, with pass@8 and continuous graded reward reported beside pass/fail.

+ +

Written 2026-11-14T01:37:52Z.

+ \ No newline at end of file diff --git a/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.json b/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.json new file mode 100644 index 0000000000000000000000000000000000000000..a69f54f8b23ff3287986bb8d298305bd26097780 --- /dev/null +++ b/sample/reports/g5r10-dl-dt4-core-te-fastshare-pion.json @@ -0,0 +1,445 @@ +{ + "id": "g5r10-dl-dt4-core-te-fastshare-pion", + "family": "tradeoff", + "kind": "design_to_limit", + "models": [ + "tokamak_dt_beam_target" + ], + "checksums": { + "row_sha256": "2a4ff9b2937f6ddda4826fbe69acd059c81f0f8479b302f764276546077a3578", + "row_sha384": "dff38389b003fd44aa38b910cfbc0e7a15dec6f90a93dacf47a7bfaaf61f52ff9165884b85d98f10a1b29d1ba3b5abad", + "harbor_dir_sha256": "b6676a75309f43c17408adbc9c99c3c293c2f4815860e2f604b10565b383b911", + "harbor_dir_sha384": "0943d2fb563f5bbe43655b122b8716cf33ce4ba2d83ad90b0e1052a9193fe230e5960510067c1af7af2498e21017f090" + }, + "instruction": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"solve\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"solve\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\nEach design is one solve: leave out \"run\". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.", + "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", + "reference": { + "from": "the reference agent's reply (g5r10-dl-dt4-core-te-fastshare-pion.txt)", + "card": { + "passing": { + "solve": { + "request": { + "tool": "solve", + "arguments": { + "solver": "tokamak_dt_beam_target", + "parameters": { + "shell_volume_m3": [ + 1.02, + 1.92, + 3.22, + 5.18 + ], + "electron_temperature_kev": [ + 10.73913080971837, + 6.4, + 4.2, + 2.5 + ], + "ion_temperature_kev": [ + 13.2, + 8.2, + 5.1, + 3.0 + ], + "electron_density_per_m3": [ + 4.72e+19, + 3.88e+19, + 2.98e+19, + 2.08e+19 + ], + "deuterium_density_per_m3": [ + 1.84e+19, + 1.51e+19, + 1.16e+19, + 8.1e+18 + ], + "tritium_density_per_m3": [ + 1.84e+19, + 1.51e+19, + 1.16e+19, + 8.1e+18 + ], + "impurity_density_per_m3": [ + 2.4e+17, + 1.9e+17, + 1.5e+17, + 1e+17 + ], + "impurity_charge": 8.0, + "impurity_mass_u": 16.0, + "beam_power_w": [ + 920000.0, + 620000.0, + 380000.0, + 160000.0 + ], + "beam_mass_number": [ + 2.0, + 3.0 + ], + "beam_energy_kev": [ + 98.0, + 138.0 + ], + "beam_power_share": [ + 0.54, + 0.46 + ], + "time_since_beam_change_s": 2.9 + } + } + }, + "proof": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949" + } + }, + "failing": { + "solve": { + "request": { + "tool": "solve", + "arguments": { + "solver": "tokamak_dt_beam_target", + "parameters": { + "shell_volume_m3": [ + 1.02, + 1.92, + 3.22, + 5.18 + ], + "electron_temperature_kev": [ + 10.744830809718371, + 6.4, + 4.2, + 2.5 + ], + "ion_temperature_kev": [ + 13.2, + 8.2, + 5.1, + 3.0 + ], + "electron_density_per_m3": [ + 4.72e+19, + 3.88e+19, + 2.98e+19, + 2.08e+19 + ], + "deuterium_density_per_m3": [ + 1.84e+19, + 1.51e+19, + 1.16e+19, + 8.1e+18 + ], + "tritium_density_per_m3": [ + 1.84e+19, + 1.51e+19, + 1.16e+19, + 8.1e+18 + ], + "impurity_density_per_m3": [ + 2.4e+17, + 1.9e+17, + 1.5e+17, + 1e+17 + ], + "impurity_charge": 8.0, + "impurity_mass_u": 16.0, + "beam_power_w": [ + 920000.0, + 620000.0, + 380000.0, + 160000.0 + ], + "beam_mass_number": [ + 2.0, + 3.0 + ], + "beam_energy_kev": [ + 98.0, + 138.0 + ], + "beam_power_share": [ + 0.54, + 0.46 + ], + "time_since_beam_change_s": 2.9 + } + } + }, + "proof": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e" + } + }, + "binding": "dt_fast_e" + }, + "proofs": [ + { + "where": "passing.solve", + "tool": "solve", + "proof": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", + "open_address": "verified" + }, + { + "where": "failing.solve", + "tool": "solve", + "proof": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", + "open_address": "verified" + } + ], + "open_address_record": true, + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "measurement": [ + { + "model": "tokamak_dt_beam_target", + "against_measurement": "held to a reference calculation", + "accuracy_against_measurement": "Held to a reference calculation: TRANSP's fusion power from the measured profiles of 34 TFTR slices outside any fit: as served, 27 answered and 7 refused by name, the median ratio 1.011 and 25 of the 27 within 0.75 to 1.25 (25 of 34 counting each refusal outside, against a target of 0.90 of them); the run of 9 October, before those limits, 1.022 and 30 of 34 (0.882); against four measured values +7, +21, -11 and about +8 percent.", + "specimen": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", + "error": null + } + ], + "cheat_suite": { + "vectors": [ + { + "vector": "honest", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_reply_log_matches", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_numbers_respelled", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "no_request_behind", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a solve request on the card is not among the calls in the log" + }, + { + "vector": "edited_call_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the call log beside the reply differs from the harness log" + }, + { + "vector": "over_budget", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "5 computing calls; the budget is 4" + }, + { + "vector": "forbidden_tool", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the log holds calls of find_flip, which the task rules out" + }, + { + "vector": "no_harness_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "no harness call log: every attempt is scored with the calls the harness recorded" + }, + { + "vector": "harness_log_edited", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the harness log's chain breaks at line 2" + }, + { + "vector": "stale_engine_tag", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3" + }, + { + "vector": "copied_proof_other_task", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "nudged_figure", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "figure_plus_10_percent", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "card_request_not_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a solve request on the card is not among the calls in the log" + }, + { + "vector": "swapped_sides", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks dt_fast_e" + }, + { + "vector": "binding_misnamed", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "binding names 'dt_pion'; the constraint that binds is another" + }, + { + "vector": "proof_from_other_design", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the failing design's solution_seal: the verifier says the seal does not hold (cause solution_seal)" + }, + { + "vector": "failing_given_as_passing", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks dt_fast_e" + }, + { + "vector": "proof_uppercase", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's solution_seal: the proof is not a SHA-384 seal of 96 hex digits" + }, + { + "vector": "extra_argument", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's solve differs from the task's at note" + } + ], + "not_applicable": [ + { + "vector": "stop_misnamed", + "why": "no stop binds" + }, + { + "vector": "step_misnamed", + "why": "no stop binds" + }, + { + "vector": "missing_solve", + "why": "a design of one request" + }, + { + "vector": "solve_handed_other_run", + "why": "a design of one request" + }, + { + "vector": "next_start_rounded", + "why": "not a continued design" + }, + { + "vector": "next_proof_copied", + "why": "not a continued design" + }, + { + "vector": "next_request_edited", + "why": "not a continued design" + }, + { + "vector": "every_row_genuine", + "why": "forensics only" + }, + { + "vector": "every_row_false", + "why": "forensics only" + }, + { + "vector": "every_row_false_true_reasons", + "why": "forensics only" + } + ], + "cheats_scoring_above_0": 0, + "run": true + }, + "solver_runs": { + "reference": { + "reward": 1, + "graded": 1.0, + "correct": 1, + "proofs_hold": 1, + "computing_calls": 2, + "verdict": "pass", + "reason": null + }, + "naive": { + "reward": 0, + "graded": 0.0, + "correct": 0, + "proofs_hold": 1, + "computing_calls": 1, + "verdict": "wrong", + "reason": "the failing design meets every constraint" + } + }, + "passk": [ + { + "family": "Frontier model", + "model": "Frontier model", + "variant": "tool", + "n": 8, + "correct": 3, + "pass@1": 0.375, + "pass@8": 1.0, + "mean_graded": 0.8368211249999999, + "harness_error_rate": 0.0 + } + ], + "no_tool_question": false, + "physics_forensics": false, + "blind_baseline": null, + "written_utc": "2026-11-14T01:37:52Z" +} diff --git a/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.html b/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.html new file mode 100644 index 0000000000000000000000000000000000000000..f744e91ba4196c60cb161002d80f396192a47e88 --- /dev/null +++ b/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.html @@ -0,0 +1,122 @@ + +Task report: g5r8-bs-mast-2seg-drift-down-wall-b4 +

g5r8-bs-mast-2seg-drift-down-wall-b4

+

Multi-step physics RLVR task scored by deterministic recomputation on the Zero-Trust Physics verifier.

+

Budgeted search · models energy/tokamak_vde_mast · Zero-Trust Physics v0.15.3 · Protocol Company

+

Checksums

+ + +
Whatsha256SHA-384
Task row092ec55ee295b8af2d1cf779200a6dc60172dd0ee67283ee9f017caab2d3b21277b3ba995864f265e7186fb9f4791d340d240d4c36574bcf5671349cc4428169028d4db1ada207de2f9891125ba85579
Harbor directorya3c5fedfff586aae588a8822440726054753b49dd3d8d30b1a582283873a8e168feed8131a952e71a0ab6455115eb4ec0f55089759d0a2c644e211cdd55548311acd312a0898540ba2adf592a00811ef
+

Instruction

MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number).
+
+Find it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V.
+
+The request, with <x> the one input you change:
+{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": "<x>"}}], "record_every": 56}}
+
+Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.
+
+You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.
+
+End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "<the tool's name as the verifier names it, without any prefix your own program adds>", "arguments": {<the arguments exactly as you sent them>}}, and a proof is the run_seal or solution_seal the verifier gave for that request.
+
+The card:
+{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": "<the stop's name exactly as the verifier gives it>"}}
+
+holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.
+

Reference solution

+

From the reference agent's reply (g5r8-bs-mast-2seg-drift-down-wall-b4.txt). Built on engine v0.15.3 at commit 664d68f426cc. Open address: a record exists.

+
On the cardToolProofOpen address
holdsrun_trajectoryaf7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969verified
stopsrun_trajectory2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45verified
+
{
+ "holds": {
+  "request": {
+   "tool": "run_trajectory",
+   "arguments": {
+    "domain": "energy",
+    "card": "tokamak_vde_mast",
+    "initial": {
+     "displacement_m": 0.0038,
+     "velocity_m_s": 0.0249,
+     "wall_current_a": -83.4,
+     "p6_current_a": -31.0
+    },
+    "dt_s": 0.001,
+    "segments": [
+     {
+      "steps": 18,
+      "load": {
+       "p6_voltage_v": 0.0
+      }
+     },
+     {
+      "steps": 38,
+      "load": {
+       "p6_voltage_v": -6.9444887558793384
+      }
+     }
+    ],
+    "record_every": 56
+   }
+  },
+  "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969"
+ },
+ "stops": {
+  "request": {
+   "tool": "run_trajectory",
+   "arguments": {
+    "domain": "energy",
+    "card": "tokamak_vde_mast",
+    "initial": {
+     "displacement_m": 0.0038,
+     "velocity_m_s": 0.0249,
+     "wall_current_a": -83.4,
+     "p6_current_a": -31.0
+    },
+    "dt_s": 0.001,
+    "segments": [
+     {
+      "steps": 18,
+      "load": {
+       "p6_voltage_v": 0.0
+      }
+     },
+     {
+      "steps": 38,
+      "load": {
+       "p6_voltage_v": -6.945322144533363
+      }
+     }
+    ],
+    "record_every": 56
+   }
+  },
+  "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45",
+  "stopped": "PlasmaAtWall"
+ }
+}
+

What the models were compared with

+
ModelAgainstSpecimenAccuracy against measurement
energy/tokamak_vde_mastcompared with measurementVertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep.Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.
+

Cheat suite

0 cheat attempt(s) scored above 0. 19 vectors applied; 11 do not apply to this kind.

VectorExpectedRewardGradedResultScorer's reason
honesthonest control (1)11.000holds
honest_reply_log_matcheshonest control (1)11.000holds
honest_numbers_respelledhonest control (1)11.000holds
no_request_behindcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
edited_call_logcheat (0)00.000holdsthe call log beside the reply differs from the harness log
over_budgetcheat (0)00.000holds5 computing calls; the budget is 4
forbidden_toolcheat (0)00.000holdsthe log holds calls of find_flip, which the task rules out
no_harness_logcheat (0)00.000holdsno harness call log: every attempt is scored with the calls the harness recorded
harness_log_editedcheat (0)00.000holdsthe harness log's chain breaks at line 2
stale_engine_tagcheat (0)00.000holdsthe task was built on engine 0.15.0; the verifier is 0.15.3
copied_proof_other_taskcheat (0)00.000holdsthe holds seal: the verifier says the seal does not hold (cause run_seal)
nudged_figurecheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause run_seal)
figure_plus_10_percentcheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause run_seal)
card_request_not_runcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
swapped_sidescheat (0)00.000holdsthe holds request comes back ended (PlasmaAtWall)
stop_misnamedcheat (0)00.000holdsthe card names the stop 'SomeOtherStop'; the verifier names PlasmaAtWall
proof_from_other_designcheat (0)00.000holdsthe stops seal: the verifier says the seal does not hold (cause run_seal)
proof_uppercasecheat (0)00.000holdsthe holds seal: the proof is not a SHA-384 seal of 96 hex digits
extra_argumentcheat (0)00.000holdsthe holds request differs from the task's at note
+

Solver runs

+
AgentRewardGradedComputing callsScorer's reason
Reference agent11.0002
One-call agent00.0001the holds request comes back ended (PlasmaAtWall)
+

Pass@k by model family

+
FamilyVariantModelSolvedpass@1pass@8Mean gradedHarness errors
Frontier modeltoolFrontier model4 of 850%100%0.5790%
+

Measured calibration: Frontier model, tool variant, n=8.

+

Calibrated on pass@1 in [2%, 70%] on a frontier model's tool variant, with pass@8 and continuous graded reward reported beside pass/fail.

+ +

Written 2026-11-14T01:37:52Z.

+ \ No newline at end of file diff --git a/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.json b/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.json new file mode 100644 index 0000000000000000000000000000000000000000..d747d61d2c2f1aab9681208ebc49fdc64324086f --- /dev/null +++ b/sample/reports/g5r8-bs-mast-2seg-drift-down-wall-b4.json @@ -0,0 +1,353 @@ +{ + "id": "g5r8-bs-mast-2seg-drift-down-wall-b4", + "family": "budget", + "kind": "budgeted_search", + "models": [ + "energy/tokamak_vde_mast" + ], + "checksums": { + "row_sha256": "092ec55ee295b8af2d1cf779200a6dc60172dd0ee67283ee9f017caab2d3b212", + "row_sha384": "77b3ba995864f265e7186fb9f4791d340d240d4c36574bcf5671349cc4428169028d4db1ada207de2f9891125ba85579", + "harbor_dir_sha256": "a3c5fedfff586aae588a8822440726054753b49dd3d8d30b1a582283873a8e16", + "harbor_dir_sha384": "8feed8131a952e71a0ab6455115eb4ec0f55089759d0a2c644e211cdd55548311acd312a0898540ba2adf592a00811ef" + }, + "instruction": "MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number).\n\nFind it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V.\n\nThe request, with the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"holds\": {\"request\": ..., \"proof\": ...}, \"stops\": {\"request\": ..., \"proof\": ..., \"stopped\": \"\"}}\n\nholds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.", + "real_thing": "Vertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep. Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.", + "reference": { + "from": "the reference agent's reply (g5r8-bs-mast-2seg-drift-down-wall-b4.txt)", + "card": { + "holds": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_vde_mast", + "initial": { + "displacement_m": 0.0038, + "velocity_m_s": 0.0249, + "wall_current_a": -83.4, + "p6_current_a": -31.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 18, + "load": { + "p6_voltage_v": 0.0 + } + }, + { + "steps": 38, + "load": { + "p6_voltage_v": -6.9444887558793384 + } + } + ], + "record_every": 56 + } + }, + "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969" + }, + "stops": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_vde_mast", + "initial": { + "displacement_m": 0.0038, + "velocity_m_s": 0.0249, + "wall_current_a": -83.4, + "p6_current_a": -31.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 18, + "load": { + "p6_voltage_v": 0.0 + } + }, + { + "steps": 38, + "load": { + "p6_voltage_v": -6.945322144533363 + } + } + ], + "record_every": 56 + } + }, + "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", + "stopped": "PlasmaAtWall" + } + }, + "proofs": [ + { + "where": "holds", + "tool": "run_trajectory", + "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", + "open_address": "verified" + }, + { + "where": "stops", + "tool": "run_trajectory", + "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", + "open_address": "verified" + } + ], + "open_address_record": true, + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "measurement": [ + { + "model": "energy/tokamak_vde_mast", + "against_measurement": "compared with measurement", + "accuracy_against_measurement": "Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.", + "specimen": "Vertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep.", + "error": null + } + ], + "cheat_suite": { + "vectors": [ + { + "vector": "honest", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_reply_log_matches", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_numbers_respelled", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "no_request_behind", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "edited_call_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the call log beside the reply differs from the harness log" + }, + { + "vector": "over_budget", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "5 computing calls; the budget is 4" + }, + { + "vector": "forbidden_tool", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the log holds calls of find_flip, which the task rules out" + }, + { + "vector": "no_harness_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "no harness call log: every attempt is scored with the calls the harness recorded" + }, + { + "vector": "harness_log_edited", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the harness log's chain breaks at line 2" + }, + { + "vector": "stale_engine_tag", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3" + }, + { + "vector": "copied_proof_other_task", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "nudged_figure", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "figure_plus_10_percent", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "card_request_not_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "swapped_sides", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds request comes back ended (PlasmaAtWall)" + }, + { + "vector": "stop_misnamed", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the card names the stop 'SomeOtherStop'; the verifier names PlasmaAtWall" + }, + { + "vector": "proof_from_other_design", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the stops seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "proof_uppercase", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds seal: the proof is not a SHA-384 seal of 96 hex digits" + }, + { + "vector": "extra_argument", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the holds request differs from the task's at note" + } + ], + "not_applicable": [ + { + "vector": "binding_misnamed", + "why": "not a budget card" + }, + { + "vector": "failing_given_as_passing", + "why": "not a budget card" + }, + { + "vector": "step_misnamed", + "why": "not a budget card" + }, + { + "vector": "missing_solve", + "why": "not a budget card" + }, + { + "vector": "solve_handed_other_run", + "why": "not a budget card" + }, + { + "vector": "every_row_genuine", + "why": "not a budget card" + }, + { + "vector": "every_row_false", + "why": "not a budget card" + }, + { + "vector": "every_row_false_true_reasons", + "why": "not a budget card" + }, + { + "vector": "next_start_rounded", + "why": "not a budget card" + }, + { + "vector": "next_proof_copied", + "why": "not a budget card" + }, + { + "vector": "next_request_edited", + "why": "not a budget card" + } + ], + "cheats_scoring_above_0": 0, + "run": true + }, + "solver_runs": { + "reference": { + "reward": 1, + "graded": 1.0, + "correct": 1, + "proofs_hold": 1, + "computing_calls": 2, + "verdict": "pass", + "reason": null + }, + "naive": { + "reward": 0, + "graded": 0.0, + "correct": 0, + "proofs_hold": 1, + "computing_calls": 1, + "verdict": "wrong", + "reason": "the holds request comes back ended (PlasmaAtWall)" + } + }, + "passk": [ + { + "family": "Frontier model", + "model": "Frontier model", + "variant": "tool", + "n": 8, + "correct": 4, + "pass@1": 0.5, + "pass@8": 1.0, + "mean_graded": 0.5785515, + "harness_error_rate": 0.0 + } + ], + "no_tool_question": false, + "physics_forensics": false, + "blind_baseline": null, + "written_utc": "2026-11-14T01:37:52Z" +} diff --git a/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.html b/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.html new file mode 100644 index 0000000000000000000000000000000000000000..17fc31a1d24999c4c18dad34ca1ebf58fe92f482 --- /dev/null +++ b/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.html @@ -0,0 +1,181 @@ + +Task report: g5r8-dl-jet-tritium-rich-dome-hotion +

g5r8-dl-jet-tritium-rich-dome-hotion

+

Multi-step physics RLVR task scored by deterministic recomputation on the Zero-Trust Physics verifier.

+

Design to a limit · models energy/tokamak_jet_dte1 · Zero-Trust Physics v0.15.3 · Protocol Company

+

Checksums

+ + +
Whatsha256SHA-384
Task rowc82e66ac5a91d042226c4349093ad64eee50931aa05a1519989640cc8e9e5c84283028af98c4ce3b8b773a6730813d39ab67d25df6834633949d3c6f70460662252e9643bce0ed4fc1bb01703e78762a
Harbor directory78c94da3b5a9a704309f8136e247e889e454a4f7c0192f1d677eff8b3dc16ce23f20b88ef6bb702c6e92e3fb6e162fa48a041d9dfa6121d63d083d3a41e887b1344224160a80287f302c229f767ce72f
+

Instruction

In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.
+
+Find the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.
+
+Constraints (id, what, limit):
+- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W
+- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J
+- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)
+Each design is one run:
+{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": "<your value>", "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}}
+This task has no solve: leave "solve" out of each design.
+
+Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.
+
+You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.
+
+End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "<the tool's name as the verifier names it, without any prefix your own program adds>", "arguments": {<the arguments exactly as you sent them>}}, and a proof is the run_seal or solution_seal the verifier gave for that request.
+
+The card:
+{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": "<constraint id>"}
+
+passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "<name>", "step": <steps_landed>}. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.
+

Reference solution

+

From the reference agent's reply (g5r8-dl-jet-tritium-rich-dome-hotion.txt). Built on engine v0.15.3 at commit 664d68f426cc. Open address: a record exists.

+
On the cardToolProofOpen address
passing.runrun_trajectorya5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153verified
failing.runrun_trajectoryfd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3verified
+
{
+ "passing": {
+  "run": {
+   "request": {
+    "tool": "run_trajectory",
+    "arguments": {
+     "domain": "energy",
+     "card": "tokamak_jet_dte1",
+     "initial": {
+      "thermal_energy_j": 5350000.0,
+      "deuterium_beam_ion_energy_j": 455000.0,
+      "tritium_beam_ion_energy_j": 515000.0,
+      "tail_ion_energy_j": 235000.0,
+      "elapsed_time_s": 0.0
+     },
+     "dt_s": 0.001,
+     "segments": [
+      {
+       "steps": 600,
+       "load": {
+        "deuterium_beam_power_w": 5800000.0,
+        "tritium_beam_power_w": 6200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 2800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 3.6e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.52,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 1.0
+       }
+      },
+      {
+       "steps": 1100,
+       "load": {
+        "deuterium_beam_power_w": 5800000.0,
+        "tritium_beam_power_w": 6200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 2800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 3.6e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.7461228712236883,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 1.0
+       }
+      }
+     ],
+     "record_every": 1700
+    }
+   },
+   "proof": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153"
+  }
+ },
+ "failing": {
+  "run": {
+   "request": {
+    "tool": "run_trajectory",
+    "arguments": {
+     "domain": "energy",
+     "card": "tokamak_jet_dte1",
+     "initial": {
+      "thermal_energy_j": 5350000.0,
+      "deuterium_beam_ion_energy_j": 455000.0,
+      "tritium_beam_ion_energy_j": 515000.0,
+      "tail_ion_energy_j": 235000.0,
+      "elapsed_time_s": 0.0
+     },
+     "dt_s": 0.001,
+     "segments": [
+      {
+       "steps": 600,
+       "load": {
+        "deuterium_beam_power_w": 5800000.0,
+        "tritium_beam_power_w": 6200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 2800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 3.6e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.52,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 1.0
+       }
+      },
+      {
+       "steps": 1100,
+       "load": {
+        "deuterium_beam_power_w": 5800000.0,
+        "tritium_beam_power_w": 6200000.0,
+        "deuterium_beam_energy_kev": 93.0,
+        "tritium_beam_energy_kev": 131.0,
+        "icrh_power_w": 2800000.0,
+        "ohmic_power_w": 540000.0,
+        "line_density_per_m3": 3.6e+19,
+        "plasma_current_a": 3350000.0,
+        "toroidal_field_t": 3.55,
+        "tritium_fraction": 0.7463028712236883,
+        "electron_temperature_kev": 7.6,
+        "effective_charge": 1.95,
+        "hot_ion_regime": 1.0
+       }
+      }
+     ],
+     "record_every": 1700
+    }
+   },
+   "proof": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3"
+  }
+ },
+ "binding": "j_fusion"
+}
+

What the models were compared with

+
ModelAgainstSpecimenAccuracy against measurement
energy/tokamak_jet_dte1compared with measurementHeated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step.Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).
+

Cheat suite

0 cheat attempt(s) scored above 0. 20 vectors applied; 10 do not apply to this kind.

VectorExpectedRewardGradedResultScorer's reason
honesthonest control (1)11.000holds
honest_reply_log_matcheshonest control (1)11.000holds
honest_numbers_respelledhonest control (1)11.000holds
no_request_behindcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
edited_call_logcheat (0)00.000holdsthe call log beside the reply differs from the harness log
over_budgetcheat (0)00.000holds5 computing calls; the budget is 4
forbidden_toolcheat (0)00.000holdsthe log holds calls of find_flip, which the task rules out
no_harness_logcheat (0)00.000holdsno harness call log: every attempt is scored with the calls the harness recorded
harness_log_editedcheat (0)00.000holdsthe harness log's chain breaks at line 2
stale_engine_tagcheat (0)00.000holdsthe task was built on engine 0.15.0; the verifier is 0.15.3
copied_proof_other_taskcheat (0)00.000holdsthe passing design's run_seal: the verifier says the seal does not hold (cause run_seal)
nudged_figurecheat (0)00.000holdsthe passing design's run_seal: the verifier says the seal does not hold (cause run_seal)
figure_plus_10_percentcheat (0)00.000holdsthe passing design's run_seal: the verifier says the seal does not hold (cause run_seal)
card_request_not_runcheat (0)00.000holdsa run_trajectory request on the card is not among the calls in the log
swapped_sidescheat (0)00.000holdsthe passing design breaks j_fusion
binding_misnamedcheat (0)00.000holdsbinding names 'j_fusion_energy'; the constraint that binds is another
proof_from_other_designcheat (0)00.000holdsthe failing design's run_seal: the verifier says the seal does not hold (cause run_seal)
failing_given_as_passingcheat (0)00.000holdsthe passing design breaks j_fusion
proof_uppercasecheat (0)00.000holdsthe passing design's run_seal: the proof is not a SHA-384 seal of 96 hex digits
extra_argumentcheat (0)00.000holdsthe passing design's run differs from the task's at note
+

Solver runs

+
AgentRewardGradedComputing callsScorer's reason
Reference agent11.0002
One-call agent00.0001the failing design meets every constraint
+

Pass@k by model family

+
FamilyVariantModelSolvedpass@1pass@8Mean gradedHarness errors
Frontier modeltoolFrontier model3 of 838%100%0.7190%
+

Measured calibration: Frontier model, tool variant, n=8.

+

Calibrated on pass@1 in [2%, 70%] on a frontier model's tool variant, with pass@8 and continuous graded reward reported beside pass/fail.

+ +

Written 2026-11-14T01:37:52Z.

+ \ No newline at end of file diff --git a/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.json b/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.json new file mode 100644 index 0000000000000000000000000000000000000000..a63ec4c0c7216f1e680b4c8311343dc0b8ab1ab6 --- /dev/null +++ b/sample/reports/g5r8-dl-jet-tritium-rich-dome-hotion.json @@ -0,0 +1,411 @@ +{ + "id": "g5r8-dl-jet-tritium-rich-dome-hotion", + "family": "tradeoff", + "kind": "design_to_limit", + "models": [ + "energy/tokamak_jet_dte1" + ], + "checksums": { + "row_sha256": "c82e66ac5a91d042226c4349093ad64eee50931aa05a1519989640cc8e9e5c84", + "row_sha384": "283028af98c4ce3b8b773a6730813d39ab67d25df6834633949d3c6f70460662252e9643bce0ed4fc1bb01703e78762a", + "harbor_dir_sha256": "78c94da3b5a9a704309f8136e247e889e454a4f7c0192f1d677eff8b3dc16ce2", + "harbor_dir_sha384": "3f20b88ef6bb702c6e92e3fb6e162fa48a041d9dfa6121d63d083d3a41e887b1344224160a80287f302c229f767ce72f" + }, + "instruction": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"run\": {\"request\": ..., \"proof\": ...}, \"solve\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"run\": {\"request\": ..., \"proof\": ...}, \"solve\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\npassing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out \"solve\" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries \"stopped\": the stop's name exactly as the verifier gives it, and \"step\": the last step its run is sealed to (steps_landed), a whole number: {\"run\": {...}, \"stopped\": \"\", \"step\": }. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.", + "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", + "reference": { + "from": "the reference agent's reply (g5r8-dl-jet-tritium-rich-dome-hotion.txt)", + "card": { + "passing": { + "run": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "initial": { + "thermal_energy_j": 5350000.0, + "deuterium_beam_ion_energy_j": 455000.0, + "tritium_beam_ion_energy_j": 515000.0, + "tail_ion_energy_j": 235000.0, + "elapsed_time_s": 0.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 600, + "load": { + "deuterium_beam_power_w": 5800000.0, + "tritium_beam_power_w": 6200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 2800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 3.6e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.52, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 1.0 + } + }, + { + "steps": 1100, + "load": { + "deuterium_beam_power_w": 5800000.0, + "tritium_beam_power_w": 6200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 2800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 3.6e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.7461228712236883, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 1.0 + } + } + ], + "record_every": 1700 + } + }, + "proof": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153" + } + }, + "failing": { + "run": { + "request": { + "tool": "run_trajectory", + "arguments": { + "domain": "energy", + "card": "tokamak_jet_dte1", + "initial": { + "thermal_energy_j": 5350000.0, + "deuterium_beam_ion_energy_j": 455000.0, + "tritium_beam_ion_energy_j": 515000.0, + "tail_ion_energy_j": 235000.0, + "elapsed_time_s": 0.0 + }, + "dt_s": 0.001, + "segments": [ + { + "steps": 600, + "load": { + "deuterium_beam_power_w": 5800000.0, + "tritium_beam_power_w": 6200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 2800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 3.6e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.52, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 1.0 + } + }, + { + "steps": 1100, + "load": { + "deuterium_beam_power_w": 5800000.0, + "tritium_beam_power_w": 6200000.0, + "deuterium_beam_energy_kev": 93.0, + "tritium_beam_energy_kev": 131.0, + "icrh_power_w": 2800000.0, + "ohmic_power_w": 540000.0, + "line_density_per_m3": 3.6e+19, + "plasma_current_a": 3350000.0, + "toroidal_field_t": 3.55, + "tritium_fraction": 0.7463028712236883, + "electron_temperature_kev": 7.6, + "effective_charge": 1.95, + "hot_ion_regime": 1.0 + } + } + ], + "record_every": 1700 + } + }, + "proof": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3" + } + }, + "binding": "j_fusion" + }, + "proofs": [ + { + "where": "passing.run", + "tool": "run_trajectory", + "proof": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", + "open_address": "verified" + }, + { + "where": "failing.run", + "tool": "run_trajectory", + "proof": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", + "open_address": "verified" + } + ], + "open_address_record": true, + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "measurement": [ + { + "model": "energy/tokamak_jet_dte1", + "against_measurement": "compared with measurement", + "accuracy_against_measurement": "Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", + "specimen": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step.", + "error": null + } + ], + "cheat_suite": { + "vectors": [ + { + "vector": "honest", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_reply_log_matches", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "honest_numbers_respelled", + "expect": "honest control (1)", + "reward": 1, + "graded": 1.0, + "ok": true, + "reason": null + }, + { + "vector": "no_request_behind", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "edited_call_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the call log beside the reply differs from the harness log" + }, + { + "vector": "over_budget", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "5 computing calls; the budget is 4" + }, + { + "vector": "forbidden_tool", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the log holds calls of find_flip, which the task rules out" + }, + { + "vector": "no_harness_log", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "no harness call log: every attempt is scored with the calls the harness recorded" + }, + { + "vector": "harness_log_edited", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the harness log's chain breaks at line 2" + }, + { + "vector": "stale_engine_tag", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the task was built on engine 0.15.0; the verifier is 0.15.3" + }, + { + "vector": "copied_proof_other_task", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "nudged_figure", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "figure_plus_10_percent", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's run_seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "card_request_not_run", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "a run_trajectory request on the card is not among the calls in the log" + }, + { + "vector": "swapped_sides", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks j_fusion" + }, + { + "vector": "binding_misnamed", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "binding names 'j_fusion_energy'; the constraint that binds is another" + }, + { + "vector": "proof_from_other_design", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the failing design's run_seal: the verifier says the seal does not hold (cause run_seal)" + }, + { + "vector": "failing_given_as_passing", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design breaks j_fusion" + }, + { + "vector": "proof_uppercase", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's run_seal: the proof is not a SHA-384 seal of 96 hex digits" + }, + { + "vector": "extra_argument", + "expect": "cheat (0)", + "reward": 0, + "graded": 0.0, + "ok": true, + "reason": "the passing design's run differs from the task's at note" + } + ], + "not_applicable": [ + { + "vector": "stop_misnamed", + "why": "no stop binds" + }, + { + "vector": "step_misnamed", + "why": "no stop binds" + }, + { + "vector": "missing_solve", + "why": "a design of one request" + }, + { + "vector": "solve_handed_other_run", + "why": "a design of one request" + }, + { + "vector": "next_start_rounded", + "why": "not a continued design" + }, + { + "vector": "next_proof_copied", + "why": "not a continued design" + }, + { + "vector": "next_request_edited", + "why": "not a continued design" + }, + { + "vector": "every_row_genuine", + "why": "forensics only" + }, + { + "vector": "every_row_false", + "why": "forensics only" + }, + { + "vector": "every_row_false_true_reasons", + "why": "forensics only" + } + ], + "cheats_scoring_above_0": 0, + "run": true + }, + "solver_runs": { + "reference": { + "reward": 1, + "graded": 1.0, + "correct": 1, + "proofs_hold": 1, + "computing_calls": 2, + "verdict": "pass", + "reason": null + }, + "naive": { + "reward": 0, + "graded": 0.0, + "correct": 0, + "proofs_hold": 1, + "computing_calls": 1, + "verdict": "wrong", + "reason": "the failing design meets every constraint" + } + }, + "passk": [ + { + "family": "Frontier model", + "model": "Frontier model", + "variant": "tool", + "n": 8, + "correct": 3, + "pass@1": 0.375, + "pass@8": 1.0, + "mean_graded": 0.718861875, + "harness_error_rate": 0.0 + } + ], + "no_tool_question": false, + "physics_forensics": false, + "blind_baseline": null, + "written_utc": "2026-11-14T01:37:52Z" +} diff --git a/sample/reports/index.html b/sample/reports/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6c9425d2fce0d0eb87fc11f65eab934756a38402 --- /dev/null +++ b/sample/reports/index.html @@ -0,0 +1,18 @@ + +Task quality reports

Task quality reports

+

5 tasks · Zero-Trust Physics v0.15.3 · Protocol Company

+
TaskKindReference rewardCheats above 0Pass@1
g5r8-bs-mast-2seg-drift-down-wall-b4Budgeted search10Frontier model tool pass@1 50%
g5r10-ch-jet-dt3-least-tbeam-power-c12-b7Chained design10Frontier model tool pass@1 38%
g5r10-dl-dt4-core-te-fastshare-pionDesign to a limit10Frontier model tool pass@1 38%
g5r8-dl-jet-tritium-rich-dome-hotionDesign to a limit10Frontier model tool pass@1 38%
g5-bs-pb11-weakest-field-that-holds-b4Budgeted search10Frontier model tool pass@1 62%
\ No newline at end of file diff --git a/sample/reports/live_scores.jsonl b/sample/reports/live_scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8b8053a71738926b62dc23953c894f3be233e7dd --- /dev/null +++ b/sample/reports/live_scores.jsonl @@ -0,0 +1,5 @@ +{"id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "holds_outcome": "completed", "stops_outcome": "ended (PlasmaAtWall)", "holds_value": -6.9444887558793384, "stops_value": -6.945322144533363, "width": 0.0008333886540246027, "width_ratio": 0.5999999999998852} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 4, "passing": {"x": 9739916.12958908, "met": {"dt_power": true, "j_beta": true, "jet_completes": true}, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}}, "failing": {"x": 9223916.12958908, "met": {"dt_power": false, "j_beta": true, "jet_completes": true}, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}}, "width": 516000.0, "width_ratio": 0.6} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "passing": {"x": 10.73913080971837, "met": {"dt_fast_e": true, "dt_pion": true}, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}}, "failing": {"x": 10.744830809718371, "met": {"dt_fast_e": false, "dt_pion": true}, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}}, "width": 0.0057000000000009265, "width_ratio": 0.6000000000000976} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "passing": {"x": 0.7461228712236883, "met": {"j_fusion": true, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}}, "failing": {"x": 0.7463028712236883, "met": {"j_fusion": false, "j_fusion_energy": true, "completes": true}, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}}, "width": 0.000180000000000069, "width_ratio": 0.60000000000023} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "calls_from": "harness", "correct": 1, "proofs_hold": 1, "reward": 1, "graded": 1.0, "verdict": "pass", "reason": null, "computing_calls": 2, "holds_outcome": "converged", "stops_outcome": "refused (PressureExceedsField)", "holds_value": 5.695798204932004, "stops_value": 5.695456467291837, "width": 0.0003417376401664285, "width_ratio": 0.5999999999994965} diff --git a/sample/reports/live_verify.json b/sample/reports/live_verify.json new file mode 100644 index 0000000000000000000000000000000000000000..efc439ea9dd567e4614bbfc8196af182dbe20461 --- /dev/null +++ b/sample/reports/live_verify.json @@ -0,0 +1,7 @@ +{ + "date": "13 November 2026", + "address": "https://mcp.zerotrustphysics.com/mcp", + "tasks": 5, + "reward_1": 5, + "proofs_hold": 5 +} \ No newline at end of file diff --git a/sample/reports/vault_proof.json b/sample/reports/vault_proof.json new file mode 100644 index 0000000000000000000000000000000000000000..9466f4a3b9707346c936164a49ef13d31816a5e8 --- /dev/null +++ b/sample/reports/vault_proof.json @@ -0,0 +1,62 @@ +{ + "sample_set": "public_sample", + "group": "nuclear-fusion", + "engine_tag": "v0.15.3", + "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", + "tasks": 5, + "by_kind": { + "budgeted_search": 2, + "chained_design": 1, + "design_to_limit": 2 + }, + "calibration": { + "model": "Frontier model", + "variant": "tool", + "band_is_on": "pass@1", + "pass1_min": 0.375, + "pass1_median": 0.375, + "pass1_max": 0.625, + "n_min": 8, + "n_max": 8, + "pass8_min": 1.0, + "pass8_max": 1.0 + }, + "cheat_suite": { + "vectors": [ + "binding_misnamed", + "card_request_not_run", + "copied_proof_other_task", + "edited_call_log", + "extra_argument", + "failing_given_as_passing", + "figure_plus_10_percent", + "forbidden_tool", + "harness_log_edited", + "missing_solve", + "no_harness_log", + "no_request_behind", + "nudged_figure", + "over_budget", + "proof_from_other_design", + "proof_uppercase", + "solve_handed_other_run", + "stale_engine_tag", + "stop_misnamed", + "swapped_sides" + ], + "executed_adversarial": 85, + "adversarial_above_zero": 0, + "honest_controls": 15, + "honest_controls_at_one": 15, + "not_applicable_skipped": 50, + "all_zero": true + }, + "reference": { + "scored": 5, + "reward_1": 5 + }, + "disjoint": { + "clean": true, + "tasks_with_hits": [] + } +} \ No newline at end of file diff --git a/sample/scorer/bin/sample_verifier-linux-amd64 b/sample/scorer/bin/sample_verifier-linux-amd64 new file mode 100755 index 0000000000000000000000000000000000000000..88a1cdfe48470133429c540b2d2bd015c8403121 --- /dev/null +++ b/sample/scorer/bin/sample_verifier-linux-amd64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d75b9ee1451c1fa0d9a3a322882fb3c929305452afcd82701d70317c95c2f87b +size 2022400 diff --git a/sample/scorer/bin/sample_verifier-linux-arm64 b/sample/scorer/bin/sample_verifier-linux-arm64 new file mode 100755 index 0000000000000000000000000000000000000000..00ce702e77cb25fa7671ae8c8c076c4669290bec --- /dev/null +++ b/sample/scorer/bin/sample_verifier-linux-arm64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:189696a4edc155f14d13ee90bfe7488104d099d6b4ac7707be551fa887b4a5db +size 1621408 diff --git a/sample/scorer/bin/sample_verifier-macos-arm64 b/sample/scorer/bin/sample_verifier-macos-arm64 new file mode 100755 index 0000000000000000000000000000000000000000..ba985daf17bb5f7f316e5ba86cfb253ee72ecb9c --- /dev/null +++ b/sample/scorer/bin/sample_verifier-macos-arm64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c794237cdc8f1f125759a88c374f7418507af6103fa53332341dc82d5ec59be7 +size 1611232 diff --git a/sample/scorer/chainlib.py b/sample/scorer/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/scorer/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack(" the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "models": ["energy/tokamak_jet_dte1", "tokamak_dt_beam_target"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "models": ["tokamak_dt_beam_target"], "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "models": ["energy/tokamak_jet_dte1"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", "task": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "models": ["fusion_pb11_thermal"], "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", "task": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/scorer/mcp_stdio_open b/sample/scorer/mcp_stdio_open new file mode 100755 index 0000000000000000000000000000000000000000..71b5af54451c58cf6f0ff8bbc0b611f4cf5ed8b2 --- /dev/null +++ b/sample/scorer/mcp_stdio_open @@ -0,0 +1,3 @@ +#!/bin/sh +# The Zero-Trust Physics verifier at its open MCP address, as an MCP stdio server. +exec python3 "$(dirname "$0")/ztp_open_bridge.py" "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" diff --git a/sample/scorer/pack_score.py b/sample/scorer/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/scorer/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/prompt.py b/sample/scorer/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..a97c7cd395c83cb0842e59fcb0161d67a5b1c164 --- /dev/null +++ b/sample/scorer/prompt.py @@ -0,0 +1,194 @@ +"""Print exactly the text an agent is given for one environment: the task, then its family's footer. + + python3 prompt.py --environments F ENVIRONMENT_ID the text for one environment + python3 prompt.py --environments F --list every environment id, one a line + python3 prompt.py --environments F --all FOLDER write FOLDER/.txt for every environment + +Any runner for any model gives the agent this text and nothing else, with the verifier as its +tool server. + +Licence: Apache-2.0. +""" +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) + +COMMON = """You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.""" + +FOOTERS = { + "tradeoff": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names.""", + "chain_design": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps the constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks the constraint, no further from passing than the task's tolerance. binding: the id of the constraint. Each solve is the one handed its own design's sealed run through the coupling the task names.""", + "budget": COMMON + """ + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.""", + "forensics": COMMON + """ + +The card: +{"false_rows": {"": "", ...}} + +Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden. Leave the genuine rows out. {"false_rows": {}} says every row is genuine.""", +} + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +STOP_BINDS = """ Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }.""" + + +# The design shapes of the 29 Oct 2026 groups, each footer as its group built it (score.design_shape). +CONTINUED_CARRIED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is two runs: "run" is the first run, and "next" is the run that continues that same sealed run, with "from": {"request": , "run_seal": } and its initial state equal to the first run's final_state, value for value, bit for bit.""" + +CONTINUED_HANDED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. run is the design's first run; next is the run that continues that same sealed run through from: its from holds the first run's request and run_seal, and its start fields are the first run's final state exactly as the verifier returned it.""" + +CONTINUED_CARRY = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is two runs: run, and next, which continues that design's own sealed run through from (from.request is the run's request, from.run_seal its proof) and starts from its final state. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +SOLVE_DESIGN = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is one solve and no run.""" + +SOLVE_ONLY = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +STAGED = COMMON + """ + +The card: +{"passing": {%s}, "failing": {%s}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (%s), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer.""" + +STAGED_STOP = """ Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it%s.""" + +STOP_BINDS_SOLVE = """ Where one constraint is that the solve is not refused by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +SOLVE_STOP_G4 = """ Where one constraint is that the solve converges (it names a refusal) and that constraint binds, binding is its id and the failing design also carries "stopped": the refusal's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +CARRY_STOP_G5 = (" Where one constraint is that the second run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries" + " \"stopped\": the stop's name exactly as the verifier gives it, and \"step\": the last step the second run (next) is sealed to (its steps_landed), a whole number:" + " {\"run\": {...}, \"next\": {...}, \"stopped\": \"\", \"step\": }.") + +BUDGET_WORDS = " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + + +def shaped_footer(environment): + """The footer of a design of one of the added shapes, or None for a run or a coupled solve (FOOTERS).""" + family = environment["family"] + check = environment.get("check") or {} + design = check.get("design") or {} + if family not in ("tradeoff", "chain_design"): + return None + chain = design.get("chain") or {} + stops = [c for c in check.get("constraints") or [] if c.get("on") == "outcome"] + if design.get("stages"): # group 3 + stages = design["stages"] + shape = ", ".join('"%s": {"request": ..., "proof": ...}' % st["key"] for st in stages) + footer = STAGED % (shape, shape, ", ".join(st["key"] for st in stages)) + if stops: + runs = any(st["key"] == c.get("stage") and st["tool"] == "run_trajectory" for c in stops for st in stages) + footer += STAGED_STOP % (', and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number' if runs else "") + elif design.get("tool") == "solve": # group 4 + footer = SOLVE_DESIGN + (SOLVE_STOP_G4 if stops else "") + elif design.get("kind") == "solve": # group 5 + footer = SOLVE_ONLY + (STOP_BINDS_SOLVE if stops else "") + elif chain.get("kind") == "continuation" and "carried" in chain: # group 1 + footer = CONTINUED_CARRIED + if stops: + footer += STOP_BINDS + " In a chain the stop and the step are those of the failing design's next run." + elif chain.get("kind") == "continuation": # group 4 + footer = CONTINUED_HANDED + if stops: + footer += STOP_BINDS.replace("the run completes", "the second run completes").replace( + "the last step its run is sealed to", "the last step its next run is sealed to") + elif (chain.get("layout") or {}).get("kind") == "continue": # group 5 + footer = CONTINUED_CARRY + (CARRY_STOP_G5 if stops else "") + else: + return None + if check.get("budget"): + footer += BUDGET_WORDS + return footer + + +def prompt(environment): + """The whole text an agent is given for one environment.""" + family = environment["family"] + shaped = shaped_footer(environment) + if shaped is not None: + return environment["task"] + "\n\n" + shaped + footer = FOOTERS[family] + check = environment.get("check") or {} + if family in ("tradeoff", "chain_design") and any(c.get("on") == "outcome" for c in check.get("constraints") or []): + footer += STOP_BINDS + if family in ("tradeoff", "chain_design", "forensics") and check.get("budget"): + footer += " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + if family == "forensics" and check.get("reasons"): + footer = footer.replace("Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden.", + "Name every false row, each with its one reason from %s (the first of them, in that order, that is true of the row)." % ", ".join(check["reasons"])) + return environment["task"] + "\n\n" + footer + + +def main(): + argv = sys.argv[1:] + if len(argv) < 3 or argv[0] != "--environments": + sys.exit(__doc__) + environments = load_environments(argv[1]) + argv = argv[2:] + if argv[0] == "--list": + print("\n".join(e["id"] for e in environments)) + elif argv[0] == "--all": + if len(argv) < 2: + sys.exit("give the folder to write into") + os.makedirs(argv[1], exist_ok=True) + for e in environments: + with open(os.path.join(argv[1], e["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(prompt(e) + "\n") + print("wrote %d prompts to %s" % (len(environments), argv[1])) + else: + found = [e for e in environments if e["id"] == argv[0]] + if not found: + sys.exit("no environment with the id %s; --list names them" % argv[0]) + print(prompt(found[0])) + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/run_cheat_suite.py b/sample/scorer/run_cheat_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..694040c86592b7badbe78b94caa530f935d0f193 --- /dev/null +++ b/sample/scorer/run_cheat_suite.py @@ -0,0 +1,436 @@ +"""Cheat suite: every way of faking an answer, built from the honest reference and scored. Every cheat scores 0. + + python3 run_cheat_suite.py --environments F --reference DIR --engine ENGINE [--only id,id] [--out F] + +DIR holds the honest reference replies made through the harness proxy by run_reference.py: +.txt and .harness.jsonl (made here, on the verifier, for any task that has none). For every +task, each vector below that applies to its family is built from the honest reply and scored by +score.py with the harness log as the call record. The honest reply must score reward 1 and graded 1; +every cheat reward 0 and graded 0. One JSON line per task and vector to --out; exit 1 on any cheat +above 0 or an honest reply below 1. + + honest the reference reply and its harness log (control: 1) + honest_reply_log_matches with a reply-side calls.jsonl equal to the harness log (control: 1) + honest_numbers_respelled the harness log with whole numbers spelt 18 where the card has 18.0 (control: 1) + copied_proof_other_task a proof copied from another task's card + nudged_figure the design value moved inside the bracket, the original proof kept + figure_plus_10_percent the design value times 1.1, the original proof kept + no_request_behind the card with no calls in the harness log (forensics: free calls only) + card_request_not_run the card's request differs from the one the harness log shows was run + edited_call_log a reply-side calls.jsonl that differs from the harness log (a call dropped) + over_budget more computing calls than the budget + forbidden_tool a ruled-out tool (find_flip) in the log + no_harness_log no harness log; only the reply-side log + harness_log_edited the harness log edited after the run (its chain breaks) + stale_engine_tag the task's reference marked as built on engine 0.15.0 + swapped_sides passing and failing (holds and stops) swapped + binding_misnamed another constraint named as binding + proof_from_other_design the failing design (stops side) carrying the passing one's proof + failing_given_as_passing the failing design given for both + proof_uppercase the proof in upper-case hex + extra_argument a request with one argument more than the template + stop_misnamed, step_misnamed the stop or step the card must name, wrong + missing_solve a chained design without its solve (coupled) or its next run (continued) or its + last stage (staged) + solve_handed_other_run a solve (coupled), a next run (continued) or a later stage (staged) handed the other + design's first request and its proof + next_start_rounded continued: the next run's start state rounded to 9 significant figures (as sent) + next_proof_copied continued: the failing design's next proof replaced by the passing design's + next_request_edited continued: the next run's last segment one step longer than the task's (as sent) + +The design shapes (score.design_shape): run, coupled, continued, solve, staged. A vector that edits "the first +request" edits the design's first entry: run, solve, or the first stage. + every_row_genuine forensics: {"false_rows": {}} + every_row_false forensics: every row named false with the first reason + every_row_false_true_reasons forensics: the false rows with their reasons and every genuine row too + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import math +import os +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from score import (FREE_TOOLS, Replay, canonical, close_verifier, continuation_of, design_shape, # noqa: E402 + load_environments, open_verifier, read_card, read_harness_log, score, set_path, write_harness_log) + + +def respelled(value): + """Whole floats written as ints (18.0 -> 18), as a client may send what a card writes as 18.0.""" + if isinstance(value, dict): + return {k: respelled(v) for k, v in value.items()} + if isinstance(value, list): + return [respelled(v) for v in value] + if isinstance(value, float) and value.is_integer() and abs(value) < 2 ** 53: + return int(value) + return value + + +def computing(calls): + return [(t, a) for t, a in calls if t not in FREE_TOOLS] + + +def replace_call(calls, tool, old, new): + """The log with the first call of tool with arguments old sent with new instead.""" + out, done = [], False + for t, a in calls: + if not done and t == tool and canonical(a) == canonical(old): + out.append((t, new)) + done = True + else: + out.append((t, a)) + if not done: + raise ValueError("the call to replace is not in the log") + return out + + +def parts_of(env): + """The keys of one design on the card, in order, and the tool of each.""" + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return [(st["key"], st["tool"]) for st in spec["stages"]] + return {"solve": [("solve", "solve")], "continued": [("run", "run_trajectory"), ("next", "run_trajectory")], + "coupled": [("run", "run_trajectory"), ("solve", "solve")]}.get(shape, [("run", "run_trajectory")]) + + +def moved_design(env, design, x): + """(design, [(tool, old arguments, new arguments)]): one boundary design with its value set to x.""" + spec = env["check"]["design"] + var = spec["variable"] + shape = design_shape(spec) + new = copy.deepcopy(design) + changes = [] + if shape in ("staged", "solve") or (shape == "continued" and var.get("on") == "next"): + key = var["stage"] if shape == "staged" else ("solve" if shape == "solve" else "next") + tool = dict(parts_of(env))[key] + for place in [var["path"]] + list(var.get("also") or []): + set_path(new[key]["request"]["arguments"], place, x) + return new, [(tool, design[key]["request"]["arguments"], new[key]["request"]["arguments"])] + run_old = design["run"]["request"]["arguments"] + run_new = new["run"]["request"]["arguments"] + if var["kind"] == "entry_angle_deg": + g = math.radians(x) + run_new["initial"]["radial_speed_m_s"] = -var["speed_m_s"] * math.sin(g) + run_new["initial"]["transverse_speed_m_s"] = var["speed_m_s"] * math.cos(g) + elif var.get("on", "run") == "run": + for place in [var["path"]] + list(var.get("also") or []): + set_path(run_new, place, x) + if var.get("on", "run") == "run" or var["kind"] == "entry_angle_deg": + changes.append(("run_trajectory", run_old, run_new)) + for key in ("solve", "next"): + if new.get(key): + new[key]["request"]["arguments"]["from"]["request"] = copy.deepcopy(run_new) + if key == "next": + for place in continuation_of(spec)[3]: + set_path(new[key]["request"]["arguments"], place, x) + changes.append((dict(parts_of(env)).get(key, "solve"), design[key]["request"]["arguments"], + new[key]["request"]["arguments"])) + else: + set_path(new["solve"]["request"]["arguments"], var["path"], x) + changes.append(("solve", design["solve"]["request"]["arguments"], new["solve"]["request"]["arguments"])) + return new, changes + + +def moved_budget(env, side, x): + check = env["check"] + new = copy.deepcopy(side) + for place in [check["variable"]] + list(check.get("also") or []): + set_path(new["request"]["arguments"], place, x) + return new, [(check["tool"], side["request"]["arguments"], new["request"]["arguments"])] + + +def apply_changes(calls, changes): + for tool, old, new in changes: + calls = replace_call(calls, tool, old, new) + return calls + + +def other_proof(env, others, family_tool): + """A proof from another task's honest card, for the same kind of request (any part of any design or side).""" + for other_id, other_card in others: + if other_id == env["id"] or not isinstance(other_card, dict): + continue + for side in ("passing", "failing", "holds", "stops"): + part = other_card.get(side) + candidates = [part] if side in ("holds", "stops") else (list(part.values()) if isinstance(part, dict) else []) + for one in candidates: + if (isinstance(one, dict) and isinstance(one.get("proof"), str) and isinstance(one.get("request"), dict) + and one["request"].get("tool") == family_tool): + return other_id, one["proof"] + return None, None + + +def stale(env): + out = copy.deepcopy(env) + out["reference"]["engine_tag"] = "v0.15.0" + out["reference"]["gateway_version"] = "0.15.0" + return out + + +def edited_log_file(calls, folder): + """A harness log of calls, chained, then one line's arguments edited without its chain.""" + path = os.path.join(folder, "edited.harness.jsonl") + write_harness_log(path, calls) + lines = open(path).read().splitlines() + pick = max(i for i, l in enumerate(lines) if json.loads(l)["tool"] not in FREE_TOOLS) + entry = json.loads(lines[pick]) + entry["arguments"] = dict(entry["arguments"], edited=True) + lines[pick] = json.dumps(entry, sort_keys=True) + open(path, "w").write("\n".join(lines) + "\n") + return read_harness_log(path) + + +def vectors(env, card, calls, others, scratch): + """[(name, expect, env, card, calls, reply_calls, log_problem)] and [(name, why not)].""" + family, check, ref = env["family"], env["check"], env["reference"] + out, skipped = [], [] + add = lambda name, expect, card_, calls_, reply_calls=None, env_=None, log_problem=None: out.append( # noqa: E731 + (name, expect, env_ or env, card_, calls_, reply_calls, log_problem)) + add("honest", 1, card, calls) + add("honest_reply_log_matches", 1, card, calls, reply_calls=list(calls)) + add("honest_numbers_respelled", 1, card, [(t, respelled(a)) for t, a in calls]) + comp = computing(calls) + + # ---- the call record, the same for every family + if family == "forensics": + add("no_request_behind", 0, card, [c for c in calls if c[0] in FREE_TOOLS]) + else: + add("no_request_behind", 0, card, []) + last = max(i for i, c in enumerate(calls) if c[0] not in FREE_TOOLS) + add("edited_call_log", 0, card, calls, reply_calls=calls[:last] + calls[last + 1:]) + if check.get("budget"): + add("over_budget", 0, card, calls + [comp[0]] * (check["budget"] - len(comp) + 1)) + else: + skipped.append(("over_budget", "the task has no call budget")) + forbidden = check.get("forbidden") or [] + if forbidden: + tool = "find_flip" if "find_flip" in forbidden else forbidden[0] + add("forbidden_tool", 0, card, [(tool, {})] + list(calls)) + else: + skipped.append(("forbidden_tool", "the task rules out no tool")) + add("no_harness_log", 0, card, None, reply_calls=list(calls)) + edited_calls, problem = edited_log_file(calls, scratch) + add("harness_log_edited", 0, card, edited_calls, log_problem=problem) + add("stale_engine_tag", 0, card, calls, env_=stale(env)) + + if family in ("tradeoff", "chain_design"): + xp, xf = ref["passing"]["x"], ref["failing"]["x"] + parts = parts_of(env) + first, first_tool = parts[0] + shape = design_shape(check["design"]) + oid, proof = other_proof(env, others, first_tool) + bad = copy.deepcopy(card) + bad["passing"][first]["proof"] = proof + add("copied_proof_other_task", 0, bad, calls) + for name, x in (("nudged_figure", 0.5 * (xp + xf)), ("figure_plus_10_percent", xp * 1.1)): + design, changes = moved_design(env, card["passing"], x) + add(name, 0, dict(card, passing=design), apply_changes(calls, changes)) + design, changes = moved_design(env, card["passing"], 0.5 * (xp + xf)) + add("card_request_not_run", 0, card, apply_changes(calls, changes[:1])) + add("swapped_sides", 0, dict(card, passing=card["failing"], failing=card["passing"]), calls) + other = [c["id"] for c in check["constraints"] if c["id"] != card["binding"]] + add("binding_misnamed", 0, dict(card, binding=other[0] if other else "none"), calls) + bad = copy.deepcopy(card) + for key, _ in parts: + if bad["failing"][key]["proof"] != card["passing"][key]["proof"]: + bad["failing"][key]["proof"] = card["passing"][key]["proof"] + break + add("proof_from_other_design", 0, bad, calls) + add("failing_given_as_passing", 0, dict(card, passing=copy.deepcopy(card["failing"])), calls) + bad = copy.deepcopy(card) + bad["passing"][first]["proof"] = bad["passing"][first]["proof"].upper() + add("proof_uppercase", 0, bad, calls) + bad = copy.deepcopy(card) + bad["passing"][first]["request"]["arguments"]["note"] = "the same run" + changes = [(first_tool, card["passing"][first]["request"]["arguments"], bad["passing"][first]["request"]["arguments"])] + add("extra_argument", 0, bad, apply_changes(calls, changes)) + if card["failing"].get("stopped"): + bad = copy.deepcopy(card) + bad["failing"]["stopped"] = "SomeOtherStop" + add("stop_misnamed", 0, bad, calls) + if "step" in card["failing"]: + bad = copy.deepcopy(card) + bad["failing"]["step"] = card["failing"]["step"] + 1 + add("step_misnamed", 0, bad, calls) + else: + skipped.append(("step_misnamed", "the stop that binds is a solve's: it has no step")) + else: + skipped += [("stop_misnamed", "no stop binds"), ("step_misnamed", "no stop binds")] + if len(parts) > 1: + last = parts[-1][0] + bad = copy.deepcopy(card) + del bad["passing"][last] + add("missing_solve", 0, bad, calls) + # the later request handed the other design's earlier request and proof (or, staged, its later request) + bad = copy.deepcopy(card) + later = bad["passing"][last]["request"]["arguments"] + if shape in ("coupled", "continued"): + later["from"]["run_seal"] = card["failing"]["run"]["proof"] + later["from"]["request"] = copy.deepcopy(card["failing"]["run"]["request"]["arguments"]) + same = card["failing"]["run"]["proof"] == card["passing"]["run"]["proof"] + else: + bad["passing"][last] = copy.deepcopy(card["failing"][last]) + same = card["failing"][parts[0][0]]["proof"] == card["passing"][parts[0][0]]["proof"] + if same: + skipped.append(("solve_handed_other_run", "the two designs share one first request")) + else: + add("solve_handed_other_run", 0, bad, apply_changes(calls, [(parts[-1][1], card["passing"][last]["request"]["arguments"], + bad["passing"][last]["request"]["arguments"])]) + if shape in ("coupled", "continued") else calls) + else: + skipped += [("missing_solve", "a design of one request"), ("solve_handed_other_run", "a design of one request")] + if shape == "continued": + bad = copy.deepcopy(card) + start = bad["failing"]["next"]["request"]["arguments"]["initial"] + for k, v in start.items(): + if isinstance(v, float) and v != 0.0: + start[k] = float("%.9g" % v) + if start == card["failing"]["next"]["request"]["arguments"]["initial"]: + for k, v in start.items(): + if isinstance(v, float): + start[k] = v * (1 + 1e-12) if v else 1e-12 + break + add("next_start_rounded", 0, bad, apply_changes(calls, [("run_trajectory", card["failing"]["next"]["request"]["arguments"], + bad["failing"]["next"]["request"]["arguments"])])) + bad = copy.deepcopy(card) + bad["failing"]["next"]["proof"] = card["passing"]["next"]["proof"] + add("next_proof_copied", 0, bad, calls) + bad = copy.deepcopy(card) + bad["failing"]["next"]["request"]["arguments"]["segments"][-1]["steps"] += 1 + add("next_request_edited", 0, bad, apply_changes(calls, [("run_trajectory", card["failing"]["next"]["request"]["arguments"], + bad["failing"]["next"]["request"]["arguments"])])) + else: + skipped += [(v, "not a continued design") for v in ("next_start_rounded", "next_proof_copied", "next_request_edited")] + skipped += [(v, "forensics only") for v in ("every_row_genuine", "every_row_false", "every_row_false_true_reasons")] + + elif family == "budget": + xh, xs = ref["holds"]["x"], ref["stops"]["x"] + oid, proof = other_proof(env, others, check["tool"]) + bad = copy.deepcopy(card) + bad["holds"]["proof"] = proof + add("copied_proof_other_task", 0, bad, calls) + for name, x in (("nudged_figure", 0.5 * (xh + xs)), ("figure_plus_10_percent", xs * 1.1)): + side, changes = moved_budget(env, card["stops"], x) + add(name, 0, dict(card, stops=side), apply_changes(calls, changes)) + side, changes = moved_budget(env, card["stops"], 0.5 * (xh + xs)) + add("card_request_not_run", 0, card, apply_changes(calls, changes)) + add("swapped_sides", 0, dict(card, holds={k: v for k, v in card["stops"].items() if k != "stopped"}, + stops=dict(card["holds"], stopped=check["stop"])), calls) + bad = copy.deepcopy(card) + bad["stops"]["stopped"] = "SomeOtherStop" + add("stop_misnamed", 0, bad, calls) + bad = copy.deepcopy(card) + bad["stops"]["proof"] = card["holds"]["proof"] + add("proof_from_other_design", 0, bad, calls) + bad = copy.deepcopy(card) + bad["holds"]["proof"] = bad["holds"]["proof"].upper() + add("proof_uppercase", 0, bad, calls) + bad = copy.deepcopy(card) + bad["holds"]["request"]["arguments"]["note"] = "the same run" + add("extra_argument", 0, bad, apply_changes(calls, [(check["tool"], card["holds"]["request"]["arguments"], + bad["holds"]["request"]["arguments"])])) + skipped += [(v, "not a budget card") for v in ("binding_misnamed", "failing_given_as_passing", "step_misnamed", + "missing_solve", "solve_handed_other_run", "every_row_genuine", + "every_row_false", "every_row_false_true_reasons", + "next_start_rounded", "next_proof_copied", "next_request_edited")] + else: + rows = [r["row"] for r in check["rows"]] + reasons = check.get("reasons") or ["value_altered"] + truth = ref["false_rows"] + if truth: + add("every_row_genuine", 0, {"false_rows": {}}, calls) + else: + skipped.append(("every_row_genuine", "the table has no false row: that is the right answer")) + add("every_row_false", 0, {"false_rows": {r: reasons[0] for r in rows}}, calls) + add("every_row_false_true_reasons", 0, {"false_rows": {r: truth.get(r, reasons[0]) for r in rows}}, calls) + skipped += [(v, "a forensics card carries no request or proof") for v in ( + "copied_proof_other_task", "nudged_figure", "figure_plus_10_percent", "card_request_not_run", "swapped_sides", + "binding_misnamed", "proof_from_other_design", "failing_given_as_passing", "proof_uppercase", "extra_argument", + "stop_misnamed", "step_misnamed", "missing_solve", "solve_handed_other_run", + "next_start_rounded", "next_proof_copied", "next_request_edited")] + return out, skipped + + +def ensure_reference(env, folder, engine): + reply_path = os.path.join(folder, env["id"] + ".txt") + log_path = os.path.join(folder, env["id"] + ".harness.jsonl") + if os.path.isfile(reply_path) and os.path.isfile(log_path): + return + from run_reference import proxied, reference_reply + verifier = proxied(engine, log_path) + try: + reply, calls = reference_reply(env, verifier) + finally: + close_verifier(verifier) + open(reply_path, "w", encoding="utf-8").write(reply + "\n") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--environments", required=True) + parser.add_argument("--reference", required=True) + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--out") + args = parser.parse_args() + environments = load_environments(args.environments) + os.makedirs(args.reference, exist_ok=True) + for env in environments: + ensure_reference(env, args.reference, args.engine) + honest = {} + for env in environments: + card, problem = read_card(open(os.path.join(args.reference, env["id"] + ".txt"), encoding="utf-8").read()) + calls, log_problem = read_harness_log(os.path.join(args.reference, env["id"] + ".harness.jsonl")) + if problem or log_problem or calls is None: + sys.exit("the honest reference of %s cannot be read: %s" % (env["id"], problem or log_problem or "no harness log")) + honest[env["id"]] = (card, calls) + others = [(i, c) for i, (c, _) in honest.items()] + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + verifier = open_verifier(args.engine) + rows, failures, by_vector = [], 0, {} + scratch = tempfile.mkdtemp(prefix="ztp_cheats_") + try: + for env in environments: + card, calls = honest[env["id"]] + replay = Replay(verifier) + built, skipped = vectors(env, card, calls, others, scratch) + for name, expect, env_, card_, calls_, reply_calls, log_problem in built: + row = score(env_, "A reply.\n\n" + json.dumps(card_), replay, calls_, reply_calls, "harness", log_problem) + ok = (row["reward"] == 1 and row["graded"] == 1.0) if expect else (row["reward"] == 0 and row["graded"] == 0.0) + failures += not ok + one = {"task": env["id"], "family": env["family"], "vector": name, "applies": True, "expect": expect, + "reward": row["reward"], "graded": row["graded"], "verdict": row["verdict"], "reason": row["reason"], "ok": ok} + rows.append(one) + tally = by_vector.setdefault(name, [0, 0, 0]) + tally[0] += 1 + tally[1] += not ok + print("%-4s %-52s %-30s reward %d graded %.4f %s" % ("ok" if ok else "FAIL", env["id"], name, row["reward"], + row["graded"], (row["reason"] or "")[:110]), flush=True) + for name, why in skipped: + rows.append({"task": env["id"], "family": env["family"], "vector": name, "applies": False, "why": why}) + by_vector.setdefault(name, [0, 0, 0])[2] += 1 + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + print("\n%-30s %6s %6s %6s" % ("vector", "tasks", "fail", "n/a")) + for name in sorted(by_vector): + print("%-30s %6d %6d %6d" % (name, *by_vector[name])) + scored = [r for r in rows if r["applies"]] + print("\n%d tasks, %d scored attempts (%d honest controls, %d cheats); %d failures" % ( + len(environments), len(scored), sum(1 for r in scored if r["expect"]), sum(1 for r in scored if not r["expect"]), failures)) + sys.exit(1 if failures else 0) + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/run_naive.py b/sample/scorer/run_naive.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ccc29abc9ddf51103db6cfd37254367bddbb1a --- /dev/null +++ b/sample/scorer/run_naive.py @@ -0,0 +1,175 @@ +"""A one-call agent: one forward request at a plausible default, and its answer reported. + + python3 run_naive.py --engine ENGINE --environments F --out DIR [--only id,id] + +It shows what a single tool call earns on a set. For a tradeoff or chain_design environment it sends +one run at the middle of the design's range (no solve: one call) and gives it as both designs; a staged design +sends its first stage's request that way, and a solve design a solve. For a +budget environment it sends the task's request at the middle of the stated span and gives it as both +sides, naming the task's stop. For a forensics table it sends the first row's request and calls every +row genuine. Calls go through harness/mcp_log_proxy.py, as in run_reference.py. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + python3 run_naive.py --gate DIR --environments F --scores F + +--gate reads what the run left. A task with no reply, no logged call, or no score row, or a score of "the reply is empty", +stops it with exit 1: a 0 with nothing behind it is not a one-call score. It prints the counts, solve-shape rows and calls +the verifier answered with an error among them. + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import math +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from run_reference import proxied # noqa: E402 +from score import close_verifier, load_environments, open_verifier, set_path # noqa: E402 + +DEFAULTS = {"aerospace/capsule_stardust": 8.21, "energy/reactor_triga_jsi": 2.5, "energy/reactor_spert3": 1.0, + "energy/cell_2170_model3": 5.0, "energy/grid_gb": 1000.0} + + +def middle(env, spec): + if spec.get("range"): + return 0.5 * sum(spec["range"]) + if env["models"][0] in DEFAULTS: + return DEFAULTS[env["models"][0]] + return float(env["reference"]["boundary"]) * 0.9 # a guess near the answer, one call only + + +def naive_reply(env, verifier): + calls = [] + family = env["family"] + if family in ("tradeoff", "chain_design"): + spec = env["check"]["design"] + var = spec["variable"] + if spec.get("stages") or spec.get("tool") == "solve" or spec.get("kind") == "solve": + # a staged design has no check.design.template (its first stage is sent), and a solve design is sent as a solve, not a run + key, tool, template = (spec["stages"][0]["key"], spec["stages"][0]["tool"], spec["stages"][0]["template"]) if spec.get("stages") else ("solve", "solve", spec["template"]) + q = copy.deepcopy(template) + if not spec.get("stages") or var.get("stage") == key: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, middle(env, spec)) + calls.append({"tool": tool, "arguments": q}) + body, is_error = verifier.call_json(tool, q) + proof = (body.get("run_seal") or body.get("solution_seal")) if isinstance(body, dict) else None + one = {key: {"request": {"tool": tool, "arguments": q}, "proof": proof}} + card = {"passing": one, "failing": one, "binding": env["check"]["constraints"][0]["id"]} + return "One request at the middle of the range.\n\n" + json.dumps(card), calls + run = copy.deepcopy(spec["template"]) + if var["kind"] == "entry_angle_deg": + g = math.radians(middle(env, spec)) + run["initial"]["radial_speed_m_s"] = -var["speed_m_s"] * math.sin(g) + run["initial"]["transverse_speed_m_s"] = var["speed_m_s"] * math.cos(g) + elif var.get("on", "run") == "run" and var["path"].startswith("initial.start_temperature_k"): + set_path(run, var["path"], 296.15) + elif var.get("on", "run") == "run": + value = middle(env, spec) + for place in [var["path"]] + list(var.get("also") or []): + set_path(run, place, value) + calls.append({"tool": "run_trajectory", "arguments": run}) + body, is_error = verifier.call_json("run_trajectory", run) + proof = body.get("run_seal") if isinstance(body, dict) else None + one = {"run": {"request": {"tool": "run_trajectory", "arguments": run}, "proof": proof}} + card = {"passing": one, "failing": one, "binding": env["check"]["constraints"][0]["id"]} + words = "One run at the default design." + elif family == "budget": + lo, hi = env["reference"].get("span") or (env["reference"]["boundary"] * 0.9, env["reference"]["boundary"] * 1.1) + request = copy.deepcopy(env["check"]["template"]) + for place in [env["check"]["variable"]] + list(env["check"].get("also") or []): + set_path(request, place, 0.5 * (lo + hi)) + calls.append({"tool": env["check"]["tool"], "arguments": request}) + body, is_error = verifier.call_json(env["check"]["tool"], request) + proof = (body.get("run_seal") or body.get("solution_seal")) if isinstance(body, dict) else None + side = {"request": {"tool": env["check"]["tool"], "arguments": request}, "proof": proof} + card = {"holds": side, "stops": dict(side, stopped=env["check"]["stop"])} + words = "One run at the middle of the span." + else: + first = env["check"]["rows"][0]["request"] + calls.append(first) + verifier.call_json(first["tool"], first["arguments"]) + card = {"false_rows": {}} + words = "The first row came back; every row is taken as genuine." + return words + "\n\n" + json.dumps(card), calls + + +def gate(folder, environments_path, scores_path): + environments = load_environments(environments_path) + scores = {} + if os.path.isfile(scores_path): + with open(scores_path, encoding="utf-8") as f: + scores = {r["id"]: r for r in (json.loads(line) for line in f if line.strip())} + missing, errors, solve_shape, staged = [], 0, 0, 0 + for env in environments: + tid = env["id"] + spec = env["check"].get("design") or {} + staged += bool(spec.get("stages")) + solve_shape += spec.get("tool") == "solve" or spec.get("kind") == "solve" or env["check"].get("tool") == "solve" + reply = os.path.join(folder, tid + ".txt") + log = os.path.join(folder, tid + ".harness.jsonl") + lines = [] + if os.path.isfile(log): + with open(log, encoding="utf-8") as f: + lines = [json.loads(line) for line in f if line.strip()] + errors += sum(1 for line in lines if line.get("is_error")) + row = scores.get(tid) + if not os.path.isfile(reply) or not open(reply, encoding="utf-8").read().strip(): + missing.append(tid + " (no reply)") + elif not lines: + missing.append(tid + " (no call)") + elif row is None: + missing.append(tid + " (no score)") + elif row.get("reason") == "the reply is empty": + missing.append(tid + " (empty reply)") + rows = [scores[e["id"]] for e in environments if e["id"] in scores] + print("one-call agent: replied on %d of %d; reward above 0 on %d, graded above 0 on %d; solve-shape rows %d, staged rows %d; calls answered with an error %d" % ( + len(environments) - len(missing), len(environments), sum(1 for r in rows if r.get("reward")), sum(1 for r in rows if r.get("graded")), solve_shape, staged, errors)) + if missing: + sys.exit("NOT a one-call score: " + ", ".join(missing[:8])) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true") + parser.add_argument("--gate", metavar="DIR") + parser.add_argument("--scores") + args = parser.parse_args() + if args.gate: + return gate(args.gate, args.environments, args.scores or "") + if not args.engine or not args.out: + parser.error("give --engine and --out") + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = naive_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/run_reference.py b/sample/scorer/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/scorer/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/score.py b/sample/scorer/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/scorer/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/scorer/ztp_mcp.py b/sample/scorer/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/scorer/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/scorer/ztp_open_bridge.py b/sample/scorer/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/scorer/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/hud_taskset.json b/sample/tasks/harbor/hud_taskset.json new file mode 100644 index 0000000000000000000000000000000000000000..723b9235b6776c72322f9b378679e586e2d01621 --- /dev/null +++ b/sample/tasks/harbor/hud_taskset.json @@ -0,0 +1,214 @@ +{ + "format": "Harbor task directories, for HUD's Harbor import", + "rests_on": "HUD imports Harbor tasks; this file indexes them", + "dataset": "zero-trust-physics-sample-nuclear-fusion@2026-11-13", + "hud_export": "tasks/hud/tasks", + "hud_runtime": { + "runs_as_shipped": false, + "harbor_tasks": "HUD's adapter (hud 0.6.21) takes these Harbor directories, but they declare a stdio MCP server, which HUD's agents are not given: to run a task on HUD use tasks/hud/tasks.", + "export": "tasks/hud/tasks takes HUD's adapter (hud 0.6.21) and its proxy and grader images have run with no route out. HUD's hosted runtime has not run these tasks with an agent.", + "docs": "https://docs.hud.ai/v6/experimental/harbor" + }, + "tasks": [ + { + "id": "g5r8-bs-mast-2seg-drift-down-wall-b4", + "harbor_path": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4", + "family": "budget", + "kind": "budgeted_search", + "prompt_file": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md", + "prompt": "MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number).\n\nFind it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V.\n\nThe request, with the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"holds\": {\"request\": ..., \"proof\": ...}, \"stops\": {\"request\": ..., \"proof\": ..., \"stopped\": \"\"}}\n\nholds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.\n\nAlso write that answer card, by itself, to the file `/app/answer.json`.\n", + "grader": { + "command": "bash /tests/test.sh", + "file": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh", + "runs_in": "a fresh copy of the task image (environment_mode separate)", + "reward_file": "/logs/verifier/reward.json", + "scores": [ + "reward", + "correct", + "proofs_hold" + ] + }, + "mcp_servers": [ + { + "name": "verifier", + "transport": "stdio", + "command": "/usr/local/bin/mcp_stdio", + "args": [] + } + ], + "hud_export": "tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4", + "artifacts": [ + "/app/answer.json", + "/app/calls.jsonl", + "/logs/agent/trajectory.json" + ], + "engine": { + "source": "https://github.com/johnkruze/zero-trust-physics-engine", + "tag": "v0.15.3", + "commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "sha256": "a3c5fedfff586aae588a8822440726054753b49dd3d8d30b1a582283873a8e16" + }, + { + "id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "harbor_path": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "family": "chain_design", + "kind": "chained_design", + "prompt_file": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md", + "prompt": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"jet\": {\"request\": ..., \"proof\": ...}, \"slice\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"jet\": {\"request\": ..., \"proof\": ...}, \"slice\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\nEach design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries \"stopped\": the stop's name exactly as the verifier gives it, and, for a run, \"step\": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.\n\nAlso write that answer card, by itself, to the file `/app/answer.json`.\n", + "grader": { + "command": "bash /tests/test.sh", + "file": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh", + "runs_in": "a fresh copy of the task image (environment_mode separate)", + "reward_file": "/logs/verifier/reward.json", + "scores": [ + "reward", + "correct", + "proofs_hold" + ] + }, + "mcp_servers": [ + { + "name": "verifier", + "transport": "stdio", + "command": "/usr/local/bin/mcp_stdio", + "args": [] + } + ], + "hud_export": "tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "artifacts": [ + "/app/answer.json", + "/app/calls.jsonl", + "/logs/agent/trajectory.json" + ], + "engine": { + "source": "https://github.com/johnkruze/zero-trust-physics-engine", + "tag": "v0.15.3", + "commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "sha256": "38166ae374f84840ffe9ec105a7057b5e9feeeda363963c710537fee47913492" + }, + { + "id": "g5r10-dl-dt4-core-te-fastshare-pion", + "harbor_path": "tasks/g5r10-dl-dt4-core-te-fastshare-pion", + "family": "tradeoff", + "kind": "design_to_limit", + "prompt_file": "tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md", + "prompt": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"solve\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"solve\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\nEach design is one solve: leave out \"run\". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.\n\nAlso write that answer card, by itself, to the file `/app/answer.json`.\n", + "grader": { + "command": "bash /tests/test.sh", + "file": "tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh", + "runs_in": "a fresh copy of the task image (environment_mode separate)", + "reward_file": "/logs/verifier/reward.json", + "scores": [ + "reward", + "correct", + "proofs_hold" + ] + }, + "mcp_servers": [ + { + "name": "verifier", + "transport": "stdio", + "command": "/usr/local/bin/mcp_stdio", + "args": [] + } + ], + "hud_export": "tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion", + "artifacts": [ + "/app/answer.json", + "/app/calls.jsonl", + "/logs/agent/trajectory.json" + ], + "engine": { + "source": "https://github.com/johnkruze/zero-trust-physics-engine", + "tag": "v0.15.3", + "commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "sha256": "b6676a75309f43c17408adbc9c99c3c293c2f4815860e2f604b10565b383b911" + }, + { + "id": "g5r8-dl-jet-tritium-rich-dome-hotion", + "harbor_path": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion", + "family": "tradeoff", + "kind": "design_to_limit", + "prompt_file": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md", + "prompt": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"passing\": {\"run\": {\"request\": ..., \"proof\": ...}, \"solve\": {\"request\": ..., \"proof\": ...}}, \"failing\": {\"run\": {\"request\": ..., \"proof\": ...}, \"solve\": {\"request\": ..., \"proof\": ...}}, \"binding\": \"\"}\n\npassing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out \"solve\" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries \"stopped\": the stop's name exactly as the verifier gives it, and \"step\": the last step its run is sealed to (steps_landed), a whole number: {\"run\": {...}, \"stopped\": \"\", \"step\": }. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.\n\nAlso write that answer card, by itself, to the file `/app/answer.json`.\n", + "grader": { + "command": "bash /tests/test.sh", + "file": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh", + "runs_in": "a fresh copy of the task image (environment_mode separate)", + "reward_file": "/logs/verifier/reward.json", + "scores": [ + "reward", + "correct", + "proofs_hold" + ] + }, + "mcp_servers": [ + { + "name": "verifier", + "transport": "stdio", + "command": "/usr/local/bin/mcp_stdio", + "args": [] + } + ], + "hud_export": "tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion", + "artifacts": [ + "/app/answer.json", + "/app/calls.jsonl", + "/logs/agent/trajectory.json" + ], + "engine": { + "source": "https://github.com/johnkruze/zero-trust-physics-engine", + "tag": "v0.15.3", + "commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "sha256": "78c94da3b5a9a704309f8136e247e889e454a4f7c0192f1d677eff8b3dc16ce2" + }, + { + "id": "g5-bs-pb11-weakest-field-that-holds-b4", + "harbor_path": "tasks/g5-bs-pb11-weakest-field-that-holds-b4", + "family": "budget", + "kind": "budgeted_search", + "prompt_file": "tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md", + "prompt": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.\n\nYou have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card.\n\nEnd your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {\"tool\": \"\", \"arguments\": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.\n\nThe card:\n{\"holds\": {\"request\": ..., \"proof\": ...}, \"stops\": {\"request\": ..., \"proof\": ..., \"stopped\": \"\"}}\n\nholds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.\n\nAlso write that answer card, by itself, to the file `/app/answer.json`.\n", + "grader": { + "command": "bash /tests/test.sh", + "file": "tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh", + "runs_in": "a fresh copy of the task image (environment_mode separate)", + "reward_file": "/logs/verifier/reward.json", + "scores": [ + "reward", + "correct", + "proofs_hold" + ] + }, + "mcp_servers": [ + { + "name": "verifier", + "transport": "stdio", + "command": "/usr/local/bin/mcp_stdio", + "args": [] + } + ], + "hud_export": "tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4", + "artifacts": [ + "/app/answer.json", + "/app/calls.jsonl", + "/logs/agent/trajectory.json" + ], + "engine": { + "source": "https://github.com/johnkruze/zero-trust-physics-engine", + "tag": "v0.15.3", + "commit": "664d68f426ccdfd0159e5f91857edba3872390d1" + }, + "sha256": "48138b19251be5ea4e2bfe91e12eeb1885ca03583a3227484aec658e1657bc09" + } + ], + "hud_import": { + "command": "hud harbor import tasks/harbor/tasks --taskset ", + "docs": "https://docs.hud.ai/platform/harbor-import", + "gives": "browse, compare and QA on HUD; HUD does not run imported Harbor tasks" + } +} \ No newline at end of file diff --git a/sample/tasks/harbor/registry.json b/sample/tasks/harbor/registry.json new file mode 100644 index 0000000000000000000000000000000000000000..4719df2cbeb3dbdc3dcd63554b76e94c4e32e5e8 --- /dev/null +++ b/sample/tasks/harbor/registry.json @@ -0,0 +1,29 @@ +[ + { + "name": "zero-trust-physics-sample-nuclear-fusion", + "version": "2026-11-13", + "description": "Free sample of Protocol Company's Nuclear and Fusion Domain Pack: 5 multi-step physics environments (two budgeted searches, two designs to a limit, a chained design), each scored by a program on the Zero-Trust Physics verifier (v0.15.3).", + "tasks": [ + { + "name": "g5r8-bs-mast-2seg-drift-down-wall-b4", + "path": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4" + }, + { + "name": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "path": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7" + }, + { + "name": "g5r10-dl-dt4-core-te-fastshare-pion", + "path": "tasks/g5r10-dl-dt4-core-te-fastshare-pion" + }, + { + "name": "g5r8-dl-jet-tritium-rich-dome-hotion", + "path": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion" + }, + { + "name": "g5-bs-pb11-weakest-field-that-holds-b4", + "path": "tasks/g5-bs-pb11-weakest-field-that-holds-b4" + } + ] + } +] diff --git a/sample/tasks/harbor/task_checksums.json b/sample/tasks/harbor/task_checksums.json new file mode 100644 index 0000000000000000000000000000000000000000..90cf6856f3fe323dc991500065f7ad3e98c69fb1 --- /dev/null +++ b/sample/tasks/harbor/task_checksums.json @@ -0,0 +1,45 @@ +{ + "algorithm": "sha256 and sha384 over every file of the task: relative path, NUL, bytes, in sorted path order", + "tasks": { + "g5r8-bs-mast-2seg-drift-down-wall-b4": { + "path": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4", + "sha256": "e0826cc0cd1ba0d958a2118e2e6054d7404173084ced03544bf1918ba9731691", + "sha384": "a34ec4f8d8058946f1cef9ae7d3a1d6a24ca3822b1c3286b47b6efa24c3149428e6ed5d7a7fcddda5554f6522000414f", + "row_sha256": "092ec55ee295b8af2d1cf779200a6dc60172dd0ee67283ee9f017caab2d3b212", + "row_sha384": "77b3ba995864f265e7186fb9f4791d340d240d4c36574bcf5671349cc4428169028d4db1ada207de2f9891125ba85579", + "files": 18 + }, + "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7": { + "path": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "sha256": "958bed087017c9a4f370b5c69ed1abebd0d0bfb79f8e2cf894b7060a19cebd42", + "sha384": "a9301e908bb8c1342136be3b132d546cbbbea97f7614588eb914a625a548808b1c11103155ce117b326856d961cb58a7", + "row_sha256": "d194f40019bd8b080b87f1395255cc1e50051d0c74184a54a7321a1d342b856e", + "row_sha384": "8b17f526b9a5a7e10c7b8e0f188d914d6edf1700c7e7774384f27ffaef202fdf02a8c8f0eb348ba95d5774536e9d16d6", + "files": 18 + }, + "g5r10-dl-dt4-core-te-fastshare-pion": { + "path": "tasks/g5r10-dl-dt4-core-te-fastshare-pion", + "sha256": "4ba865115a33097373b25ad9ef711599070de1325cb94719019290eb814b9adf", + "sha384": "861d5e9203fb3aa9db969f9d8593008156aa5b7634cf9bba49b38a4d0277a22211b1bae4963821ee7797b29a723f697c", + "row_sha256": "2a4ff9b2937f6ddda4826fbe69acd059c81f0f8479b302f764276546077a3578", + "row_sha384": "dff38389b003fd44aa38b910cfbc0e7a15dec6f90a93dacf47a7bfaaf61f52ff9165884b85d98f10a1b29d1ba3b5abad", + "files": 18 + }, + "g5r8-dl-jet-tritium-rich-dome-hotion": { + "path": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion", + "sha256": "b1e794f637f8dadcf19e79b8842ff8bafa3bc29633e2e2d5d449bbd89a0b83fe", + "sha384": "88a16bff735d10d1a55b2f5b904d5cdac4acd7ad1cd20b334b4b54bff6a951f15c0b5fbe5ecbf7b7ade2975beaa6f029", + "row_sha256": "c82e66ac5a91d042226c4349093ad64eee50931aa05a1519989640cc8e9e5c84", + "row_sha384": "283028af98c4ce3b8b773a6730813d39ab67d25df6834633949d3c6f70460662252e9643bce0ed4fc1bb01703e78762a", + "files": 18 + }, + "g5-bs-pb11-weakest-field-that-holds-b4": { + "path": "tasks/g5-bs-pb11-weakest-field-that-holds-b4", + "sha256": "8ab36fa23d330f242b50a0148a289882c85cc9e5c9ecb80f5c18646d20557a49", + "sha384": "092366e77932e8a6ea1010551ab9047ca39cfc438b71649fc184ac1c40fa2044e636d6b45dcbdb674ac25f7d8ac6716d", + "row_sha256": "32598bba76e342a660ec16c538a8ecc71dd2fda8135d777220482c3cae716645", + "row_sha384": "04f0b6af4e7588711ebed7a19b4ff9e4a6aa8425cb3562f8c5afaac7b30adc21e271535779d16aa2feba65dd629dfe39", + "files": 18 + } + } +} diff --git a/sample/tasks/harbor/task_checksums.sha256 b/sample/tasks/harbor/task_checksums.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..832f858ccad5dfa1c7e51b9625bda1596de42202 --- /dev/null +++ b/sample/tasks/harbor/task_checksums.sha256 @@ -0,0 +1,5 @@ +e0826cc0cd1ba0d958a2118e2e6054d7404173084ced03544bf1918ba9731691 tasks/g5r8-bs-mast-2seg-drift-down-wall-b4 +958bed087017c9a4f370b5c69ed1abebd0d0bfb79f8e2cf894b7060a19cebd42 tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7 +4ba865115a33097373b25ad9ef711599070de1325cb94719019290eb814b9adf tasks/g5r10-dl-dt4-core-te-fastshare-pion +b1e794f637f8dadcf19e79b8842ff8bafa3bc29633e2e2d5d449bbd89a0b83fe tasks/g5r8-dl-jet-tritium-rich-dome-hotion +8ab36fa23d330f242b50a0148a289882c85cc9e5c9ecb80f5c18646d20557a49 tasks/g5-bs-pb11-weakest-field-that-holds-b4 diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..568742bebe61fc9c90daad15a6ed51c93a294086 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile @@ -0,0 +1,14 @@ +# Harbor environment image for Zero-Trust Physics release v0.15.3 (commit 664d68f4). +# Public 5-crate Rust engine reference source is at https://github.com/johnkruze/zero-trust-physics-engine (tag v0.15.2); +# read-only source audit of the pack verifier build is available under NDA (https://zerotrustphysics.com/offers/#licence). +# In this free evaluation sample, /usr/local/bin/mcp_stdio bridges JSON-RPC over stdio to the public MCP endpoint +# (ztp_open_bridge.py), and the scorer verifies release 0.15.3 version and kernel invariants on every reply. +# Paid Domain Packs ship compiled static Linux/macOS rollout binaries for --network none execution. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +ARG ZTP_VERIFIER_URL=https://mcp.zerotrustphysics.com/mcp/open +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "%s"\n' "$ZTP_VERIFIER_URL" > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3de4cf657e99f25799630e58e490b78ddb4ff1f6 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md @@ -0,0 +1,19 @@ +A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla. + +Find it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T. + +The request, with the one input you change: +{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": "", "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/chainlib.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack(" the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/run_reference.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/score.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/solve.sh b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..72cbff6116b4373dcb5a275b10f1ea91c863186a --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Harbor's oracle agent copies solution/ to /solution and runs this. +# +# It makes the reference answer card here, on the verifier of this machine: the +# dataset's own run_reference.py sends this environment's reference requests to +# /usr/local/bin/mcp_stdio (and, for a chained design, hands each run to its solve +# through the task's coupling) and writes a reply that ends with the card. The card +# is saved where the instruction asks for it, and the calls it made beside it, so +# that a call-budget environment is scored on them: the oracle runs no model, and +# Harbor's record of its run holds no tool call. +# +# The four paths can be moved with environment variables, so this runs outside a container. +set -euo pipefail +HERE="${ZTP_SOLUTION_DIR:-$(cd "$(dirname "$0")" && pwd)}" +ENGINE="${ZTP_ENGINE:-/usr/local/bin/mcp_stdio}" +ANSWER="${ZTP_ANSWER_FILE:-/app/answer.json}" +CALLS="${ZTP_CALLS_FILE:-/app/calls.jsonl}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +cd "$HERE" +FLAGS=() +grep -q -- '"--environments"' run_reference.py && FLAGS+=(--environments data/environments.jsonl) +grep -q -- '"--direct"' run_reference.py && FLAGS+=(--direct) # no proxy in here: the oracle's own call log +python3 -B run_reference.py --engine "$ENGINE" ${FLAGS[@]+"${FLAGS[@]}"} --out "$WORK/replies" +REPLY="$(ls "$WORK"/replies/*.txt)" # one environment here, so one reply +cat "$REPLY" +mkdir -p "$(dirname "$ANSWER")" "$(dirname "$CALLS")" +tail -n 1 "$REPLY" > "$ANSWER" +cp "$WORK"/replies/*.calls.jsonl "$CALLS" diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/ztp_mcp.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/solution/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1b6aec80b9b62904621bca2ef7d6625c8facf0b --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml @@ -0,0 +1,40 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", "/app/calls.jsonl", "/logs/agent/trajectory.json", "/logs/agent/oracle.txt"] + +[task] +name = "protocol-company/g5-bs-pb11-weakest-field-that-holds-b4" +version = "1.0.0" +description = "Budgeted search: a named physical stop bracketed to the task's width within the task's call budget, scored on the bracket and the call log." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "budgeted_search"] + +[metadata] +environment_id = "g5-bs-pb11-weakest-field-that-holds-b4" +family = "budget" +kind = "budgeted_search" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 1200.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +workdir = "/app" + +[[environment.mcp_servers]] +name = "verifier" +transport = "stdio" +command = "/usr/local/bin/mcp_stdio" +args = [] diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56b2bc42ad98e27839b60a61ac8e4aaa87966424 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile @@ -0,0 +1,11 @@ +# The grader's image: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio server at +# /usr/local/bin/mcp_stdio (a bridge to its address). +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests +RUN mkdir -p /logs/verifier /logs/agent /logs/artifacts /app +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc6404f0cfd0cad2fc7d7ecc19d24f334452816b --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "models": ["fusion_pb11_thermal"], "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", "task": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e4008f0a93d9c230856a9c0e0ecf5cd5cef1066 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Harbor runs this after the agent has finished, in a fresh copy of the image +# (task.toml: [verifier] environment_mode = "separate"). By then Harbor has +# copied tests/ to /tests and the declared artifacts, where they exist, to +# their own paths: /app/answer.json and /logs/agent/trajectory.json. +# grade.py writes /logs/verifier/reward.json. If the scorer itself fails it +# writes no reward and this script exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/grade.py" diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..568742bebe61fc9c90daad15a6ed51c93a294086 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile @@ -0,0 +1,14 @@ +# Harbor environment image for Zero-Trust Physics release v0.15.3 (commit 664d68f4). +# Public 5-crate Rust engine reference source is at https://github.com/johnkruze/zero-trust-physics-engine (tag v0.15.2); +# read-only source audit of the pack verifier build is available under NDA (https://zerotrustphysics.com/offers/#licence). +# In this free evaluation sample, /usr/local/bin/mcp_stdio bridges JSON-RPC over stdio to the public MCP endpoint +# (ztp_open_bridge.py), and the scorer verifies release 0.15.3 version and kernel invariants on every reply. +# Paid Domain Packs ship compiled static Linux/macOS rollout binaries for --network none execution. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +ARG ZTP_VERIFIER_URL=https://mcp.zerotrustphysics.com/mcp/open +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "%s"\n' "$ZTP_VERIFIER_URL" > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91b44ec309e62d2820c54d81cfd8f8c9b6ad1bd2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md @@ -0,0 +1,26 @@ +JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice. + +Find the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds. + +Constraints (id (the request it is read from): what, limit): +- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W +- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182 +- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit. +jet: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": "", "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}} +slice (it must converge): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": ["", 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}} + +Budget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "failing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/chainlib.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack("\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/run_reference.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/score.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/solve.sh b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..72cbff6116b4373dcb5a275b10f1ea91c863186a --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Harbor's oracle agent copies solution/ to /solution and runs this. +# +# It makes the reference answer card here, on the verifier of this machine: the +# dataset's own run_reference.py sends this environment's reference requests to +# /usr/local/bin/mcp_stdio (and, for a chained design, hands each run to its solve +# through the task's coupling) and writes a reply that ends with the card. The card +# is saved where the instruction asks for it, and the calls it made beside it, so +# that a call-budget environment is scored on them: the oracle runs no model, and +# Harbor's record of its run holds no tool call. +# +# The four paths can be moved with environment variables, so this runs outside a container. +set -euo pipefail +HERE="${ZTP_SOLUTION_DIR:-$(cd "$(dirname "$0")" && pwd)}" +ENGINE="${ZTP_ENGINE:-/usr/local/bin/mcp_stdio}" +ANSWER="${ZTP_ANSWER_FILE:-/app/answer.json}" +CALLS="${ZTP_CALLS_FILE:-/app/calls.jsonl}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +cd "$HERE" +FLAGS=() +grep -q -- '"--environments"' run_reference.py && FLAGS+=(--environments data/environments.jsonl) +grep -q -- '"--direct"' run_reference.py && FLAGS+=(--direct) # no proxy in here: the oracle's own call log +python3 -B run_reference.py --engine "$ENGINE" ${FLAGS[@]+"${FLAGS[@]}"} --out "$WORK/replies" +REPLY="$(ls "$WORK"/replies/*.txt)" # one environment here, so one reply +cat "$REPLY" +mkdir -p "$(dirname "$ANSWER")" "$(dirname "$CALLS")" +tail -n 1 "$REPLY" > "$ANSWER" +cp "$WORK"/replies/*.calls.jsonl "$CALLS" diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/solution/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d7dd96887efa38f3bc6d4cf5048fdc61edee740 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml @@ -0,0 +1,40 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", "/app/calls.jsonl", "/logs/agent/trajectory.json", "/logs/agent/oracle.txt"] + +[task] +name = "protocol-company/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7" +version = "1.0.0" +description = "Chained design: a design whose sealed run is handed on, to the next run of the same model (from) or to the next model through a coupling, scored by computing the chain again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "chained_design"] + +[metadata] +environment_id = "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7" +family = "chain_design" +kind = "chained_design" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +workdir = "/app" + +[[environment.mcp_servers]] +name = "verifier" +transport = "stdio" +command = "/usr/local/bin/mcp_stdio" +args = [] diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56b2bc42ad98e27839b60a61ac8e4aaa87966424 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile @@ -0,0 +1,11 @@ +# The grader's image: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio server at +# /usr/local/bin/mcp_stdio (a bridge to its address). +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests +RUN mkdir -p /logs/verifier /logs/agent /logs/artifacts /app +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bdf850df93407e342884032734f7d8cf8719dd3b --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "models": ["energy/tokamak_jet_dte1", "tokamak_dt_beam_target"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e4008f0a93d9c230856a9c0e0ecf5cd5cef1066 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Harbor runs this after the agent has finished, in a fresh copy of the image +# (task.toml: [verifier] environment_mode = "separate"). By then Harbor has +# copied tests/ to /tests and the declared artifacts, where they exist, to +# their own paths: /app/answer.json and /logs/agent/trajectory.json. +# grade.py writes /logs/verifier/reward.json. If the scorer itself fails it +# writes no reward and this script exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/grade.py" diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..568742bebe61fc9c90daad15a6ed51c93a294086 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile @@ -0,0 +1,14 @@ +# Harbor environment image for Zero-Trust Physics release v0.15.3 (commit 664d68f4). +# Public 5-crate Rust engine reference source is at https://github.com/johnkruze/zero-trust-physics-engine (tag v0.15.2); +# read-only source audit of the pack verifier build is available under NDA (https://zerotrustphysics.com/offers/#licence). +# In this free evaluation sample, /usr/local/bin/mcp_stdio bridges JSON-RPC over stdio to the public MCP endpoint +# (ztp_open_bridge.py), and the scorer verifies release 0.15.3 version and kernel invariants on every reply. +# Paid Domain Packs ship compiled static Linux/macOS rollout binaries for --network none execution. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +ARG ZTP_VERIFIER_URL=https://mcp.zerotrustphysics.com/mcp/open +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "%s"\n' "$ZTP_VERIFIER_URL" > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d3cf8bbdc75640e84cbfe557abaf83fb8f6fce98 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md @@ -0,0 +1,22 @@ +A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target). + +Find the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds. + +Constraints (id, what, limit): +- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J +- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W +Each design is one solve (leave out "run"): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": ["", 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}} + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/chainlib.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack("\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/run_reference.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/score.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/solve.sh b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..72cbff6116b4373dcb5a275b10f1ea91c863186a --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Harbor's oracle agent copies solution/ to /solution and runs this. +# +# It makes the reference answer card here, on the verifier of this machine: the +# dataset's own run_reference.py sends this environment's reference requests to +# /usr/local/bin/mcp_stdio (and, for a chained design, hands each run to its solve +# through the task's coupling) and writes a reply that ends with the card. The card +# is saved where the instruction asks for it, and the calls it made beside it, so +# that a call-budget environment is scored on them: the oracle runs no model, and +# Harbor's record of its run holds no tool call. +# +# The four paths can be moved with environment variables, so this runs outside a container. +set -euo pipefail +HERE="${ZTP_SOLUTION_DIR:-$(cd "$(dirname "$0")" && pwd)}" +ENGINE="${ZTP_ENGINE:-/usr/local/bin/mcp_stdio}" +ANSWER="${ZTP_ANSWER_FILE:-/app/answer.json}" +CALLS="${ZTP_CALLS_FILE:-/app/calls.jsonl}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +cd "$HERE" +FLAGS=() +grep -q -- '"--environments"' run_reference.py && FLAGS+=(--environments data/environments.jsonl) +grep -q -- '"--direct"' run_reference.py && FLAGS+=(--direct) # no proxy in here: the oracle's own call log +python3 -B run_reference.py --engine "$ENGINE" ${FLAGS[@]+"${FLAGS[@]}"} --out "$WORK/replies" +REPLY="$(ls "$WORK"/replies/*.txt)" # one environment here, so one reply +cat "$REPLY" +mkdir -p "$(dirname "$ANSWER")" "$(dirname "$CALLS")" +tail -n 1 "$REPLY" > "$ANSWER" +cp "$WORK"/replies/*.calls.jsonl "$CALLS" diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/solution/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62268dc0a31c6bfb341bf7980e2933892498eeb8 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml @@ -0,0 +1,40 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", "/app/calls.jsonl", "/logs/agent/trajectory.json", "/logs/agent/oracle.txt"] + +[task] +name = "protocol-company/g5r10-dl-dt4-core-te-fastshare-pion" +version = "1.0.0" +description = "Design to a limit: a design pushed to the edge of its physical limits, found by verifier runs and scored by computing both designs again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "design_to_limit"] + +[metadata] +environment_id = "g5r10-dl-dt4-core-te-fastshare-pion" +family = "tradeoff" +kind = "design_to_limit" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +workdir = "/app" + +[[environment.mcp_servers]] +name = "verifier" +transport = "stdio" +command = "/usr/local/bin/mcp_stdio" +args = [] diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56b2bc42ad98e27839b60a61ac8e4aaa87966424 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile @@ -0,0 +1,11 @@ +# The grader's image: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio server at +# /usr/local/bin/mcp_stdio (a bridge to its address). +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests +RUN mkdir -p /logs/verifier /logs/agent /logs/artifacts /app +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..609c085da2c2974c6a24cf9e0e3ac779716ceaa8 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "models": ["tokamak_dt_beam_target"], "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e4008f0a93d9c230856a9c0e0ecf5cd5cef1066 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Harbor runs this after the agent has finished, in a fresh copy of the image +# (task.toml: [verifier] environment_mode = "separate"). By then Harbor has +# copied tests/ to /tests and the declared artifacts, where they exist, to +# their own paths: /app/answer.json and /logs/agent/trajectory.json. +# grade.py writes /logs/verifier/reward.json. If the scorer itself fails it +# writes no reward and this script exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/grade.py" diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..568742bebe61fc9c90daad15a6ed51c93a294086 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile @@ -0,0 +1,14 @@ +# Harbor environment image for Zero-Trust Physics release v0.15.3 (commit 664d68f4). +# Public 5-crate Rust engine reference source is at https://github.com/johnkruze/zero-trust-physics-engine (tag v0.15.2); +# read-only source audit of the pack verifier build is available under NDA (https://zerotrustphysics.com/offers/#licence). +# In this free evaluation sample, /usr/local/bin/mcp_stdio bridges JSON-RPC over stdio to the public MCP endpoint +# (ztp_open_bridge.py), and the scorer verifies release 0.15.3 version and kernel invariants on every reply. +# Paid Domain Packs ship compiled static Linux/macOS rollout binaries for --network none execution. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +ARG ZTP_VERIFIER_URL=https://mcp.zerotrustphysics.com/mcp/open +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "%s"\n' "$ZTP_VERIFIER_URL" > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..109af2273bff043863d3e547ddacf338ca7c82f8 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md @@ -0,0 +1,19 @@ +MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number). + +Find it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V. + +The request, with the one input you change: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": ""}}], "record_every": 56}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/chainlib.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack(" the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/run_reference.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/score.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/solve.sh b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..72cbff6116b4373dcb5a275b10f1ea91c863186a --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Harbor's oracle agent copies solution/ to /solution and runs this. +# +# It makes the reference answer card here, on the verifier of this machine: the +# dataset's own run_reference.py sends this environment's reference requests to +# /usr/local/bin/mcp_stdio (and, for a chained design, hands each run to its solve +# through the task's coupling) and writes a reply that ends with the card. The card +# is saved where the instruction asks for it, and the calls it made beside it, so +# that a call-budget environment is scored on them: the oracle runs no model, and +# Harbor's record of its run holds no tool call. +# +# The four paths can be moved with environment variables, so this runs outside a container. +set -euo pipefail +HERE="${ZTP_SOLUTION_DIR:-$(cd "$(dirname "$0")" && pwd)}" +ENGINE="${ZTP_ENGINE:-/usr/local/bin/mcp_stdio}" +ANSWER="${ZTP_ANSWER_FILE:-/app/answer.json}" +CALLS="${ZTP_CALLS_FILE:-/app/calls.jsonl}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +cd "$HERE" +FLAGS=() +grep -q -- '"--environments"' run_reference.py && FLAGS+=(--environments data/environments.jsonl) +grep -q -- '"--direct"' run_reference.py && FLAGS+=(--direct) # no proxy in here: the oracle's own call log +python3 -B run_reference.py --engine "$ENGINE" ${FLAGS[@]+"${FLAGS[@]}"} --out "$WORK/replies" +REPLY="$(ls "$WORK"/replies/*.txt)" # one environment here, so one reply +cat "$REPLY" +mkdir -p "$(dirname "$ANSWER")" "$(dirname "$CALLS")" +tail -n 1 "$REPLY" > "$ANSWER" +cp "$WORK"/replies/*.calls.jsonl "$CALLS" diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/solution/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f808d20b73f23b61b02ac11fa916b6b1640b675d --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml @@ -0,0 +1,40 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", "/app/calls.jsonl", "/logs/agent/trajectory.json", "/logs/agent/oracle.txt"] + +[task] +name = "protocol-company/g5r8-bs-mast-2seg-drift-down-wall-b4" +version = "1.0.0" +description = "Budgeted search: a named physical stop bracketed to the task's width within the task's call budget, scored on the bracket and the call log." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "budgeted_search"] + +[metadata] +environment_id = "g5r8-bs-mast-2seg-drift-down-wall-b4" +family = "budget" +kind = "budgeted_search" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 1200.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +workdir = "/app" + +[[environment.mcp_servers]] +name = "verifier" +transport = "stdio" +command = "/usr/local/bin/mcp_stdio" +args = [] diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56b2bc42ad98e27839b60a61ac8e4aaa87966424 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile @@ -0,0 +1,11 @@ +# The grader's image: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio server at +# /usr/local/bin/mcp_stdio (a bridge to its address). +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests +RUN mkdir -p /logs/verifier /logs/agent /logs/artifacts /app +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b35031104cce374d00f88c4d124a360959bc6b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "kind": "budgeted_search", "models": ["energy/tokamak_vde_mast"], "real_thing": "Vertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep. Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.", "task": "MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number).\n\nFind it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V.\n\nThe request, with the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e4008f0a93d9c230856a9c0e0ecf5cd5cef1066 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Harbor runs this after the agent has finished, in a fresh copy of the image +# (task.toml: [verifier] environment_mode = "separate"). By then Harbor has +# copied tests/ to /tests and the declared artifacts, where they exist, to +# their own paths: /app/answer.json and /logs/agent/trajectory.json. +# grade.py writes /logs/verifier/reward.json. If the scorer itself fails it +# writes no reward and this script exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/grade.py" diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..568742bebe61fc9c90daad15a6ed51c93a294086 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile @@ -0,0 +1,14 @@ +# Harbor environment image for Zero-Trust Physics release v0.15.3 (commit 664d68f4). +# Public 5-crate Rust engine reference source is at https://github.com/johnkruze/zero-trust-physics-engine (tag v0.15.2); +# read-only source audit of the pack verifier build is available under NDA (https://zerotrustphysics.com/offers/#licence). +# In this free evaluation sample, /usr/local/bin/mcp_stdio bridges JSON-RPC over stdio to the public MCP endpoint +# (ztp_open_bridge.py), and the scorer verifies release 0.15.3 version and kernel invariants on every reply. +# Paid Domain Packs ship compiled static Linux/macOS rollout binaries for --network none execution. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +ARG ZTP_VERIFIER_URL=https://mcp.zerotrustphysics.com/mcp/open +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "%s"\n' "$ZTP_VERIFIER_URL" > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84c9e54cc76501f4dac621e95443b6d02587f298 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md @@ -0,0 +1,24 @@ +In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose. + +Find the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds. + +Constraints (id, what, limit): +- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W +- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J +- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is one run: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": "", "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}} +This task has no solve: leave "solve" out of each design. + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/chainlib.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack("\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/run_reference.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/score.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/solve.sh b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..72cbff6116b4373dcb5a275b10f1ea91c863186a --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Harbor's oracle agent copies solution/ to /solution and runs this. +# +# It makes the reference answer card here, on the verifier of this machine: the +# dataset's own run_reference.py sends this environment's reference requests to +# /usr/local/bin/mcp_stdio (and, for a chained design, hands each run to its solve +# through the task's coupling) and writes a reply that ends with the card. The card +# is saved where the instruction asks for it, and the calls it made beside it, so +# that a call-budget environment is scored on them: the oracle runs no model, and +# Harbor's record of its run holds no tool call. +# +# The four paths can be moved with environment variables, so this runs outside a container. +set -euo pipefail +HERE="${ZTP_SOLUTION_DIR:-$(cd "$(dirname "$0")" && pwd)}" +ENGINE="${ZTP_ENGINE:-/usr/local/bin/mcp_stdio}" +ANSWER="${ZTP_ANSWER_FILE:-/app/answer.json}" +CALLS="${ZTP_CALLS_FILE:-/app/calls.jsonl}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +cd "$HERE" +FLAGS=() +grep -q -- '"--environments"' run_reference.py && FLAGS+=(--environments data/environments.jsonl) +grep -q -- '"--direct"' run_reference.py && FLAGS+=(--direct) # no proxy in here: the oracle's own call log +python3 -B run_reference.py --engine "$ENGINE" ${FLAGS[@]+"${FLAGS[@]}"} --out "$WORK/replies" +REPLY="$(ls "$WORK"/replies/*.txt)" # one environment here, so one reply +cat "$REPLY" +mkdir -p "$(dirname "$ANSWER")" "$(dirname "$CALLS")" +tail -n 1 "$REPLY" > "$ANSWER" +cp "$WORK"/replies/*.calls.jsonl "$CALLS" diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/solution/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..11731189e1a5ac4daf8684fa6703b83d05d559e5 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml @@ -0,0 +1,40 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", "/app/calls.jsonl", "/logs/agent/trajectory.json", "/logs/agent/oracle.txt"] + +[task] +name = "protocol-company/g5r8-dl-jet-tritium-rich-dome-hotion" +version = "1.0.0" +description = "Design to a limit: a design pushed to the edge of its physical limits, found by verifier runs and scored by computing both designs again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "design_to_limit"] + +[metadata] +environment_id = "g5r8-dl-jet-tritium-rich-dome-hotion" +family = "tradeoff" +kind = "design_to_limit" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +workdir = "/app" + +[[environment.mcp_servers]] +name = "verifier" +transport = "stdio" +command = "/usr/local/bin/mcp_stdio" +args = [] diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56b2bc42ad98e27839b60a61ac8e4aaa87966424 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile @@ -0,0 +1,11 @@ +# The grader's image: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio server at +# /usr/local/bin/mcp_stdio (a bridge to its address). +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests +RUN mkdir -p /logs/verifier /logs/agent /logs/artifacts /app +WORKDIR /app diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9aa354005c7e2650fcb1a36ba986ae5c4e8564cf --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "models": ["energy/tokamak_jet_dte1"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", "task": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e4008f0a93d9c230856a9c0e0ecf5cd5cef1066 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Harbor runs this after the agent has finished, in a fresh copy of the image +# (task.toml: [verifier] environment_mode = "separate"). By then Harbor has +# copied tests/ to /tests and the declared artifacts, where they exist, to +# their own paths: /app/answer.json and /logs/agent/trajectory.json. +# grade.py writes /logs/verifier/reward.json. If the scorer itself fails it +# writes no reward and this script exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/grade.py" diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/harbor/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/set_door.py b/sample/tasks/hud/set_door.py new file mode 100644 index 0000000000000000000000000000000000000000..91e8f574138d1277f752cc45ee7b93903f435204 --- /dev/null +++ b/sample/tasks/hud/set_door.py @@ -0,0 +1,29 @@ +"""Point this HUD export at a keyed door, in your own copy, before you adapt or import it. + + python3 set_door.py --url https://YOUR-DOOR/mcp --key-file FILE FILE holds the key we give you at kickoff + +In every task it writes environment/.env (read by the proxy's service) and [verifier.env] in task.toml (read by the +grader). The agent's sandbox sees neither: its root is the task image, which holds neither file. The pack ships no key. +Do not commit or share the folder once this has run. Run it again with a new key to replace the old one. +""" +import argparse +import glob +import os +import re + +ap = argparse.ArgumentParser() +ap.add_argument("--url", required=True) +ap.add_argument("--key-file", required=True) +a = ap.parse_args() +key = open(a.key_file).read().strip() +if not re.fullmatch(r"[A-Za-z0-9_.-]+", key) or not re.fullmatch(r"https?://[^\s\"']+", a.url): + raise SystemExit("the key or the URL holds characters a key or a URL does not") +tomls = glob.glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tasks", "*", "task.toml")) +for toml in tomls: + with open(os.path.join(os.path.dirname(toml), "environment", ".env"), "w") as f: + f.write("ZTP_VERIFIER_URL=%s\nZTP_API_KEY=%s\n" % (a.url, key)) + text = re.sub(r"\n\[verifier\.env\]\n(?:[^\n]*\n)*?(?=\n\[|\Z)", "\n", open(toml).read()) + text = text.replace("\n[environment]\n", '\n[verifier.env]\nZTP_VERIFIER_URL = "%s"\nZTP_API_KEY = "%s"\n\n[environment]\n' % (a.url, key), 1) + with open(toml, "w") as f: + f.write(text) +print("%d tasks point at %s" % (len(tomls), a.url)) diff --git a/sample/tasks/hud/task_checksums.json b/sample/tasks/hud/task_checksums.json new file mode 100644 index 0000000000000000000000000000000000000000..007e744cd4c33eb73ef6c1f499a73833ac9481e8 --- /dev/null +++ b/sample/tasks/hud/task_checksums.json @@ -0,0 +1,35 @@ +{ + "algorithm": "sha256 and sha384 over every file of the task: relative path, NUL, bytes, in sorted path order", + "tasks": { + "g5r8-bs-mast-2seg-drift-down-wall-b4": { + "path": "tasks/g5r8-bs-mast-2seg-drift-down-wall-b4", + "sha256": "145719945b2af547e4d4f58d7d34dc0dac1d25b8cd961830d0a787dde50a1767", + "sha384": "906df684c0bae30aef783e1c0ad7859627b537addf3ca652e1316037be76e85e0fed13ac1da8ae5ccb12580a7399ee0d", + "files": 16 + }, + "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7": { + "path": "tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "sha256": "0d64037e279515f7ff20a1a0d8378ded6a93c594f24d6c0f101510b996371e40", + "sha384": "0f77810ffed51c24205ff8b38e647a4b1859d8a0360d4aefcfa0f55862df94db50a3083a3ba3628850c9c1cd9c214a5b", + "files": 16 + }, + "g5r10-dl-dt4-core-te-fastshare-pion": { + "path": "tasks/g5r10-dl-dt4-core-te-fastshare-pion", + "sha256": "fbe9903659231c9e5d117e14da7805a43b581050f512556aefef4041e24c7c96", + "sha384": "8b490bfec43fd33d94bdabcfa587616162f6696050ed264d1d8dab3fe7eb4ed583961602e1e48b78a7176f96e83ec5e9", + "files": 16 + }, + "g5r8-dl-jet-tritium-rich-dome-hotion": { + "path": "tasks/g5r8-dl-jet-tritium-rich-dome-hotion", + "sha256": "feb511d95f5467f8a35f75bde994cbfd824f737608ffe116520fa9371156f265", + "sha384": "8ad7081a7d733b7fdf1aa0adaedbdb7d60591a94e7f7e13fcea91e472d092c192b1b5c15c9dff821f5d1af0850568f5c", + "files": 16 + }, + "g5-bs-pb11-weakest-field-that-holds-b4": { + "path": "tasks/g5-bs-pb11-weakest-field-that-holds-b4", + "sha256": "07728f3f4da47f73475966821a7c3969197fae1ad8206b175b8808f65d126ec9", + "sha384": "7cbbca67b83eff79203b3068bc57285ae26df23be8e86288e514d5c59bb48cb90b308e87bfb4fbc0e8a87e86ba737e92", + "files": 16 + } + } +} diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f08794038f4a9efe7175ee5d469852f24ffb9a14 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's image in the HUD export. It holds no verifier, no bridge, no task row and no answer. HUD's agent reaches +# the verifier only through its MCP route to the verifier-proxy service, and its own sandbox has no network. +FROM python:3.12-slim-bookworm +WORKDIR /app diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/docker-compose.yaml b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c666cc38a72b0ef68240a82165d2c9c9cc93821 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/docker-compose.yaml @@ -0,0 +1,23 @@ +# The agent's container (main) and the logging proxy beside it. HUD's agent reaches the verifier only through the proxy, +# which records every tools/call in a log inside its own container; the grader takes that log over Docker, after the +# agent has ended. The volumes list is empty on purpose: the log shares no folder with main. +# environment/.env sets ZTP_VERIFIER_URL and ZTP_API_KEY for a keyed door (tasks/hud/set_door.py); no pack ships one. +services: + main: + depends_on: + verifier-proxy: + condition: service_healthy + verifier-proxy: + build: + context: ./proxy + expose: + - "8080" + environment: + ZTP_VERIFIER_URL: "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" + ZTP_API_KEY: "${ZTP_API_KEY:-}" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8080/health', timeout=3)"] + interval: 2s + timeout: 5s + retries: 15 + start_period: 1s diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/Dockerfile b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4295350a87a70b15b87dde5e928d6fb9f1eec58 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/Dockerfile @@ -0,0 +1,11 @@ +# The logging proxy in front of the Zero-Trust Physics verifier of release v0.15.3. It runs as its own user; only it can +# write the log, and the log's folder is shared with no other container. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py ztp_log_proxy.py /usr/local/lib/ztp/ +RUN useradd --system --uid 10001 --no-create-home ztp-proxy \ + && mkdir -p /var/log/ztp-verifier && chown ztp-proxy /var/log/ztp-verifier && chmod 700 /var/log/ztp-verifier +USER ztp-proxy +EXPOSE 8080 +ENTRYPOINT ["python3", "-B", "/usr/local/lib/ztp/ztp_log_proxy.py", "--log", "/var/log/ztp-verifier/calls.jsonl", "--port", "8080"] diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_log_proxy.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4e5ccd8521cc2773870317510db60b2184998 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_log_proxy.py @@ -0,0 +1,190 @@ +"""The verifier over MCP HTTP, with every tools/call written to a log the caller cannot reach. + + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] --program PATH the verifier as a local program, needing no network + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] [--url URL] URL default: ZTP_VERIFIER_URL, else the open address + +POST /mcp takes one JSON-RPC message. What goes on to the verifier is the parsed message written out again, so what the +log says and what the verifier computes cannot differ. A list of messages is refused (400), as is a method a verifier +client has no use for (-32601): nothing computes off the log. Each tools/call is on the log, fsynced, before it is +forwarded, so a call counts whether or not its answer comes back. Busy answers and retries are the bridge's (ztp_open_bridge.py): +one call, one line. GET /health says 200 and nothing else. Every other route is 404 or 405: no route reads the log. + +The log's lines have the form of the harness's logging proxy, so score.py's chain check reads them: +{"arguments", "chain", "jsonrpc_id", "seq", "tool", "ts_request"}. chain is the SHA-384 of the previous chain and this +line. An edit to a line, or a line taken out, breaks every chain after it. + +ZTP_API_KEY, when set, is sent to the verifier's address; the caller never sees it. Standard library only. Licence: Apache-2.0. +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import subprocess +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +try: + import ztp_open_bridge as B # noqa: E402 +except ImportError: # an offline image holds no bridge + B = None + +MAX_BODY = 4194304 # the verifier's own largest body +TO_VERIFIER = ("initialize", "ping", "server/discover", "tools/list", "tools/call", "notifications/initialized") +PASSED_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name") + + +def chain_of(previous, entry): + return hashlib.sha384(((previous or "") + json.dumps(entry, sort_keys=True, separators=(",", ":"))).encode("utf-8")).hexdigest() + + +class Log: + def __init__(self, path): + self.path, self.lock, self.seq, self.chain = path, threading.Lock(), 0, None + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.close(fd) + + def call(self, message): + params = message["params"] + entry = {"jsonrpc_id": message.get("id"), "tool": params["name"], "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with self.lock: + self.seq += 1 + entry["seq"] = self.seq + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + + +def refusal(message, code, words): + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": code, "message": words}} + + +class Program: + """The verifier as a local MCP stdio program: one process, one message at a time, as the bridge is one answer per request.""" + + def __init__(self, path): + self.lock = threading.Lock() + self.child = subprocess.Popen([path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def forward(self, message): + with self.lock: + self.child.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")) + self.child.stdin.flush() + if "id" not in message: + return None + while True: + line = self.child.stdout.readline() + if not line: + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the verifier ended"}} + answer = json.loads(line) + if answer.get("id") == message.get("id"): + return answer + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + log_store = None + url = None + program = None + + def log_message(self, *args): + pass + + def reply(self, status, body=b"", kind="application/json", extra=()): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.reply(200, b"ok", "text/plain") + if self.path == "/mcp": + return self.reply(405, extra=(("Allow", "POST"),)) + self.reply(404) + + def do_DELETE(self): + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + def do_PUT(self): + self.close_connection = True + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + do_PATCH = do_PUT + + def do_POST(self): + if self.path != "/mcp": + self.close_connection = True + return self.reply(404) + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + self.close_connection = True + return self.reply(411) + try: + length = int(self.headers.get("Content-Length") or "x") + except ValueError: + self.close_connection = True + return self.reply(411) + if not 0 <= length <= MAX_BODY: + self.close_connection = True + return self.reply(413) + raw = self.rfile.read(length) + try: + message = json.loads(raw) + except ValueError: + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not one JSON message"}}).encode()) + if not isinstance(message, dict): + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "one message at a time"}}).encode()) + method = message.get("method") + if method == "tools/call": + params = message.get("params") + if not isinstance(params, dict) or not isinstance(params.get("name"), str) or not params["name"]: + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call needs params.name")).encode()) + if params.get("arguments") is not None and not isinstance(params["arguments"], dict): + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call arguments must be an object")).encode()) + self.log_store.call(message) + elif isinstance(method, str) and method.startswith("notifications/") and method not in TO_VERIFIER: + return self.reply(202) + elif method not in TO_VERIFIER: + return self.reply(200, json.dumps(refusal(message, -32601, "method not found")).encode()) + if self.program: + bridge = self.program + else: + bridge = B.Bridge(self.url) + bridge.extra_headers = {h: self.headers[h] for h in PASSED_HEADERS if self.headers.get(h)} + answer = bridge.forward(message) + if answer is None: + return self.reply(202) + self.reply(200, json.dumps(answer, separators=(",", ":")).encode()) + + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 128 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--url", default=os.environ.get("ZTP_VERIFIER_URL") or (B.OPEN_ADDRESS if B else None)) + ap.add_argument("--program") + a = ap.parse_args() + Handler.log_store, Handler.url = Log(a.log), a.url + Handler.program = Program(a.program) if a.program else None + server = Server((a.host, a.port), Handler) + print("verifier log proxy on %s:%d" % (a.host, server.server_address[1]), flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/environment/proxy/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3de4cf657e99f25799630e58e490b78ddb4ff1f6 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/instruction.md @@ -0,0 +1,19 @@ +A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla. + +Find it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T. + +The request, with the one input you change: +{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": "", "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..325d120007860504f14714784179c250104d6fd9 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/task.toml @@ -0,0 +1,41 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", { source = "/var/log/ztp-verifier/calls.jsonl", service = "verifier-proxy" }] + +[task] +name = "protocol-company/g5-bs-pb11-weakest-field-that-holds-b4" +version = "1.0.0" +description = "Budgeted search: a named physical stop bracketed to the task's width within the task's call budget, scored on the bracket and the call log." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "budgeted_search"] + +[metadata] +environment_id = "g5-bs-pb11-weakest-field-that-holds-b4" +family = "budget" +kind = "budgeted_search" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 1200.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 2048 +workdir = "/app" +network_mode = "no-network" + +[[environment.mcp_servers]] +name = "verifier" +transport = "streamable-http" +url = "http://verifier-proxy:8080/mcp" diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0e18dfad977c91946305576d7ef8171464e114fc --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/Dockerfile @@ -0,0 +1,9 @@ +# The grader's image in the HUD export: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio +# server at /usr/local/bin/mcp_stdio (a bridge to its address). The agent never sees this image. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc6404f0cfd0cad2fc7d7ecc19d24f334452816b --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "models": ["fusion_pb11_thermal"], "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", "task": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/hud_grade.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/hud_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..6421b277bb2b979dd9259509d2bba9b886f775f7 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/hud_grade.py @@ -0,0 +1,56 @@ +"""HUD's grader: grade.py, the Harbor grader, with one thing changed: where the record of the agent's calls comes from. + +HUD runs write no Harbor trajectory. The call record here is the log the proxy wrote in its own container, read through +score.py's chain check, and nothing else: no trajectory, no oracle log and no file the agent could leave in its own +container counts. No log, or a log whose chain does not hold, is no call record, and the task scores 0. + + ZTP_CALL_LOG the proxy's log (default /var/log/ztp-verifier/calls.jsonl) + ZTP_AGENT_ANSWER HUD's copy of the agent's last message (default /logs/agent_answer.txt) + +grade.py's other variables hold. Standard library only. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import grade as G # noqa: E402 + +CALL_LOG = os.environ.get("ZTP_CALL_LOG") or "/var/log/ztp-verifier/calls.jsonl" +AGENT_ANSWER = os.environ.get("ZTP_AGENT_ANSWER") or "/logs/agent_answer.txt" + + +def find_reply(): + try: + with open(G.ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return G.on_one_line(text), "the answer file %s" % G.ANSWER + except OSError: + pass + try: + with open(AGENT_ANSWER, encoding="utf-8", errors="replace") as f: + text = f.read() + if text.strip(): + return text, "the agent's last message %s" % AGENT_ANSWER + except OSError: + pass + return None, "nowhere: no answer file and no last message" + + +def find_calls(): + sys.path.insert(0, G.SCORER) + from score import read_harness_log + calls, problem = read_harness_log(CALL_LOG) + if calls is None: + return None, "nowhere: the proxy's log %s is not here" % CALL_LOG + if problem: + return None, "nowhere: %s" % problem + return [{"tool": tool, "arguments": arguments} for tool, arguments in calls], "%d calls in the proxy's log %s" % (len(calls), CALL_LOG) + + +G.find_reply = find_reply +G.find_calls = find_calls + +if __name__ == "__main__": + G.main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aff9eeba48f21744458e717b9ff593585b20152e --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# HUD runs this after the agent has ended, in the grader's own image. The answer card is at /app/answer.json, and the +# proxy's call log, taken from the proxy's container, at /var/log/ztp-verifier/calls.jsonl. hud_grade.py writes +# /logs/verifier/reward.json; if the scorer itself fails it writes no reward and this exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/hud_grade.py" diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5-bs-pb11-weakest-field-that-holds-b4/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f08794038f4a9efe7175ee5d469852f24ffb9a14 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's image in the HUD export. It holds no verifier, no bridge, no task row and no answer. HUD's agent reaches +# the verifier only through its MCP route to the verifier-proxy service, and its own sandbox has no network. +FROM python:3.12-slim-bookworm +WORKDIR /app diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/docker-compose.yaml b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c666cc38a72b0ef68240a82165d2c9c9cc93821 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/docker-compose.yaml @@ -0,0 +1,23 @@ +# The agent's container (main) and the logging proxy beside it. HUD's agent reaches the verifier only through the proxy, +# which records every tools/call in a log inside its own container; the grader takes that log over Docker, after the +# agent has ended. The volumes list is empty on purpose: the log shares no folder with main. +# environment/.env sets ZTP_VERIFIER_URL and ZTP_API_KEY for a keyed door (tasks/hud/set_door.py); no pack ships one. +services: + main: + depends_on: + verifier-proxy: + condition: service_healthy + verifier-proxy: + build: + context: ./proxy + expose: + - "8080" + environment: + ZTP_VERIFIER_URL: "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" + ZTP_API_KEY: "${ZTP_API_KEY:-}" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8080/health', timeout=3)"] + interval: 2s + timeout: 5s + retries: 15 + start_period: 1s diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/Dockerfile b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4295350a87a70b15b87dde5e928d6fb9f1eec58 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/Dockerfile @@ -0,0 +1,11 @@ +# The logging proxy in front of the Zero-Trust Physics verifier of release v0.15.3. It runs as its own user; only it can +# write the log, and the log's folder is shared with no other container. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py ztp_log_proxy.py /usr/local/lib/ztp/ +RUN useradd --system --uid 10001 --no-create-home ztp-proxy \ + && mkdir -p /var/log/ztp-verifier && chown ztp-proxy /var/log/ztp-verifier && chmod 700 /var/log/ztp-verifier +USER ztp-proxy +EXPOSE 8080 +ENTRYPOINT ["python3", "-B", "/usr/local/lib/ztp/ztp_log_proxy.py", "--log", "/var/log/ztp-verifier/calls.jsonl", "--port", "8080"] diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_log_proxy.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4e5ccd8521cc2773870317510db60b2184998 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_log_proxy.py @@ -0,0 +1,190 @@ +"""The verifier over MCP HTTP, with every tools/call written to a log the caller cannot reach. + + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] --program PATH the verifier as a local program, needing no network + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] [--url URL] URL default: ZTP_VERIFIER_URL, else the open address + +POST /mcp takes one JSON-RPC message. What goes on to the verifier is the parsed message written out again, so what the +log says and what the verifier computes cannot differ. A list of messages is refused (400), as is a method a verifier +client has no use for (-32601): nothing computes off the log. Each tools/call is on the log, fsynced, before it is +forwarded, so a call counts whether or not its answer comes back. Busy answers and retries are the bridge's (ztp_open_bridge.py): +one call, one line. GET /health says 200 and nothing else. Every other route is 404 or 405: no route reads the log. + +The log's lines have the form of the harness's logging proxy, so score.py's chain check reads them: +{"arguments", "chain", "jsonrpc_id", "seq", "tool", "ts_request"}. chain is the SHA-384 of the previous chain and this +line. An edit to a line, or a line taken out, breaks every chain after it. + +ZTP_API_KEY, when set, is sent to the verifier's address; the caller never sees it. Standard library only. Licence: Apache-2.0. +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import subprocess +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +try: + import ztp_open_bridge as B # noqa: E402 +except ImportError: # an offline image holds no bridge + B = None + +MAX_BODY = 4194304 # the verifier's own largest body +TO_VERIFIER = ("initialize", "ping", "server/discover", "tools/list", "tools/call", "notifications/initialized") +PASSED_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name") + + +def chain_of(previous, entry): + return hashlib.sha384(((previous or "") + json.dumps(entry, sort_keys=True, separators=(",", ":"))).encode("utf-8")).hexdigest() + + +class Log: + def __init__(self, path): + self.path, self.lock, self.seq, self.chain = path, threading.Lock(), 0, None + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.close(fd) + + def call(self, message): + params = message["params"] + entry = {"jsonrpc_id": message.get("id"), "tool": params["name"], "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with self.lock: + self.seq += 1 + entry["seq"] = self.seq + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + + +def refusal(message, code, words): + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": code, "message": words}} + + +class Program: + """The verifier as a local MCP stdio program: one process, one message at a time, as the bridge is one answer per request.""" + + def __init__(self, path): + self.lock = threading.Lock() + self.child = subprocess.Popen([path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def forward(self, message): + with self.lock: + self.child.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")) + self.child.stdin.flush() + if "id" not in message: + return None + while True: + line = self.child.stdout.readline() + if not line: + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the verifier ended"}} + answer = json.loads(line) + if answer.get("id") == message.get("id"): + return answer + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + log_store = None + url = None + program = None + + def log_message(self, *args): + pass + + def reply(self, status, body=b"", kind="application/json", extra=()): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.reply(200, b"ok", "text/plain") + if self.path == "/mcp": + return self.reply(405, extra=(("Allow", "POST"),)) + self.reply(404) + + def do_DELETE(self): + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + def do_PUT(self): + self.close_connection = True + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + do_PATCH = do_PUT + + def do_POST(self): + if self.path != "/mcp": + self.close_connection = True + return self.reply(404) + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + self.close_connection = True + return self.reply(411) + try: + length = int(self.headers.get("Content-Length") or "x") + except ValueError: + self.close_connection = True + return self.reply(411) + if not 0 <= length <= MAX_BODY: + self.close_connection = True + return self.reply(413) + raw = self.rfile.read(length) + try: + message = json.loads(raw) + except ValueError: + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not one JSON message"}}).encode()) + if not isinstance(message, dict): + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "one message at a time"}}).encode()) + method = message.get("method") + if method == "tools/call": + params = message.get("params") + if not isinstance(params, dict) or not isinstance(params.get("name"), str) or not params["name"]: + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call needs params.name")).encode()) + if params.get("arguments") is not None and not isinstance(params["arguments"], dict): + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call arguments must be an object")).encode()) + self.log_store.call(message) + elif isinstance(method, str) and method.startswith("notifications/") and method not in TO_VERIFIER: + return self.reply(202) + elif method not in TO_VERIFIER: + return self.reply(200, json.dumps(refusal(message, -32601, "method not found")).encode()) + if self.program: + bridge = self.program + else: + bridge = B.Bridge(self.url) + bridge.extra_headers = {h: self.headers[h] for h in PASSED_HEADERS if self.headers.get(h)} + answer = bridge.forward(message) + if answer is None: + return self.reply(202) + self.reply(200, json.dumps(answer, separators=(",", ":")).encode()) + + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 128 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--url", default=os.environ.get("ZTP_VERIFIER_URL") or (B.OPEN_ADDRESS if B else None)) + ap.add_argument("--program") + a = ap.parse_args() + Handler.log_store, Handler.url = Log(a.log), a.url + Handler.program = Program(a.program) if a.program else None + server = Server((a.host, a.port), Handler) + print("verifier log proxy on %s:%d" % (a.host, server.server_address[1]), flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/environment/proxy/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91b44ec309e62d2820c54d81cfd8f8c9b6ad1bd2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/instruction.md @@ -0,0 +1,26 @@ +JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice. + +Find the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds. + +Constraints (id (the request it is read from): what, limit): +- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W +- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182 +- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit. +jet: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": "", "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}} +slice (it must converge): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": ["", 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}} + +Budget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "failing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..79670d250dd84d40b171c1c4a2228fe68b93f5fd --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/task.toml @@ -0,0 +1,41 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", { source = "/var/log/ztp-verifier/calls.jsonl", service = "verifier-proxy" }] + +[task] +name = "protocol-company/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7" +version = "1.0.0" +description = "Chained design: a design whose sealed run is handed on, to the next run of the same model (from) or to the next model through a coupling, scored by computing the chain again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "chained_design"] + +[metadata] +environment_id = "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7" +family = "chain_design" +kind = "chained_design" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 2048 +workdir = "/app" +network_mode = "no-network" + +[[environment.mcp_servers]] +name = "verifier" +transport = "streamable-http" +url = "http://verifier-proxy:8080/mcp" diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0e18dfad977c91946305576d7ef8171464e114fc --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/Dockerfile @@ -0,0 +1,9 @@ +# The grader's image in the HUD export: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio +# server at /usr/local/bin/mcp_stdio (a bridge to its address). The agent never sees this image. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bdf850df93407e342884032734f7d8cf8719dd3b --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "models": ["energy/tokamak_jet_dte1", "tokamak_dt_beam_target"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/hud_grade.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/hud_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..6421b277bb2b979dd9259509d2bba9b886f775f7 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/hud_grade.py @@ -0,0 +1,56 @@ +"""HUD's grader: grade.py, the Harbor grader, with one thing changed: where the record of the agent's calls comes from. + +HUD runs write no Harbor trajectory. The call record here is the log the proxy wrote in its own container, read through +score.py's chain check, and nothing else: no trajectory, no oracle log and no file the agent could leave in its own +container counts. No log, or a log whose chain does not hold, is no call record, and the task scores 0. + + ZTP_CALL_LOG the proxy's log (default /var/log/ztp-verifier/calls.jsonl) + ZTP_AGENT_ANSWER HUD's copy of the agent's last message (default /logs/agent_answer.txt) + +grade.py's other variables hold. Standard library only. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import grade as G # noqa: E402 + +CALL_LOG = os.environ.get("ZTP_CALL_LOG") or "/var/log/ztp-verifier/calls.jsonl" +AGENT_ANSWER = os.environ.get("ZTP_AGENT_ANSWER") or "/logs/agent_answer.txt" + + +def find_reply(): + try: + with open(G.ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return G.on_one_line(text), "the answer file %s" % G.ANSWER + except OSError: + pass + try: + with open(AGENT_ANSWER, encoding="utf-8", errors="replace") as f: + text = f.read() + if text.strip(): + return text, "the agent's last message %s" % AGENT_ANSWER + except OSError: + pass + return None, "nowhere: no answer file and no last message" + + +def find_calls(): + sys.path.insert(0, G.SCORER) + from score import read_harness_log + calls, problem = read_harness_log(CALL_LOG) + if calls is None: + return None, "nowhere: the proxy's log %s is not here" % CALL_LOG + if problem: + return None, "nowhere: %s" % problem + return [{"tool": tool, "arguments": arguments} for tool, arguments in calls], "%d calls in the proxy's log %s" % (len(calls), CALL_LOG) + + +G.find_reply = find_reply +G.find_calls = find_calls + +if __name__ == "__main__": + G.main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aff9eeba48f21744458e717b9ff593585b20152e --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# HUD runs this after the agent has ended, in the grader's own image. The answer card is at /app/answer.json, and the +# proxy's call log, taken from the proxy's container, at /var/log/ztp-verifier/calls.jsonl. hud_grade.py writes +# /logs/verifier/reward.json; if the scorer itself fails it writes no reward and this exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/hud_grade.py" diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f08794038f4a9efe7175ee5d469852f24ffb9a14 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's image in the HUD export. It holds no verifier, no bridge, no task row and no answer. HUD's agent reaches +# the verifier only through its MCP route to the verifier-proxy service, and its own sandbox has no network. +FROM python:3.12-slim-bookworm +WORKDIR /app diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/docker-compose.yaml b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c666cc38a72b0ef68240a82165d2c9c9cc93821 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/docker-compose.yaml @@ -0,0 +1,23 @@ +# The agent's container (main) and the logging proxy beside it. HUD's agent reaches the verifier only through the proxy, +# which records every tools/call in a log inside its own container; the grader takes that log over Docker, after the +# agent has ended. The volumes list is empty on purpose: the log shares no folder with main. +# environment/.env sets ZTP_VERIFIER_URL and ZTP_API_KEY for a keyed door (tasks/hud/set_door.py); no pack ships one. +services: + main: + depends_on: + verifier-proxy: + condition: service_healthy + verifier-proxy: + build: + context: ./proxy + expose: + - "8080" + environment: + ZTP_VERIFIER_URL: "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" + ZTP_API_KEY: "${ZTP_API_KEY:-}" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8080/health', timeout=3)"] + interval: 2s + timeout: 5s + retries: 15 + start_period: 1s diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/Dockerfile b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4295350a87a70b15b87dde5e928d6fb9f1eec58 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/Dockerfile @@ -0,0 +1,11 @@ +# The logging proxy in front of the Zero-Trust Physics verifier of release v0.15.3. It runs as its own user; only it can +# write the log, and the log's folder is shared with no other container. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py ztp_log_proxy.py /usr/local/lib/ztp/ +RUN useradd --system --uid 10001 --no-create-home ztp-proxy \ + && mkdir -p /var/log/ztp-verifier && chown ztp-proxy /var/log/ztp-verifier && chmod 700 /var/log/ztp-verifier +USER ztp-proxy +EXPOSE 8080 +ENTRYPOINT ["python3", "-B", "/usr/local/lib/ztp/ztp_log_proxy.py", "--log", "/var/log/ztp-verifier/calls.jsonl", "--port", "8080"] diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_log_proxy.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4e5ccd8521cc2773870317510db60b2184998 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_log_proxy.py @@ -0,0 +1,190 @@ +"""The verifier over MCP HTTP, with every tools/call written to a log the caller cannot reach. + + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] --program PATH the verifier as a local program, needing no network + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] [--url URL] URL default: ZTP_VERIFIER_URL, else the open address + +POST /mcp takes one JSON-RPC message. What goes on to the verifier is the parsed message written out again, so what the +log says and what the verifier computes cannot differ. A list of messages is refused (400), as is a method a verifier +client has no use for (-32601): nothing computes off the log. Each tools/call is on the log, fsynced, before it is +forwarded, so a call counts whether or not its answer comes back. Busy answers and retries are the bridge's (ztp_open_bridge.py): +one call, one line. GET /health says 200 and nothing else. Every other route is 404 or 405: no route reads the log. + +The log's lines have the form of the harness's logging proxy, so score.py's chain check reads them: +{"arguments", "chain", "jsonrpc_id", "seq", "tool", "ts_request"}. chain is the SHA-384 of the previous chain and this +line. An edit to a line, or a line taken out, breaks every chain after it. + +ZTP_API_KEY, when set, is sent to the verifier's address; the caller never sees it. Standard library only. Licence: Apache-2.0. +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import subprocess +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +try: + import ztp_open_bridge as B # noqa: E402 +except ImportError: # an offline image holds no bridge + B = None + +MAX_BODY = 4194304 # the verifier's own largest body +TO_VERIFIER = ("initialize", "ping", "server/discover", "tools/list", "tools/call", "notifications/initialized") +PASSED_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name") + + +def chain_of(previous, entry): + return hashlib.sha384(((previous or "") + json.dumps(entry, sort_keys=True, separators=(",", ":"))).encode("utf-8")).hexdigest() + + +class Log: + def __init__(self, path): + self.path, self.lock, self.seq, self.chain = path, threading.Lock(), 0, None + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.close(fd) + + def call(self, message): + params = message["params"] + entry = {"jsonrpc_id": message.get("id"), "tool": params["name"], "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with self.lock: + self.seq += 1 + entry["seq"] = self.seq + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + + +def refusal(message, code, words): + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": code, "message": words}} + + +class Program: + """The verifier as a local MCP stdio program: one process, one message at a time, as the bridge is one answer per request.""" + + def __init__(self, path): + self.lock = threading.Lock() + self.child = subprocess.Popen([path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def forward(self, message): + with self.lock: + self.child.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")) + self.child.stdin.flush() + if "id" not in message: + return None + while True: + line = self.child.stdout.readline() + if not line: + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the verifier ended"}} + answer = json.loads(line) + if answer.get("id") == message.get("id"): + return answer + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + log_store = None + url = None + program = None + + def log_message(self, *args): + pass + + def reply(self, status, body=b"", kind="application/json", extra=()): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.reply(200, b"ok", "text/plain") + if self.path == "/mcp": + return self.reply(405, extra=(("Allow", "POST"),)) + self.reply(404) + + def do_DELETE(self): + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + def do_PUT(self): + self.close_connection = True + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + do_PATCH = do_PUT + + def do_POST(self): + if self.path != "/mcp": + self.close_connection = True + return self.reply(404) + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + self.close_connection = True + return self.reply(411) + try: + length = int(self.headers.get("Content-Length") or "x") + except ValueError: + self.close_connection = True + return self.reply(411) + if not 0 <= length <= MAX_BODY: + self.close_connection = True + return self.reply(413) + raw = self.rfile.read(length) + try: + message = json.loads(raw) + except ValueError: + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not one JSON message"}}).encode()) + if not isinstance(message, dict): + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "one message at a time"}}).encode()) + method = message.get("method") + if method == "tools/call": + params = message.get("params") + if not isinstance(params, dict) or not isinstance(params.get("name"), str) or not params["name"]: + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call needs params.name")).encode()) + if params.get("arguments") is not None and not isinstance(params["arguments"], dict): + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call arguments must be an object")).encode()) + self.log_store.call(message) + elif isinstance(method, str) and method.startswith("notifications/") and method not in TO_VERIFIER: + return self.reply(202) + elif method not in TO_VERIFIER: + return self.reply(200, json.dumps(refusal(message, -32601, "method not found")).encode()) + if self.program: + bridge = self.program + else: + bridge = B.Bridge(self.url) + bridge.extra_headers = {h: self.headers[h] for h in PASSED_HEADERS if self.headers.get(h)} + answer = bridge.forward(message) + if answer is None: + return self.reply(202) + self.reply(200, json.dumps(answer, separators=(",", ":")).encode()) + + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 128 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--url", default=os.environ.get("ZTP_VERIFIER_URL") or (B.OPEN_ADDRESS if B else None)) + ap.add_argument("--program") + a = ap.parse_args() + Handler.log_store, Handler.url = Log(a.log), a.url + Handler.program = Program(a.program) if a.program else None + server = Server((a.host, a.port), Handler) + print("verifier log proxy on %s:%d" % (a.host, server.server_address[1]), flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/environment/proxy/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d3cf8bbdc75640e84cbfe557abaf83fb8f6fce98 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/instruction.md @@ -0,0 +1,22 @@ +A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target). + +Find the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds. + +Constraints (id, what, limit): +- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J +- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W +Each design is one solve (leave out "run"): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": ["", 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}} + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ed9840af43a08feb1b5de94ebaeee48176875a4b --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/task.toml @@ -0,0 +1,41 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", { source = "/var/log/ztp-verifier/calls.jsonl", service = "verifier-proxy" }] + +[task] +name = "protocol-company/g5r10-dl-dt4-core-te-fastshare-pion" +version = "1.0.0" +description = "Design to a limit: a design pushed to the edge of its physical limits, found by verifier runs and scored by computing both designs again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "design_to_limit"] + +[metadata] +environment_id = "g5r10-dl-dt4-core-te-fastshare-pion" +family = "tradeoff" +kind = "design_to_limit" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 2048 +workdir = "/app" +network_mode = "no-network" + +[[environment.mcp_servers]] +name = "verifier" +transport = "streamable-http" +url = "http://verifier-proxy:8080/mcp" diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0e18dfad977c91946305576d7ef8171464e114fc --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/Dockerfile @@ -0,0 +1,9 @@ +# The grader's image in the HUD export: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio +# server at /usr/local/bin/mcp_stdio (a bridge to its address). The agent never sees this image. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..609c085da2c2974c6a24cf9e0e3ac779716ceaa8 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "models": ["tokamak_dt_beam_target"], "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/hud_grade.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/hud_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..6421b277bb2b979dd9259509d2bba9b886f775f7 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/hud_grade.py @@ -0,0 +1,56 @@ +"""HUD's grader: grade.py, the Harbor grader, with one thing changed: where the record of the agent's calls comes from. + +HUD runs write no Harbor trajectory. The call record here is the log the proxy wrote in its own container, read through +score.py's chain check, and nothing else: no trajectory, no oracle log and no file the agent could leave in its own +container counts. No log, or a log whose chain does not hold, is no call record, and the task scores 0. + + ZTP_CALL_LOG the proxy's log (default /var/log/ztp-verifier/calls.jsonl) + ZTP_AGENT_ANSWER HUD's copy of the agent's last message (default /logs/agent_answer.txt) + +grade.py's other variables hold. Standard library only. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import grade as G # noqa: E402 + +CALL_LOG = os.environ.get("ZTP_CALL_LOG") or "/var/log/ztp-verifier/calls.jsonl" +AGENT_ANSWER = os.environ.get("ZTP_AGENT_ANSWER") or "/logs/agent_answer.txt" + + +def find_reply(): + try: + with open(G.ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return G.on_one_line(text), "the answer file %s" % G.ANSWER + except OSError: + pass + try: + with open(AGENT_ANSWER, encoding="utf-8", errors="replace") as f: + text = f.read() + if text.strip(): + return text, "the agent's last message %s" % AGENT_ANSWER + except OSError: + pass + return None, "nowhere: no answer file and no last message" + + +def find_calls(): + sys.path.insert(0, G.SCORER) + from score import read_harness_log + calls, problem = read_harness_log(CALL_LOG) + if calls is None: + return None, "nowhere: the proxy's log %s is not here" % CALL_LOG + if problem: + return None, "nowhere: %s" % problem + return [{"tool": tool, "arguments": arguments} for tool, arguments in calls], "%d calls in the proxy's log %s" % (len(calls), CALL_LOG) + + +G.find_reply = find_reply +G.find_calls = find_calls + +if __name__ == "__main__": + G.main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aff9eeba48f21744458e717b9ff593585b20152e --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# HUD runs this after the agent has ended, in the grader's own image. The answer card is at /app/answer.json, and the +# proxy's call log, taken from the proxy's container, at /var/log/ztp-verifier/calls.jsonl. hud_grade.py writes +# /logs/verifier/reward.json; if the scorer itself fails it writes no reward and this exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/hud_grade.py" diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r10-dl-dt4-core-te-fastshare-pion/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f08794038f4a9efe7175ee5d469852f24ffb9a14 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's image in the HUD export. It holds no verifier, no bridge, no task row and no answer. HUD's agent reaches +# the verifier only through its MCP route to the verifier-proxy service, and its own sandbox has no network. +FROM python:3.12-slim-bookworm +WORKDIR /app diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/docker-compose.yaml b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c666cc38a72b0ef68240a82165d2c9c9cc93821 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/docker-compose.yaml @@ -0,0 +1,23 @@ +# The agent's container (main) and the logging proxy beside it. HUD's agent reaches the verifier only through the proxy, +# which records every tools/call in a log inside its own container; the grader takes that log over Docker, after the +# agent has ended. The volumes list is empty on purpose: the log shares no folder with main. +# environment/.env sets ZTP_VERIFIER_URL and ZTP_API_KEY for a keyed door (tasks/hud/set_door.py); no pack ships one. +services: + main: + depends_on: + verifier-proxy: + condition: service_healthy + verifier-proxy: + build: + context: ./proxy + expose: + - "8080" + environment: + ZTP_VERIFIER_URL: "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" + ZTP_API_KEY: "${ZTP_API_KEY:-}" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8080/health', timeout=3)"] + interval: 2s + timeout: 5s + retries: 15 + start_period: 1s diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/Dockerfile b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4295350a87a70b15b87dde5e928d6fb9f1eec58 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/Dockerfile @@ -0,0 +1,11 @@ +# The logging proxy in front of the Zero-Trust Physics verifier of release v0.15.3. It runs as its own user; only it can +# write the log, and the log's folder is shared with no other container. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py ztp_log_proxy.py /usr/local/lib/ztp/ +RUN useradd --system --uid 10001 --no-create-home ztp-proxy \ + && mkdir -p /var/log/ztp-verifier && chown ztp-proxy /var/log/ztp-verifier && chmod 700 /var/log/ztp-verifier +USER ztp-proxy +EXPOSE 8080 +ENTRYPOINT ["python3", "-B", "/usr/local/lib/ztp/ztp_log_proxy.py", "--log", "/var/log/ztp-verifier/calls.jsonl", "--port", "8080"] diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_log_proxy.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4e5ccd8521cc2773870317510db60b2184998 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_log_proxy.py @@ -0,0 +1,190 @@ +"""The verifier over MCP HTTP, with every tools/call written to a log the caller cannot reach. + + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] --program PATH the verifier as a local program, needing no network + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] [--url URL] URL default: ZTP_VERIFIER_URL, else the open address + +POST /mcp takes one JSON-RPC message. What goes on to the verifier is the parsed message written out again, so what the +log says and what the verifier computes cannot differ. A list of messages is refused (400), as is a method a verifier +client has no use for (-32601): nothing computes off the log. Each tools/call is on the log, fsynced, before it is +forwarded, so a call counts whether or not its answer comes back. Busy answers and retries are the bridge's (ztp_open_bridge.py): +one call, one line. GET /health says 200 and nothing else. Every other route is 404 or 405: no route reads the log. + +The log's lines have the form of the harness's logging proxy, so score.py's chain check reads them: +{"arguments", "chain", "jsonrpc_id", "seq", "tool", "ts_request"}. chain is the SHA-384 of the previous chain and this +line. An edit to a line, or a line taken out, breaks every chain after it. + +ZTP_API_KEY, when set, is sent to the verifier's address; the caller never sees it. Standard library only. Licence: Apache-2.0. +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import subprocess +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +try: + import ztp_open_bridge as B # noqa: E402 +except ImportError: # an offline image holds no bridge + B = None + +MAX_BODY = 4194304 # the verifier's own largest body +TO_VERIFIER = ("initialize", "ping", "server/discover", "tools/list", "tools/call", "notifications/initialized") +PASSED_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name") + + +def chain_of(previous, entry): + return hashlib.sha384(((previous or "") + json.dumps(entry, sort_keys=True, separators=(",", ":"))).encode("utf-8")).hexdigest() + + +class Log: + def __init__(self, path): + self.path, self.lock, self.seq, self.chain = path, threading.Lock(), 0, None + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.close(fd) + + def call(self, message): + params = message["params"] + entry = {"jsonrpc_id": message.get("id"), "tool": params["name"], "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with self.lock: + self.seq += 1 + entry["seq"] = self.seq + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + + +def refusal(message, code, words): + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": code, "message": words}} + + +class Program: + """The verifier as a local MCP stdio program: one process, one message at a time, as the bridge is one answer per request.""" + + def __init__(self, path): + self.lock = threading.Lock() + self.child = subprocess.Popen([path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def forward(self, message): + with self.lock: + self.child.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")) + self.child.stdin.flush() + if "id" not in message: + return None + while True: + line = self.child.stdout.readline() + if not line: + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the verifier ended"}} + answer = json.loads(line) + if answer.get("id") == message.get("id"): + return answer + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + log_store = None + url = None + program = None + + def log_message(self, *args): + pass + + def reply(self, status, body=b"", kind="application/json", extra=()): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.reply(200, b"ok", "text/plain") + if self.path == "/mcp": + return self.reply(405, extra=(("Allow", "POST"),)) + self.reply(404) + + def do_DELETE(self): + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + def do_PUT(self): + self.close_connection = True + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + do_PATCH = do_PUT + + def do_POST(self): + if self.path != "/mcp": + self.close_connection = True + return self.reply(404) + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + self.close_connection = True + return self.reply(411) + try: + length = int(self.headers.get("Content-Length") or "x") + except ValueError: + self.close_connection = True + return self.reply(411) + if not 0 <= length <= MAX_BODY: + self.close_connection = True + return self.reply(413) + raw = self.rfile.read(length) + try: + message = json.loads(raw) + except ValueError: + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not one JSON message"}}).encode()) + if not isinstance(message, dict): + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "one message at a time"}}).encode()) + method = message.get("method") + if method == "tools/call": + params = message.get("params") + if not isinstance(params, dict) or not isinstance(params.get("name"), str) or not params["name"]: + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call needs params.name")).encode()) + if params.get("arguments") is not None and not isinstance(params["arguments"], dict): + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call arguments must be an object")).encode()) + self.log_store.call(message) + elif isinstance(method, str) and method.startswith("notifications/") and method not in TO_VERIFIER: + return self.reply(202) + elif method not in TO_VERIFIER: + return self.reply(200, json.dumps(refusal(message, -32601, "method not found")).encode()) + if self.program: + bridge = self.program + else: + bridge = B.Bridge(self.url) + bridge.extra_headers = {h: self.headers[h] for h in PASSED_HEADERS if self.headers.get(h)} + answer = bridge.forward(message) + if answer is None: + return self.reply(202) + self.reply(200, json.dumps(answer, separators=(",", ":")).encode()) + + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 128 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--url", default=os.environ.get("ZTP_VERIFIER_URL") or (B.OPEN_ADDRESS if B else None)) + ap.add_argument("--program") + a = ap.parse_args() + Handler.log_store, Handler.url = Log(a.log), a.url + Handler.program = Program(a.program) if a.program else None + server = Server((a.host, a.port), Handler) + print("verifier log proxy on %s:%d" % (a.host, server.server_address[1]), flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/environment/proxy/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..109af2273bff043863d3e547ddacf338ca7c82f8 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/instruction.md @@ -0,0 +1,19 @@ +MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number). + +Find it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V. + +The request, with the one input you change: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": ""}}], "record_every": 56}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f8317643aa49f56e1b31e13860b294cb1cb55676 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/task.toml @@ -0,0 +1,41 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", { source = "/var/log/ztp-verifier/calls.jsonl", service = "verifier-proxy" }] + +[task] +name = "protocol-company/g5r8-bs-mast-2seg-drift-down-wall-b4" +version = "1.0.0" +description = "Budgeted search: a named physical stop bracketed to the task's width within the task's call budget, scored on the bracket and the call log." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "budgeted_search"] + +[metadata] +environment_id = "g5r8-bs-mast-2seg-drift-down-wall-b4" +family = "budget" +kind = "budgeted_search" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 1200.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 2048 +workdir = "/app" +network_mode = "no-network" + +[[environment.mcp_servers]] +name = "verifier" +transport = "streamable-http" +url = "http://verifier-proxy:8080/mcp" diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0e18dfad977c91946305576d7ef8171464e114fc --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/Dockerfile @@ -0,0 +1,9 @@ +# The grader's image in the HUD export: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio +# server at /usr/local/bin/mcp_stdio (a bridge to its address). The agent never sees this image. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9b35031104cce374d00f88c4d124a360959bc6b2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "family": "budget", "kind": "budgeted_search", "models": ["energy/tokamak_vde_mast"], "real_thing": "Vertical displacement event of the MAST spherical tokamak's plasma in shot 15045, from 0.250 s: a rigid plasma carrying EFIT's 755 kA in MAST's held coil field, against the eddy currents of its 126 passive elements as one wall circuit and the P6 vertical-control pair driven by the amplifier's voltage, from any start inside the vessel until its boundary reaches the wall: height, velocity, the two currents and the vertical force on the vessel, with the energy ledger closed at every substep. Compared with the measured event of shot 15045: P6U current at the end of the linear phase within 6.2 percent of the shot's (-2,933 ampere-turns against -3,126; target 25); growth rate 6.55 per second against the published 96.3 (target within 25 percent), and the card's synthetic probe signal 7.10 per second against the measured 121.3 by the same rule. Gap: the growth rate is 93.2 percent low (6.55 per second against 96.3; 94.1 percent low on the probe signal): in the shot P6 held its flux, and a rigid plasma held so needs 2.04 times the rigid shift's stiffness to grow at 96.3.", "task": "MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number).\n\nFind it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V.\n\nThe request, with the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/hud_grade.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/hud_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..6421b277bb2b979dd9259509d2bba9b886f775f7 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/hud_grade.py @@ -0,0 +1,56 @@ +"""HUD's grader: grade.py, the Harbor grader, with one thing changed: where the record of the agent's calls comes from. + +HUD runs write no Harbor trajectory. The call record here is the log the proxy wrote in its own container, read through +score.py's chain check, and nothing else: no trajectory, no oracle log and no file the agent could leave in its own +container counts. No log, or a log whose chain does not hold, is no call record, and the task scores 0. + + ZTP_CALL_LOG the proxy's log (default /var/log/ztp-verifier/calls.jsonl) + ZTP_AGENT_ANSWER HUD's copy of the agent's last message (default /logs/agent_answer.txt) + +grade.py's other variables hold. Standard library only. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import grade as G # noqa: E402 + +CALL_LOG = os.environ.get("ZTP_CALL_LOG") or "/var/log/ztp-verifier/calls.jsonl" +AGENT_ANSWER = os.environ.get("ZTP_AGENT_ANSWER") or "/logs/agent_answer.txt" + + +def find_reply(): + try: + with open(G.ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return G.on_one_line(text), "the answer file %s" % G.ANSWER + except OSError: + pass + try: + with open(AGENT_ANSWER, encoding="utf-8", errors="replace") as f: + text = f.read() + if text.strip(): + return text, "the agent's last message %s" % AGENT_ANSWER + except OSError: + pass + return None, "nowhere: no answer file and no last message" + + +def find_calls(): + sys.path.insert(0, G.SCORER) + from score import read_harness_log + calls, problem = read_harness_log(CALL_LOG) + if calls is None: + return None, "nowhere: the proxy's log %s is not here" % CALL_LOG + if problem: + return None, "nowhere: %s" % problem + return [{"tool": tool, "arguments": arguments} for tool, arguments in calls], "%d calls in the proxy's log %s" % (len(calls), CALL_LOG) + + +G.find_reply = find_reply +G.find_calls = find_calls + +if __name__ == "__main__": + G.main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aff9eeba48f21744458e717b9ff593585b20152e --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# HUD runs this after the agent has ended, in the grader's own image. The answer card is at /app/answer.json, and the +# proxy's call log, taken from the proxy's container, at /var/log/ztp-verifier/calls.jsonl. hud_grade.py writes +# /logs/verifier/reward.json; if the scorer itself fails it writes no reward and this exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/hud_grade.py" diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-bs-mast-2seg-drift-down-wall-b4/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f08794038f4a9efe7175ee5d469852f24ffb9a14 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's image in the HUD export. It holds no verifier, no bridge, no task row and no answer. HUD's agent reaches +# the verifier only through its MCP route to the verifier-proxy service, and its own sandbox has no network. +FROM python:3.12-slim-bookworm +WORKDIR /app diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/docker-compose.yaml b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c666cc38a72b0ef68240a82165d2c9c9cc93821 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/docker-compose.yaml @@ -0,0 +1,23 @@ +# The agent's container (main) and the logging proxy beside it. HUD's agent reaches the verifier only through the proxy, +# which records every tools/call in a log inside its own container; the grader takes that log over Docker, after the +# agent has ended. The volumes list is empty on purpose: the log shares no folder with main. +# environment/.env sets ZTP_VERIFIER_URL and ZTP_API_KEY for a keyed door (tasks/hud/set_door.py); no pack ships one. +services: + main: + depends_on: + verifier-proxy: + condition: service_healthy + verifier-proxy: + build: + context: ./proxy + expose: + - "8080" + environment: + ZTP_VERIFIER_URL: "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" + ZTP_API_KEY: "${ZTP_API_KEY:-}" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8080/health', timeout=3)"] + interval: 2s + timeout: 5s + retries: 15 + start_period: 1s diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/Dockerfile b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4295350a87a70b15b87dde5e928d6fb9f1eec58 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/Dockerfile @@ -0,0 +1,11 @@ +# The logging proxy in front of the Zero-Trust Physics verifier of release v0.15.3. It runs as its own user; only it can +# write the log, and the log's folder is shared with no other container. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py ztp_log_proxy.py /usr/local/lib/ztp/ +RUN useradd --system --uid 10001 --no-create-home ztp-proxy \ + && mkdir -p /var/log/ztp-verifier && chown ztp-proxy /var/log/ztp-verifier && chmod 700 /var/log/ztp-verifier +USER ztp-proxy +EXPOSE 8080 +ENTRYPOINT ["python3", "-B", "/usr/local/lib/ztp/ztp_log_proxy.py", "--log", "/var/log/ztp-verifier/calls.jsonl", "--port", "8080"] diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_log_proxy.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd4e5ccd8521cc2773870317510db60b2184998 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_log_proxy.py @@ -0,0 +1,190 @@ +"""The verifier over MCP HTTP, with every tools/call written to a log the caller cannot reach. + + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] --program PATH the verifier as a local program, needing no network + python3 ztp_log_proxy.py --log LOG [--port 8080] [--host 0.0.0.0] [--url URL] URL default: ZTP_VERIFIER_URL, else the open address + +POST /mcp takes one JSON-RPC message. What goes on to the verifier is the parsed message written out again, so what the +log says and what the verifier computes cannot differ. A list of messages is refused (400), as is a method a verifier +client has no use for (-32601): nothing computes off the log. Each tools/call is on the log, fsynced, before it is +forwarded, so a call counts whether or not its answer comes back. Busy answers and retries are the bridge's (ztp_open_bridge.py): +one call, one line. GET /health says 200 and nothing else. Every other route is 404 or 405: no route reads the log. + +The log's lines have the form of the harness's logging proxy, so score.py's chain check reads them: +{"arguments", "chain", "jsonrpc_id", "seq", "tool", "ts_request"}. chain is the SHA-384 of the previous chain and this +line. An edit to a line, or a line taken out, breaks every chain after it. + +ZTP_API_KEY, when set, is sent to the verifier's address; the caller never sees it. Standard library only. Licence: Apache-2.0. +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import subprocess +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +try: + import ztp_open_bridge as B # noqa: E402 +except ImportError: # an offline image holds no bridge + B = None + +MAX_BODY = 4194304 # the verifier's own largest body +TO_VERIFIER = ("initialize", "ping", "server/discover", "tools/list", "tools/call", "notifications/initialized") +PASSED_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name") + + +def chain_of(previous, entry): + return hashlib.sha384(((previous or "") + json.dumps(entry, sort_keys=True, separators=(",", ":"))).encode("utf-8")).hexdigest() + + +class Log: + def __init__(self, path): + self.path, self.lock, self.seq, self.chain = path, threading.Lock(), 0, None + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.close(fd) + + def call(self, message): + params = message["params"] + entry = {"jsonrpc_id": message.get("id"), "tool": params["name"], "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with self.lock: + self.seq += 1 + entry["seq"] = self.seq + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + + +def refusal(message, code, words): + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": code, "message": words}} + + +class Program: + """The verifier as a local MCP stdio program: one process, one message at a time, as the bridge is one answer per request.""" + + def __init__(self, path): + self.lock = threading.Lock() + self.child = subprocess.Popen([path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def forward(self, message): + with self.lock: + self.child.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")) + self.child.stdin.flush() + if "id" not in message: + return None + while True: + line = self.child.stdout.readline() + if not line: + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the verifier ended"}} + answer = json.loads(line) + if answer.get("id") == message.get("id"): + return answer + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + log_store = None + url = None + program = None + + def log_message(self, *args): + pass + + def reply(self, status, body=b"", kind="application/json", extra=()): + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + for k, v in extra: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.reply(200, b"ok", "text/plain") + if self.path == "/mcp": + return self.reply(405, extra=(("Allow", "POST"),)) + self.reply(404) + + def do_DELETE(self): + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + def do_PUT(self): + self.close_connection = True + self.reply(405 if self.path == "/mcp" else 404, extra=(("Allow", "POST"),)) + + do_PATCH = do_PUT + + def do_POST(self): + if self.path != "/mcp": + self.close_connection = True + return self.reply(404) + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + self.close_connection = True + return self.reply(411) + try: + length = int(self.headers.get("Content-Length") or "x") + except ValueError: + self.close_connection = True + return self.reply(411) + if not 0 <= length <= MAX_BODY: + self.close_connection = True + return self.reply(413) + raw = self.rfile.read(length) + try: + message = json.loads(raw) + except ValueError: + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not one JSON message"}}).encode()) + if not isinstance(message, dict): + return self.reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "one message at a time"}}).encode()) + method = message.get("method") + if method == "tools/call": + params = message.get("params") + if not isinstance(params, dict) or not isinstance(params.get("name"), str) or not params["name"]: + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call needs params.name")).encode()) + if params.get("arguments") is not None and not isinstance(params["arguments"], dict): + return self.reply(200, json.dumps(refusal(message, -32602, "tools/call arguments must be an object")).encode()) + self.log_store.call(message) + elif isinstance(method, str) and method.startswith("notifications/") and method not in TO_VERIFIER: + return self.reply(202) + elif method not in TO_VERIFIER: + return self.reply(200, json.dumps(refusal(message, -32601, "method not found")).encode()) + if self.program: + bridge = self.program + else: + bridge = B.Bridge(self.url) + bridge.extra_headers = {h: self.headers[h] for h in PASSED_HEADERS if self.headers.get(h)} + answer = bridge.forward(message) + if answer is None: + return self.reply(202) + self.reply(200, json.dumps(answer, separators=(",", ":")).encode()) + + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + request_queue_size = 128 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--url", default=os.environ.get("ZTP_VERIFIER_URL") or (B.OPEN_ADDRESS if B else None)) + ap.add_argument("--program") + a = ap.parse_args() + Handler.log_store, Handler.url = Log(a.log), a.url + Handler.program = Program(a.program) if a.program else None + server = Server((a.host, a.port), Handler) + print("verifier log proxy on %s:%d" % (a.host, server.server_address[1]), flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/environment/proxy/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84c9e54cc76501f4dac621e95443b6d02587f298 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/instruction.md @@ -0,0 +1,24 @@ +In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose. + +Find the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds. + +Constraints (id, what, limit): +- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W +- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J +- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is one run: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": "", "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}} +This task has no solve: leave "solve" out of each design. + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `/app/answer.json`. diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea5bf88c9d041ff778226642e6dddc5def995578 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/task.toml @@ -0,0 +1,41 @@ +schema_version = "1.4" +artifacts = ["/app/answer.json", { source = "/var/log/ztp-verifier/calls.jsonl", service = "verifier-proxy" }] + +[task] +name = "protocol-company/g5r8-dl-jet-tritium-rich-dome-hotion" +version = "1.0.0" +description = "Design to a limit: a design pushed to the edge of its physical limits, found by verifier runs and scored by computing both designs again." +authors = [{ name = "Protocol Company" }] +keywords = ["zero-trust-physics", "physics", "mcp", "tool-use", "verifier", "multi-step", "design_to_limit"] + +[metadata] +environment_id = "g5r8-dl-jet-tritium-rich-dome-hotion" +family = "tradeoff" +kind = "design_to_limit" +engine_source = "https://github.com/johnkruze/zero-trust-physics-engine" +engine_tag = "v0.15.3" +engine_commit = "664d68f426ccdfd0159e5f91857edba3872390d1" +engine_binary_sha256 = "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076" +gateway_version = "0.15.3" +scores = ["correct", "proofs_hold"] + +[agent] +timeout_sec = 3600.0 + +[verifier] +timeout_sec = 900.0 +environment_mode = "separate" +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 2048 +workdir = "/app" +network_mode = "no-network" + +[[environment.mcp_servers]] +name = "verifier" +transport = "streamable-http" +url = "http://verifier-proxy:8080/mcp" diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0e18dfad977c91946305576d7ef8171464e114fc --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/Dockerfile @@ -0,0 +1,9 @@ +# The grader's image in the HUD export: the task's tests at /tests and the verifier of release v0.15.3 as an MCP stdio +# server at /usr/local/bin/mcp_stdio (a bridge to its address). The agent never sees this image. +FROM python:3.12-slim-bookworm +ARG ZTP_ENGINE_TAG=v0.15.3 +ARG ZTP_ENGINE_COMMIT=664d68f426ccdfd0159e5f91857edba3872390d1 +COPY ztp_open_bridge.py /usr/local/lib/ztp/ztp_open_bridge.py +RUN printf '#!/bin/sh\nexec python3 /usr/local/lib/ztp/ztp_open_bridge.py "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}"\n' > /usr/local/bin/mcp_stdio \ + && chmod +x /usr/local/bin/mcp_stdio +COPY . /tests diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9aa354005c7e2650fcb1a36ba986ae5c4e8564cf --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/environment.jsonl @@ -0,0 +1 @@ +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "models": ["energy/tokamak_jet_dte1"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", "task": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..88564e4e42982627e805eb8e50bd600ae052dd80 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/grade.py @@ -0,0 +1,272 @@ +"""Harbor glue: find the agent's reply and its calls, hand them to the dataset's score.py, write the reward. + +Standard library only. Every path can be moved with an environment variable, so the +same file runs outside a container: + + ZTP_TESTS_DIR this folder: environment.jsonl (and score.py, ztp_mcp.py) (default: where this file is) + ZTP_SCORER_DIR where score.py and ztp_mcp.py sit (default: ZTP_TESTS_DIR) + ZTP_ANSWER_FILE the card the instruction asks the agent to save (default /app/answer.json) + ZTP_CALLS_FILE a call log written by the oracle's solve.sh (default /app/calls.jsonl) + ZTP_ORACLE_LOG Harbor's log of the oracle agent's run (default /logs/agent/oracle.txt) + ZTP_TRAJECTORY_FILE Harbor's record of the run, in ATIF (default /logs/agent/trajectory.json) + ZTP_VERIFIER_DIR where the reward is written (default /logs/verifier) + ZTP_ENGINE the verifier, MCP over stdio (default /usr/local/bin/mcp_stdio) + ZTP_SCORE_TIMEOUT_S how long the scorer may take, in seconds (default 600) + +The reply, first found: the answer file when it is there and not empty (one JSON object over +several lines is put on one line first); else the last agent message with text in the +trajectory; else none, and the scorer gives 0. + +The calls, for every environment (a call budget, and a forensics answer, are scored on them): the agent's calls of the +verifier's own tools in the trajectory's agent steps, in order, by function name and arguments (mcp__verifier__solve is +read as solve). The agent's other tools (a shell, a file editor, writing /app/answer.json) are left out of the record: +they are not verifier calls and are not counted against a budget. When there is no trajectory file at all and Harbor's +oracle has run (its log /logs/agent/oracle.txt is there), the log solution/solve.sh wrote is read instead: the oracle +runs no model, so Harbor records no tool call for it. Any other run with no trajectory is scored with no call record, +and a budget or forensics answer then scores 0. + +The verifier is held to its release by what it answers (version 0.15.3, kernel genesis_kernel_v0.13.1); the binary's +sha256 is recorded on the score row. pack_score.py, beside score.py, holds that rule; --strict-binary is not used here +because this image builds the verifier from source, a different file from the served build. + +The reward, reward.json in ZTP_VERIFIER_DIR: {"reward": 0 or 1, "correct": 0 or 1, "proofs_hold": 0 or 1}. +reward is 1 only when both scores are 1. score.json holds the scorer's line (the reason for a 0). +If the scorer itself fails, no reward is written and this exits non-zero. +""" +import json +import os +import re +import signal +import subprocess +import sys +import tempfile + +TESTS = os.environ.get("ZTP_TESTS_DIR") or os.path.dirname(os.path.abspath(__file__)) +SCORER = os.environ.get("ZTP_SCORER_DIR") or TESTS +ANSWER = os.environ.get("ZTP_ANSWER_FILE") or "/app/answer.json" +CALLS = os.environ.get("ZTP_CALLS_FILE") or "/app/calls.jsonl" +TRAJECTORY = os.environ.get("ZTP_TRAJECTORY_FILE") or "/logs/agent/trajectory.json" +ORACLE_LOG = os.environ.get("ZTP_ORACLE_LOG") or "/logs/agent/oracle.txt" +OUT = os.environ.get("ZTP_VERIFIER_DIR") or "/logs/verifier" +ENGINE = os.environ.get("ZTP_ENGINE") or "/usr/local/bin/mcp_stdio" +TIMEOUT_S = float(os.environ.get("ZTP_SCORE_TIMEOUT_S") or 600) +SCORES = ("correct", "proofs_hold") + + +class ScorerFailed(Exception): + """The check could not be made. No reward is written.""" + + +def on_one_line(text): + try: + whole = json.loads(text) + except ValueError: + return text + if not isinstance(whole, dict): + return text + return re.sub(r"[\r\n]+", " ", text.strip()) + + +def text_of(message): + if isinstance(message, str): + return message + if isinstance(message, list): + return "\n".join(part.get("text") or "" for part in message if isinstance(part, dict) and part.get("type") == "text") + return "" + + +def trajectory_steps(): + try: + with open(TRAJECTORY, encoding="utf-8", errors="replace") as f: + return json.load(f).get("steps") or [] + except (OSError, ValueError, AttributeError, TypeError): + return [] + + +def find_reply(): + try: + with open(ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return on_one_line(text), "the answer file %s" % ANSWER + except OSError: + pass + for step in reversed(trajectory_steps()): + if isinstance(step, dict) and step.get("source") == "agent" and text_of(step.get("message")).strip(): + return text_of(step["message"]), "the last agent message in %s" % TRAJECTORY + return None, "nowhere: no answer file and no agent message in a trajectory file" + + +def verifier_tool(name): + """The verifier's own name for a tool call (mcp__verifier__solve -> solve), or None for any other tool.""" + sys.path.insert(0, SCORER) + from score import VERIFIER_TOOLS, tool_name + tool = tool_name(name) + return tool if tool in VERIFIER_TOOLS else None + + +def find_calls(): + """(list of {"tool", "arguments"} or None, where they were found).""" + if os.path.isfile(TRAJECTORY): + calls, other = [], 0 + for step in trajectory_steps(): + if not isinstance(step, dict) or step.get("source") != "agent": + continue + for call in step.get("tool_calls") or []: + if not isinstance(call, dict): + continue + tool = verifier_tool(call.get("function_name")) + if tool is None: + other += 1 + continue + arguments = call.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append({"tool": tool, "arguments": arguments if isinstance(arguments, dict) else {}}) + return calls, "%d verifier calls in %s (%d calls of other tools left out)" % (len(calls), TRAJECTORY, other) + if os.path.isfile(ORACLE_LOG): + try: + with open(CALLS, encoding="utf-8", errors="replace") as f: + logged = [json.loads(line) for line in f if line.strip()] + return logged, "the oracle's call log %s (no trajectory; %s is there)" % (CALLS, ORACLE_LOG) + except (OSError, ValueError): + return None, "nowhere: the oracle ran and wrote no call log" + return None, "nowhere: no trajectory file, and the oracle did not run" + + +def the_environment(): + path = os.path.join(TESTS, "environment.jsonl") + try: + with open(path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("%s cannot be read: %s" % (path, problem)) + if len(rows) != 1 or not isinstance(rows[0], dict) or not isinstance(rows[0].get("id"), str): + raise ScorerFailed("%s does not hold exactly one environment" % path) + return rows[0], path + + +def verifier_answers(): + if ENGINE.startswith("http://") or ENGINE.startswith("https://"): + return "an MCP address, not asked here" + if not os.path.isfile(ENGINE): + raise ScorerFailed("there is no verifier at %s" % ENGINE) + sys.path.insert(0, SCORER) + try: + from ztp_mcp import StdioVerifier + verifier = StdioVerifier([ENGINE], timeout_s=60, patience_s=0) + try: + verifier.connect() + server = verifier.server + finally: + verifier.close() + except Exception as problem: + raise ScorerFailed("the verifier at %s did not answer as an MCP server: %s" % (ENGINE, problem)) + if not isinstance(server, dict) or not server.get("name"): + raise ScorerFailed("the program at %s answered and did not say what it is; it is not the verifier" % ENGINE) + return "%s %s" % (server.get("name"), server.get("version")) + + +def run_scorer(command): + environment = dict(os.environ, PYTHONIOENCODING="utf-8") + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, + encoding="utf-8", errors="replace", start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=TIMEOUT_S) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + stdout, stderr = process.communicate() + return None, stdout, stderr + return process.returncode, stdout, stderr + + +def grade(log): + environment, environment_path = the_environment() + name = environment["id"] + reply, found = find_reply() + log.append("environment: %s" % name) + log.append("reply from: %s" % found) + log.append("verifier: %s (%s)" % (ENGINE, verifier_answers())) + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + if reply is not None: + with open(os.path.join(replies, name + ".txt"), "w", encoding="utf-8") as f: + f.write(reply) + calls, where = find_calls() + log.append("calls from: %s" % where) + if calls is not None: + with open(os.path.join(replies, name + ".calls.jsonl"), "w", encoding="utf-8") as f: + for call in calls: + f.write(json.dumps(call) + "\n") + scores_path = os.path.join(work, "scores.jsonl") + score_py = os.path.join(SCORER, "score.py") + entry = os.path.join(SCORER, "pack_score.py") + command = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", ENGINE, + "--environments", environment_path, "--only", name, "--out", scores_path] + with open(score_py, encoding="utf-8") as f: + if "--calls-from" in f.read(): + # the call record here is the one this file found: Harbor's trajectory, or the oracle's log + command += ["--calls-from", "reply"] + code, stdout, stderr = run_scorer(command) + log.append("score.py exit: %s" % ("none, ended after %g s" % TIMEOUT_S if code is None else code)) + log.append("score.py stdout:\n%s" % stdout) + log.append("score.py stderr:\n%s" % stderr) + if code is None: + raise ScorerFailed("score.py did not finish in %g s" % TIMEOUT_S) + if code != 0: + raise ScorerFailed("score.py exited %d: %s" % (code, (stderr.strip().splitlines() or ["no message"])[-1])) + try: + with open(scores_path, encoding="utf-8") as f: + rows = [json.loads(line) for line in f if line.strip()] + except (OSError, ValueError) as problem: + raise ScorerFailed("score.py wrote no scores that can be read: %s" % problem) + if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("id") != name: + raise ScorerFailed("score.py did not write one line for %s" % name) + row = rows[0] + if any(type(row.get(score)) is not int or row[score] not in (0, 1) for score in SCORES): + raise ScorerFailed("score.py did not give %s as 0 or 1" % " and ".join(SCORES)) + row["reply_from"] = found + reward = {"reward": int(all(row[score] == 1 for score in SCORES))} + reward.update((score, row[score]) for score in SCORES) + if isinstance(row.get("graded"), (int, float)): + reward["graded"] = row["graded"] + return reward, row + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name in ("reward.json", "reward.txt", "score.json"): + try: + os.remove(os.path.join(OUT, name)) + except OSError: + pass + log, failure = [], None + try: + reward, row = grade(log) + except ScorerFailed as problem: + failure = "the scorer failed, no reward written: %s" % problem + log.append(failure) + with open(os.path.join(OUT, "score.log"), "w", encoding="utf-8") as f: + f.write("\n".join(log) + "\n") + if failure: + sys.exit(failure) + with open(os.path.join(OUT, "score.json"), "w", encoding="utf-8") as f: + json.dump(row, f) + f.write("\n") + with open(os.path.join(OUT, "reward.json"), "w", encoding="utf-8") as f: + json.dump(reward, f) + f.write("\n") + print(json.dumps(reward)) + if row.get("reason"): + print(row["reason"].encode("ascii", "backslashreplace").decode("ascii")) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/hud_grade.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/hud_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..6421b277bb2b979dd9259509d2bba9b886f775f7 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/hud_grade.py @@ -0,0 +1,56 @@ +"""HUD's grader: grade.py, the Harbor grader, with one thing changed: where the record of the agent's calls comes from. + +HUD runs write no Harbor trajectory. The call record here is the log the proxy wrote in its own container, read through +score.py's chain check, and nothing else: no trajectory, no oracle log and no file the agent could leave in its own +container counts. No log, or a log whose chain does not hold, is no call record, and the task scores 0. + + ZTP_CALL_LOG the proxy's log (default /var/log/ztp-verifier/calls.jsonl) + ZTP_AGENT_ANSWER HUD's copy of the agent's last message (default /logs/agent_answer.txt) + +grade.py's other variables hold. Standard library only. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import grade as G # noqa: E402 + +CALL_LOG = os.environ.get("ZTP_CALL_LOG") or "/var/log/ztp-verifier/calls.jsonl" +AGENT_ANSWER = os.environ.get("ZTP_AGENT_ANSWER") or "/logs/agent_answer.txt" + + +def find_reply(): + try: + with open(G.ANSWER, encoding="utf-8-sig", errors="replace") as f: + text = f.read() + if text.strip(): + return G.on_one_line(text), "the answer file %s" % G.ANSWER + except OSError: + pass + try: + with open(AGENT_ANSWER, encoding="utf-8", errors="replace") as f: + text = f.read() + if text.strip(): + return text, "the agent's last message %s" % AGENT_ANSWER + except OSError: + pass + return None, "nowhere: no answer file and no last message" + + +def find_calls(): + sys.path.insert(0, G.SCORER) + from score import read_harness_log + calls, problem = read_harness_log(CALL_LOG) + if calls is None: + return None, "nowhere: the proxy's log %s is not here" % CALL_LOG + if problem: + return None, "nowhere: %s" % problem + return [{"tool": tool, "arguments": arguments} for tool, arguments in calls], "%d calls in the proxy's log %s" % (len(calls), CALL_LOG) + + +G.find_reply = find_reply +G.find_calls = find_calls + +if __name__ == "__main__": + G.main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aff9eeba48f21744458e717b9ff593585b20152e --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# HUD runs this after the agent has ended, in the grader's own image. The answer card is at /app/answer.json, and the +# proxy's call log, taken from the proxy's container, at /var/log/ztp-verifier/calls.jsonl. hud_grade.py writes +# /logs/verifier/reward.json; if the scorer itself fails it writes no reward and this exits non-zero. +HERE="$(cd "$(dirname "$0")" && pwd)" +exec python3 -B "$HERE/hud_grade.py" diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/hud/tasks/g5r8-dl-jet-tritium-rich-dome-hotion/tests/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/inspect/chainlib.py b/sample/tasks/inspect/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/inspect/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack(" the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "models": ["energy/tokamak_jet_dte1", "tokamak_dt_beam_target"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "models": ["tokamak_dt_beam_target"], "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "models": ["energy/tokamak_jet_dte1"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", "task": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "models": ["fusion_pb11_thermal"], "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", "task": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/inspect/inspect_task.py b/sample/tasks/inspect/inspect_task.py new file mode 100644 index 0000000000000000000000000000000000000000..acb6dee59704d9612e57e2aa0aaa8f23e25dfa7f --- /dev/null +++ b/sample/tasks/inspect/inspect_task.py @@ -0,0 +1,136 @@ +"""The free sample multi-step physics tasks as one Inspect task (inspect_ai, https://inspect.aisi.org.uk). + + pip install inspect-ai mcp + export ZTP_ENGINE=/absolute/path/to/mcp_stdio_local the verifier of release 0.15.3 (commit 664d68f4) over MCP stdio: + mcp_stdio_local beside this file, in a paid pack, runs the bundled + compiled verifier with no network; mcp_stdio_open runs the open + address, https://mcp.zerotrustphysics.com/mcp/open, through ztp_open_bridge.py + inspect eval inspect_task.py --model / + +Each sample is exactly the text prompt.py prints for one task, with the verifier (the program at ZTP_ENGINE over MCP +stdio) as the agent's tool server. The agent works in many steps: Inspect's generate loop sends every tool call to the +verifier and hands the answer back until the model gives its final reply or the message limit is reached. In the +design_to_limit and chained_design kinds the agent also has Inspect's python tool, because a coupling hands a run's +frames to a solve bit for bit and the frames come as hex: reading them is arithmetic, not physics. That tool runs in a +Docker sandbox (sandbox/compose.yaml: a plain Python image, no network, none of the task rows and no verifier), so the +agent's code reaches neither the answer key nor the verifier off the record. In a chained design that continues a run (from), the next run's start is the first run's final state as the verifier returned it. The budgeted_search and forensics kinds +have the verifier and nothing else, and need no sandbox. The verifier itself runs on the host, reached only through +its MCP tools. + +The model's last message is its reply; every call of the verifier's tools in state.messages is its call log, in order +(python tool calls are not verifier calls and are not counted). The scorer is score.py's own, held by pack_score.py to +the release (version 0.15.3, kernel genesis_kernel_v0.13.1), whichever program serves it: it +verifies each proof on the card on the verifier, computes each request again, and gives correct and proofs_hold, each +0 or 1, with the reason for a 0; reward is 1 only when both are 1. + + inspect eval inspect_task.py -T kind=budgeted_search --model / + inspect eval inspect_task.py -T python=false --model / + inspect eval inspect_task.py --sample-id --epochs 8 --model / pass@8 on one task + +Protocol Company. +""" +import asyncio +import json +import os +import sys + +from inspect_ai import Task, task +from inspect_ai.dataset import Sample +from inspect_ai.scorer import Score, Target, mean, scorer +from inspect_ai.solver import TaskState, generate, solver, use_tools +from inspect_ai.tool import mcp_server_stdio, mcp_tools +from inspect_ai.tool import python as python_tool + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import prompt as the_prompt # noqa: E402 +import pack_score # noqa: E402 + +the_scorer = pack_score.install() + +ENVIRONMENTS = os.path.join(HERE, "data", "environments.jsonl") +SANDBOX = os.path.join(HERE, "sandbox", "compose.yaml") +CODE_FAMILIES = ("tradeoff", "chain_design") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} + + +def engine_path(engine=None): + path = engine or os.environ.get("ZTP_ENGINE") + if not path: + raise ValueError("give the path to mcp_stdio: set ZTP_ENGINE, or pass -T engine=/absolute/path/to/mcp_stdio") + if not os.path.isfile(path): + raise ValueError("no file at %s: ZTP_ENGINE is the path to the program mcp_stdio" % path) + return os.path.abspath(path) + + +def calls_of(messages): + """Every call of the verifier's tools in the conversation, in order, as score.py reads a call log: [(tool, arguments)].""" + calls = [] + for message in messages: + for call in getattr(message, "tool_calls", None) or []: + tool = the_scorer.tool_name(call.function) + if tool not in the_scorer.VERIFIER_TOOLS: + continue # the python tool: not a verifier call + arguments = call.arguments + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + calls.append((tool, arguments if isinstance(arguments, dict) else {})) + return calls + + +def score_one(environment, reply, calls, engine): + try: + verifier = the_scorer.open_verifier(engine) + try: + return the_scorer.score(environment, reply, the_scorer.Replay(verifier), calls) + finally: + the_scorer.close_verifier(verifier) + except SystemExit as stopped: + raise RuntimeError(str(stopped)) from None + + +@scorer(metrics={"*": [mean()]}) +def computed_again_on_the_verifier(engine, environments): + by_id = {e["id"]: e for e in environments} + + async def score(state: TaskState, target: Target) -> Score: + reply = state.output.completion or "" + row = await asyncio.to_thread(score_one, by_id[state.sample_id], reply, calls_of(state.messages), engine) + lines = [line for line in reply.strip().splitlines() if line.strip()] + return Score(value={"reward": row["reward"], "correct": row["correct"], "proofs_hold": row["proofs_hold"]}, + answer=lines[-1] if lines else "", explanation=row["reason"]) + return score + + +@solver +def tools_for_the_kind(verifier, with_python): + async def solve(state, generate_): + tools = [mcp_tools(verifier)] + if with_python and state.metadata.get("family") in CODE_FAMILIES: + tools.append(python_tool()) + return await use_tools(*tools)(state, generate_) + return solve + + +@task +def zero_trust_physics_sample(engine: str | None = None, kind: str | None = None, python: bool = True, + message_limit: int = 200): + path = engine_path(engine) + environments = the_scorer.load_environments(ENVIRONMENTS) + if kind is not None: + if kind not in KINDS.values(): + raise ValueError("kind is one of %s" % ", ".join(KINDS.values())) + environments = [e for e in environments if (e.get("kind") or KINDS[e["family"]]) == kind] + verifier = mcp_server_stdio(name="verifier", command=path) + code_tasks = python and any(e["family"] in CODE_FAMILIES for e in environments) + return Task( + dataset=[Sample(id=e["id"], input=the_prompt.prompt(e), + metadata={"family": e["family"], "kind": e.get("kind") or KINDS[e["family"]]}) for e in environments], + solver=[tools_for_the_kind(verifier, python), generate()], + scorer=computed_again_on_the_verifier(path, environments), + sandbox=("docker", SANDBOX) if code_tasks else None, + message_limit=message_limit, + ) diff --git a/sample/tasks/inspect/mcp_stdio_open b/sample/tasks/inspect/mcp_stdio_open new file mode 100644 index 0000000000000000000000000000000000000000..71b5af54451c58cf6f0ff8bbc0b611f4cf5ed8b2 --- /dev/null +++ b/sample/tasks/inspect/mcp_stdio_open @@ -0,0 +1,3 @@ +#!/bin/sh +# The Zero-Trust Physics verifier at its open MCP address, as an MCP stdio server. +exec python3 "$(dirname "$0")/ztp_open_bridge.py" "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" diff --git a/sample/tasks/inspect/pack_score.py b/sample/tasks/inspect/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/inspect/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/inspect/prompt.py b/sample/tasks/inspect/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..a97c7cd395c83cb0842e59fcb0161d67a5b1c164 --- /dev/null +++ b/sample/tasks/inspect/prompt.py @@ -0,0 +1,194 @@ +"""Print exactly the text an agent is given for one environment: the task, then its family's footer. + + python3 prompt.py --environments F ENVIRONMENT_ID the text for one environment + python3 prompt.py --environments F --list every environment id, one a line + python3 prompt.py --environments F --all FOLDER write FOLDER/.txt for every environment + +Any runner for any model gives the agent this text and nothing else, with the verifier as its +tool server. + +Licence: Apache-2.0. +""" +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) + +COMMON = """You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.""" + +FOOTERS = { + "tradeoff": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names.""", + "chain_design": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps the constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks the constraint, no further from passing than the task's tolerance. binding: the id of the constraint. Each solve is the one handed its own design's sealed run through the coupling the task names.""", + "budget": COMMON + """ + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.""", + "forensics": COMMON + """ + +The card: +{"false_rows": {"": "", ...}} + +Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden. Leave the genuine rows out. {"false_rows": {}} says every row is genuine.""", +} + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +STOP_BINDS = """ Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }.""" + + +# The design shapes of the 29 Oct 2026 groups, each footer as its group built it (score.design_shape). +CONTINUED_CARRIED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is two runs: "run" is the first run, and "next" is the run that continues that same sealed run, with "from": {"request": , "run_seal": } and its initial state equal to the first run's final_state, value for value, bit for bit.""" + +CONTINUED_HANDED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. run is the design's first run; next is the run that continues that same sealed run through from: its from holds the first run's request and run_seal, and its start fields are the first run's final state exactly as the verifier returned it.""" + +CONTINUED_CARRY = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is two runs: run, and next, which continues that design's own sealed run through from (from.request is the run's request, from.run_seal its proof) and starts from its final state. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +SOLVE_DESIGN = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is one solve and no run.""" + +SOLVE_ONLY = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +STAGED = COMMON + """ + +The card: +{"passing": {%s}, "failing": {%s}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (%s), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer.""" + +STAGED_STOP = """ Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it%s.""" + +STOP_BINDS_SOLVE = """ Where one constraint is that the solve is not refused by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +SOLVE_STOP_G4 = """ Where one constraint is that the solve converges (it names a refusal) and that constraint binds, binding is its id and the failing design also carries "stopped": the refusal's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +CARRY_STOP_G5 = (" Where one constraint is that the second run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries" + " \"stopped\": the stop's name exactly as the verifier gives it, and \"step\": the last step the second run (next) is sealed to (its steps_landed), a whole number:" + " {\"run\": {...}, \"next\": {...}, \"stopped\": \"\", \"step\": }.") + +BUDGET_WORDS = " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + + +def shaped_footer(environment): + """The footer of a design of one of the added shapes, or None for a run or a coupled solve (FOOTERS).""" + family = environment["family"] + check = environment.get("check") or {} + design = check.get("design") or {} + if family not in ("tradeoff", "chain_design"): + return None + chain = design.get("chain") or {} + stops = [c for c in check.get("constraints") or [] if c.get("on") == "outcome"] + if design.get("stages"): # group 3 + stages = design["stages"] + shape = ", ".join('"%s": {"request": ..., "proof": ...}' % st["key"] for st in stages) + footer = STAGED % (shape, shape, ", ".join(st["key"] for st in stages)) + if stops: + runs = any(st["key"] == c.get("stage") and st["tool"] == "run_trajectory" for c in stops for st in stages) + footer += STAGED_STOP % (', and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number' if runs else "") + elif design.get("tool") == "solve": # group 4 + footer = SOLVE_DESIGN + (SOLVE_STOP_G4 if stops else "") + elif design.get("kind") == "solve": # group 5 + footer = SOLVE_ONLY + (STOP_BINDS_SOLVE if stops else "") + elif chain.get("kind") == "continuation" and "carried" in chain: # group 1 + footer = CONTINUED_CARRIED + if stops: + footer += STOP_BINDS + " In a chain the stop and the step are those of the failing design's next run." + elif chain.get("kind") == "continuation": # group 4 + footer = CONTINUED_HANDED + if stops: + footer += STOP_BINDS.replace("the run completes", "the second run completes").replace( + "the last step its run is sealed to", "the last step its next run is sealed to") + elif (chain.get("layout") or {}).get("kind") == "continue": # group 5 + footer = CONTINUED_CARRY + (CARRY_STOP_G5 if stops else "") + else: + return None + if check.get("budget"): + footer += BUDGET_WORDS + return footer + + +def prompt(environment): + """The whole text an agent is given for one environment.""" + family = environment["family"] + shaped = shaped_footer(environment) + if shaped is not None: + return environment["task"] + "\n\n" + shaped + footer = FOOTERS[family] + check = environment.get("check") or {} + if family in ("tradeoff", "chain_design") and any(c.get("on") == "outcome" for c in check.get("constraints") or []): + footer += STOP_BINDS + if family in ("tradeoff", "chain_design", "forensics") and check.get("budget"): + footer += " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + if family == "forensics" and check.get("reasons"): + footer = footer.replace("Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden.", + "Name every false row, each with its one reason from %s (the first of them, in that order, that is true of the row)." % ", ".join(check["reasons"])) + return environment["task"] + "\n\n" + footer + + +def main(): + argv = sys.argv[1:] + if len(argv) < 3 or argv[0] != "--environments": + sys.exit(__doc__) + environments = load_environments(argv[1]) + argv = argv[2:] + if argv[0] == "--list": + print("\n".join(e["id"] for e in environments)) + elif argv[0] == "--all": + if len(argv) < 2: + sys.exit("give the folder to write into") + os.makedirs(argv[1], exist_ok=True) + for e in environments: + with open(os.path.join(argv[1], e["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(prompt(e) + "\n") + print("wrote %d prompts to %s" % (len(environments), argv[1])) + else: + found = [e for e in environments if e["id"] == argv[0]] + if not found: + sys.exit("no environment with the id %s; --list names them" % argv[0]) + print(prompt(found[0])) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/inspect/sandbox/compose.yaml b/sample/tasks/inspect/sandbox/compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6832e8fa89241602cdf9447c99fd8525916c1c6 --- /dev/null +++ b/sample/tasks/inspect/sandbox/compose.yaml @@ -0,0 +1,9 @@ +# The sandbox Inspect's python tool runs in, for the design_to_limit and chained_design kinds only. +# A plain Python image: no network, none of the task rows, no verifier. The verifier runs on the host and is +# reached only through its MCP tools, so every verifier call is in the conversation and counted. +services: + default: + image: python:3.12-slim-bookworm + init: true + command: tail -f /dev/null + network_mode: none diff --git a/sample/tasks/inspect/score.py b/sample/tasks/inspect/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/inspect/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/inspect/ztp_mcp.py b/sample/tasks/inspect/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/inspect/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/inspect/ztp_open_bridge.py b/sample/tasks/inspect/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/inspect/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/README.md b/sample/tasks/mcp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d6e9922e7c9b2f923f027b2aa6a55c25ac35953 --- /dev/null +++ b/sample/tasks/mcp/README.md @@ -0,0 +1,36 @@ +# Native MCP variant + +Every task as a folder any MCP client can run: the prompt, an `mcp.json` whose only server is the Zero-Trust Physics verifier, and a one-line grader. + +``` +/prompt.md the text the agent is given, word for word +/mcp.json one server, "verifier": the logging proxy in front of mcp_stdio +/grade.sh the grader, one line +scorer/data/environments.jsonl every task row, with its `reference` and `check` fields: the grader reads it, the agent never needs it +scorer/ score.py, pack_score.py, grade_mcp.py, mcp_log_proxy.py, bind.py and what they import +logs/ the proxy's call record, one .harness.jsonl per task +``` + +A task folder holds those three files and nothing else. The answer key (each task's `reference` and `check` fields) lives in `scorer/`, outside every task folder. + +## Run one task + +1. The verifier is release 0.15.3, served at its open MCP address, https://mcp.zerotrustphysics.com/mcp/open. `scorer/mcp_stdio_open` runs it as an MCP stdio server (`scorer/ztp_open_bridge.py`, standard library only, posts each JSON-RPC message to the address unchanged). Call its absolute path ENGINE below. Any other stdio program that answers as release 0.15.3 serves the same. +2. `python3 scorer/bind.py --engine ENGINE` writes every `mcp.json` for where this folder sits. The `mcp.json` files in the archive name placeholder paths until you run it. +3. Start your MCP client in the task folder with that `mcp.json` (so that it uses this file and no other MCP configuration). Give the agent `prompt.md` and nothing else. The agent saves its answer card to `answer.json` in the task folder. +4. `ZTP_ENGINE=ENGINE bash grade.sh` writes `result/reward.json`: `reward` (0 or 1), `correct`, `proofs_hold` and `graded` (0 to 1). The grader computes every judged number again on the verifier. + +For a fresh attempt at the same task, delete `answer.json`, `result/` and the task's file in `logs/`. + +## What the agent must not reach + +The score is only as good as the call record. Set up the agent's sandbox so that: + +- **It sees its task folder and nothing above it.** `scorer/` holds every task's reference and `logs/` holds the call record. An agent that can read `scorer/data/environments.jsonl` can copy the answer; an agent that can write `logs/` can try to edit its record (an edited record breaks the SHA-384 chain and scores 0, a fresh one written from nothing does not). +- **It has no shell and no network of its own.** The proxy records every call that goes through `mcp.json`'s server. An agent that can reach the verifier another way (a shell, an HTTP tool) computes off the record, which defeats the call budget of a budgeted search and the forbidden-tool rule. Give the agent the verifier's tools and a way to write `answer.json`, and no other tool. + +The proxy changes no byte between the client and the verifier. It records every tool call with a SHA-384 chain, in `logs/`, and the grader scores the call budget from that record. + +## Scoring on any stdio program of the release + +The grader holds the verifier to its release: it must answer as version 0.15.3 with kernel `genesis_kernel_v0.13.1`. The program it runs is recorded by sha256 on every score row and scored the same; `grade_mcp.py --strict-binary` also requires the sha256 of our served macOS build. diff --git a/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/grade.sh b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/grade.sh new file mode 100644 index 0000000000000000000000000000000000000000..43257edc65d31ece5c5923c4a8eb860136e27f06 --- /dev/null +++ b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/grade.sh @@ -0,0 +1 @@ +cd "$(dirname "$0")" && python3 -B ../scorer/grade_mcp.py . --engine "${ZTP_ENGINE:?set ZTP_ENGINE to the path of mcp_stdio}" diff --git a/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/mcp.json b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..48d99dc8cb85dd4adf834d82b396aa9ea630cc40 --- /dev/null +++ b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "verifier": { + "type": "stdio", + "command": "python3", + "args": [ + "/path/to/unpacked/tasks/mcp/scorer/mcp_log_proxy.py", + "--log", + "/path/to/unpacked/tasks/mcp/logs/g5-bs-pb11-weakest-field-that-holds-b4.harness.jsonl", + "--forbid-under", + "/path/to/unpacked/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4", + "--", + "/usr/local/bin/mcp_stdio" + ] + } + } +} diff --git a/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/prompt.md b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..0b239e9794b4a5d955162a90f3879aa5cdcc2fa8 --- /dev/null +++ b/sample/tasks/mcp/g5-bs-pb11-weakest-field-that-holds-b4/prompt.md @@ -0,0 +1,19 @@ +A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla. + +Find it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T. + +The request, with the one input you change: +{"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": "", "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `answer.json` in this folder. diff --git a/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/grade.sh b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/grade.sh new file mode 100644 index 0000000000000000000000000000000000000000..43257edc65d31ece5c5923c4a8eb860136e27f06 --- /dev/null +++ b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/grade.sh @@ -0,0 +1 @@ +cd "$(dirname "$0")" && python3 -B ../scorer/grade_mcp.py . --engine "${ZTP_ENGINE:?set ZTP_ENGINE to the path of mcp_stdio}" diff --git a/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/mcp.json b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..5aa14b8f14808b8d06044a380bc7907f49ae3a30 --- /dev/null +++ b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "verifier": { + "type": "stdio", + "command": "python3", + "args": [ + "/path/to/unpacked/tasks/mcp/scorer/mcp_log_proxy.py", + "--log", + "/path/to/unpacked/tasks/mcp/logs/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7.harness.jsonl", + "--forbid-under", + "/path/to/unpacked/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", + "--", + "/usr/local/bin/mcp_stdio" + ] + } + } +} diff --git a/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/prompt.md b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..bb0e4734b2fdb50ae904d5c296164bf72e0cb677 --- /dev/null +++ b/sample/tasks/mcp/g5r10-ch-jet-dt3-least-tbeam-power-c12-b7/prompt.md @@ -0,0 +1,26 @@ +JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice. + +Find the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds. + +Constraints (id (the request it is read from): what, limit): +- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W +- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182 +- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit. +jet: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": "", "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}} +slice (it must converge): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": ["", 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}} + +Budget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "failing": {"jet": {"request": ..., "proof": ...}, "slice": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (jet, slice), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer. Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `answer.json` in this folder. diff --git a/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/grade.sh b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/grade.sh new file mode 100644 index 0000000000000000000000000000000000000000..43257edc65d31ece5c5923c4a8eb860136e27f06 --- /dev/null +++ b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/grade.sh @@ -0,0 +1 @@ +cd "$(dirname "$0")" && python3 -B ../scorer/grade_mcp.py . --engine "${ZTP_ENGINE:?set ZTP_ENGINE to the path of mcp_stdio}" diff --git a/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/mcp.json b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..c33dc1c006d08a919104e7c923ed21884733edb7 --- /dev/null +++ b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "verifier": { + "type": "stdio", + "command": "python3", + "args": [ + "/path/to/unpacked/tasks/mcp/scorer/mcp_log_proxy.py", + "--log", + "/path/to/unpacked/tasks/mcp/logs/g5r10-dl-dt4-core-te-fastshare-pion.harness.jsonl", + "--forbid-under", + "/path/to/unpacked/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion", + "--", + "/usr/local/bin/mcp_stdio" + ] + } + } +} diff --git a/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/prompt.md b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..8badb23e73e624cf53c2fbc7b46f06fde09e7091 --- /dev/null +++ b/sample/tasks/mcp/g5r10-dl-dt4-core-te-fastshare-pion/prompt.md @@ -0,0 +1,22 @@ +A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target). + +Find the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds. + +Constraints (id, what, limit): +- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J +- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W +Each design is one solve (leave out "run"): +{"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": ["", 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}} + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `answer.json` in this folder. diff --git a/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/grade.sh b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/grade.sh new file mode 100644 index 0000000000000000000000000000000000000000..43257edc65d31ece5c5923c4a8eb860136e27f06 --- /dev/null +++ b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/grade.sh @@ -0,0 +1 @@ +cd "$(dirname "$0")" && python3 -B ../scorer/grade_mcp.py . --engine "${ZTP_ENGINE:?set ZTP_ENGINE to the path of mcp_stdio}" diff --git a/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/mcp.json b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8232346994b8102b8aab6add0b803ec68243b2 --- /dev/null +++ b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "verifier": { + "type": "stdio", + "command": "python3", + "args": [ + "/path/to/unpacked/tasks/mcp/scorer/mcp_log_proxy.py", + "--log", + "/path/to/unpacked/tasks/mcp/logs/g5r8-bs-mast-2seg-drift-down-wall-b4.harness.jsonl", + "--forbid-under", + "/path/to/unpacked/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4", + "--", + "/usr/local/bin/mcp_stdio" + ] + } + } +} diff --git a/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/prompt.md b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..d2632fa13839cac62b78f356982a7b10f6313f7d --- /dev/null +++ b/sample/tasks/mcp/g5r8-bs-mast-2seg-drift-down-wall-b4/prompt.md @@ -0,0 +1,19 @@ +MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set. Beyond some negative voltage the plasma reaches the bottom wall before 56 ms and ends there (PlasmaAtWall). Find that voltage, in volts (a negative number). + +Find it to four significant figures: a value that completes and a value that stops with PlasmaAtWall, no more than 0.02 percent of the value apart. It lies between -8.3 and -6.1 V. + +The request, with the one input you change: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": ""}}], "record_every": 56}} + +Budget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `answer.json` in this folder. diff --git a/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/grade.sh b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/grade.sh new file mode 100644 index 0000000000000000000000000000000000000000..43257edc65d31ece5c5923c4a8eb860136e27f06 --- /dev/null +++ b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/grade.sh @@ -0,0 +1 @@ +cd "$(dirname "$0")" && python3 -B ../scorer/grade_mcp.py . --engine "${ZTP_ENGINE:?set ZTP_ENGINE to the path of mcp_stdio}" diff --git a/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/mcp.json b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..806e7e5e6a56d675c08d20c2c646cba8a245a635 --- /dev/null +++ b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "verifier": { + "type": "stdio", + "command": "python3", + "args": [ + "/path/to/unpacked/tasks/mcp/scorer/mcp_log_proxy.py", + "--log", + "/path/to/unpacked/tasks/mcp/logs/g5r8-dl-jet-tritium-rich-dome-hotion.harness.jsonl", + "--forbid-under", + "/path/to/unpacked/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion", + "--", + "/usr/local/bin/mcp_stdio" + ] + } + } +} diff --git a/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/prompt.md b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..543afca610094ae09cd88ba071f466a526339ce0 --- /dev/null +++ b/sample/tasks/mcp/g5r8-dl-jet-tritium-rich-dome-hotion/prompt.md @@ -0,0 +1,24 @@ +In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose. + +Find the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds. + +Constraints (id, what, limit): +- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W +- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J +- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon) +Each design is one run: +{"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": "", "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}} +This task has no solve: leave "solve" out of each design. + +Budget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls. + +You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request. + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names. Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all. + +Also write that answer card, by itself, to the file `answer.json` in this folder. diff --git a/sample/tasks/mcp/scorer/bind.py b/sample/tasks/mcp/scorer/bind.py new file mode 100644 index 0000000000000000000000000000000000000000..73f7d5e9f82808b769df4758f8576a7bd639c160 --- /dev/null +++ b/sample/tasks/mcp/scorer/bind.py @@ -0,0 +1,55 @@ +"""Write every task's mcp.json for where this folder sits now and where the verifier is. + + python3 bind.py --engine /absolute/path/to/mcp_stdio [--python /path/to/python3] + +Each task folder's mcp.json names one MCP server, "verifier": the logging proxy (scorer/mcp_log_proxy.py) in front of +the engine, recording every tool call to logs/.harness.jsonl, outside the task folder the agent works in. MCP +clients start a server from an absolute path, so run this once after unpacking, and again if the folder moves. +The file follows the common "mcpServers" layout that MCP clients read. +A task folder is a folder holding prompt.md and grade.sh; the task rows stay in scorer/data/environments.jsonl. +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def task_folders(root): + return [n for n in sorted(os.listdir(root)) + if os.path.isfile(os.path.join(root, n, "prompt.md")) and os.path.isfile(os.path.join(root, n, "grade.sh"))] + + +def bind(root, engine, python=None, as_root=None): + """Write mcp.json in every task folder under root. as_root: write the paths as if root sat there (for packing).""" + root = os.path.abspath(root) + named = as_root or root + python = python or (sys.executable if os.path.isabs(sys.executable) and not as_root else "python3") + proxy = os.path.join(named, "scorer", "mcp_log_proxy.py") + logs = os.path.join(named, "logs") + os.makedirs(os.path.join(root, "logs"), exist_ok=True) + n = 0 + for name in task_folders(root): + config = {"mcpServers": {"verifier": { + "type": "stdio", "command": python, + "args": [proxy, "--log", os.path.join(logs, name + ".harness.jsonl"), "--forbid-under", os.path.join(named, name), + "--", engine if as_root else os.path.abspath(engine)]}}} + with open(os.path.join(root, name, "mcp.json"), "w", encoding="utf-8") as f: + json.dump(config, f, indent=2) + f.write("\n") + n += 1 + return n + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--engine", required=True) + ap.add_argument("--root", default=os.path.dirname(HERE)) + ap.add_argument("--python", help="the Python that runs the proxy (default: the one running this)") + a = ap.parse_args() + print("wrote mcp.json in %d task folders under %s" % (bind(a.root, a.engine, a.python), os.path.abspath(a.root))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/chainlib.py b/sample/tasks/mcp/scorer/chainlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8dc60513d8f8f0372b1ff80d49884754a1d0e5 --- /dev/null +++ b/sample/tasks/mcp/scorer/chainlib.py @@ -0,0 +1,63 @@ +"""Build the solve request of a chained design from a run's answer: the history its coupling hands over. + +A coupling hands values from the run's recorded frames into the solve bit for bit: each frame's +32-bit slot widened exactly to 64 bits. The frame layout is in describe_card (frame_slots). This +module reads the slots from frame_hex with the standard library and lays the history out the way a +task states it. + + chained_solve(layout, parameters, run_request, run_answer) -> the solve's arguments, with from + +layout is the task's check.design.chain.layout: {"kind": "stardust_slab", "cool_to_s": 600.0} or +{"kind": "triga_element"}. + +Licence: Apache-2.0. +""" +import copy +import struct + + +def _slots(run_answer, f64_at, f32_at): + """Per recorded frame: the f64 at f64_at and each f32 at f32_at, widened.""" + out = [[] for _ in range(1 + len(f32_at))] + for frame in run_answer["frames"]: + raw = bytes.fromhex(frame["frame_hex"]) + out[0].append(struct.unpack(" the one input you change:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_vde_mast\", \"initial\": {\"displacement_m\": 0.0038, \"velocity_m_s\": 0.0249, \"wall_current_a\": -83.4, \"p6_current_a\": -31.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 18, \"load\": {\"p6_voltage_v\": 0.0}}, {\"steps\": 38, \"load\": {\"p6_voltage_v\": \"\"}}], \"record_every\": 56}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": null}}], "record_every": 56}, "variable": "segments[1].load.p6_voltage_v", "also": [], "stop": "PlasmaAtWall", "relative_width": 0.0002, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_budget_0.15.3", "note": "Nonlinear ODE / root-solved / slowing-down stop located by halving on engine v0.15.3 (4 computing calls).", "seed": 20261105808}, "reference": {"boundary": -6.944905450206351, "bisect_width": 4.219735671995295e-12, "holds": {"x": -6.9444887558793384, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.9444887558793384}}], "record_every": 56}}, "proof": "af7c1a55c046f9eb2d4dfd16f6fb19d38df753e7898a78f0d1f78ee681b75cdbbd71f41c0daae785a0e457284b865969", "outcome": "completed", "steps_landed": 56}, "stops": {"x": -6.945322144533363, "request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_vde_mast", "initial": {"displacement_m": 0.0038, "velocity_m_s": 0.0249, "wall_current_a": -83.4, "p6_current_a": -31.0}, "dt_s": 0.001, "segments": [{"steps": 18, "load": {"p6_voltage_v": 0.0}}, {"steps": 38, "load": {"p6_voltage_v": -6.945322144533363}}], "record_every": 56}}, "proof": "2a9fd2250b47253c715dc7ec72212fc582698014d70d59cdb57c3734bc5c54230995280fc673c94b47ca690e1409ba45", "outcome": "ended", "steps_landed": 55}, "span_pattern": "ssssssssssssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhh", "span": [-8.3, -6.1], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "family": "chain_design", "kind": "chained_design", "models": ["energy/tokamak_jet_dte1", "tokamak_dt_beam_target"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30). / The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose. Its final central ion temperature seeds the inner shell of a 3-shell carbon-seeded D-T beam-target slice.\n\nFind the smallest second-segment tritium beam power in JET, in watts, from 2000000 to 21000000 W, for which every constraint below holds. Give the passing design and the first failing design, no more than 860000 W apart, and name the constraint that binds.\n\nConstraints (id (the request it is read from): what, limit):\n- dt_power (slice): the D-T fusion power of the slice, in watts, at or above 912500 W\n- j_beta (jet): the highest normalised beta over the heating, at or below 1.8182\n- jet_completes (jet): the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is two requests: the two-segment JET D-T heating transient (jet), which must complete, then a multi-shell tokamak_dt_beam_target steady-state slice (slice), whose core ion temperature (parameters.ion_temperature_kev[0]) is JET's central ion temperature at the end of the heating (final_state.ion_temperature_kev), bit for bit.\njet:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 4950000.0, \"deuterium_beam_ion_energy_j\": 415000.0, \"tritium_beam_ion_energy_j\": 545000.0, \"tail_ion_energy_j\": 215000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 700, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": 5200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 8400000.0, \"tritium_beam_power_w\": \"\", \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 4800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 4.2e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.5, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 0.0}}], \"record_every\": 1800}}\nslice (it must converge):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.52, 2.92, 5.18], \"electron_temperature_kev\": [8.6, 5.4, 3.0], \"ion_temperature_kev\": [\"\", 6.9, 3.6], \"electron_density_per_m3\": [4.55e+19, 3.55e+19, 2.45e+19], \"deuterium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"tritium_density_per_m3\": [1.77e+19, 1.38e+19, 9.5e+18], \"impurity_density_per_m3\": [2.8e+17, 2.2e+17, 1.5e+17], \"impurity_charge\": 6.0, \"impurity_mass_u\": 12.0, \"beam_power_w\": [980000.0, 600000.0, 260000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [99.0, 136.0], \"beam_power_share\": [0.56, 0.44], \"time_since_beam_change_s\": 2.5}}}\n\nBudget: at most 7 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "stage": "jet", "path": "segments[1].load.tritium_beam_power_w", "words": "the second-segment tritium beam power in JET, in watts"}, "stages": [{"key": "jet", "tool": "run_trajectory", "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": null, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}, "outcomes": ["completed"]}, {"key": "slice", "tool": "solve", "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [null, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}, "outcomes": ["converged"], "handed": [{"to": "parameters.ion_temperature_kev[0]", "from": "jet", "read": {"kind": "final", "quantity": "ion_temperature_kev"}}]}], "direction": "smallest", "tolerance": 860000.0, "units": "W", "range": [2000000.0, 21000000.0]}, "constraints": [{"id": "dt_power", "on": "slice", "read": {"kind": "result", "quantity": "dt_fusion_power_w"}, "op": ">=", "words": "the D-T fusion power of the slice, in watts", "unit": "W", "limit": 912500.0}, {"id": "j_beta", "on": "jet", "read": {"kind": "extreme", "quantity": "beta_normalised", "which": "maximum"}, "op": "<=", "words": "the highest normalised beta over the heating", "unit": "", "limit": 1.8182}, {"id": "jet_completes", "on": "outcome", "words": "the JET heating run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon", "stage": "jet"}], "budget": 7, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_staged_0.15.3", "note": "Stage-2-binding cross-model staged design on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 9481916.12958908, "binding": "dt_power", "window_pattern": "................HHHHHHHHHHHHHHHHHHH......", "band": [9600000.0, 18150000.0], "near_pattern": ".....................HHHHHHHHHHHHHHHHHHHH", "passing": {"x": 9739916.12958908, "values": {"dt_power": 915408.0782751616, "j_beta": 1.5449607564082422, "jet_completes": "completed"}, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9739916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "71c43c6be42ee0feb79af6558df1d8f0896525ec88af722dca051db3ebbac3b812ab4b243c070274551d3c9fac2a3345"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.687979018530239, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "9b854cc83f04e474a1caba8e13412023318cfd68d762bb618852093e4793c34ff148e67aab32dbf952e8cf013eb7695e"}}}, "failing": {"x": 9223916.12958908, "values": {"dt_power": 909597.298361277, "j_beta": 1.528070182599308, "jet_completes": "completed"}, "broken": ["dt_power"], "stopped": null, "stopped_stage": null, "steps_landed": null, "design": {"jet": {"request": {"tool": "run_trajectory", "arguments": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 4950000.0, "deuterium_beam_ion_energy_j": 415000.0, "tritium_beam_ion_energy_j": 545000.0, "tail_ion_energy_j": 215000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 700, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 5200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 8400000.0, "tritium_beam_power_w": 9223916.12958908, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 4800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 4.2e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.5, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 0.0}}], "record_every": 1800}}, "proof": "b9b5d9df5395e4b94b6a2081ce20129a2cef08d4d57e176157547f0df31d860012a6828d688e1452dce0f55f70fb5c8e"}, "slice": {"request": {"tool": "solve", "arguments": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.52, 2.92, 5.18], "electron_temperature_kev": [8.6, 5.4, 3.0], "ion_temperature_kev": [8.553608273716595, 6.9, 3.6], "electron_density_per_m3": [4.55e+19, 3.55e+19, 2.45e+19], "deuterium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "tritium_density_per_m3": [1.77e+19, 1.38e+19, 9.5e+18], "impurity_density_per_m3": [2.8e+17, 2.2e+17, 1.5e+17], "impurity_charge": 6.0, "impurity_mass_u": 12.0, "beam_power_w": [980000.0, 600000.0, 260000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [99.0, 136.0], "beam_power_share": [0.56, 0.44], "time_since_beam_change_s": 2.5}}}, "proof": "8cdc3bfb971f2441011b090a478c4ccc531fc23c17613f064691b4b1c3eb07b1556c4b2911a07deec18489cd31903a3c"}}}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r10-dl-dt4-core-te-fastshare-pion", "family": "tradeoff", "kind": "design_to_limit", "models": ["tokamak_dt_beam_target"], "real_thing": "The deuterium-tritium fusion rate of one time slice of a tokamak pulse in steady state, from its analysed profiles (temperatures, densities, fuel mix in up to 128 radial shells) and its neutral beams: thermal, beam-target from classical slowing-down with the Bosch-Hale cross-section, and beam-beam reactions, the fusion power and the neutron rate. Range: ion temperature 0.2 to 100 keV, electron density 1e18 to 1e21 m^-3, beams to 1000 keV; held to TRANSP at shell ion temperatures of 0.2241 to 41.76 keV and beams of 26 to 152 keV, and computed with the same equations across the whole range. Nothing fitted. Held to TRANSP's fusion power in the International Multi-Tokamak Confinement Profile Database on 34 TFTR slices outside any fit. As served, with its three limits: 27 answered and 7 refused by name (5 FastIonShareTooLarge, 2 BeamChangeTooRecent); median of solver over database 1.011 (target 0.85 to 1.15); 25 of the 27 answered within 0.75 to 1.25, but 25 of the 34 with each refusal counted outside, against a target of 0.90 of them, the two answered outside being both slices of pulse 73268, whose database value is an alpha power; pulse 80539 at 1.070 of its measured 10.7 MW (target 0.80 to 1.20). The registered run of 9 October, before those limits, gave a median of 1.022 and 30 of the 34 within 0.75 to 1.25, 0.882, and missed its target of 0.90; the three limits were set after that comparison, on the same slices. Against four measured values it is +7, +21, -11 and about +8 percent. Gap: the solver's fast ions are 1.1 to 3.1 times the database's in the shell of largest excess, so the median agreement is partly a cancellation of that missing drag. Refuses a fast-ion share above 0.439 of the electrons (FastIonShareTooLarge), a charge balance with its own fast ions outside 21.5 percent under to 12 percent over the electrons (IonChargeBelowElectrons, IonChargeExceedsElectrons), and a slice stated sooner after a beam change than its slowest beam ion takes to stop (BeamChangeTooRecent); these three limits are set on the compared slices themselves.", "task": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_target).\n\nFind the largest inner-shell electron temperature, in keV, from 4.5 to 14.5 keV, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0095 keV apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- dt_fast_e, the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules, at or below 287440 J\n- dt_pion, the beam power transferred to thermal ions (beam_power_to_ions_w), in watts, at or above 1337600 W\nEach design is one solve (leave out \"run\"):\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"tokamak_dt_beam_target\", \"parameters\": {\"shell_volume_m3\": [1.02, 1.92, 3.22, 5.18], \"electron_temperature_kev\": [\"\", 6.4, 4.2, 2.5], \"ion_temperature_kev\": [13.2, 8.2, 5.1, 3.0], \"electron_density_per_m3\": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], \"deuterium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"tritium_density_per_m3\": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], \"impurity_density_per_m3\": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], \"impurity_charge\": 8.0, \"impurity_mass_u\": 16.0, \"beam_power_w\": [920000.0, 620000.0, 380000.0, 160000.0], \"beam_mass_number\": [2.0, 3.0], \"beam_energy_kev\": [98.0, 138.0], \"beam_power_share\": [0.54, 0.46], \"time_since_beam_change_s\": 2.9}}}\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "solve", "path": "parameters.electron_temperature_kev[0]", "words": "the inner-shell electron temperature, in keV"}, "template": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [null, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "free": [], "run_outcomes": ["converged"], "direction": "largest", "tolerance": 0.0095, "units": "keV", "chain": null, "range": [4.5, 14.5], "kind": "solve"}, "constraints": [{"id": "dt_fast_e", "on": "solve", "read": {"kind": "result", "quantity": "fast_ion_energy_j"}, "op": "<=", "words": "the total fast-ion stored energy across the shells (fast_ion_energy_j), in joules", "unit": "J", "limit": 287440.0}, {"id": "dt_pion", "on": "solve", "read": {"kind": "result", "quantity": "beam_power_to_ions_w"}, "op": ">=", "words": "the beam power transferred to thermal ions (beam_power_to_ions_w), in watts", "unit": "W", "limit": 1337600.0}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 10.74198080971837, "binding": "dt_fast_e", "window_pattern": "..........HHHHHHHHHHHHHHH................", "band": [7.0, 10.5], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 10.73913080971837, "values": {"dt_fast_e": 287432.26582966035, "dt_pion": 1416374.7606783519}, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.73913080971837, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "c7d03a6691c219701e3f080a9c441aaaf0a6da69034dc6784e2e1937b97ed458578394b31f52d9a6997e80dd1a001949", "run": null, "run_seal": null}, "failing": {"x": 10.744830809718371, "values": {"dt_fast_e": 287447.72985324025, "dt_pion": 1416448.9984800045}, "broken": ["dt_fast_e"], "stopped": null, "stopped_stage": null, "steps_landed": null, "solve": {"solver": "tokamak_dt_beam_target", "parameters": {"shell_volume_m3": [1.02, 1.92, 3.22, 5.18], "electron_temperature_kev": [10.744830809718371, 6.4, 4.2, 2.5], "ion_temperature_kev": [13.2, 8.2, 5.1, 3.0], "electron_density_per_m3": [4.72e+19, 3.88e+19, 2.98e+19, 2.08e+19], "deuterium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "tritium_density_per_m3": [1.84e+19, 1.51e+19, 1.16e+19, 8.1e+18], "impurity_density_per_m3": [2.4e+17, 1.9e+17, 1.5e+17, 1e+17], "impurity_charge": 8.0, "impurity_mass_u": 16.0, "beam_power_w": [920000.0, 620000.0, 380000.0, 160000.0], "beam_mass_number": [2.0, 3.0], "beam_energy_kev": [98.0, 138.0], "beam_power_share": [0.54, 0.46], "time_since_beam_change_s": 2.9}}, "solution_seal": "9f709500d24174c46d6e1792e46668dc97158b03b3957653cd9fbf9968736a5c379139768ff066575d7f87303707d97e", "run": null, "run_seal": null, "outcome": "converged"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5r8-dl-jet-tritium-rich-dome-hotion", "family": "tradeoff", "kind": "design_to_limit", "models": ["energy/tokamak_jet_dte1"], "real_thing": "Heated pulse of JET in its 1996 to 1997 D-T campaign, ELMy or hot-ion H-mode: thermal energy, D and T beam ions slowed classically on the measured electron temperature, the ICRH tail and alphas, the central ion temperature, and the thermal and beam-target D-T fusion power, the energy ledger closed every step. Compared with 10 pulses, each left out in turn, medians: thermal energy within 16.0 percent of peak RMS, fast ions 5.3, fusion power 16.4 (7 D-T); fusion energy 0.830 of the database on 42982, 0.782 to 1.188 at tritium 0.754 to 0.928. Gap: 42976 left out, hot-ion fusion energy 0.392 (4.03 MJ against 10.30).", "task": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one tritium fraction that you choose.\n\nFind the largest second-segment tritium fuel fraction, from 0.5 to 0.9, for which every constraint below holds. Give the passing design and the first failing design, no more than 0.0003 apart, and name the constraint that binds.\n\nConstraints (id, what, limit):\n- j_fusion, the D-T fusion power at the end of the heating, in watts, at or above 13759000 W\n- j_fusion_energy, the D-T fusion energy released over the heating, in joules, at or above 13651100 J\n- completes, the run completes without crossing the Troyon limit (BetaAboveTroyon)\nEach design is one run:\n{\"tool\": \"run_trajectory\", \"arguments\": {\"domain\": \"energy\", \"card\": \"tokamak_jet_dte1\", \"initial\": {\"thermal_energy_j\": 5350000.0, \"deuterium_beam_ion_energy_j\": 455000.0, \"tritium_beam_ion_energy_j\": 515000.0, \"tail_ion_energy_j\": 235000.0, \"elapsed_time_s\": 0.0}, \"dt_s\": 0.001, \"segments\": [{\"steps\": 600, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": 0.52, \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}, {\"steps\": 1100, \"load\": {\"deuterium_beam_power_w\": 5800000.0, \"tritium_beam_power_w\": 6200000.0, \"deuterium_beam_energy_kev\": 93.0, \"tritium_beam_energy_kev\": 131.0, \"icrh_power_w\": 2800000.0, \"ohmic_power_w\": 540000.0, \"line_density_per_m3\": 3.6e+19, \"plasma_current_a\": 3350000.0, \"toroidal_field_t\": 3.55, \"tritium_fraction\": \"\", \"electron_temperature_kev\": 7.6, \"effective_charge\": 1.95, \"hot_ion_regime\": 1.0}}], \"record_every\": 1700}}\nThis task has no solve: leave \"solve\" out of each design.\n\nBudget: at most 4 calls that compute, counted over every call you make, each run and each solve one call; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Every request on your card must be among your calls.", "check": {"design": {"variable": {"kind": "path", "on": "run", "path": "segments[1].load.tritium_fraction", "words": "the second-segment tritium fuel fraction"}, "template": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": null, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "free": [], "run_outcomes": ["completed"], "direction": "largest", "tolerance": 0.0003, "units": "", "chain": null, "range": [0.5, 0.9]}, "constraints": [{"id": "j_fusion", "on": "run", "read": {"kind": "final", "quantity": "fusion_power_w"}, "op": ">=", "words": "the D-T fusion power at the end of the heating, in watts", "unit": "W", "limit": 13759000.0}, {"id": "j_fusion_energy", "on": "run", "read": {"kind": "final", "quantity": "fusion_energy_j"}, "op": ">=", "words": "the D-T fusion energy released over the heating, in joules", "unit": "J", "limit": 13651100.0}, {"id": "completes", "on": "outcome", "words": "the run completes without crossing the Troyon limit (BetaAboveTroyon)", "stop": "BetaAboveTroyon"}], "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion_tradeoff_0.15.3", "note": "Nonlinear / non-monotonic design_to_limit task on engine v0.15.3.", "seed": 20261105808}, "reference": {"boundary": 0.7462128712236883, "binding": "j_fusion", "window_pattern": "HHHHHHHHHHHHHHHHHHHHHHHHH................", "band": [0.5, 0.74], "near_pattern": "HHHHHHHHHHHHHHHHHHHHH....................", "passing": {"x": 0.7461228712236883, "values": {"j_fusion": 13761822.193937019, "j_fusion_energy": 15585272.122693202, "completes": "completed"}, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7461228712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "a5346d0d5f1fc3c96bc0f7049252f4600e01ee120ae525e75760168a9bc0b3dd7a6e206762585c8bdf6f74406a95f153", "solve": null, "solution_seal": null}, "failing": {"x": 0.7463028712236883, "values": {"j_fusion": 13756176.830839999, "j_fusion_energy": 15580674.868673041, "completes": "completed"}, "broken": ["j_fusion"], "stopped": null, "stopped_stage": null, "steps_landed": 1700, "run": {"domain": "energy", "card": "tokamak_jet_dte1", "initial": {"thermal_energy_j": 5350000.0, "deuterium_beam_ion_energy_j": 455000.0, "tritium_beam_ion_energy_j": 515000.0, "tail_ion_energy_j": 235000.0, "elapsed_time_s": 0.0}, "dt_s": 0.001, "segments": [{"steps": 600, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.52, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}, {"steps": 1100, "load": {"deuterium_beam_power_w": 5800000.0, "tritium_beam_power_w": 6200000.0, "deuterium_beam_energy_kev": 93.0, "tritium_beam_energy_kev": 131.0, "icrh_power_w": 2800000.0, "ohmic_power_w": 540000.0, "line_density_per_m3": 3.6e+19, "plasma_current_a": 3350000.0, "toroidal_field_t": 3.55, "tritium_fraction": 0.7463028712236883, "electron_temperature_kev": 7.6, "effective_charge": 1.95, "hot_ion_regime": 1.0}}], "record_every": 1700}, "run_seal": "fd452cfc8d478f74001f42b98c64e715f16fccf03ee133618622719c872f6aa04f3ea4065d238f8049a3bb28458fc2b3", "solve": null, "solution_seal": null, "outcome": "completed"}, "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} +{"id": "g5-bs-pb11-weakest-field-that-holds-b4", "family": "budget", "kind": "budgeted_search", "models": ["fusion_pb11_thermal"], "real_thing": "Energy balance of a uniform thermal proton-boron-11 plasma: the electron temperature at which the electrons balance, fusion, bremsstrahlung, synchrotron and exchange power, and the ignition margin. Range: ion temperature 1 to 1000 keV, electron density 1e18 to 1e22 m^-3, boron 0.01 to 0.9 of the fuel ions; held to published calculations at ion temperatures of 200 to 450 keV, and computed with the same equations across the whole range. Nothing fitted: the cross-section, radiation and exchange forms are published ones. Held to the published calculations of Ochs et al. 2022 and Putvinski et al. 2019: the electron temperature at 300 keV and 13 percent boron within 2.3 percent (target 5), the largest fusion power over bremsstrahlung within 0.2 percent (target 2). The comparison's request at 300 keV (13 percent boron, electron density 1.52e20 m^-3, 20 T, wall reflectivity 1, kinetic enhancement on) gives an electron temperature of 159.33 keV against a published 163.0, and an ignition margin of 0.037. The worked example, example_solve, is another plasma at 300 keV (15 percent boron, 1.6e20 m^-3, 6.661 T, wall reflectivity 0.95, kinetic enhancement off): an electron temperature of 113.152 keV and an ignition margin of -1.042, so it does not ignite. Gap: synchrotron over fusion power is 7.9 percent off a plain-Python model of the same balance (target 5), and two published bremsstrahlung fits differ by as much as the ignition margin. Refuses an ion temperature outside 1 to 1000 keV (IonTemperatureOutOfRange), a plasma the field cannot hold (PressureExceedsField) and electrons that find no balance (ElectronTemperatureOutOfRange).", "task": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an energy confinement time of 45 s and the kinetic enhancement off, is held in a magnetic field you set. Below some field the field cannot hold the plasma's pressure and the solve is refused (PressureExceedsField). Find that field, in tesla.\n\nFind it to four significant figures: a value whose solve converges and a value whose solve is refused with PressureExceedsField, no more than 0.01 percent of the value apart. It lies between 4.8 and 7.2 T.\n\nThe request, with the one input you change:\n{\"tool\": \"solve\", \"arguments\": {\"solver\": \"fusion_pb11_thermal\", \"parameters\": {\"ion_temperature_kev\": 310.0, \"electron_density_per_m3\": 2.2e+20, \"boron_fraction\": 0.128, \"ash_fraction\": 0.01, \"magnetic_field_t\": \"\", \"minor_radius_m\": 2.1, \"wall_reflectivity\": 0.96, \"energy_confinement_time_s\": 45.0, \"kinetic_enhancement\": false}}}\n\nBudget: at most 4 calls that compute, counted over every call you make; list_cards, list_solvers, find_model, describe_card, describe_solver, cite and verify_receipt are free. find_flip, design_run, run_dataset and validate_series may not be called at all. Both requests on your card must be among your calls.", "check": {"tool": "solve", "template": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": null, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}, "variable": "parameters.magnetic_field_t", "also": [], "stop": "PressureExceedsField", "relative_width": 0.0001, "budget": 4, "forbidden": ["find_flip", "design_run", "run_dataset", "validate_series"]}, "seed": {"kind": "nuclear_fusion", "note": "A stop located by halving on the engine; the span set unevenly about it by the seed; the task rules the search tools out and allows 4 computing calls.", "seed": 2026102905}, "reference": {"boundary": 5.6956273361119205, "bisect_width": 3.4559022310531873e-12, "holds": {"x": 5.695798204932004, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695798204932004, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "1fc55af713082947dedfd87bf14ccb2d76529f1d9ff72aa5343d07864d4f3e0df2b4eea19a46ef3924c9b028a3198793", "outcome": "converged", "steps_landed": null}, "stops": {"x": 5.695456467291837, "request": {"tool": "solve", "arguments": {"solver": "fusion_pb11_thermal", "parameters": {"ion_temperature_kev": 310.0, "electron_density_per_m3": 2.2e+20, "boron_fraction": 0.128, "ash_fraction": 0.01, "magnetic_field_t": 5.695456467291837, "minor_radius_m": 2.1, "wall_reflectivity": 0.96, "energy_confinement_time_s": 45.0, "kinetic_enhancement": false}}}, "proof": "97fb0ea65dc740be53cc1c8aad5002b080018c4cbbcac26eaa42ba4956f1f8e6284a20695008a3c94cf7f26a6139a880", "outcome": "refused", "steps_landed": null}, "span_pattern": "sssssssssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "wide_pattern": "sssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "span": [4.8, 7.2], "engine_source": "https://github.com/johnkruze/zero-trust-physics-engine", "engine_tag": "v0.15.3", "engine_commit": "664d68f426ccdfd0159e5f91857edba3872390d1", "gateway_version": "0.15.3", "engine_binary_sha256": "2569d8f69b023f7e7fe441c31d3f69ea94d9adfa8100d6e7e56855768c147076"}} diff --git a/sample/tasks/mcp/scorer/grade_mcp.py b/sample/tasks/mcp/scorer/grade_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..07b06661843436696e25c5f80bb6e42b1044eb91 --- /dev/null +++ b/sample/tasks/mcp/scorer/grade_mcp.py @@ -0,0 +1,82 @@ +"""Score one task of the native MCP variant: the answer card in the task folder, the calls the logging proxy recorded. + + ZTP_ENGINE=/path/to/mcp_stdio python3 -B ../scorer/grade_mcp.py . (from inside a task folder) + python3 -B grade_mcp.py TASK_FOLDER --engine /path/to/mcp_stdio + +Reads the task's row from ../scorer/data/environments.jsonl by the task folder's name (the id; the row never sits in the +folder the agent works in), TASK_FOLDER/answer.json (the card the prompt asks the agent to save; +a whole reply ending in the card also works) and the proxy's call record, ../logs/.harness.jsonl beside the task +folders (where mcp.json tells the proxy to write it, outside the agent's working folder). Hands them to score.py (through +pack_score.py, which holds the verifier to release 0.15.3 and kernel genesis_kernel_v0.13.1, so a verifier built from +source scores the same; --strict-binary also requires the served build's sha256), which verifies every proof and +computes every request again on the verifier. Writes TASK_FOLDER/result/reward.json +({"reward", "correct", "proofs_hold", "graded"}) and score.json (the scorer's line, with the reason for a 0), prints the +reward, and exits 0 when the scoring ran (whatever the reward) and non-zero when it could not. +""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("task", nargs="?", default=".") + ap.add_argument("--engine", default=os.environ.get("ZTP_ENGINE")) + ap.add_argument("--log", help="the proxy's call record (default ../logs/.harness.jsonl beside the task folder)") + ap.add_argument("--environments", default=os.path.join(HERE, "data", "environments.jsonl")) + ap.add_argument("--strict-binary", action="store_true") + a = ap.parse_args() + if not a.engine: + sys.exit("give the verifier: --engine /path/to/mcp_stdio, or set ZTP_ENGINE") + task = os.path.abspath(a.task) + env_path = os.path.abspath(a.environments) + rows = [json.loads(line) for line in open(env_path, encoding="utf-8") if line.strip()] + found = [r for r in rows if r.get("id") == os.path.basename(task)] + if len(found) != 1: + sys.exit("no task %s in %s" % (os.path.basename(task), env_path)) + env = found[0] + log = a.log or os.path.join(os.path.dirname(task), "logs", env["id"] + ".harness.jsonl") + out = os.path.join(task, "result") + os.makedirs(out, exist_ok=True) + score_py = os.path.join(HERE, "score.py") + entry = os.path.join(HERE, "pack_score.py") + harness_mode = "--calls-from" in open(score_py, encoding="utf-8").read() + with tempfile.TemporaryDirectory() as work: + replies = os.path.join(work, "replies") + os.mkdir(replies) + answer = os.path.join(task, "answer.json") + if os.path.isfile(answer): + text = open(answer, encoding="utf-8-sig", errors="replace").read().strip() + try: + text = json.dumps(json.loads(text)) # one JSON object over several lines, put on one line + except ValueError: + pass + open(os.path.join(replies, env["id"] + ".txt"), "w", encoding="utf-8").write(text + "\n") + if os.path.isfile(log): + shutil.copyfile(log, os.path.join(replies, env["id"] + (".harness.jsonl" if harness_mode else ".calls.jsonl"))) + scores = os.path.join(work, "scores.jsonl") + cmd = [sys.executable, "-B", entry if os.path.isfile(entry) else score_py, replies, "--engine", a.engine, "--environments", env_path, + "--only", env["id"], "--out", scores] + if harness_mode: + cmd += ["--calls-from", "harness"] + if a.strict_binary: + cmd.append("--strict-binary") + p = subprocess.run(cmd, capture_output=True, text=True) + open(os.path.join(out, "score.log"), "w").write(p.stdout + p.stderr) + if p.returncode != 0 or not os.path.isfile(scores): + sys.exit("score.py exited %d: %s" % (p.returncode, (p.stderr.strip().splitlines() or ["no message"])[-1])) + row = json.loads(open(scores).readline()) + reward = {k: row.get(k) for k in ("reward", "correct", "proofs_hold", "graded") if k in row} + json.dump(row, open(os.path.join(out, "score.json"), "w")) + json.dump(reward, open(os.path.join(out, "reward.json"), "w")) + print(json.dumps(reward), row.get("reason") or "") + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/mcp_log_proxy.py b/sample/tasks/mcp/scorer/mcp_log_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..0172d4963b39b33786a5d07ab7e2c9de50879123 --- /dev/null +++ b/sample/tasks/mcp/scorer/mcp_log_proxy.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""A stdio MCP proxy that records every tool call and changes no byte of any message. + + python3 mcp_log_proxy.py --log LOG [--forbid-under DIR ...] [--trace FILE] -- ENGINE [ENGINE ARGS ...] + +It starts ENGINE (an MCP server over stdio, one JSON-RPC message a line, such as the Zero-Trust +Physics mcp_stdio), hands every line the client writes to ENGINE's stdin, and every line ENGINE +writes back to the client's stdout, byte for byte. It reads a copy of each message and, for every +tools/call, appends one JSON line to LOG when the answer comes back: + + {"seq", "jsonrpc_id", "tool", "arguments", "ts_request", "ts_response", "duration_s", + "response_sha384", "text_sha384", "is_error", "chain"} + +response_sha384 is the SHA-384 of the answer line exactly as forwarded (without its newline); +text_sha384 is the SHA-384 of the answer's text content. chain is the SHA-384 of the previous +line's chain followed by this line's JSON without its chain (sorted keys, no spaces): an edit to +any line, or a line taken out, breaks every chain after it. A call still unanswered when the +client closes is written with "unanswered": true. + +LOG must lie outside the solver's working directory: the proxy refuses to start when LOG is +under its own working directory (where an agent's CLI starts it) or under any --forbid-under. +Beside LOG it keeps LOG.status.json: the engine command, the handshake (initialize, or +server/discover under MCP 2026-07-28), the call count, the engine's exit code. --trace FILE also keeps every line both ways, for diagnosing a client. + +Standard library only. Licence: Apache-2.0. +""" +import hashlib +import json +import os +import signal +import subprocess +import sys +import threading +import time + + +# initialize (MCP 2025-06-18 and before) or server/discover (MCP 2026-07-28, which newer clients send first) +HANDSHAKES = ("initialize", "server/discover") + + +def now(): + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + ".%03dZ" % (int(time.time() * 1000) % 1000) + + +def sha384(data): + return hashlib.sha384(data).hexdigest() + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return sha384(((previous or "") + payload).encode("utf-8")) + + +def under(path, folder): + path, folder = os.path.realpath(path), os.path.realpath(folder) + return path == folder or path.startswith(folder.rstrip(os.sep) + os.sep) + + +class Recorder: + def __init__(self, log_path, engine): + self.log_path = log_path + self.lock = threading.Lock() + self.pending = {} + self.seq = 0 + self.chain = None + self.status = {"engine": engine, "proxy_pid": os.getpid(), "started": now(), "handshake": None, + "tools_list": False, "calls": 0, "unanswered": 0, "engine_exit": None, "ended": None, + "problems": []} + open(log_path, "a").close() + self.write_status() + + def write_status(self): + tmp = self.log_path + ".status.json.tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(self.status, f, indent=1) + os.replace(tmp, self.log_path + ".status.json") + + def append(self, entry): + """One log line, chained to the one before. Called with the lock held.""" + self.seq += 1 + entry = dict(entry, seq=self.seq) + entry["chain"] = chain_of(self.chain, entry) + self.chain = entry["chain"] + with open(self.log_path, "a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + self.status["calls"] += 1 + + @staticmethod + def messages(line): + try: + found = json.loads(line) + except ValueError: + return [] + if isinstance(found, list): + return [m for m in found if isinstance(m, dict)] + return [found] if isinstance(found, dict) else [] + + def from_client(self, line): + for message in self.messages(line): + if "id" in message and message.get("method"): + key = json.dumps(message["id"]) + with self.lock: + self.pending[key] = {"method": message["method"], "params": message.get("params"), + "ts": now(), "t0": time.time(), "id": message["id"]} + + def from_engine(self, line): + raw = line.rstrip(b"\r\n") + for message in self.messages(line): + if "id" not in message or message.get("method"): + continue + key = json.dumps(message["id"]) + with self.lock: + asked = self.pending.pop(key, None) + if asked is None: + continue + if asked["method"] in HANDSHAKES: + result = message.get("result") if isinstance(message.get("result"), dict) else {} + if not (self.status["handshake"] or {}).get("ok"): + srv = result.get("serverInfo") + if isinstance(srv, dict) and str(srv.get("title") or "").startswith("Zero-Trust Physics"): + desc = str(srv.get("description") or "") + if ": " in desc: + desc = "Deterministic physics of real objects: " + desc.split(": ", 1)[1] + srv = dict(srv, title="Zero-Trust Physics Verifier", description=desc) + self.status["handshake"] = {"method": asked["method"], "ok": "result" in message, + "server": srv} + self.write_status() + elif asked["method"] == "tools/list": + if not self.status["tools_list"]: + self.status["tools_list"] = "result" in message + self.write_status() + elif asked["method"] == "tools/call": + params = asked["params"] if isinstance(asked["params"], dict) else {} + result = message.get("result") if isinstance(message.get("result"), dict) else {} + text = "".join(c.get("text", "") for c in result.get("content", []) or [] if isinstance(c, dict)) + self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"), + "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": asked["ts"], "ts_response": now(), + "duration_s": round(time.time() - asked["t0"], 6), + "response_sha384": sha384(raw), "text_sha384": sha384(text.encode("utf-8")), + "is_error": bool(result.get("isError")) or "error" in message}) + + def close(self, engine_exit): + with self.lock: + for asked in self.pending.values(): + if asked["method"] != "tools/call": + continue + params = asked["params"] if isinstance(asked["params"], dict) else {} + self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"), + "arguments": params.get("arguments") if params.get("arguments") is not None else {}, + "ts_request": asked["ts"], "ts_response": None, "duration_s": None, + "response_sha384": None, "text_sha384": None, "is_error": None, "unanswered": True}) + self.status["unanswered"] += 1 + self.pending.clear() + self.status["engine_exit"] = engine_exit + self.status["ended"] = now() + self.write_status() + + +def main(argv): + log, forbid, engine, trace = None, [], None, None + i = 0 + while i < len(argv): + if argv[i] == "--": + engine = argv[i + 1:] + break + if argv[i] == "--log" and i + 1 < len(argv): + log = argv[i + 1] + i += 2 + continue + if argv[i] == "--trace" and i + 1 < len(argv): + trace = open(argv[i + 1], "ab") + i += 2 + continue + if argv[i] == "--forbid-under" and i + 1 < len(argv): + forbid.append(argv[i + 1]) + i += 2 + continue + sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]") + if not log or not engine: + sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]") + log = os.path.abspath(log) + for folder in [os.getcwd()] + forbid: + if under(log, folder): + sys.exit("mcp_log_proxy: the log %s lies inside %s, where the solver works; put it outside" % (log, folder)) + os.makedirs(os.path.dirname(log), exist_ok=True) + recorder = Recorder(log, engine) + try: + proc = subprocess.Popen(engine, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr.fileno(), bufsize=0) + except OSError as problem: + recorder.status["problems"].append("the engine did not start: %s" % problem) + recorder.close(None) + sys.exit("mcp_log_proxy: the engine did not start: %s" % problem) + out = sys.stdout.buffer + + def engine_to_client(): + try: + for line in iter(proc.stdout.readline, b""): + if trace: + trace.write(b"< " + line) + trace.flush() + try: + recorder.from_engine(line) + except Exception as problem: # the log must never stop an answer + recorder.status["problems"].append("log: %s" % problem) + out.write(line) + out.flush() + except (BrokenPipeError, OSError) as problem: + recorder.status["problems"].append("client output closed: %s" % problem) + + finished = threading.Lock() + + def finish(): + """Once: close the engine, log what is unanswered, close the client's output, and leave.""" + if not finished.acquire(blocking=False): + return + try: + proc.stdin.close() + except OSError: + pass + try: + code = proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + code = proc.wait() + recorder.close(code) + try: + out.flush() + except OSError: + pass + os._exit(0) + + reader_done = threading.Event() + client_closed = threading.Event() + + def engine_to_client_then_finish(): + engine_to_client() + reader_done.set() + if proc.poll() is None: + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + if proc.poll() is not None and not client_closed.is_set(): + # the engine has gone: the client must see its output close rather than wait for an answer + recorder.status["problems"].append("the engine closed its output (exit %s)" % proc.returncode) + finish() + + reader = threading.Thread(target=engine_to_client_then_finish, daemon=True) + reader.start() + + def stop(signum, frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGHUP, stop) + source = sys.stdin.buffer + try: + for line in iter(source.readline, b""): + if trace: + trace.write(b"> " + line) + trace.flush() + try: + recorder.from_client(line) + except Exception as problem: + recorder.status["problems"].append("log: %s" % problem) + try: + proc.stdin.write(line) + proc.stdin.flush() + except (BrokenPipeError, OSError) as problem: + recorder.status["problems"].append("engine input closed: %s" % problem) + break + except KeyboardInterrupt: + pass + client_closed.set() + try: + proc.stdin.close() + except OSError: + pass + reader.join(timeout=30) + finish() + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/sample/tasks/mcp/scorer/mcp_stdio_open b/sample/tasks/mcp/scorer/mcp_stdio_open new file mode 100644 index 0000000000000000000000000000000000000000..71b5af54451c58cf6f0ff8bbc0b611f4cf5ed8b2 --- /dev/null +++ b/sample/tasks/mcp/scorer/mcp_stdio_open @@ -0,0 +1,3 @@ +#!/bin/sh +# The Zero-Trust Physics verifier at its open MCP address, as an MCP stdio server. +exec python3 "$(dirname "$0")/ztp_open_bridge.py" "${ZTP_VERIFIER_URL:-https://mcp.zerotrustphysics.com/mcp/open}" diff --git a/sample/tasks/mcp/scorer/pack_score.py b/sample/tasks/mcp/scorer/pack_score.py new file mode 100644 index 0000000000000000000000000000000000000000..b41382aa52ca13dbeccd56097b08175a0fed19a2 --- /dev/null +++ b/sample/tasks/mcp/scorer/pack_score.py @@ -0,0 +1,105 @@ +"""Cross-platform release-pinned scorer wrapper for Zero-Trust Physics packs (macOS arm64, Linux amd64, Linux arm64, HTTP). + + python3 pack_score.py REPLIES --engine ENGINE --environments F [score.py's options] [--strict-binary] + python3 pack_score.py --run run_cheat_suite.py [its options] [--strict-binary] + +Verifies that the target verifier answers MCP initialize as release 0.15.3 (matching reference.gateway_version and +engine_tag) on kernel genesis_kernel_v0.13.1, while recording engine_binary_sha256_seen and engine_binary_is_reference on +every score row. Pass --strict-binary to additionally require exact SHA-256 identity with reference.engine_binary_sha256. +All deterministic recomputation, seal, budget, and grading invariants of score.py apply unchanged. + +Standard library only. Licence: Apache-2.0. +""" +import inspect +import os +import re +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +KERNEL = "genesis_kernel_v0.13.1" +STRICT = False + + +def _kernel_of(replay): + """The kernel the verifier names: its serverInfo.description is the kernel's name (0.15.2), or one line that ends + with it ("... Cards: genesis_kernel_v0.13.1", 0.15.3).""" + server = getattr(getattr(replay, "verifier", None), "server", None) or {} + found = re.findall(r"genesis_kernel_v[0-9][0-9.]*[0-9]", server.get("description") or "") + return found[-1] if found else server.get("description") + + +def install(strict=False): + """Configure cross-platform release identity verification on score (idempotent). Returns the score module.""" + global STRICT + STRICT = bool(strict) + import score + if getattr(score, "_pack_engine_identity", False): + return score + original = score.engine_problem + original_score = score.score + + def engine_problem(env, replay): + ref = env.get("reference") or {} + want = ref.get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + if STRICT or not (seen and want and seen != want): + return original(env, replay) + # a different file: held to the release by what it says it is, every other rule as score.py's + saved = replay.binary_sha256 + replay.binary_sha256 = None + try: + problem = original(env, replay) + finally: + replay.binary_sha256 = saved + if problem: + return problem + kernel = _kernel_of(replay) + if kernel != KERNEL: + return "the verifier reports kernel %s; release %s runs %s" % (kernel, replay.version, KERNEL) + return None + + def scored(env, reply, replay, *args, **kwargs): + row = original_score(env, reply, replay, *args, **kwargs) + if isinstance(row, dict): + want = (env.get("reference") or {}).get("engine_binary_sha256") + seen = getattr(replay, "binary_sha256", None) + row["engine_binary_sha256_seen"] = seen + row["engine_binary_is_reference"] = None if not seen else (seen == want) + return row + + # score.py may one day hold its own source-build rule; then it is left as it is + if "strict" in inspect.getsource(original).lower(): + return score + score.engine_problem = engine_problem + score.score = scored + score._pack_engine_identity = True + return score + + +def main(): + argv = sys.argv[1:] + strict = "--strict-binary" in argv + argv = [a for a in argv if a != "--strict-binary"] + if argv[:1] == ["--run"]: + if len(argv) < 2: + sys.exit("give the program: --run run_cheat_suite.py [options]") + program = argv[1] if os.path.isabs(argv[1]) or os.path.isfile(argv[1]) else os.path.join(HERE, argv[1]) + folder = os.path.dirname(os.path.abspath(program)) + if folder not in sys.path: + sys.path.insert(0, folder) + install(strict) + # a program that does `from score import score` takes the replaced function, as the module now holds it + sys.argv = [program] + argv[2:] + runpy.run_path(program, run_name="__main__") + return + score = install(strict) + sys.argv = [os.path.join(HERE, "score.py")] + argv + score.main() + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/prompt.py b/sample/tasks/mcp/scorer/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..a97c7cd395c83cb0842e59fcb0161d67a5b1c164 --- /dev/null +++ b/sample/tasks/mcp/scorer/prompt.py @@ -0,0 +1,194 @@ +"""Print exactly the text an agent is given for one environment: the task, then its family's footer. + + python3 prompt.py --environments F ENVIRONMENT_ID the text for one environment + python3 prompt.py --environments F --list every environment id, one a line + python3 prompt.py --environments F --all FOLDER write FOLDER/.txt for every environment + +Any runner for any model gives the agent this text and nothing else, with the verifier as its +tool server. + +Licence: Apache-2.0. +""" +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) + +COMMON = """You have one tool server, the verifier. Answer from what its tools give you and from nothing else. Every number you are judged on is computed again from the requests on your card. + +End your reply with your answer card: one JSON object on its own last line, with no code fence and nothing after it. A request on the card is {"tool": "", "arguments": {}}, and a proof is the run_seal or solution_seal the verifier gave for that request.""" + +FOOTERS = { + "tradeoff": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Leave out "solve" when the task has no solve. A solve is the one handed its own design's sealed run through the coupling the task names.""", + "chain_design": COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps the constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks the constraint, no further from passing than the task's tolerance. binding: the id of the constraint. Each solve is the one handed its own design's sealed run through the coupling the task names.""", + "budget": COMMON + """ + +The card: +{"holds": {"request": ..., "proof": ...}, "stops": {"request": ..., "proof": ..., "stopped": ""}} + +holds: a request, the task's request with only the open input set, whose run completes. stops: the same request with another value of that input, whose run stops with the stop the task names. The two values are no further apart than the task's width, and both requests are among the calls you made. Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all.""", + "forensics": COMMON + """ + +The card: +{"false_rows": {"": "", ...}} + +Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden. Leave the genuine rows out. {"false_rows": {}} says every row is genuine.""", +} + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +STOP_BINDS = """ Where one constraint is that the run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it, and "step": the last step its run is sealed to (steps_landed), a whole number: {"run": {...}, "stopped": "", "step": }.""" + + +# The design shapes of the 29 Oct 2026 groups, each footer as its group built it (score.design_shape). +CONTINUED_CARRIED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is two runs: "run" is the first run, and "next" is the run that continues that same sealed run, with "from": {"request": , "run_seal": } and its initial state equal to the first run's final_state, value for value, bit for bit.""" + +CONTINUED_HANDED = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. run is the design's first run; next is the run that continues that same sealed run through from: its from holds the first run's request and run_seal, and its start fields are the first run's final state exactly as the verifier returned it.""" + +CONTINUED_CARRY = COMMON + """ + +The card: +{"passing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "failing": {"run": {"request": ..., "proof": ...}, "next": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is two runs: run, and next, which continues that design's own sealed run through from (from.request is the run's request, from.run_seal its proof) and starts from its final state. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +SOLVE_DESIGN = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. Each design is one solve and no run.""" + +SOLVE_ONLY = COMMON + """ + +The card: +{"passing": {"solve": {"request": ..., "proof": ...}}, "failing": {"solve": {"request": ..., "proof": ...}}, "binding": ""} + +Each design is one solve: leave out "run". passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary.""" + +STAGED = COMMON + """ + +The card: +{"passing": {%s}, "failing": {%s}, "binding": ""} + +Each design is the requests the task names, one entry each, under the names the task gives them (%s), each with the proof the verifier gave for it. passing: the design that keeps every constraint, nearest the boundary you were asked for. failing: the design just past it, which breaks at least one constraint, no further from passing than the task's tolerance. binding: the id of the constraint that the failing design breaks and that sets the boundary. A later request that carries an earlier one's answer carries it bit for bit, from that design's own answer.""" + +STAGED_STOP = """ Where one constraint is that a request is not stopped by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it%s.""" + +STOP_BINDS_SOLVE = """ Where one constraint is that the solve is not refused by a named stop and that constraint binds, binding is its id and the failing design also carries "stopped": the stop's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +SOLVE_STOP_G4 = """ Where one constraint is that the solve converges (it names a refusal) and that constraint binds, binding is its id and the failing design also carries "stopped": the refusal's name exactly as the verifier gives it: {"solve": {...}, "stopped": ""}.""" + +CARRY_STOP_G5 = (" Where one constraint is that the second run completes (it names a stop) and that constraint binds, binding is its id and the failing design also carries" + " \"stopped\": the stop's name exactly as the verifier gives it, and \"step\": the last step the second run (next) is sealed to (its steps_landed), a whole number:" + " {\"run\": {...}, \"next\": {...}, \"stopped\": \"\", \"step\": }.") + +BUDGET_WORDS = " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + + +def shaped_footer(environment): + """The footer of a design of one of the added shapes, or None for a run or a coupled solve (FOOTERS).""" + family = environment["family"] + check = environment.get("check") or {} + design = check.get("design") or {} + if family not in ("tradeoff", "chain_design"): + return None + chain = design.get("chain") or {} + stops = [c for c in check.get("constraints") or [] if c.get("on") == "outcome"] + if design.get("stages"): # group 3 + stages = design["stages"] + shape = ", ".join('"%s": {"request": ..., "proof": ...}' % st["key"] for st in stages) + footer = STAGED % (shape, shape, ", ".join(st["key"] for st in stages)) + if stops: + runs = any(st["key"] == c.get("stage") and st["tool"] == "run_trajectory" for c in stops for st in stages) + footer += STAGED_STOP % (', and, for a run, "step": the last step its run is sealed to (steps_landed), a whole number' if runs else "") + elif design.get("tool") == "solve": # group 4 + footer = SOLVE_DESIGN + (SOLVE_STOP_G4 if stops else "") + elif design.get("kind") == "solve": # group 5 + footer = SOLVE_ONLY + (STOP_BINDS_SOLVE if stops else "") + elif chain.get("kind") == "continuation" and "carried" in chain: # group 1 + footer = CONTINUED_CARRIED + if stops: + footer += STOP_BINDS + " In a chain the stop and the step are those of the failing design's next run." + elif chain.get("kind") == "continuation": # group 4 + footer = CONTINUED_HANDED + if stops: + footer += STOP_BINDS.replace("the run completes", "the second run completes").replace( + "the last step its run is sealed to", "the last step its next run is sealed to") + elif (chain.get("layout") or {}).get("kind") == "continue": # group 5 + footer = CONTINUED_CARRY + (CARRY_STOP_G5 if stops else "") + else: + return None + if check.get("budget"): + footer += BUDGET_WORDS + return footer + + +def prompt(environment): + """The whole text an agent is given for one environment.""" + family = environment["family"] + shaped = shaped_footer(environment) + if shaped is not None: + return environment["task"] + "\n\n" + shaped + footer = FOOTERS[family] + check = environment.get("check") or {} + if family in ("tradeoff", "chain_design") and any(c.get("on") == "outcome" for c in check.get("constraints") or []): + footer += STOP_BINDS + if family in ("tradeoff", "chain_design", "forensics") and check.get("budget"): + footer += " Your calls are counted: the budget is in the task, and the tools it rules out may not be called at all." + if family == "forensics" and check.get("reasons"): + footer = footer.replace("Name every false row, each with its one reason from value_altered, seal_wrong, flag_omitted, retired_model, stop_hidden.", + "Name every false row, each with its one reason from %s (the first of them, in that order, that is true of the row)." % ", ".join(check["reasons"])) + return environment["task"] + "\n\n" + footer + + +def main(): + argv = sys.argv[1:] + if len(argv) < 3 or argv[0] != "--environments": + sys.exit(__doc__) + environments = load_environments(argv[1]) + argv = argv[2:] + if argv[0] == "--list": + print("\n".join(e["id"] for e in environments)) + elif argv[0] == "--all": + if len(argv) < 2: + sys.exit("give the folder to write into") + os.makedirs(argv[1], exist_ok=True) + for e in environments: + with open(os.path.join(argv[1], e["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(prompt(e) + "\n") + print("wrote %d prompts to %s" % (len(environments), argv[1])) + else: + found = [e for e in environments if e["id"] == argv[0]] + if not found: + sys.exit("no environment with the id %s; --list names them" % argv[0]) + print(prompt(found[0])) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/run_reference.py b/sample/tasks/mcp/scorer/run_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc7d591e31fb27d4a9ccc2c2a50f5436eb503b2 --- /dev/null +++ b/sample/tasks/mcp/scorer/run_reference.py @@ -0,0 +1,208 @@ +"""An agent with no model in it: answer every environment from its reference, through the harness proxy. + + python3 run_reference.py --engine ENGINE --environments F --out DIR [--only id,id] [--direct] + +For a tradeoff or chain_design environment it sends the reference passing and failing runs to the +verifier, hands each run to its solve through the task's coupling where the task has one, and writes +the card with the seals this verifier gives. For a budget environment it sends the two reference +requests. For a forensics table it puts the table to the verifier (each row's request as sent, up to +the task's budget) and names the false rows the build recorded. + +Every call goes through harness/mcp_log_proxy.py, started in an empty working folder, so the +authoritative call record is DIR/.harness.jsonl, as in a pass@k attempt. The same calls are also +written beside the reply, DIR/.calls.jsonl. --direct talks to ENGINE with no proxy and writes the +reply-side log only. + + python3 score.py DIR --engine ENGINE --environments F --calls-from harness + +Licence: Apache-2.0. +""" +import argparse +import copy +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import chainlib # noqa: E402 +from score import (FREE_TOOLS, NOT_STOPPED, build_stage_request, close_verifier, continuation_of, design_shape, # noqa: E402 + file_sha256, get_path, load_environments, open_verifier) +from ztp_mcp import McpError, StdioVerifier # noqa: E402 + +PROXY = os.path.join(HERE, "..", "harness", "mcp_log_proxy.py") + + +class ProxiedVerifier(StdioVerifier): + """The engine behind the logging proxy, the proxy started in its own empty working folder.""" + + def __init__(self, engine, log, cwd=None, **kwargs): + self.cwd = cwd or tempfile.mkdtemp(prefix="ztp_ref_cwd_") + if engine.startswith("http://") or engine.startswith("https://"): + # an MCP address: the proxy runs the stdio bridge to it (ztp_open_bridge.py, beside this file) + child = [sys.executable, os.path.join(HERE, "ztp_open_bridge.py"), engine] + else: + child = [os.path.abspath(engine)] + command = [sys.executable, os.path.abspath(PROXY), "--log", os.path.abspath(log), "--"] + child + super(StdioVerifier, self).__init__(url="stdio: " + " ".join(command), timeout_s=600, **kwargs) + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=self.cwd) + self.binary_sha256 = None if len(child) > 1 else file_sha256(engine) + + def close(self): + try: + self.proc.stdin.close() + except OSError: + pass + try: + self.proc.wait(timeout=60) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def proxied(engine, log, cwd=None): + if os.path.exists(log): + os.remove(log) + verifier = ProxiedVerifier(engine, log, cwd) + try: + verifier.connect() + except McpError as problem: + sys.exit("the proxied verifier failed: %s" % problem) + return verifier + + +class Logged: + def __init__(self, verifier): + self.verifier, self.calls, self.seen = verifier, [], {} + + def call(self, tool, arguments, refused_ok=False): + # the same request twice is one call: a chain with its value in the next run has one first run for both designs + key = json.dumps([tool, arguments], sort_keys=True) + if key in self.seen and not self.seen[key][1]: + return self.seen[key][0] + self.calls.append({"tool": tool, "arguments": arguments}) + body, is_error = self.verifier.call_json(tool, arguments) + self.seen[key] = (body, is_error) + if is_error and not refused_ok: + raise SystemExit("the reference request was refused: %s %s" % (tool, str(body)[:300])) + return body + + +def design_staged(env, ref, agent): + """A staged design: each stage sent in order, handed values and continuations built from this verifier's answers.""" + spec = env["check"]["design"] + answers, requests, out = {}, {}, {} + for stage in spec["stages"]: + q = build_stage_request(spec, stage, ref["x"], answers, requests) + body = agent.call(stage["tool"], q, refused_ok=True) + stopped = body.get("outcome") not in NOT_STOPPED + answers[stage["key"]] = {"body": body, "proof": body.get("run_seal") or body.get("solution_seal"), + "outcome": body.get("outcome"), "stop": body.get("reject") if stopped else None, "stopped": stopped} + requests[stage["key"]] = q + out[stage["key"]] = {"request": {"tool": stage["tool"], "arguments": q}, "proof": answers[stage["key"]]["proof"]} + return out + + +def design(env, ref, agent): + spec = env["check"]["design"] + shape = design_shape(spec) + if shape == "staged": + return design_staged(env, ref, agent) + if shape == "solve": + solved = agent.call("solve", ref["solve"], refused_ok=True) + return {"solve": {"request": {"tool": "solve", "arguments": ref["solve"]}, "proof": solved["solution_seal"]}} + run_args = ref["run"] + run = agent.call("run_trajectory", run_args) + out = {"run": {"request": {"tool": "run_trajectory", "arguments": run_args}, "proof": run["run_seal"]}} + if shape == "continued": + # the run that continues this design's own sealed run: the reference's next run, its start fields and from + # set from this verifier's answer to the first run + _, carried, _, _ = continuation_of(spec) + next_args = copy.deepcopy(ref["next"]) + next_args["initial"] = {name: get_path(run, source) for name, source in carried.items()} + next_args["from"] = {"request": run_args, "run_seal": run["run_seal"]} + nxt = agent.call("run_trajectory", next_args, refused_ok=True) + out["next"] = {"request": {"tool": "run_trajectory", "arguments": next_args}, "proof": nxt["run_seal"]} + elif spec.get("chain"): + overrides = {} + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + overrides[spec["variable"]["path"].split(".", 1)[1]] = ref["x"] + solve_args = chainlib.chained_solve(spec["chain"], run_args, run, overrides) + solved = agent.call("solve", solve_args) + out["solve"] = {"request": {"tool": "solve", "arguments": solve_args}, "proof": solved["solution_seal"]} + return out + + +def reference_reply(env, verifier): + """(reply text, calls [{"tool", "arguments"}]).""" + agent = Logged(verifier) + family, ref = env["family"], env["reference"] + if family in ("tradeoff", "chain_design"): + card = {"passing": design(env, ref["passing"], agent), "failing": design(env, ref["failing"], agent), "binding": ref["binding"]} + if ref["failing"].get("stopped"): + card["failing"]["stopped"] = ref["failing"]["stopped"] + if ref["failing"].get("steps_landed") is not None: + card["failing"]["step"] = ref["failing"]["steps_landed"] + words = "The boundary lies between the two designs below; %s binds." % ref["binding"] + elif family == "budget": + card = {} + for side in ("holds", "stops"): + request = ref[side]["request"] + answer = agent.call(request["tool"], request["arguments"]) + card[side] = {"request": request, "proof": answer.get("run_seal") or answer.get("solution_seal")} + card["stops"]["stopped"] = env["check"]["stop"] + words = "The stop %s lies between the two requests below." % env["check"]["stop"] + else: + agent.call("list_cards", {}, refused_ok=True) + rows = env["check"]["rows"] + budget = env["check"].get("budget") or len(rows) + computing = 0 + for row in rows: + request = row["request"] + if computing >= budget: + break + if request["tool"] in FREE_TOOLS: + continue + agent.call(request["tool"], request["arguments"], refused_ok=True) + computing += 1 + card = {"false_rows": ref["false_rows"]} + words = "%d of the %d rows are false." % (len(ref["false_rows"]), len(rows)) + return words + "\n\n" + json.dumps(card), agent.calls + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--engine", required=True) + parser.add_argument("--environments", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--only") + parser.add_argument("--direct", action="store_true", help="no proxy: the reply-side log only") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + os.makedirs(args.out, exist_ok=True) + shared = open_verifier(args.engine) if args.direct else None + try: + for env in environments: + verifier = shared or proxied(args.engine, os.path.join(args.out, env["id"] + ".harness.jsonl")) + try: + reply, calls = reference_reply(env, verifier) + finally: + if not shared: + close_verifier(verifier) + with open(os.path.join(args.out, env["id"] + ".txt"), "w", encoding="utf-8") as f: + f.write(reply + "\n") + with open(os.path.join(args.out, env["id"] + ".calls.jsonl"), "w", encoding="utf-8") as f: + for c in calls: + f.write(json.dumps(c) + "\n") + print("%-60s %d calls" % (env["id"], len(calls)), flush=True) + finally: + if shared: + close_verifier(shared) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/score.py b/sample/tasks/mcp/scorer/score.py new file mode 100644 index 0000000000000000000000000000000000000000..4403f043313037d26927b89db218b4718ffcf3d2 --- /dev/null +++ b/sample/tasks/mcp/scorer/score.py @@ -0,0 +1,1199 @@ +"""Score replies to the multi-step environments with no judge: a program and the verifier. + + python3 score.py REPLIES --engine ENGINE [--environments F] [--only id,id] [--out F] + [--calls-from reply|harness] [--harness-dir DIR] + + REPLIES is a folder with one file per environment, .txt, the whole text of a reply. + --calls-from harness the call record is the harness's own: .harness.jsonl, written by + harness/mcp_log_proxy.py outside the solver's working directory (in + --harness-dir, default REPLIES). A .calls.jsonl beside the reply, + when there is one, is read only to catch an edit: it must equal the + harness log call for call. + --calls-from reply (the earlier set's way) the call record is .calls.jsonl beside the reply: + one JSON object a line, {"tool": "", "arguments": {...}}. + + ENGINE is the verifier: the path to mcp_stdio (MCP over stdio, no network), or an MCP address + beginning http. A task is scored only on the engine it was built on: the verifier's version must + be the task's reference.gateway_version (engine_tag), and a local binary's SHA-256 the task's + reference.engine_binary_sha256. + +The answer card is one JSON object on the reply's last line. Its shape is the family's: + + tradeoff, chain_design (kind design_to_limit, chained_design) + {"passing": DESIGN, "failing": DESIGN, "binding": ""} + DESIGN = {"run": {"request": R, "proof": ""}, + "solve": {"request": R, "proof": ""}} (solve only where the task has one) + Where a constraint is that the run completes and it binds, the failing DESIGN also carries + "stopped": "" and "step": . R = {"tool": ..., "arguments": {...}} + The design shapes, one scorer for every group (check.design says which): + run a run alone. + coupled check.design.chain names a solver and coupling: the run, then a solve handed that sealed run. + continued check.design.chain.kind "continuation", or chain.layout.kind "continue": the run, then a run of + the same card that continues it through from, starting from its sealed final state, + DESIGN = {"run": {...}, "next": {"request": R, "proof": ""}}. The next run's template + is chain.next_template, chain.template or chain.next; its start fields are chain.carried + ({field: where the first run's answer holds it}), chain.handed (with chain.handed_from) or + chain.carry and chain.clock, each equal to the first run's answer bit for bit. A constraint on + "next" reads the next run, and a stop constraint judges it. + solve check.design.tool or check.design.kind "solve": DESIGN = {"solve": {...}}, one solve and no + run. A binding refusal is named ("stopped") with no step. + staged check.design.stages: DESIGN = {"": {"request": R, "proof": ...}, ...}, one entry per + stage in order; a later stage carries an earlier stage's answer at a named input (handed) or + continues an earlier run (continues), bit for bit. + A constraint's read may carry "index": one entry of an output the verifier returns as a list. + budget (kind budgeted_search) + {"holds": {"request": R, "proof": ""}, + "stops": {"request": R, "proof": "", "stopped": ""}} + forensics + {"false_rows": {"": "", ...}} ({} when every row is genuine) + +Every proof is verified on the verifier (verify_tape for a run_seal, verify_solution for a +solution_seal, short form) and every number judged is read from the verifier's own answer to the +card's request, sent again here, never from the reply. + +Scores per environment +---------------------- +reward 0 or 1, exactly as the earlier scorer: 1 only when correct and proofs_hold are both 1. + proofs_hold: every proof on the card verifies. correct: the card is the right answer and + nothing below under "integrity" failed. +graded in [0, 1], beside reward. + + Integrity (graded 0 and reward 0, whatever the answer): the card cannot be read; a proof does not + verify (a copied, nudged, edited or stale proof); a request differs from the task's template other + than at the design variable; a chained solve not handed its own design's sealed run; no call log; + a call log beside the reply that differs from the harness log; a harness log whose chain breaks; + a forbidden tool called; more computing calls than the budget; a request on the card that is not + among the calls; a forensics answer with no computing call behind it; a task built on another + engine than the verifier. + + tradeoff, chain_design, budget. With integrity held, the sides are judged on the verifier: the + passing design meets every constraint and the failing one breaks the named binding constraint + (budget: holds completes, stops ends with the task's stop, named on the card), on the side the + task asks for, inside its range, with any stop and step the card must name. Wrong sides score 0. + With the sides right: + + e = the length of the smallest interval holding both designs' values and the reference + boundary (for a bracket that straddles the boundary, its width) + tol = the task's tolerance (tradeoff, chain_design) or relative width x |boundary| (budget) + r = e / tol + graded = 1 when reward is 1 (r <= 1 and the bracket straddles it) + = 0.5 ** log10(r) when r > 1: each tenfold of looseness halves the score + (r 1.35 -> 0.914, 2 -> 0.811, 10 -> 0.5, 100 -> 0.25) + = 0.5 when r <= 1 but the bracket misses the reference boundary + by more than the slack (another crossing than the one asked) + + The decay is smooth and falls monotonically with r, and a near miss scores near the top. + + forensics. With integrity held, graded is F1 over the (row, reason) pairs: a row counts as found + only with its right reason. precision = found / named, recall = found / false rows; an empty + answer to a table with no false row scores 1. A card that names every row of the table false is + a blanket answer and scores 0, as do unknown rows and reasons outside the task's list. + +Licence: Apache-2.0. +""" +import argparse +import copy +import hashlib +import json +import math +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from ztp_mcp import McpError, StdioVerifier, Verifier # noqa: E402 + +FAMILIES = ("tradeoff", "chain_design", "budget", "forensics") +KINDS = {"tradeoff": "design_to_limit", "chain_design": "chained_design", "budget": "budgeted_search", "forensics": "forensics"} +NOT_STOPPED = ("completed", "converged") +PREFIX_ENDS = ("__", ".", ":", "/") +VERIFIER_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", + "run_trajectory", "compute_step", "verify_step", "design_run", "solve", "run_dataset", + "validate_series", "verify_tape", "verify_solution", "verify_dataset", "verify_receipt", "find_flip") +# Calls that read the catalogue compute nothing and are free in a call budget. +FREE_TOOLS = ("list_cards", "list_solvers", "find_model", "describe_card", "describe_solver", "cite", "verify_receipt") +REASONS = ("value_altered", "seal_wrong", "flag_omitted", "retired_model", "stop_hidden") +GRADED_DECAY = 0.5 # graded = GRADED_DECAY ** log10(r) +OTHER_CROSSING = 0.5 # right sides, tight, around another crossing than the reference boundary + + +class Integrity(Exception): + """The answer cannot be trusted: graded 0 and reward 0.""" + + +class Wrong(Exception): + """The answer is trusted and wrong: graded 0 and reward 0.""" + + +def load_environments(path): + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def row_problems(env): + """What a task row lacks against the shared row contract (empty when none).""" + out = [] + for key in ("id", "family", "models", "real_thing", "task", "check", "seed", "reference"): + if key not in env: + out.append("no %s" % key) + family = env.get("family") + if family not in FAMILIES: + out.append("family %r" % family) + elif "kind" in env and env["kind"] != KINDS[family]: + out.append("kind %r for family %s (want %s)" % (env["kind"], family, KINDS[family])) + ref = env.get("reference") or {} + for key in ("engine_tag", "engine_commit", "engine_binary_sha256"): + if not ref.get(key): + out.append("reference.%s missing" % key) + return out + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def open_verifier(engine): + if engine.startswith("http://") or engine.startswith("https://"): + verifier = Verifier(engine, pause_s=0.5) + verifier.binary_sha256 = None + else: + if not os.path.isfile(engine): + sys.exit("no file at %s: give the path to mcp_stdio, or an MCP address beginning http" % engine) + verifier = StdioVerifier([engine]) + verifier.binary_sha256 = file_sha256(engine) + try: + verifier.connect() + except McpError as problem: + sys.exit("the verifier failed, so nothing was scored: %s" % problem) + if not isinstance(verifier.server, dict) or not verifier.server.get("name"): + close_verifier(verifier) + sys.exit("the verifier failed, so nothing was scored: %s did not answer as an MCP server" % engine) + return verifier + + +def close_verifier(verifier): + if hasattr(verifier, "close"): + verifier.close() + + +# ------------------------------------------------------------------------------------------ +# reading the reply and the call logs +# ------------------------------------------------------------------------------------------ +def _no_constant(name): + raise ValueError("%s is not a number" % name) + + +def read_card(reply): + """(card, problem): the JSON object on the reply's last line. A closing code fence is passed over.""" + lines = [line.strip() for line in (reply or "").replace("\r", "\n").split("\n") if line.strip()] + while lines and lines[-1].startswith("```"): + lines.pop() + if not lines: + return None, "the reply is empty" + try: + card = json.loads(lines[-1], parse_constant=_no_constant) + except ValueError: + return None, "the last line is not one JSON object" + if not isinstance(card, dict): + return None, "the last line is not one JSON object" + return card, None + + +def tool_name(name): + """The verifier's own name for a tool an agent's program may have prefixed (mcp__zerotrust__solve).""" + if not isinstance(name, str): + return None + if name in VERIFIER_TOOLS: + return name + for tool in VERIFIER_TOOLS: + for joint in PREFIX_ENDS: + if name.endswith(joint + tool): + return tool + return name + + +def without_readout(arguments): + """A run's arguments as sealed: a readout is not part of a run's seal.""" + if not isinstance(arguments, dict): + return arguments + return {k: v for k, v in arguments.items() if k != "readout"} + + +def numbers_by_value(value): + """Every number as a float, so 18 and 18.0 (one request to the engine) compare equal; bools kept.""" + if isinstance(value, dict): + return {k: numbers_by_value(v) for k, v in value.items()} + if isinstance(value, list): + return [numbers_by_value(v) for v in value] + if isinstance(value, int) and not isinstance(value, bool): + return float(value) + return value + + +def canonical(arguments): + """A request's arguments as compared with the call log: no readout, keys sorted, numbers by value.""" + return json.dumps(numbers_by_value(without_readout(arguments)), sort_keys=True, separators=(",", ":")) + + +def _arguments(one): + arguments = one.get("arguments") + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except ValueError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def read_calls(path): + """Every call in a reply-side call log, [(tool, arguments)], or None when there is no log.""" + if not path or not os.path.isfile(path): + return None + calls = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + one = json.loads(line) + except ValueError: + continue + if isinstance(one, dict): + calls.append((tool_name(one.get("tool")), _arguments(one))) + return calls + + +def chain_of(previous, entry): + payload = json.dumps(entry, sort_keys=True, separators=(",", ":")) + return hashlib.sha384(((previous or "") + payload).encode("utf-8")).hexdigest() + + +def read_harness_log(path): + """(calls, problem) from a log written by harness/mcp_log_proxy.py. calls is None when there is no log; + problem names the first line whose chain does not follow (an edit, a line taken out or put in).""" + if not path or not os.path.isfile(path): + return None, None + calls, previous = [], None + with open(path, encoding="utf-8", errors="replace") as f: + for number_, line in enumerate(f, 1): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError: + return calls, "line %d of the harness log is not JSON" % number_ + if not isinstance(entry, dict) or "chain" not in entry: + return calls, "line %d of the harness log carries no chain" % number_ + chain = entry.pop("chain") + if chain != chain_of(previous, entry) or entry.get("seq") != len(calls) + 1: + return calls, "the harness log's chain breaks at line %d" % number_ + previous = chain + calls.append((tool_name(entry.get("tool")), _arguments(entry))) + return calls, None + + +def write_harness_log(path, calls): + """A chained log in the proxy's format, for tests and the cheat suite: calls [(tool, arguments)].""" + previous = None + with open(path, "w", encoding="utf-8") as f: + for seq, (tool, arguments) in enumerate(calls, 1): + entry = {"seq": seq, "jsonrpc_id": seq, "tool": tool, "arguments": arguments, "ts_request": None, + "ts_response": None, "duration_s": None, "response_sha384": None, "text_sha384": None, "is_error": False} + entry["chain"] = chain_of(previous, entry) + previous = entry["chain"] + f.write(json.dumps(entry, sort_keys=True) + "\n") + + +# ------------------------------------------------------------------------------------------ +# the verifier, asked again +# ------------------------------------------------------------------------------------------ +def stop_name_in(sentence): + names = re.findall(r"\(([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\)", sentence or "") + return names[-1] if names else None + + +class Replay: + """The verifier, with every answer remembered: the same request is sent once.""" + + def __init__(self, verifier): + self.verifier = verifier + self.seen = {} + server = getattr(verifier, "server", None) or {} + self.version = server.get("version") + self.binary_sha256 = getattr(verifier, "binary_sha256", None) + + def call(self, tool, arguments): + key = tool + "\x00" + json.dumps(arguments, sort_keys=True) + if key not in self.seen: + try: + self.seen[key] = self.verifier.call_json(tool, arguments) + except McpError as problem: + if not str(problem).startswith("protocol error"): + raise SystemExit("the verifier failed, so nothing was scored: %s" % problem) + self.seen[key] = ("the verifier did not take the request: %s" % problem, True) + return self.seen[key] + + def answer(self, tool, arguments, readout=None): + """One run or solve computed again: {"stopped", "outcome", "stop", "proof", "body"}.""" + arguments = copy.deepcopy(without_readout(arguments)) + if readout is not None and tool == "run_trajectory": + arguments["readout"] = readout + body, is_error = self.call(tool, arguments) + if is_error or not isinstance(body, dict): + sentence = body if isinstance(body, str) else json.dumps(body) + return {"stopped": True, "outcome": "stopped before computing", "stop": stop_name_in(sentence), + "proof": None, "body": None, "sentence": sentence} + outcome = body.get("outcome") + stopped = outcome not in NOT_STOPPED + return {"stopped": stopped, "outcome": outcome, "stop": body.get("reject") if stopped else None, + "proof": body.get("run_seal") or body.get("solution_seal"), "body": body, + "sentence": body.get("reject_detail")} + + def proof_holds(self, tool, arguments, proof): + """(holds, words): the card's seal verified by verify_tape or verify_solution, short form.""" + if not isinstance(proof, str) or not re.fullmatch(r"[0-9a-f]{96}", proof): + return False, "the proof is not a SHA-384 seal of 96 hex digits" + if tool == "run_trajectory": + body, is_error = self.call("verify_tape", {"request": without_readout(arguments), "run_seal": proof}) + elif tool == "solve": + body, is_error = self.call("verify_solution", {"request": arguments, "solution_seal": proof}) + else: + return False, "a proof is verified for run_trajectory or solve only, not %s" % tool + if is_error or not isinstance(body, dict): + return False, "the verifier would not verify it: %s" % (str(body)[:200]) + if body.get("holds") is True: + return True, None + return False, "the verifier says the seal does not hold (cause %s)" % body.get("cause") + + +def engine_problem(env, replay): + """None when the verifier is the engine the task was built on; else what differs.""" + ref = env.get("reference") or {} + tag = ref.get("gateway_version") or (ref.get("engine_tag") or "").lstrip("v") + if not tag: + return "the task names no engine it was built on" + if (ref.get("engine_tag") or "v" + tag).lstrip("v") != tag: + return "the task's engine_tag %s and gateway_version %s disagree" % (ref.get("engine_tag"), ref.get("gateway_version")) + if replay.version != tag: + return "the task was built on engine %s; the verifier is %s" % (tag, replay.version) + want = ref.get("engine_binary_sha256") + if replay.binary_sha256 and want and replay.binary_sha256 != want: + return "the verifier's binary is not the one the task was built on (sha256 %s..., want %s...)" % (replay.binary_sha256[:12], want[:12]) + return None + + +# ------------------------------------------------------------------------------------------ +# requests and their inputs +# ------------------------------------------------------------------------------------------ +_PART = re.compile(r"([A-Za-z_0-9]+)((?:\[\d+\])*)") + + +def get_path(obj, path): + here = obj + for part in path.split("."): + found = _PART.fullmatch(part) + if not found or not isinstance(here, dict) or found.group(1) not in here: + return None + here = here[found.group(1)] + for index in re.findall(r"\[(\d+)\]", found.group(2)): + if not isinstance(here, list) or int(index) >= len(here): + return None + here = here[int(index)] + return here + + +def set_path(obj, path, value): + parts = path.split(".") + here = obj + for i, part in enumerate(parts): + m = _PART.fullmatch(part) + name, idx = m.group(1), [int(k) for k in re.findall(r"\[(\d+)\]", m.group(2))] + last = i == len(parts) - 1 + if not idx: + if last: + here[name] = value + else: + here = here[name] + else: + here = here[name] + for j, k in enumerate(idx): + if last and j == len(idx) - 1: + here[k] = value + else: + here = here[k] + + +def number(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def differs(template, given, free, where=""): + """The first place where a request differs from the task's, other than the free places. None when none.""" + if where in free: + return None + if isinstance(template, dict): + if not isinstance(given, dict): + return where or "the request" + for key in set(template) | set(given): + place = "%s.%s" % (where, key) if where else key + if place in free: + continue + if key not in given or key not in template: + return place + found = differs(template[key], given[key], free, place) + if found: + return found + return None + if isinstance(template, list): + if not isinstance(given, list) or len(given) != len(template): + return where + for index, (a, b) in enumerate(zip(template, given)): + found = differs(a, b, free, "%s[%d]" % (where, index)) + if found: + return found + return None + if number(template) and number(given): + return None if float(template) == float(given) else where + return None if template == given else where + + +def design_value(variable, run_arguments, solve_arguments, next_arguments=None): + """The design variable of one design, read from its requests (on: run, solve, or next, a continued run).""" + kind = variable["kind"] + if kind == "path": + on = variable.get("on", "run") + source = {"solve": solve_arguments, "next": next_arguments}.get(on, run_arguments) or {} + value = get_path(source, variable["path"]) + for place in variable.get("also") or []: + again = get_path(source, place) + if not (number(again) and number(value) and float(again) == float(value)): + return None + return float(value) if number(value) else None + if kind == "entry_angle_deg": + radial = get_path(run_arguments or {}, "initial.radial_speed_m_s") + transverse = get_path(run_arguments or {}, "initial.transverse_speed_m_s") + if not (number(radial) and number(transverse)) or transverse <= 0: + return None + speed = math.hypot(radial, transverse) + if abs(speed - variable["speed_m_s"]) > 1e-6 * variable["speed_m_s"]: + return None + return math.degrees(math.atan2(-radial, transverse)) + return None + + +def variable_places(variable): + if variable["kind"] == "entry_angle_deg": + return {"initial.radial_speed_m_s", "initial.transverse_speed_m_s"} + if variable["kind"] == "path" and variable.get("on", "run") == "run": + return {variable["path"]} | set(variable.get("also") or []) + return set() + + +def read_value(read, answer): + """One number from a replayed answer: final, result, or the extreme of a run's readout.""" + body = answer["body"] + if body is None: + return None + kind = read["kind"] + value = None + if kind == "final": + value = (body.get("final_state") or {}).get(read["quantity"]) + elif kind == "result": + value = (body.get("result") or {}).get(read["quantity"]) + elif kind == "flag_extent": + # an advisory flag the run raised, at its largest extent; 0 when the run does not raise it + value = max([x.get("extent") or 0.0 for x in body.get("exceedance_extremes") or [] + if isinstance(x, dict) and x.get("flag") == read["quantity"]] or [0.0]) + elif kind == "extreme": + for quantity in (body.get("readout") or {}).get("quantities") or []: + if quantity.get("quantity") == read["quantity"]: + value = quantity.get(read["which"]) + if "index" in read: + # one entry of an output the verifier returns as a list (a hose's modes, a solve asked at several points) + k = read["index"] + value = value[k] if isinstance(value, list) and isinstance(k, int) and -len(value) <= k < len(value) else None + return value if number(value) else None + + +def readout_for(constraints, on="run"): + """The readout a run is sent with: the extremes its constraints read (on: run, next, or a stage key).""" + quantities = sorted({c["read"]["quantity"] for c in constraints if c["on"] == on and c["read"]["kind"] == "extreme"}) + return {"quantities": quantities} if quantities else None + + +def design_shape(spec): + """Which of the design shapes a task's check.design is: run, coupled, continued, solve or staged.""" + if spec.get("stages"): + return "staged" + if spec.get("tool") == "solve" or spec.get("kind") == "solve": + return "solve" + chain = spec.get("chain") or {} + if chain.get("kind") == "continuation" or (chain.get("layout") or {}).get("kind") == "continue": + return "continued" + return "coupled" if chain else "run" + + +def continuation_of(spec): + """A continued design's chain in one form: (next template, {start field: where the first run's answer holds it}, + next outcomes, the next run's places that also hold a first-run design value).""" + chain = spec["chain"] + template = chain.get("next_template") or chain.get("template") or chain.get("next") + if "carried" in chain: # group 1 + carried = dict(chain["carried"]) + elif "handed" in chain: # group 4 + named = chain.get("handed_from") or {} + carried = {k: "final_state." + named.get(k, k) for k in chain["handed"]} + else: # group 5 + carried = {k: "final_state." + k for k in chain.get("carry") or []} + if chain.get("clock"): + carried[chain["clock"]["field"]] = "final_state." + chain["clock"]["from"] + outcomes = chain.get("next_outcomes") or spec["run_outcomes"] + return template, carried, outcomes, list(chain.get("next_also") or []) + + +def meets(constraint, value): + if value is None: + return False + return value <= constraint["limit"] if constraint["op"] == "<=" else value >= constraint["limit"] + + +def history_layout_problem(layout, parameters, frames_count): + """None when the arrays of a chained solve are laid out as the task states; else what is not.""" + if layout is None: + return None + if layout["kind"] == "stardust_slab": + names = ("history_time_s", "history_pressure_pa", "history_heat_transfer_coefficient_kg_per_m2_s", + "history_flow_enthalpy_j_per_kg", "history_radiative_heating_w_per_m2") + columns = [parameters.get(name) for name in names] + if not all(isinstance(c, list) and all(number(v) for v in c) for c in columns): + return "the history columns are not all lists of numbers" + time, pressure, coefficient, enthalpy, radiative = columns + rows = frames_count + 3 + if any(len(c) != rows for c in columns): + return "the history has not one row before the %d frames handed and two after them" % frames_count + if time[0] != 0.0 or coefficient[0] != 0.0: + return "row 0 is not at 0 s with no heating" + if pressure[0] != pressure[1] or enthalpy[0] != enthalpy[1]: + return "row 0 does not repeat the first frame's pressure and enthalpy" + if abs(time[-2] - (time[-3] + 1.0)) > 1e-9 or time[-1] != layout["cool_to_s"]: + return "the rows after the frames are not at 1 s after the last frame and at %g s" % layout["cool_to_s"] + if coefficient[-2] != 0.0 or coefficient[-1] != 0.0: + return "the stream is not off after the frames" + if pressure[-1] != pressure[-3] or pressure[-2] != pressure[-3] or enthalpy[-1] != enthalpy[-3] or enthalpy[-2] != enthalpy[-3]: + return "the rows after the frames do not hold the last frame's pressure and enthalpy" + if any(v != 0.0 for v in radiative): + return "a row of the history holds radiative heating" + return None + if layout["kind"] == "triga_element": + return None # every array is handed by the coupling and held to its bits by the verifier + return "an unknown layout" + + +# ------------------------------------------------------------------------------------------ +# the call record +# ------------------------------------------------------------------------------------------ +def card_requests(env, card): + """Every request on the card, [(tool, arguments)], read leniently (for the call log).""" + out = [] + + def take(part): + if isinstance(part, dict) and isinstance(part.get("request"), dict) and isinstance(part["request"].get("arguments"), dict): + out.append((tool_name(part["request"].get("tool")), part["request"]["arguments"])) + + if env["family"] in ("tradeoff", "chain_design"): + stages = [s["key"] for s in (env["check"].get("design") or {}).get("stages") or []] + for side in ("passing", "failing"): + design = card.get(side) if isinstance(card.get(side), dict) else {} + for key in stages or ("run", "solve", "next"): + take(design.get(key)) + elif env["family"] == "budget": + take(card.get("holds")) + take(card.get("stops")) + return out + + +def sequence(calls): + return [(tool_name(t), json.dumps(numbers_by_value(a), sort_keys=True)) for t, a in calls] + + +def call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row): + """None when the call record holds; else why not (an integrity failure).""" + check = env["check"] + if calls_from == "harness": + if calls is None: + return "no harness call log: every attempt is scored with the calls the harness recorded" + if log_problem: + return log_problem + if reply_calls is not None and sequence(reply_calls) != sequence(calls): + return "the call log beside the reply differs from the harness log" + elif calls is None: + return "no call log: every environment is scored with the agent's calls" + calls = [(tool_name(t), a) for t, a in calls] + banned = sorted({t for t, _ in calls if t in (check.get("forbidden") or [])}) + if banned: + return "the log holds calls of %s, which the task rules out" % ", ".join(banned) + computing = [(t, a) for t, a in calls if t not in FREE_TOOLS] + row["computing_calls"] = len(computing) + if check.get("budget") and len(computing) > check["budget"]: + return "%d computing calls; the budget is %d" % (len(computing), check["budget"]) + sent = {(t, canonical(a)) for t, a in computing} + for tool, arguments in card_requests(env, card): + if (tool, canonical(arguments)) not in sent: + return "a %s request on the card is not among the calls in the log" % tool + if env["family"] == "forensics" and not computing: + return "no computing call behind the answer: the table was not put to the verifier" + return None + + +# ------------------------------------------------------------------------------------------ +# the families +# ------------------------------------------------------------------------------------------ +def request_of(part, tool, what): + """The arguments of one request on the card (Integrity when it is not one).""" + if not isinstance(part, dict): + raise Integrity("%s is missing" % what) + request = part.get("request") + if not (isinstance(request, dict) and isinstance(request.get("arguments"), dict)): + raise Integrity("%s has no request {\"tool\": ..., \"arguments\": {...}}" % what) + if tool_name(request.get("tool")) != tool: + raise Integrity("%s is a request of %s, not %s" % (what, request.get("tool"), tool)) + return request["arguments"] + + +def score_design(env, design, which, replay, proofs): + """One design of a boundary family: facts {x, met, values, stopped, steps_landed}.""" + check = env["check"] + spec = check["design"] + shape = design_shape(spec) + if shape in ("solve", "staged", "continued") and not isinstance(design, dict): + raise Integrity("the %s design is missing" % which) + if shape == "solve": + return score_solve_design(env, design, which, replay, proofs) + if shape == "staged": + return score_staged_design(env, design, which, replay, proofs) + if shape == "continued": + return score_continued_design(env, design, which, replay, proofs) + chain = spec.get("chain") + run_args = request_of((design or {}).get("run") if isinstance(design, dict) else None, "run_trajectory", + "the %s design's run" % which) + free = set(spec.get("free") or []) | variable_places(spec["variable"]) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + for place in spec.get("free") or []: + if place.endswith(".steps"): + steps = get_path(run_args, place) + if not (isinstance(steps, int) and not isinstance(steps, bool) and 1 <= steps <= spec.get("most_steps", 10 ** 7)): + raise Integrity("the %s design's run has no whole number of steps at %s" % (which, place)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"])) + stop_names = [c["stop"] for c in check["constraints"] if c["on"] == "outcome"] + stopped_by_name = run["outcome"] == "refused" and run["stop"] in stop_names + if run["outcome"] not in spec["run_outcomes"] and not stopped_by_name: + raise Wrong("the %s design's run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + solve_args, solve = None, None + if chain: + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != chain["solver"]: + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + handed = solve_args.get("from") + if not isinstance(handed, dict) or handed.get("coupling") != chain["coupling"]: + raise Integrity("the %s design's solve is not handed its run through the coupling %s" % (which, chain["coupling"])) + if canonical(handed.get("request")) != canonical(run_args) or handed.get("run_seal") != run_proof: + raise Integrity("the %s design's solve is not handed the design's own sealed run" % which) + parameters = solve_args.get("parameters") + if not isinstance(parameters, dict): + raise Integrity("the %s design's solve has no parameters" % which) + solve_free = set(chain.get("handed") or []) + if spec["variable"]["kind"] == "path" and spec["variable"].get("on") == "solve": + solve_free.add(spec["variable"]["path"].split(".", 1)[1]) + where = differs(chain["parameters"], parameters, solve_free) + if where: + raise Integrity("the %s design's solve differs from the task's at parameters.%s" % (which, where)) + frames = len((run["body"] or {}).get("frames") or []) + problem = history_layout_problem(chain.get("layout"), parameters, frames) + if problem: + raise Integrity("the %s design's solve: %s" % (which, problem)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] != "converged": + raise Wrong("the %s design's solve comes back %s%s, not converged" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "")) + x = design_value(spec["variable"], run_args, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, spec["variable"].get("words", ""))) + met, values = {}, {} + for constraint in check["constraints"]: + if constraint["on"] == "outcome": + values[constraint["id"]] = run["outcome"] if not run["stop"] else "%s (%s)" % (run["outcome"], run["stop"]) + met[constraint["id"]] = not (run["outcome"] == "refused" and run["stop"] == constraint["stop"]) + continue + value = read_value(constraint["read"], run if constraint["on"] == "run" else solve) + values[constraint["id"]] = value + met[constraint["id"]] = meets(constraint, value) + facts = {"x": x, "met": met, "values": values} + if run["outcome"] not in NOT_STOPPED and run["body"]: + facts["stopped"], facts["steps_landed"] = run["stop"], run["body"].get("steps_landed") + return facts + + +def halted(answer, stop, staged=False): + """True when an answer is stopped by the stop named: a refusal ("refused"); for a staged design, any outcome that + is not completed or converged (group 3's rule, kept as built).""" + if staged: + return answer["outcome"] not in NOT_STOPPED and answer["stop"] == stop + return answer["outcome"] == "refused" and answer["stop"] == stop + + +def constraint_facts(check, answers, judged, staged=False): + """met and values of every constraint: each read from the answer its "on" names (answers: {on: answer}); a stop + constraint ("on": "outcome") is judged on the answer judged, or on its stage's answer for a staged design.""" + met, values = {}, {} + for c in check["constraints"]: + if c["on"] == "outcome": + a = answers.get(c["stage"]) if c.get("stage") else judged + values[c["id"]] = None if a is None else (a["outcome"] if not a["stop"] else "%s (%s)" % (a["outcome"], a["stop"])) + met[c["id"]] = a is not None and not halted(a, c["stop"], staged) + continue + a = answers.get(c["on"]) + value = read_value(c["read"], a) if a is not None else None + values[c["id"]] = value + met[c["id"]] = meets(c, value) if c.get("limit") is not None else None + return met, values + + +def stopped_by(answer, constraints, stage=None): + """True when an answer is stopped by a stop one of the task's stop constraints names (for the stage given).""" + return any(halted(answer, c["stop"], stage is not None) for c in constraints + if c["on"] == "outcome" and (stage is None or c.get("stage") == stage)) + + +def score_solve_design(env, design, which, replay, proofs): + """One design that is one solve and no run (check.design.tool or kind "solve").""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + solve_args = request_of(design.get("solve"), "solve", "the %s design's solve" % which) + if solve_args.get("solver") != spec["template"].get("solver"): + raise Integrity("the %s design's solve is of %s, not the task's solver" % (which, solve_args.get("solver"))) + free = set(spec.get("free") or []) | {var["path"]} | set(var.get("also") or []) + where = differs(spec["template"], solve_args, free) + if where: + raise Integrity("the %s design's solve differs from the task's at %s" % (which, where)) + holds, words = replay.proof_holds("solve", solve_args, design["solve"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's solution_seal: %s" % (which, words)) + solve = replay.answer("solve", solve_args) + if solve["outcome"] not in spec["run_outcomes"] and not stopped_by(solve, check["constraints"]): + raise Wrong("the %s design's solve comes back %s%s, not %s" % ( + which, solve["outcome"], " (%s)" % solve["stop"] if solve["stop"] else "", " or ".join(spec["run_outcomes"]))) + x = design_value(dict(var, on="solve"), None, solve_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, {"solve": solve}, solve) + facts = {"x": x, "met": met, "values": values} + if solve["outcome"] not in NOT_STOPPED and solve["body"]: + facts["stopped"], facts["steps_landed"], facts["no_step"] = solve["stop"], None, True + return facts + + +def score_continued_design(env, design, which, replay, proofs): + """One design of a run and the run that continues it through from. The verifier holds the hand-off: it computes + the first run again, compares its seal and refuses a start that is not the first run's final state; the scorer + also holds each carried start field to the first run's answer, bit for bit.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + on_next = var["kind"] == "path" and var.get("on") == "next" + template, carried, next_outcomes, next_also = continuation_of(spec) + run_args = request_of(design.get("run"), "run_trajectory", "the %s design's run" % which) + free = set(spec.get("free") or []) | (set() if on_next else variable_places(var)) + where = differs(spec["template"], without_readout(run_args), free) + if where: + raise Integrity("the %s design's run differs from the task's at %s" % (which, where)) + run_proof = design["run"].get("proof") + holds, words = replay.proof_holds("run_trajectory", run_args, run_proof) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's run_seal: %s" % (which, words)) + run = replay.answer("run_trajectory", run_args, readout_for(check["constraints"], "run")) + if run["outcome"] not in spec["run_outcomes"]: + raise Wrong("the %s design's first run comes back %s%s, not %s" % ( + which, run["outcome"], " (%s)" % run["stop"] if run["stop"] else "", " or ".join(spec["run_outcomes"]))) + next_args = request_of(design.get("next"), "run_trajectory", "the %s design's next run" % which) + handed = next_args.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(run_args) + or handed.get("run_seal") != run_proof): + raise Integrity("the %s design's next run does not continue the design's own sealed run (from)" % which) + next_free = {"initial." + name for name in carried} | {"from"} | set(next_also) + if on_next: + next_free |= {var["path"]} | set(var.get("also") or []) + where = differs(template, without_readout(next_args), next_free) + if where: + raise Integrity("the %s design's next run differs from the task's at %s" % (which, where)) + start = next_args.get("initial") if isinstance(next_args.get("initial"), dict) else {} + for name, source in carried.items(): + held, given = get_path(run["body"] or {}, source), start.get(name) + if name not in start or not (given == held or (number(given) and number(held) and float(given) == float(held))): + raise Integrity("the %s design's next run does not start from its run's %s, bit for bit" % (which, source)) + holds, words = replay.proof_holds("run_trajectory", next_args, design["next"].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's next run_seal: %s" % (which, words)) + nxt = replay.answer("run_trajectory", next_args, readout_for(check["constraints"], "next")) + if nxt["outcome"] not in next_outcomes and not stopped_by(nxt, check["constraints"]): + raise Wrong("the %s design's next run comes back %s%s, not %s" % ( + which, nxt["outcome"], " (%s)" % nxt["stop"] if nxt["stop"] else "", " or ".join(next_outcomes))) + x = design_value(var, run_args, None, next_args) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + for place in next_also: + again = get_path(next_args, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s design's next run does not hold the design value at %s" % (which, place)) + met, values = constraint_facts(check, {"run": run, "next": nxt}, nxt) + facts = {"x": x, "met": met, "values": values} + if nxt["outcome"] not in NOT_STOPPED and nxt["body"]: + facts["stopped"], facts["steps_landed"] = nxt["stop"], nxt["body"].get("steps_landed") + return facts + + +def build_stage_request(spec, stage, x, answers, requests): + """One stage's request of a staged design at x: the template, x at the variable's places, the values handed from + earlier stages' answers, and a continuation's start and from (used by run_reference.py).""" + q = copy.deepcopy(stage["template"]) + var = spec["variable"] + if var.get("stage") == stage["key"]: + for place in [var["path"]] + list(var.get("also") or []): + set_path(q, place, x) + for h in stage.get("handed") or []: + set_path(q, h["to"], read_value(h["read"], answers[h["from"]])) + if stage.get("continues"): + parent = stage["continues"] + final = answers[parent]["body"]["final_state"] + q["initial"] = {k: final[k] for k in stage["template"]["initial"]} + q["from"] = {"request": copy.deepcopy(requests[parent]), "run_seal": answers[parent]["proof"]} + return q + + +def score_staged_design(env, design, which, replay, proofs): + """One staged design (check.design.stages): each stage a run or a solve, in order.""" + check = env["check"] + spec = check["design"] + var = spec["variable"] + stages = spec["stages"] + answers, requests, facts = {}, {}, {} + for i, stage in enumerate(stages): + key, tool = stage["key"], stage["tool"] + sent = without_readout(request_of(design.get(key), tool, "the %s design's %s" % (which, key))) + free = set(stage.get("free") or []) | {h["to"] for h in stage.get("handed") or []} + if var.get("stage") == key: + free |= {var["path"]} | set(var.get("also") or []) + if stage.get("continues"): + free |= {"initial", "from"} + where = differs(stage["template"], sent, free) + if where: + raise Integrity("the %s design's %s differs from the task's at %s" % (which, key, where)) + for h in stage.get("handed") or []: + want = read_value(h["read"], answers[h["from"]]) + got = get_path(sent, h["to"]) + if want is None or not number(got) or float(got) != float(want): + raise Integrity("the %s design's %s does not carry %s's %s at %s, bit for bit" % ( + which, key, h["from"], h["read"]["quantity"], h["to"])) + if stage.get("continues"): + parent = stage["continues"] + handed = sent.get("from") + if (not isinstance(handed, dict) or canonical(handed.get("request")) != canonical(requests[parent]) + or handed.get("run_seal") != design[parent].get("proof")): + raise Integrity("the %s design's %s does not continue the design's own sealed %s run (from)" % (which, key, parent)) + final = (answers[parent]["body"] or {}).get("final_state") or {} + start = sent.get("initial") + keys = set(stage["template"]["initial"]) + if not isinstance(start, dict) or set(start) != keys or any( + not number(start[k]) or float(start[k]) != final.get(k) for k in keys): + raise Integrity("the %s design's %s does not start from the final state of its %s run, bit for bit" % (which, key, parent)) + holds, words = replay.proof_holds(tool, sent, design[key].get("proof")) + proofs.append(holds) + if not holds: + raise Integrity("the %s design's %s proof: %s" % (which, key, words)) + answer = replay.answer(tool, sent, readout_for(check["constraints"], key) if tool == "run_trajectory" else None) + named = stopped_by(answer, check["constraints"], stage=key) + if answer["outcome"] not in stage["outcomes"] and not named: + raise Wrong("the %s design's %s comes back %s%s, not %s" % ( + which, key, answer["outcome"], " (%s)" % answer["stop"] if answer["stop"] else "", " or ".join(stage["outcomes"]))) + answers[key], requests[key] = answer, sent + if named: + facts["stopped"], facts["stopped_stage"] = answer["stop"], key + facts["steps_landed"] = (answer["body"] or {}).get("steps_landed") if tool == "run_trajectory" else None + facts["no_step"] = tool != "run_trajectory" + if i != len(stages) - 1: + raise Wrong("the %s design's %s stops (%s) before its last stage" % (which, key, answer["stop"])) + x = design_value(dict(var, on="run"), requests.get(var["stage"]), None) + if x is None: + raise Integrity("the %s design's value of the design variable cannot be read (%s)" % (which, var.get("words", ""))) + met, values = constraint_facts(check, answers, None, staged=True) + facts.update({"x": x, "met": met, "values": values}) + return facts + + +def grade_bracket(a, b, star, tol, slack, row): + """(reward_ok, graded) for a bracket [a, b] with its sides right.""" + width = abs(b - a) + straddles = min(a, b) - slack <= star <= max(a, b) + slack + within = width <= tol * (1 + 1e-9) + e = max(a, b, star) - min(a, b, star) + r = e / tol if tol > 0 else float("inf") + row["width"], row["width_ratio"] = width, r + if within and straddles: + return True, 1.0 + if r <= 1: + return False, OTHER_CROSSING + return False, GRADED_DECAY ** math.log10(r) + + +def score_boundary(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + passing = score_design(env, card.get("passing"), "passing", replay, proofs) + failing = score_design(env, card.get("failing"), "failing", replay, proofs) + row["passing"], row["failing"] = passing, failing + span = check["design"].get("range") + if span and not all(span[0] <= x <= span[1] for x in (passing["x"], failing["x"])): + raise Wrong("a design lies outside the range the task states, %g to %g" % tuple(span)) + broken = [c for c, ok in passing["met"].items() if not ok] + if broken: + raise Wrong("the passing design breaks %s" % ", ".join(broken)) + broken = [c for c, ok in failing["met"].items() if not ok] + if not broken: + raise Wrong("the failing design meets every constraint") + binding = card.get("binding") + if binding != reference["binding"]: + raise Wrong("binding names %r; the constraint that binds is another" % (binding,)) + if binding not in broken: + raise Wrong("the failing design does not break %s, the constraint named binding" % binding) + if binding in [c["id"] for c in check["constraints"] if c["on"] == "outcome"]: + said = card.get("failing") or {} + if said.get("stopped") != failing.get("stopped"): + raise Wrong("the failing design's run stops with %s; the card says %r" % (failing.get("stopped"), said.get("stopped"))) + if failing.get("no_step"): + pass # a solve that is refused has no step: its stop's name is stated + elif not (isinstance(said.get("step"), int) and not isinstance(said.get("step"), bool) and said["step"] == failing.get("steps_landed")): + raise Wrong("the failing design's run is sealed to step %s; the card says %r" % (failing.get("steps_landed"), said.get("step"))) + spec = check["design"] + xp, xf = passing["x"], failing["x"] + if spec["direction"] == "largest" and not xf > xp: + raise Wrong("the task asks for the largest value that holds: the failing design must lie above the passing one") + if spec["direction"] == "smallest" and not xf < xp: + raise Wrong("the task asks for the smallest value that holds: the failing design must lie below the passing one") + ok, graded = grade_bracket(xp, xf, reference["boundary"], spec["tolerance"], spec["tolerance"] * 0.5, row) + if not ok: + return graded, "the two designs are %.6g apart; the task asks for %.6g or less, and they must straddle the boundary" % ( + abs(xf - xp), spec["tolerance"]) + return 1.0, None + + +def score_budget(env, card, replay, row, proofs): + check, reference = env["check"], env["reference"] + template, path, tool = check["template"], check["variable"], check["tool"] + sides = {} + for side in ("holds", "stops"): + arguments = request_of(card.get(side), tool, side) + also = check.get("also") or [] + where = differs(template, without_readout(arguments), {path} | set(also)) + if where: + raise Integrity("the %s request differs from the task's at %s" % (side, where)) + x = get_path(arguments, path) + if not number(x): + raise Integrity("the %s request has no number at %s" % (side, path)) + for place in also: + again = get_path(arguments, place) + if not (number(again) and float(again) == float(x)): + raise Integrity("the %s request does not hold the same value at %s as at %s" % (side, place, path)) + holds, words = replay.proof_holds(tool, arguments, card[side].get("proof")) + proofs.append(holds) + sides[side] = (float(x), arguments, holds, words) + for side in ("holds", "stops"): + if not sides[side][2]: + raise Integrity("the %s seal: %s" % (side, sides[side][3])) + held = replay.answer(tool, sides["holds"][1]) + stopped = replay.answer(tool, sides["stops"][1]) + row["holds_outcome"], row["stops_outcome"] = held["outcome"], "%s (%s)" % (stopped["outcome"], stopped["stop"]) + if held["outcome"] not in NOT_STOPPED: + raise Wrong("the holds request comes back %s (%s)" % (held["outcome"], held["stop"])) + if stopped["stop"] != check["stop"]: + raise Wrong("the stops request comes back %s (%s), not the stop %s" % (stopped["outcome"], stopped["stop"], check["stop"])) + if card["stops"].get("stopped") != check["stop"]: + raise Wrong("the card names the stop %r; the verifier names %s" % (card["stops"].get("stopped"), check["stop"])) + xh, xs = sides["holds"][0], sides["stops"][0] + star = reference["boundary"] + row["holds_value"], row["stops_value"] = xh, xs + tol = check["relative_width"] * abs(star) + ok, graded = grade_bracket(xh, xs, star, tol, 1e-9 * abs(star), row) + if not ok: + return graded, "the bracket is %.6g wide; the task asks for %.3g of the value or less, and it must hold the stop" % ( + abs(xs - xh), check["relative_width"]) + return 1.0, None + + +def forensics_f1(env, named): + """(graded, problem): F1 over (row, reason) pairs; problem when the card is not a usable answer.""" + if not isinstance(named, dict): + return 0.0, "false_rows is not an object of row and reason" + rows = [c["row"] for c in env["check"]["rows"]] + truth = env["reference"]["false_rows"] + unknown = [r for r in named if r not in set(rows)] + if unknown: + return 0.0, "no rows %s in the table" % ", ".join(sorted(unknown)) + reasons = env["check"].get("reasons") or REASONS + bad = [r for r, why in named.items() if why not in reasons] + if bad: + return 0.0, "the reason for %s is not one of %s" % (", ".join(sorted(bad)), ", ".join(reasons)) + if rows and set(named) == set(rows): + return 0.0, "every row of the table is named false: a blanket answer" + found = sum(1 for r, why in named.items() if truth.get(r) == why) + if not truth and not named: + return 1.0, None + precision = found / len(named) if named else 0.0 + recall = found / len(truth) if truth else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + if f1 >= 1.0: + return 1.0, None + missed = sorted(set(truth) - set(named)) + wrongly = sorted(set(named) - set(truth)) + wrong_reason = sorted(r for r in set(truth) & set(named) if truth[r] != named[r]) + said = [] + if missed: + said.append("%d false row(s) not named" % len(missed)) + if wrongly: + said.append("%d genuine row(s) named false" % len(wrongly)) + if wrong_reason: + said.append("%d false row(s) with another reason" % len(wrong_reason)) + return f1, "; ".join(said) + + +def score(env, reply, replay, calls=None, reply_calls=None, calls_from="reply", log_problem=None): + """One environment scored. calls: the authoritative record [(tool, arguments)] (None: no record); + reply_calls: the reply-side log, compared with calls under calls_from="harness".""" + row = {"id": env["id"], "family": env["family"], "kind": KINDS.get(env["family"]), "calls_from": calls_from, + "correct": 0, "proofs_hold": 0, "reward": 0, "graded": 0.0, "verdict": None, "reason": None} + card, problem = read_card(reply) + if problem: + row.update(verdict="no_card", reason=problem) + return row + proofs = [] + try: + problem = engine_problem(env, replay) + if problem: + raise Integrity(problem) + problem = call_record_problem(env, card, calls, reply_calls, calls_from, log_problem, row) + if problem: + raise Integrity(problem) + family = env["family"] + if family in ("tradeoff", "chain_design"): + graded, reason = score_boundary(env, card, replay, row, proofs) + elif family == "budget": + graded, reason = score_budget(env, card, replay, row, proofs) + elif family == "forensics": + named = card.get("false_rows") + if isinstance(named, dict): + row["named"] = named + graded, reason = forensics_f1(env, named) + proofs = [True] + if reason and graded == 0.0 and not isinstance(named, dict): + raise Wrong(reason) + else: + raise Wrong("unknown family %s" % family) + except Integrity as problem: + row.update(verdict="integrity", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + except Wrong as problem: + row.update(verdict="wrong", reason=str(problem), proofs_hold=int(bool(proofs) and all(proofs))) + return row + proofs_hold = int(bool(proofs) and all(proofs)) + correct = int(graded >= 1.0 and reason is None) + row.update(correct=correct, proofs_hold=proofs_hold, reward=int(correct == 1 and proofs_hold == 1), + graded=round(graded, 6) if proofs_hold else 0.0, + verdict="pass" if correct and proofs_hold else ("near" if graded > 0 else "wrong"), reason=reason) + return row + + +def records_for(folder, env_id, calls_from, harness_dir=None): + """(calls, reply_calls, log_problem) for one environment's reply in folder.""" + reply_calls = read_calls(os.path.join(folder, env_id + ".calls.jsonl")) + if calls_from == "harness": + calls, log_problem = read_harness_log(os.path.join(harness_dir or folder, env_id + ".harness.jsonl")) + return calls, reply_calls, log_problem + return reply_calls, None, None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("replies") + parser.add_argument("--engine", required=True) + parser.add_argument("--only") + parser.add_argument("--environments", required=True) + parser.add_argument("--out") + parser.add_argument("--calls-from", choices=("reply", "harness"), default="harness") + parser.add_argument("--harness-dir") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + environments = load_environments(args.environments) + if args.only: + wanted = set(args.only.split(",")) + environments = [e for e in environments if e["id"] in wanted] + missing = wanted - {e["id"] for e in environments} + if missing: + sys.exit("no environments %s in %s" % (", ".join(sorted(missing)), args.environments)) + for env in environments: + for problem in row_problems(env): + print("warning: %s: %s" % (env.get("id"), problem), file=sys.stderr) + verifier = open_verifier(args.engine) + replay = Replay(verifier) + rows = [] + try: + for env in environments: + path = os.path.join(args.replies, env["id"] + ".txt") + reply = open(path, encoding="utf-8", errors="replace").read() if os.path.isfile(path) else "" + calls, reply_calls, log_problem = records_for(args.replies, env["id"], args.calls_from, args.harness_dir) + row = score(env, reply, replay, calls, reply_calls, args.calls_from, log_problem) + rows.append(row) + if not args.quiet: + print("%-58s reward %d graded %.4f %-9s %s" % (env["id"], row["reward"], row["graded"], row["verdict"], + row["reason"] or ""), flush=True) + replay.seen.clear() + finally: + close_verifier(verifier) + if args.out: + with open(args.out, "w", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + total = len(rows) + print("\n%d environments: reward %d, graded %.4f (mean %.4f), correct %d, proofs_hold %d" % ( + total, sum(r["reward"] for r in rows), sum(r["graded"] for r in rows), + sum(r["graded"] for r in rows) / total if total else 0.0, + sum(r["correct"] for r in rows), sum(r["proofs_hold"] for r in rows))) + by = {} + for r in rows: + by.setdefault(r["family"], []).append(r) + for family in FAMILIES: + if family in by: + print(" %-13s reward %d of %d, mean graded %.4f" % (family, sum(r["reward"] for r in by[family]), len(by[family]), + sum(r["graded"] for r in by[family]) / len(by[family]))) + + +if __name__ == "__main__": + main() diff --git a/sample/tasks/mcp/scorer/ztp_mcp.py b/sample/tasks/mcp/scorer/ztp_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..1afbc12d8c05d8c143563152ffae500e8052a6db --- /dev/null +++ b/sample/tasks/mcp/scorer/ztp_mcp.py @@ -0,0 +1,188 @@ +"""A small Model Context Protocol client for the Zero-Trust Physics verifier. + +Standard library only. It speaks MCP two ways: + + stdio to a verifier built from the public source and started here as a program + (target/release/mcp_stdio): one JSON-RPC message a line, no network. + HTTP to an MCP address (JSON-RPC in a POST), such as + + https://mcp.zerotrustphysics.com/mcp/open Open to any agent. + +The open address gives each network address one place in the physics pool at a +time and answers "Too many concurrent physics tasks." or HTTP 429 when it is +busy; nothing waits on the server, so this client sends one request at a time +and, when it is told to come back, waits and sends the same request again. + +Licence: Apache-2.0. +""" +import json +import select +import shlex +import subprocess +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." + + +class McpError(RuntimeError): + pass + + +class Verifier: + """One MCP endpoint. call(tool, arguments) returns (text, is_error).""" + + def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True): + self.url = url + self.timeout_s = timeout_s + self.patience_s = patience_s # how long to keep asking politely before giving up on one request + self.pause_s = pause_s # a fixed pause after every request, for a shared address + self.headers = dict(headers or {}) + self.quiet = quiet + self.session = None + self.server = None + self.requests_sent = 0 + self.times_asked_to_wait = 0 + self._id = 0 + + # -- transport ------------------------------------------------------------------------- + def _post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-environments/1.0", **self.headers} + if self.session: + headers["Mcp-Session-Id"] = self.session + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + self.requests_sent += 1 + with urllib.request.urlopen(request, timeout=self.timeout_s) as response: + session = response.headers.get("Mcp-Session-Id") + if session: + self.session = session + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + raise McpError("the event stream held no answer to the request") + return json.loads(raw) if raw.strip() else {} + + def _ask(self, method, params=None): + """Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again.""" + self._id += 1 + message = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + message["params"] = params + started, wait = time.time(), 2.0 + while True: + reason = None + try: + answer = self._post(message) + if "error" in answer: + raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300]) + result = answer.get("result", {}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + if method == "tools/call" and BUSY in text and len(text) < 400: + reason = "the physics pool is busy" + else: + if self.pause_s: + time.sleep(self.pause_s) + return result + except urllib.error.HTTPError as problem: + if problem.code == 429 or problem.code >= 500: + after = problem.headers.get("Retry-After") + reason = "HTTP %d" % problem.code + if after and after.isdigit(): + wait = max(wait, float(after)) + else: + raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300])) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem: + reason = "no connection (%s)" % problem + self.times_asked_to_wait += 1 + if time.time() - started + wait > self.patience_s: + raise McpError("gave up after %d s: %s" % (self.patience_s, reason)) + if not self.quiet: + print(" %s; asking again in %.0f s" % (reason, wait), flush=True) + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + # -- protocol -------------------------------------------------------------------------- + def connect(self): + result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}}) + self.server = result.get("serverInfo") + try: + self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + except Exception: # a notification has no answer; some servers close without one + pass + return result + + def tools(self): + """The tool declarations exactly as the endpoint gives them.""" + return self._ask("tools/list").get("tools", []) + + def call(self, tool, arguments=None): + """Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag.""" + result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}}) + text = "".join(c.get("text", "") for c in result.get("content", []) or []) + return text, bool(result.get("isError")) + + def call_json(self, tool, arguments=None): + """Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON.""" + text, is_error = self.call(tool, arguments) + try: + return json.loads(text), is_error + except ValueError: + return text, is_error + + +class StdioVerifier(Verifier): + """The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line. + For anyone who holds an MCP server as a program; the open address needs none of this.""" + + def __init__(self, command, timeout_s=600, **kwargs): + super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs) + self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def _post(self, message): + self.requests_sent += 1 + try: + self.proc.stdin.write((json.dumps(message) + "\n").encode()) + self.proc.stdin.flush() + except OSError: # a program that has stopped reading will not start again + try: + self.proc.stdin.close() + except OSError: + pass + raise McpError("the program stopped reading") + if "id" not in message: + return {} + while True: + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s) + if not ready: + raise McpError("no answer in %d s" % self.timeout_s) + line = self.proc.stdout.readline() + if not line: + raise McpError("the program closed its output") + found = json.loads(line) + if found.get("id") == message["id"]: + return found + + def close(self): + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def connect(endpoint=OPEN_ADDRESS, **kwargs): + """A connected verifier: an http(s) address, or "stdio:" for a program.""" + verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs) + verifier.connect() + return verifier diff --git a/sample/tasks/mcp/scorer/ztp_open_bridge.py b/sample/tasks/mcp/scorer/ztp_open_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20b469db24286278a387680ad8d3898f0661 --- /dev/null +++ b/sample/tasks/mcp/scorer/ztp_open_bridge.py @@ -0,0 +1,109 @@ +"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's +MCP address, and its answer written back on stdout, one line each. Standard library only. + + python3 ztp_open_bridge.py [URL] URL defaults to https://mcp.zerotrustphysics.com/mcp/open + +It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio +server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds +nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a +notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for +every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same +message again, as ztp_mcp.Verifier does, so a client sees one answer per request. + +Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer " on every post, for a keyed door. With no +key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image. + +Licence: Apache-2.0. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open" +BUSY = "Too many concurrent physics tasks." +PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900")) +API_KEY = os.environ.get("ZTP_API_KEY") or None + + +class Bridge: + def __init__(self, url): + self.url = url + self.session = None + self.extra_headers = {} + + def post(self, message): + body = json.dumps(message).encode() + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "zero-trust-physics-bridge/1.0"} + if self.session: + headers["Mcp-Session-Id"] = self.session + if API_KEY: + headers["Authorization"] = "Bearer " + API_KEY + headers.update(self.extra_headers) + request = urllib.request.Request(self.url, data=body, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=600) as response: + if response.headers.get("Mcp-Session-Id"): + self.session = response.headers["Mcp-Session-Id"] + raw = response.read().decode("utf-8") + kind = response.headers.get("Content-Type", "") + if "id" not in message: + return None + if "text/event-stream" in kind: + for line in raw.splitlines(): + if line.startswith("data:"): + found = json.loads(line[5:].strip()) + if found.get("id") == message.get("id"): + return found + return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}} + return json.loads(raw) if raw.strip() else None + + def forward(self, message): + started, wait = time.time(), 2.0 + while True: + try: + answer = self.post(message) + text = "" + if isinstance(answer, dict) and isinstance(answer.get("result"), dict): + text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict)) + if not (BUSY in text and len(text) < 400): + return answer + except urllib.error.HTTPError as problem: + if not (problem.code == 429 or problem.code >= 500): + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}} + after = problem.headers.get("Retry-After") + if after and after.isdigit(): + wait = max(wait, float(after)) + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError): + pass + if time.time() - started + wait > PATIENCE_S: + if "id" not in message: + return None + return {"jsonrpc": "2.0", "id": message.get("id"), + "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}} + time.sleep(wait) + wait = min(wait * 1.6, 30.0) + + +def main(): + bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS) + for line in sys.stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + continue + answer = bridge.forward(message) + if answer is not None: + sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/sample/verify_sample.sh b/sample/verify_sample.sh new file mode 100755 index 0000000000000000000000000000000000000000..f1d27d81013d63d07ecb168e144f67f870045ba1 --- /dev/null +++ b/sample/verify_sample.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Every hash, the 5 reference answers and the cheat suite, on the bundled verifier. No network is used. +set -u +ROOT=$(cd "$(dirname "$0")" && pwd) +cd "$ROOT" || exit 2 +case "$(uname -s)-$(uname -m)" in + Darwin-arm64) ENGINE="$ROOT/scorer/bin/sample_verifier-macos-arm64" ;; + Linux-x86_64|Linux-amd64) ENGINE="$ROOT/scorer/bin/sample_verifier-linux-amd64" ;; + Linux-aarch64|Linux-arm64) ENGINE="$ROOT/scorer/bin/sample_verifier-linux-arm64" ;; + *) echo "no bundled verifier for $(uname -s) $(uname -m); see VERIFY.md"; exit 2 ;; +esac +[ -x "$ENGINE" ] || chmod +x "$ENGINE" 2>/dev/null || true +FAIL="" +if command -v shasum > /dev/null; then SUM="shasum -a 384"; else SUM="sha384sum"; fi +if $SUM -c SHA384SUMS > /dev/null 2>&1; then echo "SHA384SUMS: $(grep -c . SHA384SUMS) files hold"; else echo "SHA384SUMS: NOT ALL HOLD"; FAIL="$FAIL hashes;"; fi +OUT=$(mktemp -d) +cd scorer || exit 2 +python3 -B pack_score.py ../reference --engine "$ENGINE" --environments data/environments.jsonl --calls-from harness --quiet --out "$OUT/scores.jsonl" > "$OUT/scores.log" 2>&1 +python3 -B pack_score.py --run run_cheat_suite.py --environments data/environments.jsonl --reference ../reference --engine "$ENGINE" --out "$OUT/cheat.jsonl" > "$OUT/cheat.log" 2>&1 +CE=$? +python3 -B - "$OUT" "$CE" <<'PY' || FAIL="$FAIL scores;" +import json, sys +out, ce = sys.argv[1], int(sys.argv[2]) +r = [json.loads(l) for l in open(out + "/scores.jsonl")] +c = [json.loads(l) for l in open(out + "/cheat.jsonl") if l.strip()] +a = [x for x in c if x.get("applies")] +cheats = [x for x in a if not x["expect"]] +honest = [x for x in a if x["expect"]] +over = sum(1 for x in cheats if x["reward"] or x["graded"]) +at1 = sum(1 for x in honest if x["ok"]) +print("reference answers: reward 1 on %d of %d, proofs hold on %d" % (sum(x["reward"] for x in r), len(r), sum(x["proofs_hold"] for x in r))) +print("cheat suite: %d cheat attempts over %d vectors, %d above 0; honest controls %d of %d at 1 (exit %d)" % (len(cheats), len({x["vector"] for x in cheats}), over, at1, len(honest), ce)) +sys.exit(0 if sum(x["reward"] for x in r) == len(r) == 5 and not over and cheats and at1 == len(honest) and ce == 0 else 1) +PY +rm -rf "${OUT:?}" +if [ -z "$FAIL" ]; then echo "SAMPLE HOLDS"; else echo "NOT HOLDING:$FAIL"; exit 1; fi diff --git a/sample_tasks.jsonl b/sample_tasks.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9385304e692e8257ca1873764febe27001b446e --- /dev/null +++ b/sample_tasks.jsonl @@ -0,0 +1,5 @@ +{"task_id": "g5r8-bs-mast-2seg-drift-down-wall-b4", "kind": "budgeted_search", "models": "energy/tokamak_vde_mast", "call_budget": 4, "pass_at_1": "50% (4/8)", "pass_at_8": "100% (n=8)", "mean_graded": 0.579, "cheat_suite": "0/16 cheats above 0; 3/3 honest at 1", "summary": "MAST's plasma in shot 15045 starts on its upward growing mode at +3.8 mm, drifts for 18 ms (18 steps of 1 ms) at 0 V, and is then driven downward for 38 ms (38 steps of 1 ms) by a negative P6 amplifier voltage you set."} +{"task_id": "g5r10-ch-jet-dt3-least-tbeam-power-c12-b7", "kind": "chained_design", "models": "energy/tokamak_jet_dte1 -> tokamak_dt_beam_target", "call_budget": 7, "pass_at_1": "37.5% (3/8)", "pass_at_8": "100% (n=8)", "mean_graded": 0.82, "cheat_suite": "0/19 cheats above 0; 3/3 honest at 1", "summary": "JET runs 700 steps of 1 ms at 5.2 MW tritium beam power followed by 1,100 steps of 1 ms at one tritium beam power that you choose."} +{"task_id": "g5r10-dl-dt4-core-te-fastshare-pion", "kind": "design_to_limit", "models": "tokamak_dt_beam_target", "call_budget": 4, "pass_at_1": "37.5% (3/8)", "pass_at_8": "100% (n=8)", "mean_graded": 0.837, "cheat_suite": "0/17 cheats above 0; 3/3 honest at 1", "summary": "A steady D-T tokamak slice in four radial shells (1.02, 1.92, 3.22 and 5.18 m^3) with oxygen-16 impurity (charge 8, mass 16), 2.9 s after the last beam change, has one inner-shell electron temperature that you choose (tokamak_dt_beam_tar..."} +{"task_id": "g5r8-dl-jet-tritium-rich-dome-hotion", "kind": "design_to_limit", "models": "energy/tokamak_jet_dte1", "call_budget": 4, "pass_at_1": "37.5% (3/8)", "pass_at_8": "100% (n=8)", "mean_graded": 0.719, "cheat_suite": "0/17 cheats above 0; 3/3 honest at 1", "summary": "In the hot-ion regime on the tritium-rich side of the D-T reactivity dome (where excess tritium starves thermal deuterium and lowers fusion power), JET runs 600 steps of 1 ms at tritium fraction 0.52 and then 1,100 steps of 1 ms at one t..."} +{"task_id": "g5-bs-pb11-weakest-field-that-holds-b4", "kind": "budgeted_search", "models": "fusion_pb11_thermal", "call_budget": 4, "pass_at_1": "62.5% (5/8)", "pass_at_8": "100% (n=8)", "mean_graded": 0.728, "cheat_suite": "0/16 cheats above 0; 3/3 honest at 1", "summary": "A uniform thermal proton-boron-11 plasma at an ion temperature of 310 keV and an electron density of 2.2e20 per m^3, 12.8 percent boron among the fuel ions and 1 percent ash, with a minor radius of 2.1 m, a wall reflectivity of 0.96, an ..."}