diff --git a/README.md b/README.md index 68aa3ecaf9bbe28ca9609175ece9e248f916344a..f8ac77fa033e054d0780f4f51944b9f526e36356 100644 --- a/README.md +++ b/README.md @@ -64,10 +64,11 @@ existing one. > suite and cannot be reproduced from this subset alone. > [!IMPORTANT] -> Doc2Harness is an **executable** benchmark. This dataset lets you browse and -> analyze the scenarios, the development document, and the contract skeleton. -> To actually score a harness (Docker, mock gateway, drivers), use the code on -> [GitHub](https://github.com/YuyaoGe/doc2harness). +> Doc2Harness is an **executable** benchmark. The `scenarios` and `leaderboard` +> configs are for browsing and analysis; `load_dataset` alone does not score +> anything. To score a harness, use the full evaluation code shipped in +> [`code/`](#run-the-benchmark) (a snapshot of the +> [GitHub repository](https://github.com/YuyaoGe/doc2harness)) with Docker. ## Contents @@ -77,6 +78,7 @@ existing one. | `data/leaderboard.jsonl` | Pass rates of 19 frontier models on the full 328-case suite (config `leaderboard`) | | `development_document/functional_spec_v6.md` | The development document given to the build model in Stage 1 | | `contract_skeleton/` | The interface-only contract skeleton (CLI, headless entry point, evaluation API), plus `AGENT_CONTRACT-v2.md` | +| `code/` | Full evaluation code: Stage 1 build pipeline and Stage 2 framework (catalog, drivers, mock gateway), identical to GitHub commit [`5411f53`](https://github.com/YuyaoGe/doc2harness/tree/5411f53d497a6c76c1dd41bd55f08cc033203d2b) | ## Usage @@ -99,6 +101,47 @@ path = snapshot_download("YuyaoGe/doc2harness", repo_type="dataset", allow_patterns=["development_document/*", "contract_skeleton/**"]) ``` +## Run the benchmark + +**Requirements:** Python 3.11+ and Docker. Both stages use the standard library only. + +```bash +pip install -U huggingface_hub +hf download YuyaoGe/doc2harness --repo-type dataset --include "code/*" --local-dir doc2harness +cd doc2harness/code + +# sanity check: loading the catalog verifies its digests +PYTHONPATH=src python3 -c "from doc2harness.benchmark.dispatch import active_scenario_ids as a; print(len(a()))" +# 94 +``` + +**Stage 2 only: score an existing harness.** No model key is needed; scenarios +drive the product against a mock gateway. + +```bash +docker build --target evaluation -t doc2harness/evaluation:candidate -f containers/Dockerfile . + +PYTHONPATH=src:tools:run python3 tools/run_production_catalog.py \ + --artifact /path/to/product --artifact-id my-product \ + --output /tmp/scores --concurrency 12 --timeout 300 +``` + +Each scenario writes a JSON receipt, plus a `catalog_receipt.json`. The score is +`pass / (pass + fail)` over applicable scenarios; a scenario that cannot be +observed on a product is `INCONCLUSIVE`, not a failure. Narrow the selection +with `--family headless` or `--scenario-id `. + +**Stage 1: build a new harness, then score it.** This needs the builder image +and a local LiteLLM gateway holding your own API key; see +`code/src/stage1/README.md`. + +```bash +docker pull ghcr.io/yuyaoge/doc2harness-builder:latest +PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag --dry-run # prints the plan, no key needed +PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag --out-dir results/ +# then score results//agent as above +``` + ## Scenario fields (`scenarios`) | Field | Type | Description | diff --git a/code/.d2a_spec/typed_event_hooks.json b/code/.d2a_spec/typed_event_hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..ec4bf140fec97ba7c12601ade3014a22ddd42de7 --- /dev/null +++ b/code/.d2a_spec/typed_event_hooks.json @@ -0,0 +1,7 @@ +{ + "schema": "doc2harness.typed-event-hooks/1", + "tool_lifecycle": true, + "subprocess": true, + "workspace": true, + "cleanup": true +} diff --git a/code/.github/workflows/quality.yml b/code/.github/workflows/quality.yml new file mode 100644 index 0000000000000000000000000000000000000000..4c856a7e833cc334a0465c8647c6d1ebc1699261 --- /dev/null +++ b/code/.github/workflows/quality.yml @@ -0,0 +1,133 @@ +name: quality + +on: + workflow_dispatch: + +permissions: + contents: read + +env: + LC_ALL: C.UTF-8 + PYTHONHASHSEED: "0" + SOURCE_DATE_EPOCH: "315532800" + TZ: UTC + +jobs: + clean-wheel: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12"] + steps: + - name: Check out source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: ${{ matrix.python-version }} + check-latest: false + - name: Install hash-locked verification tools + env: + PIP_DISABLE_PIP_VERSION_CHECK: "1" + run: python -m pip install --require-hashes -r requirements/build-tools.txt + - name: Build distributions without dependency discovery + run: python -m build --no-isolation --sdist --wheel + - name: Compile source + run: python -m compileall -q src + - name: Rebuild the wheel offline from the source distribution + shell: bash + env: + PIP_NO_INDEX: "1" + run: | + sdist_archive=(dist/*.tar.gz) + test "${#sdist_archive[@]}" -eq 1 + export SDIST_ARCHIVE="${sdist_archive[0]}" + export SDIST_UNPACK_ROOT="${RUNNER_TEMP}/sdist-source" + python - <<'PY' + import os + import tarfile + from pathlib import Path, PurePosixPath + + archive_path = Path(os.environ["SDIST_ARCHIVE"]) + destination = Path(os.environ["SDIST_UNPACK_ROOT"]) + destination.mkdir() + with tarfile.open(archive_path, mode="r:gz") as archive: + member_names = set() + for member in archive.getmembers(): + path = PurePosixPath(member.name) + if path.is_absolute() or ".." in path.parts: + raise SystemExit("unsafe source-distribution member") + if path.as_posix() != member.name or member.name in member_names: + raise SystemExit("non-canonical source-distribution member") + member_names.add(member.name) + if member.issym() or member.islnk() or not ( + member.isfile() or member.isdir() + ): + raise SystemExit("unsupported source-distribution member type") + archive.extractall(destination, filter="data") + PY + sdist_root="${SDIST_UNPACK_ROOT}/doc2harness-0.0.0" + mkdir "${sdist_root}/dist" + cp "${SDIST_ARCHIVE}" "${sdist_root}/dist/" + python -m build --no-isolation --wheel --outdir "${sdist_root}/dist" "${sdist_root}" + cmp dist/*.whl "${sdist_root}/dist/"*.whl + - name: Install source-distribution wheel into a clean environment + shell: bash + run: | + python -m venv --without-pip "${RUNNER_TEMP}/installed" + python -m pip --python "${RUNNER_TEMP}/installed/bin/python" install \ + --no-index --no-deps \ + "${RUNNER_TEMP}/sdist-source/doc2harness-0.0.0/dist/"*.whl + - name: Smoke-import the installed wheel + shell: bash + run: | + "${RUNNER_TEMP}/installed/bin/python" -I -c " + import doc2harness + from doc2harness.benchmark.dispatch import active_scenario_ids + ids = active_scenario_ids() + print('installed wheel ok, scenarios:', len(ids)) + assert len(ids) == 94 + " + + # Verify the catalog from source (the wheel only ships src/doc2harness; stage1 + # runs from source and is not packaged into the wheel). + source-catalog: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12"] + steps: + - name: Check out source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: ${{ matrix.python-version }} + check-latest: false + - name: Verify catalog integrity and size + run: | + PYTHONPATH=src python - <<'PY' + from doc2harness.benchmark.dispatch import active_scenario_ids, load_scenario_owner + from collections import Counter + ids = active_scenario_ids() + families = Counter( + load_scenario_owner(i).definition.classification.primary for i in ids + ) + print("scenarios:", len(ids)) + for name, count in sorted(families.items()): + print(f" {name} {count}") + assert len(ids) == 94, f"active catalog changed size: {len(ids)}" + assert len(families) == 9, f"family count changed: {sorted(families)}" + PY diff --git a/code/.gitignore b/code/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8cf985c38b2b387ce78c27e321da2bf32c9c4615 --- /dev/null +++ b/code/.gitignore @@ -0,0 +1,12 @@ +.venv/ +build/ +dist/ +*.egg-info/ +__pycache__/ +.pytest_cache/ +run-results/ + +# stage1 local build outputs and artifact registry: large, and they contain +# products emitted by the model under test, so they stay out of the repository. +/results/ +/artifacts_store/ diff --git a/code/LICENSE b/code/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ad63d32c1b74cb42334175bf00dfc5eafc9e0f0f --- /dev/null +++ b/code/LICENSE @@ -0,0 +1,160 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship made available under + the License, as indicated by a copyright notice that is included in + or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean, as defined by the Licensor, any work of + authorship, including the original version of the Work and any + modifications or additions to that Work or Derivative Works of the Work, + that is intentionally submitted to the Licensor for inclusion in the Work + by the copyright owner or by an individual or Legal Entity authorized to + submit on behalf of the copyright owner. + + "Contributor" shall mean Licensor and any Legal Entity on behalf of + whom a Contribution has been received by the Licensor and included + within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by the combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a cross-claim + or counterclaim in a lawsuit) alleging that the Work or any + Contribution embodied within the Work constitutes direct or + contributory patent infringement, then any patent licenses granted to + You under this License for that Work shall terminate as of the date + such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, You must include a readable copy of the + attribution notices contained within such NOTICE file, in + at least one of the following places: within a NOTICE text + file distributed as part of the Derivative Works; within + the Source form or documentation, if provided along with the + Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the License. + + You may add Your own license statement for Your modifications and + may provide additional grant of rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Work + and derivative works. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or reproducing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or exemplary damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or all other + commercial damages or losses), even if such Contributor has been + advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may offer only + conditions consistent with this License. + + END OF TERMS AND CONDITIONS diff --git a/code/MANIFEST.in b/code/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..7ef872a0c9782d269400603a9d1706d7ab2cd435 --- /dev/null +++ b/code/MANIFEST.in @@ -0,0 +1,12 @@ +include README.md +include NOTICE +include LICENSE +include pyproject.toml +include .github/workflows/quality.yml +include requirements/build-tools.txt +include requirements/run.txt +recursive-include src/doc2harness *.py *.toml +recursive-include run *.sh *.py *.yaml *.md +prune containers +global-exclude *.py[cod] +global-exclude .DS_Store diff --git a/code/NOTICE b/code/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..723338c34b58463c82e1ee1f64cab35a3c0d6e1a --- /dev/null +++ b/code/NOTICE @@ -0,0 +1,45 @@ +# Third-party notices + +doc2harness evaluates coding-agent products. This file records the upstream work +it builds on and relates to. It is an attribution record, not a license grant โ€” +see `LICENSE` for this project's own terms. + +## mini-swe-agent + +MIT License, Copyright (c) 2025 Kilian A. Lieret and Carlos E. Jimenez +https://mini-swe-agent.com/ ยท https://github.com/SWE-agent/mini-swe-agent + +stage1 asks a model to build a harness product by implementing a hollowed +skeleton. That skeleton derives from mini-swe-agent's project layout. + +Scope of what is redistributed here: **no mini-swe-agent source code is vendored +in this repository.** The skeleton at `src/stage1/f0_clean/` is a few small +files of contract sockets that raise `NotImplementedError`; it carries no upstream +implementation, and neither image installs mini-swe-agent. A product a builder +derives from mini-swe-agent remains subject to the MIT license above โ€” anyone +distributing such a product needs to carry that notice with it. + +Note for product builders: the stage1 build prompt instructs the model to +present the product under its own name and to suppress the upstream startup +banner. That is an evaluation-fidelity measure (the benchmark observes the +product's own declared behaviour), not an attempt to obscure provenance. It does +not remove the MIT attribution obligation, which this notice discharges for the +benchmark and which a product's own distribution must discharge for itself. + +## OpenCode + +https://opencode.ai/ + +The builder image installs the OpenCode CLI binary, which drives the model +during a stage1 build. It is installed from upstream at image build time under +its own license; this repository redistributes no OpenCode code. The published +builder image does contain the binary โ€” consult OpenCode's terms before +redistributing that image. + +## LiteLLM + +https://github.com/BerriAI/LiteLLM + +Used at runtime as the model gateway. It is a runtime dependency supplied by the +operator, is not a dependency of the published wheel, and no LiteLLM code is +redistributed here. diff --git a/code/README.md b/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cfd69b0c2faed37ddea2f3ffd73178397c912e4f --- /dev/null +++ b/code/README.md @@ -0,0 +1,177 @@ +

+ Doc2Harness +

+ +

Benchmarking LLMs on Long-Horizon Harness Engineering of Coding Agents

+ +

+ Project Page + arXiv:2610.20344 + License + Python 3.11+ + stdlib only + Docker + Builder image +

+ +

+ ๐ŸŒ Website โ€ข + ๐Ÿ“„ Paper โ€ข + โšก Quick start โ€ข + ๐Ÿงช Scenarios โ€ข + ๐Ÿ† Leaderboard โ€ข + ๐Ÿ“ Citation +

+ +--- + +Doc2Harness measures how well a model can **build a working coding agent** โ€” +the harness itself โ€” rather than how well it writes a patch inside one. + +- ๐Ÿ—๏ธ **Stage 1 โ€” Build.** A build model, working through + [OpenCode](https://github.com/anomalyco/opencode) in an isolated container, + receives a development document and an interface-only skeleton and has to + implement a complete agent harness. +- ๐Ÿ”ฌ **Stage 2 โ€” Evaluate.** The harness is frozen, moved to a separate + container, and driven end to end by a scripted **mock model**. Each scenario + reads four observable channels โ€” requests sent to the model, files on disk, + exit code, command output โ€” and **positive controls** rule out vacuous passes. + +

+ Doc2Harness pipeline +

+ +> [!NOTE] +> ๐Ÿ“ฆ **This is a partial open-source release.** The full benchmark in the paper +> has **328 test cases**; this repository releases a subset of **94 scenarios** +> (53 scored test cases plus the 41 positive controls that gate them). The +> remaining test cases are held out. Numbers on the leaderboard below come from +> the full suite and cannot be reproduced from this subset alone. + +## ๐Ÿ† Leaderboard + +

+ Pass rate of nineteen models +

+ +Pass rate of **19 frontier models** on the full 328-case suite, strongest on the +left. Each model built **three independent harnesses**; a bar is their mean. +The best model reaches **53.05%** and the weakest **27.44%** โ€” even the +strongest still fails nearly half the cases. See the +[project page](https://geyuyao.com/doc2harness/) for per-category breakdowns +and case studies. + +## โšก Quick start + +**Requirements:** Python 3.11+ and Docker. No third-party Python packages โ€” +both stages are standard library only. + +### 1๏ธโƒฃ Score an existing harness (Stage 2 only) + +No model key needed: scenarios drive the product against a mock gateway. + +```bash +# build the evaluation image once (see containers/README.md for mirror options) +docker build --target evaluation -t doc2harness/evaluation:candidate -f containers/Dockerfile . + +# run all 94 scenarios against a product directory (one containing src/yuyao/) +PYTHONPATH=src:tools:run python3 tools/run_production_catalog.py \ + --artifact /path/to/product --artifact-id my-product \ + --output /tmp/scores --concurrency 12 --timeout 300 +``` + +- Narrow the selection with `--family headless` or `--scenario-id `. +- Output: one JSON receipt per scenario plus `catalog_receipt.json`. The + score is `pass / (pass + fail)` over applicable scenarios; a scenario that + cannot be observed on a product is `INCONCLUSIVE`, not a failure. +- The full catalog takes about 25โ€“90 seconds at concurrency 12. + +### 2๏ธโƒฃ Build a new harness (Stage 1), then score it + +Needs the builder image and a local [LiteLLM](https://github.com/BerriAI/litellm) +gateway holding **your** API key โ€” setup in +[`src/stage1/README.md`](src/stage1/README.md). + +```bash +docker pull ghcr.io/yuyaoge/doc2harness-builder:latest + +# free: prints the full orchestration plan, starts nothing, needs no key +PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag --dry-run + +# the real build (~15 minutes) +PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag --out-dir results/ + +# then score results//agent with step 1๏ธโƒฃ +``` + +### โœ… Sanity check + +```bash +PYTHONPATH=src python3 -c "from doc2harness.benchmark.dispatch import active_scenario_ids as a; print(len(a()))" +# 94 +``` + +Loading the catalog also verifies its digests, so an edited or inconsistent +catalog fails here instead of silently scoring a different set. + +## ๐Ÿงช Scenario catalog + +| Family | Total | Scored | Controls | What it observes | +|---|--:|--:|--:|---| +| ๐Ÿ“„ `file` | 17 | 9 | 8 | Read / edit / patch tools, including hostile encodings | +| ๐Ÿ”’ `permission` | 16 | 8 | 8 | Whether permission rules really constrain spawned processes | +| ๐Ÿ’พ `state` | 14 | 7 | 7 | Slash commands and session state | +| ๐Ÿค– `headless` | 13 | 6 | 7 | Non-interactive runs and contract entry points | +| ๐Ÿ”Œ `direct` | 11 | 6 | 5 | Wire-level model protocol against a mock gateway | +| ๐Ÿ–ฅ๏ธ `tui` | 9 | 5 | 4 | Interactive terminal behaviour over a real pty | +| ๐Ÿ“ฆ `artifact` | 7 | 7 | 0 | Product shape: entry point, launcher, lockfile, wheels | +| ๐Ÿš€ `startup` | 5 | 4 | 1 | Install and launch, ambient-environment isolation | +| ๐Ÿงฉ `extension` | 2 | 1 | 1 | Extension points that must not fire without their trigger | +| **Total** | **94** | **53** | **41** | | + +Each scenario is one file: +`src/doc2harness/benchmark/harnesses//scenarios/.py`. + +**Controls are not scored and are not free passes.** A control proves that the +command *can* succeed when nothing blocks it, so a blocked run reads as "the +rule held" rather than "the command never worked". Each scored scenario +declares its controls in `definition.dependencies`; if you narrow the selection, +keep it closed under those dependencies. + +## ๐Ÿ“ Repository layout + +```text +src/doc2harness/ Stage 2 evaluation framework: catalog, drivers, mock gateway +src/stage1/ Stage 1 build pipeline: spec, skeleton, builder image, smoke layers +tools/ run_production_catalog.py โ€” score a product +run/ YAML-driven launchers +containers/ evaluation image +assets/ figures for this README +``` + +## ๐Ÿ“ Citation + +If you find Doc2Harness useful, please cite the +[paper](https://arxiv.org/abs/2610.20344): + +```bibtex +@article{ge2026doc2harness, + title = {Doc2Harness: Benchmarking LLMs on Long-Horizon Harness Engineering of Coding Agents}, + author = {Ge, Yuyao and Liu, Shenghua and Gao, Peizhong and Ge, Chendi and Liu, Chenxu and + Wang, Yiwei and Mei, Lingrui and Bi, Baolong and Yao, Jiayu and Guo, Jiafeng and + Cheng, Xueqi}, + journal = {arXiv preprint arXiv:2610.20344}, + year = {2026} +} +``` + +## ๐Ÿ™ Acknowledgments + +The product skeleton derives from the project layout of +**[mini-swe-agent](https://github.com/SWE-agent/mini-swe-agent)** (MIT). +Builds run through **[OpenCode](https://github.com/anomalyco/opencode)**, and +the model gateway is **[LiteLLM](https://github.com/BerriAI/litellm)**. We +thank their authors and contributors. + +Licensed under [Apache 2.0](LICENSE); see [`NOTICE`](NOTICE) for upstream +attribution. diff --git a/code/assets/leaderboard.png b/code/assets/leaderboard.png new file mode 100644 index 0000000000000000000000000000000000000000..af93b02df60e91fd2c421cd03aa86f9efb68fa11 --- /dev/null +++ b/code/assets/leaderboard.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f789477a5a24535462d47c4f31e540e3a3b1fa697e23997d0fb8c0d9d2a8005 +size 182310 diff --git a/code/assets/logo.png b/code/assets/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..9019a6769abac1124eed726509f9d7988ae8eebc --- /dev/null +++ b/code/assets/logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c10a641f41596c38e5fad58b44808805bc44df469a351d0e597fd8a91a774bf +size 22521 diff --git a/code/assets/pipeline.png b/code/assets/pipeline.png new file mode 100644 index 0000000000000000000000000000000000000000..5bc77a89102457f85d08f23f5a8d46716076e7af --- /dev/null +++ b/code/assets/pipeline.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbff56c7405f33c5e6ca20393955b2f85c503adbc5723bc70e3409a6a9bd5ea2 +size 145952 diff --git a/code/containers/Dockerfile b/code/containers/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b3724c5eac2ee138c73228e22a5334b27bcda48 --- /dev/null +++ b/code/containers/Dockerfile @@ -0,0 +1,53 @@ +# syntax=docker/dockerfile:1.7 + +ARG PYTHON_IMAGE=python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 + +FROM ${PYTHON_IMAGE} AS runtime +ARG DEBIAN_MIRROR=https://mirrors.aliyun.com/debian +ARG DEBIAN_SECURITY_MIRROR=https://mirrors.aliyun.com/debian-security +ARG PYPI_INDEX_URL=https://mirrors.aliyun.com/pypi/simple +ARG SOURCE_DATE_EPOCH=315532800 +ENV DEBIAN_FRONTEND=noninteractive \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PIP_NO_CACHE_DIR=1 \ + PYTHONDONTWRITEBYTECODE=1 +RUN sed -i \ + -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" \ + -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" \ + /etc/apt/sources.list.d/debian.sources \ + && apt-get update \ + && apt-get install -y --no-install-recommends \ + bash ca-certificates curl dnsutils git iproute2 iptables ripgrep unzip \ + && rm -rf /var/lib/apt/lists/* /var/log/apt/* \ + && rm -f /var/log/alternatives.log /var/log/dpkg.log \ + /var/cache/ldconfig/aux-cache +COPY containers/requirements/runtime.lock /tmp/runtime.lock +RUN python -m pip install --no-cache-dir --index-url "${PYPI_INDEX_URL}" \ + --requirement /tmp/runtime.lock \ + && python -m pip check \ + && find /usr/local/lib/python3.12/site-packages \ + -type f -name '*.pyc' -delete \ + && PYTHONHASHSEED=0 SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH}" \ + python -m compileall -q -f --invalidation-mode checked-hash \ + /usr/local/lib/python3.12/site-packages \ + && python - <<'PY' +import importlib.metadata +import importlib.util + +assert importlib.util.find_spec("minisweagent") is None +try: + importlib.metadata.distribution("mini-swe-agent") +except importlib.metadata.PackageNotFoundError: + pass +else: + raise SystemExit("mini-swe-agent distribution leaked into runtime image") +PY +RUN mkdir -p /opt/f0 && test -z "$(find /opt/f0 -mindepth 1 -print -quit)" +WORKDIR /opt/f0 + +FROM runtime AS evaluation +LABEL org.opencontainers.image.title="doc2harness evaluation environment" \ + org.opencontainers.image.description="Minimal environment for isolated artifact evaluation" +RUN test ! -e /usr/local/bin/opencode \ + && test ! -e /root/.opencode \ + && test -z "$(find /opt/f0 -mindepth 1 -print -quit)" diff --git a/code/containers/README.md b/code/containers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..604749d4fa0d9a157d370de668f2341fced9408f --- /dev/null +++ b/code/containers/README.md @@ -0,0 +1,46 @@ +# Evaluation image + +stage2 runs every scenario that needs isolation inside one image, built from +`containers/Dockerfile`: a Python runtime with the pinned dependencies in +`requirements/runtime.lock`, an empty `/opt/f0`, and no OpenCode. + +The image contains no product. The caller injects the artifact under test at +run time, so one image serves every product. + +The stage1 builder image is a different image; see +[`src/stage1/README.md`](../src/stage1/README.md). + +## Building + +```sh +docker build --target evaluation \ + --tag doc2harness/evaluation:candidate \ + --file containers/Dockerfile . +``` + +That tag is the default the code looks for. Override it with +`SBH_EVALUATION_IMAGE` if you tag differently. + +## Mirrors + +The checked-in defaults use Aliyun's Debian and PyPI mirrors. They are build +arguments, not edits to the Dockerfile: + +```sh +docker build --target evaluation \ + --build-arg DEBIAN_MIRROR=https://deb.debian.org/debian \ + --build-arg DEBIAN_SECURITY_MIRROR=https://security.debian.org/debian-security \ + --build-arg PYPI_INDEX_URL=https://pypi.org/simple \ + --tag doc2harness/evaluation:candidate \ + --file containers/Dockerfile . +``` + +Changing a mirror must not change what lands in the image. The Python base is +pinned by digest and the Python dependencies by `requirements/runtime.lock`; a +mirror serves those same packages or the build fails. + +## What the build asserts + +The build ends with checks that fail it rather than ship a wrong image: +OpenCode is absent, `/opt/f0` is empty, and no mini-swe-agent tree, +distribution, or cache is present. diff --git a/code/containers/requirements/runtime.lock b/code/containers/requirements/runtime.lock new file mode 100644 index 0000000000000000000000000000000000000000..07a58bff993cf83afbc077c0bc4db0e31805fdc2 --- /dev/null +++ b/code/containers/requirements/runtime.lock @@ -0,0 +1,74 @@ +# Exact runtime inventory of the evaluation image. +# mini-swe-agent is intentionally absent. +Jinja2==3.1.6 +MarkupSafe==3.0.3 +PyYAML==6.0.3 +Pygments==2.20.0 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.3 +aiosignal==1.4.0 +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.14.2 +attrs==26.1.0 +certifi==2026.7.22 +charset-normalizer==3.4.9 +click==8.4.2 +datasets==5.0.1 +dill==0.4.1 +distro==1.9.0 +fastuuid==0.14.0 +filelock==3.32.2 +frozenlist==1.8.0 +fsspec==2026.6.0 +h11==0.16.0 +hf-xet==1.6.0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface_hub==1.26.1 +idna==3.18 +importlib_metadata==8.9.0 +jiter==0.16.0 +jsonschema-specifications==2025.9.1 +jsonschema==4.26.0 +linkify-it-py==2.1.0 +litellm==1.95.0 +markdown-it-py==4.2.0 +mdit-py-plugins==0.6.1 +mdurl==0.1.2 +multidict==6.7.1 +multiprocess==0.70.19 +numpy==2.5.1 +openai==2.53.0 +packaging==26.3 +pandas==3.0.5 +platformdirs==4.11.0 +prompt_toolkit==3.0.53 +propcache==0.5.2 +pyarrow==25.0.0 +pydantic==2.13.4 +pydantic_core==2.46.4 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.2 +referencing==0.37.0 +regex==2026.7.19 +requests==2.34.2 +rich==15.0.0 +rpds-py==2026.6.3 +shellingham==1.5.4 +six==1.17.0 +sniffio==1.3.1 +tenacity==9.1.4 +textual==8.2.8 +tiktoken==0.13.0 +tokenizers==0.23.1 +tqdm==4.70.0 +typer==0.27.1 +typing-inspection==0.4.2 +typing_extensions==4.16.0 +uc-micro-py==2.0.0 +urllib3==2.7.0 +wcwidth==0.8.2 +xxhash==3.8.1 +yarl==1.24.5 +zipp==4.1.0 diff --git a/code/pyproject.toml b/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f562bd9d1d5c412ffbeebdc6d38297c1eb98b7d --- /dev/null +++ b/code/pyproject.toml @@ -0,0 +1,31 @@ +[build-system] +requires = ["setuptools==84.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "doc2harness" +version = "0.0.0" +description = "doc2harness: a two-stage benchmark for coding-agent evaluation" +readme = "README.md" +requires-python = ">=3.11" +dependencies = [] + +[tool.setuptools] +include-package-data = false + +[tool.setuptools.package-data] +"doc2harness.benchmark" = ["*.toml", "*.json"] +"doc2harness.benchmark.harnesses.artifact" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.direct" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.extension" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.file" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.headless" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.permission" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.startup" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.state" = ["catalog.toml"] +"doc2harness.benchmark.harnesses.tui" = ["catalog.toml"] + +[tool.setuptools.packages.find] +where = ["src"] +include = ["doc2harness*"] +namespaces = false diff --git a/code/requirements/build-tools.txt b/code/requirements/build-tools.txt new file mode 100644 index 0000000000000000000000000000000000000000..558ea88529914038c66864e3a555e56b679aa7ae --- /dev/null +++ b/code/requirements/build-tools.txt @@ -0,0 +1,17 @@ +--index-url https://pypi.org/simple +--only-binary :all: + +# Audited 2026-08-25 from the PyPI project release files. This lock is for +# build and verification only; none of these packages is a runtime dependency. +build==1.5.0 \ + --hash=sha256:13f3eecb844759ab66efec90ca17639bbf14dc06cb2fdf37a9010322d9c50a6f +packaging==26.3 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c +pip==26.2.1 \ + --hash=sha256:71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e +pyproject-hooks==1.2.0 \ + --hash=sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913 +setuptools==84.0.0 \ + --hash=sha256:51a52592b3b99e102b609654876bd65f19f999935166d1352678931132b0c670 +wheel==0.48.0 \ + --hash=sha256:3217dcc807155e45db462d7ef2431f5ddda0d7273b700d05a67b271ceb1287ab diff --git a/code/requirements/run.txt b/code/requirements/run.txt new file mode 100644 index 0000000000000000000000000000000000000000..1910948f82d7b228755552cd3f5b343cebbca412 --- /dev/null +++ b/code/requirements/run.txt @@ -0,0 +1 @@ +PyYAML>=6.0,<7 diff --git a/code/run/README.md b/code/run/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9168e1d751d1fba0ee05fee98c54d796d6673ab6 --- /dev/null +++ b/code/run/README.md @@ -0,0 +1,34 @@ +# Run commands + +`run_from_config.sh` is the generic YAML entry point: + +```sh +./run/run_from_config.sh run/configs/project.yaml --dry-run +``` + +Install the small YAML-only run dependency when setting up a fresh environment: + +```sh +python3 -m pip install -r requirements/run.txt +``` + +The YAML declares the catalog selection, models, output directory, and an +explicit production executor command. The command is executed once per model +with `SBH_MODEL_ID`, `SBH_RUN_CONFIG`, `SBH_SCENARIO_COUNT`, and the validated +`SBH_IDS_FILE` selection in its environment. There is no built-in fallback +executor, and an existing receipt is never re-read as if it were a fresh score. + +The two-candidate command is deliberately strict: + +```sh +export CANDIDATE_A_ARTIFACT=/path/to/first/artifact +export CANDIDATE_B_ARTIFACT=/path/to/second/artifact +./run/run_94_example.sh --dry-run +``` + +It requires exactly the complete active catalog (currently 94 IDs) and the +two model IDs `candidate-a` and `candidate-b`. A real run uses the +`run_production_executor.py` adapter and requires both artifact directories. +Missing or unresolved paths fail closed instead of claiming that the 94-point +run completed. The executor drives each scenario directly; it never reads old +result rows or verdicts. diff --git a/code/run/configs/example-94.yaml b/code/run/configs/example-94.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9389e54fb9ff0920f0af62bd41d2e77e1d35f58a --- /dev/null +++ b/code/run/configs/example-94.yaml @@ -0,0 +1,29 @@ +schema: doc2harness.run-config/1 + +run: + id: example-94 + output_dir: run-results/example-94 + concurrency: 2 + catalog_concurrency: 2 + catalog_timeout: 900 + opencode_compression: false + +selection: + mode: all + +# Set this to the reviewed production artifact executor before running. A +# blank command is rejected; no previously recorded receipt is substituted. +executor: + command: + - python3 + - run/run_production_executor.py + +models: + - id: candidate-a + artifact_ref: ${CANDIDATE_A_ARTIFACT} + env: + SBH_ARTIFACT_REF: ${CANDIDATE_A_ARTIFACT} + - id: candidate-b + artifact_ref: ${CANDIDATE_B_ARTIFACT} + env: + SBH_ARTIFACT_REF: ${CANDIDATE_B_ARTIFACT} diff --git a/code/run/configs/project.yaml b/code/run/configs/project.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d71c795274d9408712d2613f02957214152ad57 --- /dev/null +++ b/code/run/configs/project.yaml @@ -0,0 +1,19 @@ +schema: doc2harness.run-config/1 + +run: + id: project-run + output_dir: run-results/project-run + concurrency: 4 + opencode_compression: false + +selection: + mode: all + +# The executor is intentionally explicit. Replace this with the reviewed +# production executor command; the launcher has no fallback executor. +executor: + command: [] + +models: + - id: configured-model + env: {} diff --git a/code/run/run_94_example.sh b/code/run/run_94_example.sh new file mode 100644 index 0000000000000000000000000000000000000000..d02e3ac57a0fcf2305f2a457e8284f93ad39e138 --- /dev/null +++ b/code/run/run_94_example.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +# Run the frozen 94-point catalog for two candidate artifacts. +# This deliberately uses the same YAML-driven runner as run_from_config.sh; +# it does not reuse recorded verdicts or manufacture a score from old receipts. + +script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +repo_root="$(cd -- "${script_dir}/.." && pwd -P)" +config_path="${repo_root}/run/configs/example-94.yaml" + +exec python3 "${script_dir}/run_config.py" \ + --repo-root "${repo_root}" \ + --config "${config_path}" \ + --require-models candidate-a,candidate-b \ + --require-count 94 \ + "$@" diff --git a/code/run/run_config.py b/code/run/run_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f60d1830104c250814ef5582eac0ae02b2259e53 --- /dev/null +++ b/code/run/run_config.py @@ -0,0 +1,262 @@ +"""Validate and execute a YAML-defined doc2harness run. + +A run must name an executable production backend in ``executor.command`` (or +through ``SBH_PRODUCTION_EXECUTOR``); there is no built-in stand-in that would +let a misconfigured run look like it scored something. ``--dry-run`` validates +the complete plan and writes no model result; without it, each configured model +is invoked through the declared executor, respecting the configured concurrency +limit. +""" + +from __future__ import annotations + +import argparse +import json +import os +import shlex +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +from typing import Any + + +class RunConfigError(ValueError): + """Raised when a run configuration is incomplete or unsafe.""" + + +def _load_yaml(path: Path) -> dict[str, Any]: + try: + import yaml # type: ignore[import-not-found] + except ImportError as exc: # pragma: no cover - environment dependent + raise RunConfigError( + "PyYAML is required for YAML run configs; install the run requirements" + ) from exc + try: + value = yaml.safe_load(path.read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError) as exc: + raise RunConfigError(f"cannot read YAML config {path}: {exc}") from exc + if not isinstance(value, dict): + raise RunConfigError("top-level YAML value must be a mapping") + return value + + +def _mapping(value: Any, name: str) -> dict[str, Any]: + if not isinstance(value, dict): + raise RunConfigError(f"{name} must be a mapping") + return value + + +def _nonempty_string(value: Any, name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise RunConfigError(f"{name} must be a non-empty string") + return value.strip() + + +def _repo_path(repo_root: Path, value: Any, name: str) -> Path: + raw = Path(_nonempty_string(value, name)).expanduser() + return raw if raw.is_absolute() else repo_root / raw + + +def _catalog_ids(repo_root: Path) -> tuple[str, ...]: + from doc2harness.benchmark.catalog import ( + load_catalog_sources, + parse_catalog_root, + ) + + package = repo_root / "src" / "doc2harness" + benchmark = package / "benchmark" + root = parse_catalog_root((benchmark / "catalog_root.toml").read_bytes()) + resources = { + root.taxonomy_resource: (benchmark / "taxonomy.toml").read_bytes(), + **{ + shard.resource: (package / Path(*shard.resource.segments)).read_bytes() + for shard in root.shards + }, + } + definitions = load_catalog_sources( + root, + resources, + lambda module, export: __import__(module, fromlist=[export]).__dict__[export], + ) + return tuple(item.scenario_id for item in definitions) + + +def _expand(value: str) -> str: + return os.path.expandvars(value) + + +def _command(executor: dict[str, Any], *, allow_missing: bool) -> list[str]: + configured = executor.get("command") + if configured is None or configured == []: + env_command = os.environ.get("SBH_PRODUCTION_EXECUTOR", "").strip() + if not env_command: + if allow_missing: + return [] + raise RunConfigError( + "executor.command is missing; set a production executor explicitly " + "(SBH_PRODUCTION_EXECUTOR may provide one)" + ) + configured = shlex.split(env_command) + if isinstance(configured, str): + configured = shlex.split(configured) + if not isinstance(configured, list) or not configured or not all( + isinstance(item, str) and item.strip() for item in configured + ): + raise RunConfigError("executor.command must be a non-empty string/list command") + return [_expand(item) for item in configured] + + +def _validate( + repo_root: Path, + config_path: Path, + document: dict[str, Any], + required_models: tuple[str, ...] = (), + required_count: int | None = None, +) -> dict[str, Any]: + if document.get("schema") != "doc2harness.run-config/1": + raise RunConfigError("schema must be doc2harness.run-config/1") + run = _mapping(document.get("run"), "run") + selection = _mapping(document.get("selection"), "selection") + executor = _mapping(document.get("executor"), "executor") + models_value = document.get("models") + if not isinstance(models_value, list) or not models_value: + raise RunConfigError("models must be a non-empty list") + catalog = _catalog_ids(repo_root) + requested = selection.get("mode", "all") + if requested == "all": + selected = catalog + elif requested == "ids_file": + ids_file = _repo_path(repo_root, selection.get("ids_file"), "selection.ids_file") + try: + selected = tuple( + line.strip() + for line in ids_file.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + except OSError as exc: + raise RunConfigError(f"cannot read selection.ids_file: {ids_file}") from exc + else: + raise RunConfigError("selection.mode must be all or ids_file") + if not selected or len(selected) != len(set(selected)): + raise RunConfigError("selection must contain unique non-empty scenario IDs") + if required_count is not None and len(selected) != required_count: + raise RunConfigError( + f"selection must contain exactly {required_count} scenario IDs, found {len(selected)}" + ) + unknown = sorted(set(selected) - set(catalog)) + if unknown: + raise RunConfigError(f"selection contains unknown scenario IDs: {unknown[:5]}") + if required_models: + names = tuple(_nonempty_string(_mapping(item, "model").get("id"), "model.id") for item in models_value) + if names != required_models: + raise RunConfigError(f"models must be exactly {list(required_models)}, found {list(names)}") + command = _command(executor, allow_missing=bool(document.get("_dry_run"))) + output_dir = _repo_path(repo_root, run.get("output_dir", "run-results"), "run.output_dir") + if not output_dir.is_relative_to(repo_root): + raise RunConfigError("run.output_dir must remain inside the repository") + concurrency = run.get("concurrency", 1) + if type(concurrency) is not int or concurrency < 1: + raise RunConfigError("run.concurrency must be a positive integer") + return { + "repo_root": str(repo_root), + "config_path": str(config_path), + "run": run, + "selection": {"mode": requested, "count": len(selected), "ids": selected}, + "models": models_value, + "executor": {"command": command, "output_dir": str(output_dir)}, + } + + +def _execute(plan: dict[str, Any], *, dry_run: bool) -> int: + output_dir = Path(plan["executor"]["output_dir"]) + output_dir.mkdir(parents=True, exist_ok=True) + manifest = output_dir / "run-plan.json" + manifest.write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + selection_file = output_dir / "selected-scenarios.txt" + selection_file.write_text( + "".join(f"{scenario_id}\n" for scenario_id in plan["selection"]["ids"]), + encoding="utf-8", + ) + if dry_run: + print(json.dumps({"status": "VALID", "selection_count": plan["selection"]["count"], "models": [item["id"] for item in plan["models"]]}, ensure_ascii=False)) + return 0 + command = plan["executor"]["command"] + if not command: + raise RunConfigError( + "no production executor configured; set executor.command or " + "SBH_PRODUCTION_EXECUTOR before a real run" + ) + def run_model(model: Any) -> tuple[str, int]: + model_map = _mapping(model, "model") + model_id = _nonempty_string(model_map.get("id"), "model.id") + environment = os.environ.copy() + environment.update( + { + str(key): _expand(str(value)) + for key, value in _mapping(model_map.get("env", {}), "model.env").items() + } + ) + environment["SBH_RUN_CONFIG"] = plan["config_path"] + environment["SBH_MODEL_ID"] = model_id + environment["SBH_SCENARIO_COUNT"] = str(plan["selection"]["count"]) + environment["SBH_IDS_FILE"] = str(selection_file) + environment["SBH_RUN_OUTPUT_DIR"] = plan["executor"]["output_dir"] + environment["SBH_CATALOG_CONCURRENCY"] = str( + plan["run"].get("catalog_concurrency", 1) + ) + environment["SBH_CATALOG_TIMEOUT"] = str( + plan["run"].get("catalog_timeout", 900) + ) + print( + f"[doc2harness] starting model={model_id} " + f"scenarios={plan['selection']['count']}", + flush=True, + ) + result = subprocess.run(command, cwd=Path(plan["repo_root"]), env=environment, check=False) + return model_id, result.returncode + + concurrency = min(int(plan["run"].get("concurrency", 1)), len(plan["models"])) + with ThreadPoolExecutor(max_workers=concurrency) as pool: + futures = [pool.submit(run_model, model) for model in plan["models"]] + for future in as_completed(futures): + model_id, returncode = future.result() + if returncode != 0: + print( + f"[doc2harness] executor failed model={model_id} rc={returncode}", + file=sys.stderr, + ) + return returncode + print(json.dumps({"status": "COMPLETED", "selection_count": plan["selection"]["count"], "models": [item["id"] for item in plan["models"]]}, ensure_ascii=False)) + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo-root", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--require-models", default="") + parser.add_argument("--require-count", type=int) + args = parser.parse_args() + try: + repo_root = args.repo_root.resolve() + config_path = args.config.resolve() + sys.path.insert(0, str(repo_root / "src")) + document = _load_yaml(config_path) + document["_dry_run"] = args.dry_run + plan = _validate( + repo_root, + config_path, + document, + tuple(item for item in args.require_models.split(",") if item), + args.require_count, + ) + return _execute(plan, dry_run=args.dry_run) + except (OSError, RunConfigError, ImportError) as exc: + print(f"error[SBH-RUN-CONFIG]: {exc}", file=sys.stderr) + return 4 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/run/run_from_config.sh b/code/run/run_from_config.sh new file mode 100644 index 0000000000000000000000000000000000000000..80fe1bc5ee6cec70a0ec54c452b8342935465fd9 --- /dev/null +++ b/code/run/run_from_config.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +# Run the harness from a YAML run configuration. +# The Python entry point performs schema, catalog, and executor checks before +# starting any model process. Paths in the YAML file are resolved relative to +# the repository unless they are explicitly absolute. + +script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +repo_root="$(cd -- "${script_dir}/.." && pwd -P)" + +if [[ $# -lt 1 ]]; then + printf 'usage: %s CONFIG.yaml [--dry-run]\n' "$0" >&2 + exit 2 +fi + +config_path="$1" +shift +if [[ "${config_path}" != /* ]]; then + config_path="${repo_root}/${config_path}" +fi + +exec python3 "${script_dir}/run_config.py" \ + --repo-root "${repo_root}" \ + --config "${config_path}" \ + "$@" diff --git a/code/run/run_production_executor.py b/code/run/run_production_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..8754aa13e0907379847e7657ed76064c1b6b5e02 --- /dev/null +++ b/code/run/run_production_executor.py @@ -0,0 +1,112 @@ +"""Bridge the YAML launch boundary to the reviewed production catalog runner. + +The generic YAML launcher owns validation and per-model scheduling. This +adapter owns only the explicit argument translation needed by the production +catalog executor; it never reads previously recorded verdicts. The deterministic model stimulus ships inside the package, so +running a scenario needs nothing beyond the artifact under test. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + + +def _required(name: str) -> str: + value = os.environ.get(name, "").strip() + if not value or value.startswith("${"): + raise SystemExit(f"SBH production executor requires {name}") + return value + + +def _positive_int(name: str, default: int) -> int: + value = os.environ.get(name, str(default)).strip() + try: + parsed = int(value) + except ValueError as exc: + raise SystemExit(f"{name} must be a positive integer") from exc + if parsed < 1: + raise SystemExit(f"{name} must be a positive integer") + return parsed + + +def _positive_float(name: str, default: float) -> str: + value = os.environ.get(name, str(default)).strip() + try: + parsed = float(value) + except ValueError as exc: + raise SystemExit(f"{name} must be a positive number") from exc + if not 0 < parsed <= 3600: + raise SystemExit(f"{name} must be in (0, 3600]") + return value + + +def build_command() -> tuple[list[str], Path]: + """Build the reviewed catalog command from explicit launcher bindings.""" + + repo_root = Path(__file__).resolve().parents[1] + artifact = Path(_required("SBH_ARTIFACT_REF")).expanduser().resolve() + output_root = Path(_required("SBH_RUN_OUTPUT_DIR")).expanduser() + if not output_root.is_absolute(): + output_root = (repo_root / output_root).resolve() + model_id = _required("SBH_MODEL_ID") + scenario_count = _positive_int("SBH_SCENARIO_COUNT", 1) + concurrency = _positive_int("SBH_CATALOG_CONCURRENCY", 1) + timeout = _positive_float("SBH_CATALOG_TIMEOUT", 900.0) + output = output_root / model_id + if not artifact.is_dir() or not (artifact / "run_agent.sh").is_file(): + raise SystemExit("SBH_ARTIFACT_REF must contain run_agent.sh") + command = [ + sys.executable, + str(repo_root / "tools" / "run_production_catalog.py"), + "--repo-root", + str(repo_root), + "--artifact", + str(artifact), + "--artifact-id", + model_id, + "--output", + str(output), + "--concurrency", + str(concurrency), + "--timeout", + timeout, + ] + scenario_id = os.environ.get("SBH_SCENARIO_ID", "").strip() + ids_file = os.environ.get("SBH_IDS_FILE", "").strip() + if scenario_id and ids_file: + raise SystemExit("set only one of SBH_SCENARIO_ID and SBH_IDS_FILE") + if scenario_id: + command.extend(["--scenario-id", scenario_id]) + elif ids_file: + command.extend(["--ids-file", str(Path(ids_file).expanduser().resolve())]) + if scenario_count < 1: + raise SystemExit("SBH_SCENARIO_COUNT must be positive") + return command, output + + +def main() -> int: + command, output = build_command() + output.mkdir(parents=True, exist_ok=True) + repo_root = Path(__file__).resolve().parents[1] + environment = os.environ.copy() + source_path = str(repo_root / "src") + existing_pythonpath = environment.get("PYTHONPATH", "") + environment["PYTHONPATH"] = ( + source_path + if not existing_pythonpath + else source_path + os.pathsep + existing_pythonpath + ) + completed = subprocess.run( + command, + cwd=repo_root, + env=environment, + check=False, + ) + return completed.returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/__init__.py b/code/src/doc2harness/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a2c5b3bb437bff74e283b62c894075e8c15331 --- /dev/null +++ b/code/src/doc2harness/__init__.py @@ -0,0 +1 @@ +__all__ = [] diff --git a/code/src/doc2harness/benchmark/__init__.py b/code/src/doc2harness/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cabc54610eb46b4b68735f0716b7dda44837fa7 --- /dev/null +++ b/code/src/doc2harness/benchmark/__init__.py @@ -0,0 +1,57 @@ +"""Typed, non-executing benchmark catalog contracts.""" + +from doc2harness.benchmark.catalog import ( + CatalogRoot, + CatalogShard, + CatalogVerification, + LogicalCatalogResource, + load_catalog_sources, + parse_catalog_root, + parse_catalog_shard, + verify_catalog_sources, +) +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.benchmark.taxonomy import ( + Taxonomy, + TaxonomyEntry, + parse_taxonomy, + validate_classification, +) + +__all__ = [ + "CatalogRoot", + "CatalogShard", + "CatalogVerification", + "Classification", + "ComponentKind", + "ComponentRef", + "DependencyKind", + "DependencyRef", + "ExperimentBinding", + "LogicalCatalogResource", + "ScenarioDefinition", + "ScenarioDifficulty", + "ScenarioRole", + "Taxonomy", + "TaxonomyEntry", + "UnsupportedPolicy", + "definition_digest", + "load_catalog_sources", + "parse_catalog_root", + "parse_catalog_shard", + "parse_taxonomy", + "validate_classification", + "verify_catalog_sources", +] diff --git a/code/src/doc2harness/benchmark/catalog.py b/code/src/doc2harness/benchmark/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..43cca0082ccd3b6ab99f28f252636f8349c4ecf2 --- /dev/null +++ b/code/src/doc2harness/benchmark/catalog.py @@ -0,0 +1,470 @@ +"""Explicit catalog sources, verification, and authority-backed sealing.""" + +from __future__ import annotations + +import hashlib +import re +from collections.abc import Callable +from dataclasses import dataclass + +from doc2harness.benchmark.definition import ( + DependencyKind, + ScenarioDefinition, + ScenarioRole, + definition_digest, +) +from doc2harness.benchmark.taxonomy import ( + Taxonomy, + _exact_keys, + _parse_closed_toml, + parse_taxonomy, + validate_classification, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ( + ContractDocumentError, + require_digest, +) + +_SEGMENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z", re.ASCII) +_IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_MODULE = re.compile(r"[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*\Z", re.ASCII) +_EXPORT = re.compile(r"[a-z][a-z0-9_]{0,127}\Z", re.ASCII) +_MODULE_PREFIX = "doc2harness.benchmark.harnesses." +_MAX_DEFINITIONS = 4096 +_MAX_EXPORTS = 4096 +_MAX_SHARDS = 4096 +_MAX_SOURCE_BYTES = 1_048_576 +_SHARD_DOMAIN = b"doc2harness.catalog-shard/1\x00" +_ROOT_DOMAIN = b"doc2harness.catalog-root/1\x00" +_VERIFICATION_DOMAIN = b"doc2harness.catalog-verification/1\x00" + + +@dataclass(frozen=True, slots=True) +class LogicalCatalogResource: + """A package-relative resource identity, never a host filesystem path.""" + + segments: tuple[str, ...] + + def __post_init__(self) -> None: + if type(self.segments) is not tuple or not self.segments or len(self.segments) > 32: + raise ContractDocumentError("catalog resource must have bounded exact segments") + for segment in self.segments: + if type(segment) is not str or _SEGMENT.fullmatch(segment) is None: + raise ContractDocumentError("catalog resource contains an unsafe segment") + if segment in {".", ".."} or segment.startswith("~") or ":" in segment: + raise ContractDocumentError("catalog resource contains an unsafe segment") + + +def _digest(value: object, name: str) -> str: + try: + return require_digest(value, name=name) + except ContractDocumentError: + raise + + +def _raw_digest(raw: bytes) -> str: + return "sha256:" + hashlib.sha256(raw).hexdigest() + + +def _resource(value: object, name: str) -> LogicalCatalogResource: + if type(value) is not str or not value or value.startswith(("/", "~")): + raise ContractDocumentError(f"{name} is not a canonical relative resource") + if ( + value.endswith("/") + or "//" in value + or "\\" in value + or ":" in value + or "%" in value + or not value.isascii() + ): + raise ContractDocumentError(f"{name} is not a canonical relative resource") + return LogicalCatalogResource(tuple(value.split("/"))) + + +def _module_export(value: object, name: str) -> tuple[str, str]: + row = _exact_keys(value, frozenset({"module", "export"}), name) + module = row["module"] + export = row["export"] + if ( + type(module) is not str + or len(module) > 255 + or _MODULE.fullmatch(module) is None + or not module.startswith(_MODULE_PREFIX) + ): + raise ContractDocumentError(f"{name} module is not canonical") + if type(export) is not str or _EXPORT.fullmatch(export) is None: + raise ContractDocumentError(f"{name} export is not canonical") + return module, export + + +def _exports(value: object, name: str) -> tuple[tuple[str, str], ...]: + if type(value) is not list or not value or len(value) > _MAX_EXPORTS: + raise ContractDocumentError(f"{name} must be a bounded non-empty array") + result = tuple(_module_export(item, name) for item in value) + if result != tuple(sorted(result)) or len(set(result)) != len(result): + raise ContractDocumentError(f"{name} must be sorted and unique") + return result + + +def _shard_semantic_body( + function_id: str, + resource: LogicalCatalogResource, + exports: tuple[tuple[str, str], ...], +) -> dict[str, object]: + return { + "exports": [ + {"export": export, "module": module} for module, export in exports + ], + "function_id": function_id, + "resource": list(resource.segments), + } + + +def _semantic_digest(domain: bytes, body: dict[str, object]) -> str: + return "sha256:" + hashlib.sha256(domain + canonical_json(body)).hexdigest() + + +@dataclass(frozen=True, slots=True) +class CatalogShard: + function_id: str + resource: LogicalCatalogResource + exports: tuple[tuple[str, str], ...] + source_digest: str + semantic_digest: str + + def __post_init__(self) -> None: + if type(self.function_id) is not str or _IDENTIFIER.fullmatch(self.function_id) is None: + raise ContractDocumentError("shard function id is not canonical") + if type(self.resource) is not LogicalCatalogResource: + raise ContractDocumentError("shard resource must be a logical resource") + expected_resource = ( + "benchmark", + "harnesses", + *self.function_id.split("."), + "catalog.toml", + ) + if self.resource.segments != expected_resource: + raise ContractDocumentError("shard resource does not match its function") + if type(self.exports) is not tuple or not self.exports or len(self.exports) > _MAX_EXPORTS: + raise ContractDocumentError("shard exports must be a bounded exact tuple") + for item in self.exports: + if type(item) is not tuple or len(item) != 2: + raise ContractDocumentError("shard exports require exact pairs") + module, export = item + _module_export({"module": module, "export": export}, "shard export") + if self.exports != tuple(sorted(self.exports)) or len(set(self.exports)) != len(self.exports): + raise ContractDocumentError("shard exports must be sorted and unique") + _digest(self.source_digest, "shard source digest") + _digest(self.semantic_digest, "shard semantic digest") + expected_semantic = _semantic_digest( + _SHARD_DOMAIN, + _shard_semantic_body(self.function_id, self.resource, self.exports), + ) + if self.semantic_digest != expected_semantic: + raise ContractDocumentError("shard semantic digest differs from its fields") + + +@dataclass(frozen=True, slots=True) +class CatalogRoot: + taxonomy_resource: LogicalCatalogResource + taxonomy_digest: str + shards: tuple[CatalogShard, ...] + source_digest: str + semantic_digest: str + + def __post_init__(self) -> None: + if ( + type(self.taxonomy_resource) is not LogicalCatalogResource + or self.taxonomy_resource.segments != ("benchmark", "taxonomy.toml") + ): + raise ContractDocumentError("taxonomy resource is not canonical") + _digest(self.taxonomy_digest, "taxonomy digest") + if type(self.shards) is not tuple or not self.shards or len(self.shards) > _MAX_SHARDS: + raise ContractDocumentError("catalog root must contain a bounded exact shard tuple") + if any(type(item) is not CatalogShard for item in self.shards): + raise ContractDocumentError("catalog root shards must use CatalogShard") + identities = tuple(item.function_id for item in self.shards) + resources = tuple(item.resource for item in self.shards) + if identities != tuple(sorted(identities)) or len(set(identities)) != len(identities): + raise ContractDocumentError("catalog root shard functions must be sorted and unique") + if len(set(resources)) != len(resources): + raise ContractDocumentError("catalog root shard resources must be unique") + export_count = 0 + seen_exports: set[tuple[str, str]] = set() + for shard in self.shards: + for export in shard.exports: + export_count += 1 + if export_count > _MAX_EXPORTS: + raise ContractDocumentError("catalog root exports exceed the total limit") + if export in seen_exports: + raise ContractDocumentError("catalog root exports must be globally unique") + seen_exports.add(export) + _digest(self.source_digest, "root source digest") + _digest(self.semantic_digest, "root semantic digest") + expected_semantic = _semantic_digest( + _ROOT_DOMAIN, + _root_body(self.taxonomy_resource, self.taxonomy_digest, self.shards), + ) + if self.semantic_digest != expected_semantic: + raise ContractDocumentError("root semantic digest differs from its fields") + + +@dataclass(frozen=True, slots=True) +class CatalogVerification: + definitions: tuple[ScenarioDefinition, ...] + source_digests: tuple[str, ...] + semantic_digest: str + + def __post_init__(self) -> None: + if type(self.definitions) is not tuple or not self.definitions: + raise ContractDocumentError("catalog verification requires definitions") + if any(type(item) is not ScenarioDefinition for item in self.definitions): + raise ContractDocumentError("verified definitions must use ScenarioDefinition") + if type(self.source_digests) is not tuple or not self.source_digests: + raise ContractDocumentError("catalog verification requires source digests") + for item in self.source_digests: + _digest(item, "source digest") + _digest(self.semantic_digest, "catalog semantic digest") + + +CatalogImporter = Callable[[str, str], ScenarioDefinition] + + +def _root_body( + taxonomy_resource: LogicalCatalogResource, + taxonomy_digest: str, + shards: tuple[CatalogShard, ...], +) -> dict[str, object]: + return { + "shards": [ + { + "exports": [ + {"export": export, "module": module} + for module, export in shard.exports + ], + "function_id": shard.function_id, + "resource": list(shard.resource.segments), + "semantic_digest": shard.semantic_digest, + "source_digest": shard.source_digest, + } + for shard in shards + ], + "taxonomy_resource": list(taxonomy_resource.segments), + "taxonomy_source_digest": taxonomy_digest, + } + + +def parse_catalog_root(raw: bytes, /) -> CatalogRoot: + source = _exact_keys( + _parse_closed_toml(raw, "catalog root"), + frozenset({"format", "taxonomy_resource", "taxonomy_source_digest", "shards"}), + "catalog root", + ) + if source["format"] != "doc2harness.catalog-root-source/1": + raise ContractDocumentError("catalog root format is unsupported") + taxonomy_resource = _resource(source["taxonomy_resource"], "taxonomy resource") + taxonomy_digest = _digest(source["taxonomy_source_digest"], "taxonomy source digest") + raw_shards = source["shards"] + if type(raw_shards) is not list or not raw_shards or len(raw_shards) > _MAX_SHARDS: + raise ContractDocumentError("catalog root shards must be a bounded non-empty array") + shards: list[CatalogShard] = [] + total_exports = 0 + for item in raw_shards: + row = _exact_keys( + item, + frozenset({"function_id", "resource", "source_digest", "semantic_digest", "exports"}), + "catalog root shard", + ) + exports = _exports(row["exports"], "catalog root exports") + total_exports += len(exports) + if total_exports > _MAX_EXPORTS: + raise ContractDocumentError("catalog root exports exceed the total limit") + shards.append( + CatalogShard( + row["function_id"], + _resource(row["resource"], "shard resource"), + exports, + _digest(row["source_digest"], "shard source digest"), + _digest(row["semantic_digest"], "shard semantic digest"), + ) + ) + typed_shards = tuple(shards) + semantic = _semantic_digest( + _ROOT_DOMAIN, + _root_body(taxonomy_resource, taxonomy_digest, typed_shards), + ) + return CatalogRoot( + taxonomy_resource, + taxonomy_digest, + typed_shards, + _raw_digest(raw), + semantic, + ) + + +def parse_catalog_shard(raw: bytes, /) -> CatalogShard: + source = _exact_keys( + _parse_closed_toml(raw, "catalog shard"), + frozenset({"format", "function_id", "resource", "exports"}), + "catalog shard", + ) + if source["format"] != "doc2harness.catalog-shard-source/1": + raise ContractDocumentError("catalog shard format is unsupported") + function_id = source["function_id"] + resource = _resource(source["resource"], "shard resource") + exports = _exports(source["exports"], "catalog shard exports") + semantic = _semantic_digest( + _SHARD_DOMAIN, + _shard_semantic_body(function_id, resource, exports), + ) + return CatalogShard(function_id, resource, exports, _raw_digest(raw), semantic) + + +def _ordered_definitions( + definitions: tuple[ScenarioDefinition, ...], +) -> tuple[dict[str, int], dict[str, ScenarioDefinition]]: + if ( + type(definitions) is not tuple + or not definitions + or len(definitions) > _MAX_DEFINITIONS + or any(type(item) is not ScenarioDefinition for item in definitions) + ): + raise ContractDocumentError("definitions must be a bounded non-empty exact tuple") + order: dict[str, int] = {} + by_id: dict[str, ScenarioDefinition] = {} + for ordinal, definition in enumerate(definitions): + if definition.scenario_id in order: + raise ContractDocumentError("scenario ids must be globally unique") + order[definition.scenario_id] = ordinal + by_id[definition.scenario_id] = definition + graph: dict[str, set[str]] = {} + for definition in definitions: + dependency_ids = tuple(item.scenario_id for item in definition.dependencies) + if len(set(dependency_ids)) != len(dependency_ids): + raise ContractDocumentError("a scenario cannot reference one id with multiple kinds") + unknown = set(dependency_ids) - set(order) + if unknown: + raise ContractDocumentError("scenario dependency is unknown") + for dependency in definition.dependencies: + target = by_id[dependency.scenario_id] + if dependency.kind in {DependencyKind.CONTROL, DependencyKind.GATE} and ( + target.role is not ScenarioRole.CONTROL or target.weight_microunits != 0 + ): + raise ContractDocumentError("control and gate dependencies require controls") + graph[definition.scenario_id] = set(dependency_ids) + remaining = {node: len(edges) for node, edges in graph.items()} + dependents: dict[str, set[str]] = {node: set() for node in graph} + for node, edges in graph.items(): + for edge in edges: + dependents[edge].add(node) + ready = [node for node, count in remaining.items() if count == 0] + visited = 0 + while ready: + node = ready.pop() + visited += 1 + for dependent in dependents[node]: + remaining[dependent] -= 1 + if remaining[dependent] == 0: + ready.append(dependent) + if visited != len(graph): + raise ContractDocumentError("scenario dependency graph contains a cycle") + return order, by_id + + +def verify_catalog_sources( + root: CatalogRoot, + definitions: tuple[ScenarioDefinition, ...], + /, +) -> CatalogVerification: + if type(root) is not CatalogRoot: + raise ContractDocumentError("catalog root must use the exact typed structure") + flattened = tuple( + (shard.function_id, export) + for shard in root.shards + for export in shard.exports + ) + if type(definitions) is not tuple or len(definitions) != len(flattened): + raise ContractDocumentError("definition count does not match catalog exports") + _ordered_definitions(definitions) + for definition, (function_id, _export) in zip(definitions, flattened, strict=True): + if definition.classification.primary != function_id: + raise ContractDocumentError("definition primary classification differs from owner shard") + digests = tuple(definition_digest(item) for item in definitions) + semantic = _semantic_digest( + _VERIFICATION_DOMAIN, + {"definition_digests": list(digests), "root_semantic_digest": root.semantic_digest}, + ) + source_digests = ( + root.source_digest, + root.taxonomy_digest, + *(shard.source_digest for shard in root.shards), + ) + return CatalogVerification(definitions, source_digests, semantic) + + +def load_catalog_sources( + root: CatalogRoot, + resources: dict[LogicalCatalogResource, bytes], + importer: CatalogImporter, + /, +) -> tuple[ScenarioDefinition, ...]: + if type(root) is not CatalogRoot or type(resources) is not dict or not callable(importer): + raise ContractDocumentError("catalog loading requires exact root, dict resources and importer") + if len(resources) > _MAX_SHARDS + 1: + raise ContractDocumentError("catalog resources exceed the size limit") + if any(type(key) is not LogicalCatalogResource or type(value) is not bytes for key, value in resources.items()): + raise ContractDocumentError("catalog resources require exact logical keys and byte values") + if any(not value or len(value) > _MAX_SOURCE_BYTES for value in resources.values()): + raise ContractDocumentError("catalog resource bytes exceed source limits") + snapshot = dict(resources) + expected = {root.taxonomy_resource, *(shard.resource for shard in root.shards)} + if set(snapshot) != expected: + raise ContractDocumentError("catalog resource set does not match the root") + taxonomy_raw = snapshot[root.taxonomy_resource] + if _raw_digest(taxonomy_raw) != root.taxonomy_digest: + raise ContractDocumentError("taxonomy source digest differs from the root") + taxonomy: Taxonomy = parse_taxonomy(taxonomy_raw) + known_functions = frozenset(item.function_id for item in taxonomy.entries) + if any(shard.function_id not in known_functions for shard in root.shards): + raise ContractDocumentError("catalog root contains an unknown taxonomy function") + parsed_shards: list[CatalogShard] = [] + for expected_shard in root.shards: + raw = snapshot[expected_shard.resource] + if _raw_digest(raw) != expected_shard.source_digest: + raise ContractDocumentError("shard source digest differs from the root") + parsed = parse_catalog_shard(raw) + if parsed != expected_shard: + raise ContractDocumentError("shard source differs from its root descriptor") + parsed_shards.append(parsed) + definitions: list[ScenarioDefinition] = [] + object_ids: set[int] = set() + for shard in parsed_shards: + for module, export in shard.exports: + try: + definition = importer(module, export) + except Exception: + raise ContractDocumentError("catalog importer failed") from None + if type(definition) is not ScenarioDefinition: + raise ContractDocumentError("catalog importer returned an invalid definition") + if id(definition) in object_ids: + raise ContractDocumentError("catalog importer reused a definition object") + object_ids.add(id(definition)) + if definition.classification.primary != shard.function_id: + raise ContractDocumentError("imported definition differs from its owner shard") + validate_classification(definition.classification, taxonomy) + definitions.append(definition) + return verify_catalog_sources(root, tuple(definitions)).definitions + + +__all__ = [ + "CatalogImporter", + "CatalogRoot", + "CatalogShard", + "CatalogVerification", + "LogicalCatalogResource", + "load_catalog_sources", + "parse_catalog_root", + "parse_catalog_shard", + "verify_catalog_sources", +] diff --git a/code/src/doc2harness/benchmark/catalog_root.toml b/code/src/doc2harness/benchmark/catalog_root.toml new file mode 100644 index 0000000000000000000000000000000000000000..9b353ba8164db3cf0cb6ffc498adb448bbade70f --- /dev/null +++ b/code/src/doc2harness/benchmark/catalog_root.toml @@ -0,0 +1,169 @@ +format = "doc2harness.catalog-root-source/1" +taxonomy_resource = "benchmark/taxonomy.toml" +taxonomy_source_digest = "sha256:43b99ad485708c75a6ce93c95669b85bd9c384f03cbff027dfb490cc9df3c779" + +[[shards]] +function_id = "artifact" +resource = "benchmark/harnesses/artifact/catalog.toml" +source_digest = "sha256:ab17d776974982aabacdaf55493fedef33225bf9f21ba7f4674a3c3430bf6325" +semantic_digest = "sha256:e0f2c5d47ad715c4b0e56a6166ae4c2e31138327fe0770721da2b237d1fbbd1c" +exports = [ + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_declares_dependencies", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_entry_py", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_install_sh", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_offline_wheel", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_requirements_lock", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_run_agent_sh", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_version_file", export = "definition" }, +] + +[[shards]] +function_id = "direct" +resource = "benchmark/harnesses/direct/catalog.toml" +source_digest = "sha256:b83648161b87b31473c4eaf384b44830a2a9a1a9ed874119c1b6cbe152f66cb7" +semantic_digest = "sha256:7555e696b9886c9f87c30bbaa01b3afaa0817a9e40e9368841d967e5577db54c" +exports = [ + { module = "doc2harness.benchmark.harnesses.direct.scenarios.exfil_glob_pem_not_leaked", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.secret_probe_mechanism_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.unreferenced_secret_not_in_request_body", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure_control", export = "definition" }, +] + +[[shards]] +function_id = "extension" +resource = "benchmark/harnesses/extension/catalog.toml" +source_digest = "sha256:78ca3a4f9b32aae12a3f901fa8fe6ba621de830fa0c01319f226743a59d7ecfb" +semantic_digest = "sha256:1cd6e9811b82411ccd00fa4f43828beff035d9ec9d7e35a1354c75cc92ae7abc" +exports = [ + { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_definition_symlink_outside_fenced", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_inside_symlink_discovery_control", export = "definition" }, +] + +[[shards]] +function_id = "file" +resource = "benchmark/harnesses/file/catalog.toml" +source_digest = "sha256:7f3ae97eca67f93812bef69a8d591b9d76527593b8c237548d39a1f42939faf5" +semantic_digest = "sha256:202e42f04f066970a2e65ad02f6b7bea1b86398be2cbcb0183a2dd1a7936bc45" +exports = [ + { module = "doc2harness.benchmark.harnesses.file.scenarios.file_symlink_inside_still_readable_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_finds_inside_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_truncation_keeps_sorted_end", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_default_mode_returns_path_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_finds_needle_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_head_limit_zero_not_unlimited", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_type_filter_ignored", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.memory_get_abs_path_escapes_workspace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_cell_isolation", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_delete_keeps_neighbors", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.p32_ctl_memory_get_reads_inside_workspace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_char_device_bounded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_regular_file_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_via_symlink_outside_workspace_bounded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.rewind_restores_edited_file", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.symlink_to_outside_target_readable_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.undo_reverts_overwrite_control", export = "definition" }, +] + +[[shards]] +function_id = "headless" +resource = "benchmark/harnesses/headless/catalog.toml" +source_digest = "sha256:ec48824b157b32c10beab39254d57924756a62069e91c547a89e5f3ae5618704" +semantic_digest = "sha256:f29ef08c7ea259da1515f99be1860413a083c95f127141c8f25ccefb42567b55" +exports = [ + { module = "doc2harness.benchmark.harnesses.headless.scenarios.at_ref_expands_in_headless", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_model_error_wellformed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_wellformed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_bare_mention_not_auto_read", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_task_text_reaches_wire", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict_control", export = "definition" }, +] + +[[shards]] +function_id = "permission" +resource = "benchmark/harnesses/permission/catalog.toml" +source_digest = "sha256:c515c06dbb8a17857ce86242bd0045a573c6684b4e56e7a1ee4e342980058be4" +semantic_digest = "sha256:d0cd5ba6de354ad72f8abbc46b7353db084e86325d99b2c26a36bf1a2cfc6b83" +exports = [ + { module = "doc2harness.benchmark.harnesses.permission.scenarios.ask_mode_denies_write_and_allows_read", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoedit_blocks_mutable_shell", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoreview_blocks_canonical_danger", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_fail_closed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_read_fences_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_respects_read_fences", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.deny_blocks_monitor_spawned_cmd", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_absent_bash_write_runs_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_blocks_bash_write", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.monitor_spawns_command_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.network_off_blocks_offline_npm_test", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p37_ctl_plain_cmd_chain_runs", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p46_ctl_yolo_rm_really_deletes", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p60_ctl_yolo_both_work", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.yolo_mutable_shell_lands_control", export = "definition" }, +] + +[[shards]] +function_id = "startup" +resource = "benchmark/harnesses/startup/catalog.toml" +source_digest = "sha256:9893ae5607570c43319ca2934f2c2eb451276c7cff31fe9496aee84fd4391f20" +semantic_digest = "sha256:7439429b84748b822599c2bd4a4cbab0270f39c0ececc93eb991d632ebf010c1" +exports = [ + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_ambient_python_isolated", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_health_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_python_minimum_fallback", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_bom_config", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_broken_config_file", export = "definition" }, +] + +[[shards]] +function_id = "state" +resource = "benchmark/harnesses/state/catalog.toml" +source_digest = "sha256:29d6d7694b1821cd86e0767784ab8fe17851de947a117557acf59bcd60b4b193" +semantic_digest = "sha256:bfb6dfab995d43d01c912c0c05eb7ef919281e30c16b5009134693fd7679fcdc" +exports = [ + { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_bytes", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_no_secondary_expansion", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_single_expansion_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.p30_ctl_security_review_sees_worktree_change", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_declared_command_reaches_wire", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_toplevel_command_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.security_review_covers_branch_commits", export = "definition" }, +] + +[[shards]] +function_id = "tui" +resource = "benchmark/harnesses/tui/catalog.toml" +source_digest = "sha256:33c5b7a874a86ed54b7dd7bef266298e13ad78c0618968fa05c586e20a39e6bd" +semantic_digest = "sha256:71eb0680a3a71bb9e913bb666c282d30aa43802baca4f3a41c859433acb54a98" +exports = [ + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_realpath_key", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_a_fresh_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_b_fresh_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_bang_alone_enters_shell_mode", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_ctrl_byte_storm_survives", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/definition.py b/code/src/doc2harness/benchmark/definition.py new file mode 100644 index 0000000000000000000000000000000000000000..92261eb0134ecd8a1f67348d8669e09c874cff55 --- /dev/null +++ b/code/src/doc2harness/benchmark/definition.py @@ -0,0 +1,220 @@ +"""Immutable scenario definitions without execution behavior.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_REVISION = re.compile(r"[1-9][0-9]{0,8}\Z", re.ASCII) +_DIGEST_DOMAIN = b"doc2harness.scenario-definition/1\x00" +_MAX_CLASSIFICATIONS = 32 +_MAX_DEPENDENCIES = 256 +_MAX_WEIGHT = 2**63 - 1 + + +def _identifier(value: object, name: str) -> str: + if type(value) is not str or _IDENTIFIER.fullmatch(value) is None: + raise ContractDocumentError(f"{name} is not a canonical identifier") + return value + + +class ScenarioRole(str, Enum): + TARGET = "TARGET" + CONTROL = "CONTROL" + + +class ScenarioDifficulty(str, Enum): + STANDARD = "STANDARD" + HARD = "HARD" + + +class UnsupportedPolicy(str, Enum): + FAIL = "FAIL" + NOT_APPLICABLE = "NOT_APPLICABLE" + + +class ComponentKind(str, Enum): + FIXTURE = "FIXTURE" + STIMULUS = "STIMULUS" + OBSERVER = "OBSERVER" + ORACLE = "ORACLE" + CLEANUP = "CLEANUP" + NO_OP = "NO_OP" + + +class DependencyKind(str, Enum): + REQUIREMENT = "REQUIREMENT" + CONTROL = "CONTROL" + GATE = "GATE" + + +@dataclass(frozen=True, slots=True) +class Classification: + """One stable primary function and zero or more ordered secondary functions.""" + + primary: str + secondary: tuple[str, ...] = () + + def __post_init__(self) -> None: + _identifier(self.primary, "primary classification") + if type(self.secondary) is not tuple: + raise ContractDocumentError("secondary classifications must be an exact tuple") + if len(self.secondary) > _MAX_CLASSIFICATIONS: + raise ContractDocumentError("secondary classifications exceed the size limit") + for item in self.secondary: + _identifier(item, "secondary classification") + if self.primary in self.secondary or len(set(self.secondary)) != len(self.secondary): + raise ContractDocumentError("classifications must be unique") + if self.secondary != tuple(sorted(self.secondary)): + raise ContractDocumentError("secondary classifications must be sorted") + + +@dataclass(frozen=True, slots=True) +class ComponentRef: + """A versioned component identity; NO_OP is explicit, never represented by None.""" + + component_id: str + revision: str + kind: ComponentKind + + def __post_init__(self) -> None: + _identifier(self.component_id, "component id") + if type(self.revision) is not str or _REVISION.fullmatch(self.revision) is None: + raise ContractDocumentError("component revision is not canonical") + if type(self.kind) is not ComponentKind: + raise ContractDocumentError("component kind must use ComponentKind") + if self.kind is ComponentKind.NO_OP and self.component_id != "no-op": + raise ContractDocumentError("NO_OP must use the canonical no-op component") + if self.kind is not ComponentKind.NO_OP and self.component_id == "no-op": + raise ContractDocumentError("the canonical no-op component must use NO_OP") + + @classmethod + def no_op(cls) -> ComponentRef: + return cls("no-op", "1", ComponentKind.NO_OP) + + +@dataclass(frozen=True, slots=True) +class DependencyRef: + scenario_id: str + kind: DependencyKind + + def __post_init__(self) -> None: + _identifier(self.scenario_id, "dependency scenario id") + if type(self.kind) is not DependencyKind: + raise ContractDocumentError("dependency kind must use DependencyKind") + + +@dataclass(frozen=True, slots=True) +class ExperimentBinding: + fixture: ComponentRef + stimulus: ComponentRef + observer: ComponentRef + oracle: ComponentRef + cleanup: ComponentRef + + def __post_init__(self) -> None: + expected = ( + (self.fixture, ComponentKind.FIXTURE), + (self.stimulus, ComponentKind.STIMULUS), + (self.observer, ComponentKind.OBSERVER), + (self.oracle, ComponentKind.ORACLE), + (self.cleanup, ComponentKind.CLEANUP), + ) + for value, kind in expected: + if type(value) is not ComponentRef: + raise ContractDocumentError("experiment bindings require exact ComponentRef values") + if value.kind not in {kind, ComponentKind.NO_OP}: + raise ContractDocumentError("component kind does not match its binding slot") + + +@dataclass(frozen=True, slots=True) +class ScenarioDefinition: + scenario_id: str + revision: str + classification: Classification + role: ScenarioRole + weight_microunits: int + difficulty: ScenarioDifficulty + dependencies: tuple[DependencyRef, ...] + experiment: ExperimentBinding + unsupported_policy: UnsupportedPolicy + + def __post_init__(self) -> None: + _identifier(self.scenario_id, "scenario id") + if type(self.revision) is not str or _REVISION.fullmatch(self.revision) is None: + raise ContractDocumentError("scenario revision is not canonical") + if type(self.classification) is not Classification: + raise ContractDocumentError("classification must use the exact typed structure") + if type(self.role) is not ScenarioRole: + raise ContractDocumentError("role must use ScenarioRole") + if ( + type(self.weight_microunits) is not int + or self.weight_microunits < 0 + or self.weight_microunits > _MAX_WEIGHT + ): + raise ContractDocumentError("weight must be a bounded non-negative exact integer") + if (self.role is ScenarioRole.TARGET) != (self.weight_microunits > 0): + raise ContractDocumentError("targets require positive weight and controls require zero weight") + if type(self.difficulty) is not ScenarioDifficulty: + raise ContractDocumentError("difficulty must use ScenarioDifficulty") + if type(self.dependencies) is not tuple or len(self.dependencies) > _MAX_DEPENDENCIES: + raise ContractDocumentError("dependencies must be a bounded exact tuple") + if any(type(item) is not DependencyRef for item in self.dependencies): + raise ContractDocumentError("dependencies must be an exact tuple of DependencyRef") + identities = tuple((item.scenario_id, item.kind.value) for item in self.dependencies) + if len(set(identities)) != len(identities) or identities != tuple(sorted(identities)): + raise ContractDocumentError("dependencies must be sorted and unique") + if any(item.scenario_id == self.scenario_id for item in self.dependencies): + raise ContractDocumentError("scenario cannot depend on itself") + if type(self.experiment) is not ExperimentBinding: + raise ContractDocumentError("experiment must use ExperimentBinding") + if type(self.unsupported_policy) is not UnsupportedPolicy: + raise ContractDocumentError("unsupported policy must use UnsupportedPolicy") + + +def _component_body(value: ComponentRef) -> dict[str, str]: + return {"component_id": value.component_id, "kind": value.kind.value, "revision": value.revision} + + +def definition_digest(definition: ScenarioDefinition, /) -> str: + """Return the domain-separated semantic digest of one typed definition.""" + + if type(definition) is not ScenarioDefinition: + raise ContractDocumentError("definition must use ScenarioDefinition") + body = { + "classification": { + "primary": definition.classification.primary, + "secondary": list(definition.classification.secondary), + }, + "dependencies": [ + {"kind": item.kind.value, "scenario_id": item.scenario_id} + for item in definition.dependencies + ], + "difficulty": definition.difficulty.value, + "experiment": { + "cleanup": _component_body(definition.experiment.cleanup), + "fixture": _component_body(definition.experiment.fixture), + "observer": _component_body(definition.experiment.observer), + "oracle": _component_body(definition.experiment.oracle), + "stimulus": _component_body(definition.experiment.stimulus), + }, + "revision": definition.revision, + "role": definition.role.value, + "scenario_id": definition.scenario_id, + "unsupported_policy": definition.unsupported_policy.value, + "weight_microunits": definition.weight_microunits, + } + return "sha256:" + hashlib.sha256(_DIGEST_DOMAIN + canonical_json(body)).hexdigest() + + +__all__ = [ + "Classification", "ComponentKind", "ComponentRef", "DependencyKind", + "DependencyRef", "ExperimentBinding", "ScenarioDefinition", "ScenarioDifficulty", + "ScenarioRole", "UnsupportedPolicy", "definition_digest", +] diff --git a/code/src/doc2harness/benchmark/dispatch.py b/code/src/doc2harness/benchmark/dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7d1f1bfb550927c7a18936d4ada16b3aa4e97e --- /dev/null +++ b/code/src/doc2harness/benchmark/dispatch.py @@ -0,0 +1,108 @@ +"""Resolve active catalog IDs to their scenario-local execution owners.""" + +from __future__ import annotations + +import importlib +from dataclasses import dataclass +from functools import lru_cache +from importlib.resources import files +from typing import Callable + +from doc2harness.benchmark.catalog import ( + CatalogRoot, + load_catalog_sources, + parse_catalog_root, +) +from doc2harness.benchmark.definition import ScenarioDefinition +from doc2harness.contracts.primitives import ContractDocumentError + +_PACKAGE = "doc2harness" +_BENCHMARK = "benchmark" + + +@dataclass(frozen=True, slots=True) +class ScenarioOwner: + """One catalog definition and the module that owns its runtime recipe.""" + + definition: ScenarioDefinition + scenario: object + judge: Callable[[object], object] + module: str + + +def _catalog_root() -> CatalogRoot: + root = files(_PACKAGE).joinpath(_BENCHMARK) + return parse_catalog_root(root.joinpath("catalog_root.toml").read_bytes()) + + +@lru_cache(maxsize=1) +def _definitions_and_modules() -> tuple[ + tuple[ScenarioDefinition, ...], dict[str, str] +]: + package = files(_PACKAGE) + benchmark = package.joinpath(_BENCHMARK) + root = _catalog_root() + resources = { + root.taxonomy_resource: benchmark.joinpath("taxonomy.toml").read_bytes(), + **{ + shard.resource: package.joinpath(*shard.resource.segments).read_bytes() + for shard in root.shards + }, + } + definitions = load_catalog_sources( + root, + resources, + lambda module, export: getattr(importlib.import_module(module), export), + ) + modules = { + getattr(importlib.import_module(module), export).scenario_id: module + for shard in root.shards + for module, export in shard.exports + } + if len(modules) != len(definitions): + raise ContractDocumentError("active catalog module index is ambiguous") + return definitions, modules + + +def active_scenario_ids() -> tuple[str, ...]: + """Return the complete, catalog-ordered active scenario universe.""" + + definitions, _ = _definitions_and_modules() + return tuple(item.scenario_id for item in definitions) + + +def load_scenario_owner(scenario_id: str, /) -> ScenarioOwner: + """Load one local recipe/judge owner and verify its catalog binding.""" + + if type(scenario_id) is not str or not scenario_id: + raise ContractDocumentError("scenario id must be a non-empty string") + definitions, modules = _definitions_and_modules() + definitions_by_id = {item.scenario_id: item for item in definitions} + definition = definitions_by_id.get(scenario_id) + module_name = modules.get(scenario_id) + if definition is None or module_name is None: + raise ContractDocumentError("scenario id is absent from the active catalog") + module = importlib.import_module(module_name) + scenario = getattr(module, "SCENARIO", None) + alias = getattr(module, "scenario", None) + judge = getattr(module, "judge", None) + local_definition = getattr(module, "definition", None) + if scenario is None or alias is None: + raise ContractDocumentError("scenario module has no canonical local owner") + if local_definition is not definition: + raise ContractDocumentError("scenario module definition differs from catalog import") + owned_definition = getattr(scenario, "definition", None) + if owned_definition is not definition: + raise ContractDocumentError("scenario owner definition differs from catalog import") + if getattr(alias, "definition", None) is not definition: + raise ContractDocumentError("catalog compatibility scenario differs from catalog import") + if not callable(judge): + raise ContractDocumentError("scenario module has no local judge") + return ScenarioOwner(definition, scenario, judge, module_name) + + +__all__ = [ + "ScenarioOwner", + "active_scenario_ids", + "load_scenario_owner", +] diff --git a/code/src/doc2harness/benchmark/harnesses/__init__.py b/code/src/doc2harness/benchmark/harnesses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a71017ff1f7f676033e4b16621424e31f562cad3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/__init__.py @@ -0,0 +1,3 @@ +"""Primary Harness layer packages.""" + +__all__: list[str] = [] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/__init__.py b/code/src/doc2harness/benchmark/harnesses/artifact/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4855458fef17eeb99a820e781cf7fd19f317f95 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/__init__.py @@ -0,0 +1,29 @@ +"""Typed declarations for the static artifact Harness layer.""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeApplicability, + ArtifactProbeEvaluation, + ArtifactProbeKind, + ArtifactProbeMetrics, + ArtifactProbeObservation, + ArtifactProbeOutcome, + ArtifactScenario, + create_artifact_probe_observation, + define_artifact_scenario, +) + +__all__ = [ + "ArtifactLogicalPath", + "ArtifactProbe", + "ArtifactProbeApplicability", + "ArtifactProbeEvaluation", + "ArtifactProbeKind", + "ArtifactProbeMetrics", + "ArtifactProbeObservation", + "ArtifactProbeOutcome", + "ArtifactScenario", + "create_artifact_probe_observation", + "define_artifact_scenario", +] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/catalog.toml b/code/src/doc2harness/benchmark/harnesses/artifact/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5b3b1c119fbfa0c9faa242543f03bba735792d3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/catalog.toml @@ -0,0 +1,12 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "artifact" +resource = "benchmark/harnesses/artifact/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_declares_dependencies", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_entry_py", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_install_sh", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_offline_wheel", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_requirements_lock", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_run_agent_sh", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_version_file", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/contracts.py b/code/src/doc2harness/benchmark/harnesses/artifact/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..932c6a349df8df14f88fcf6cf92e12d9b1ae3142 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/contracts.py @@ -0,0 +1,394 @@ +"""Fail-closed declaration boundary for static artifact scenarios.""" + +from __future__ import annotations + +import re +import unicodedata +import hashlib +from dataclasses import dataclass +from enum import Enum + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_SCENARIO_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_MAX_PATHS = 8 +_MAX_SEGMENTS = 32 +_MAX_SEGMENT_BYTES = 255 + + +class ArtifactProbeKind(str, Enum): + FILE_PRESENT = "FILE_PRESENT" + FILE_NONEMPTY = "FILE_NONEMPTY" + DIRECTORY_MEMBER_SUFFIX = "DIRECTORY_MEMBER_SUFFIX" + DEPENDENCY_DECLARATION = "DEPENDENCY_DECLARATION" + + +class ArtifactProbeOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class ArtifactProbeApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + + +@dataclass(frozen=True, slots=True) +class ArtifactLogicalPath: + """A bounded path relative to the runtime-owned artifact root.""" + + segments: tuple[str, ...] + + def __post_init__(self) -> None: + if type(self.segments) is not tuple or not self.segments or len(self.segments) > _MAX_SEGMENTS: + raise ContractDocumentError("artifact path must contain bounded exact segments") + for segment in self.segments: + if type(segment) is not str or segment in {"", ".", ".."}: + raise ContractDocumentError("artifact path contains an invalid segment") + if unicodedata.normalize("NFC", segment) != segment: + raise ContractDocumentError("artifact path segment is not Unicode NFC") + try: + encoded = segment.encode("utf-8", errors="strict") + except UnicodeError: + raise ContractDocumentError("artifact path segment is not valid UTF-8") from None + if ( + len(encoded) > _MAX_SEGMENT_BYTES + or "/" in segment + or "\\" in segment + or any(ord(character) < 32 or ord(character) == 127 for character in segment) + ): + raise ContractDocumentError("artifact path segment is unsafe") + + +@dataclass(frozen=True, slots=True) +class ArtifactProbe: + """Declarative probe intent; it contains no host path or execution behavior.""" + + kind: ArtifactProbeKind + paths: tuple[ArtifactLogicalPath, ...] + member_suffix: str | None = None + + def __post_init__(self) -> None: + if type(self.kind) is not ArtifactProbeKind: + raise ContractDocumentError("artifact probe kind must use the closed vocabulary") + if ( + type(self.paths) is not tuple + or not self.paths + or len(self.paths) > _MAX_PATHS + or any(type(path) is not ArtifactLogicalPath for path in self.paths) + ): + raise ContractDocumentError("artifact probe paths must be a bounded exact tuple") + if len(set(self.paths)) != len(self.paths): + raise ContractDocumentError("artifact probe paths must be unique") + if self.kind is ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX: + if ( + len(self.paths) != 1 + or type(self.member_suffix) is not str + or not self.member_suffix.startswith(".") + or len(self.member_suffix) > 32 + or not self.member_suffix.isascii() + or any(character in self.member_suffix for character in "/\\") + ): + raise ContractDocumentError("directory member probes require one safe suffix") + elif self.kind is ArtifactProbeKind.DEPENDENCY_DECLARATION: + expected = ( + ArtifactLogicalPath(("pyproject.toml",)), + ArtifactLogicalPath(("requirements.txt",)), + ) + if self.paths != expected or self.member_suffix is not None: + raise ContractDocumentError("dependency probes require the canonical manifest paths") + elif len(self.paths) != 1 or self.member_suffix is not None: + raise ContractDocumentError("file probes require one path and no suffix") + + +@dataclass(frozen=True, slots=True) +class ArtifactScenario: + """One immutable scenario definition paired with its declarative probe.""" + + definition: ScenarioDefinition + probe: ArtifactProbe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.probe) is not ArtifactProbe: + raise ContractDocumentError("artifact scenarios require exact typed values") + if self.definition.classification.primary != "artifact": + raise ContractDocumentError("artifact scenario owner differs from its Harness layer") + + +@dataclass(frozen=True, slots=True) +class ArtifactProbeMetrics: + """Closed path-free facts emitted by the four static probe shapes.""" + + file_exists: bool | None = None + directory_exists: bool | None = None + size_bytes: int | None = None + matching_members: int | None = None + project_marker: bool | None = None + requirements_nonempty: bool | None = None + + def __post_init__(self) -> None: + for value in ( + self.file_exists, + self.directory_exists, + self.project_marker, + self.requirements_nonempty, + ): + if value is not None and type(value) is not bool: + raise ContractDocumentError("artifact metric booleans must be exact bool values") + for value in (self.size_bytes, self.matching_members): + if value is not None and (type(value) is not int or value < 0): + raise ContractDocumentError("artifact metric counts must be non-negative exact integers") + + +def _digest(value: object, name: str) -> str: + if ( + type(value) is not str + or not value.startswith("sha256:") + or len(value) != 71 + or any(character not in "0123456789abcdef" for character in value[7:]) + ): + raise ContractDocumentError(f"{name} is invalid") + return value + + +def _probe_body(probe: ArtifactProbe) -> dict[str, object]: + return { + "kind": probe.kind.value, + "member_suffix": probe.member_suffix, + "paths": [list(path.segments) for path in probe.paths], + } + + +def _metrics_body(metrics: ArtifactProbeMetrics) -> dict[str, object]: + return { + "directory_exists": metrics.directory_exists, + "file_exists": metrics.file_exists, + "matching_members": metrics.matching_members, + "project_marker": metrics.project_marker, + "requirements_nonempty": metrics.requirements_nonempty, + "size_bytes": metrics.size_bytes, + } + + +def _observation_digest( + scenario_id: str, + scenario_revision: str, + semantic_definition_digest: str, + artifact_id: str, + artifact_digest: str, + probe: ArtifactProbe, + metrics: ArtifactProbeMetrics, + runtime_evidence_digests: tuple[str, ...], +) -> str: + body = { + "artifact": {"artifact_id": artifact_id, "content_digest": artifact_digest}, + "definition_digest": semantic_definition_digest, + "metrics": _metrics_body(metrics), + "probe": _probe_body(probe), + "runtime_evidence_digests": list(runtime_evidence_digests), + "scenario_id": scenario_id, + "scenario_revision": scenario_revision, + } + domain = b"doc2harness.artifact-static-probe-evidence/1\0" + return "sha256:" + hashlib.sha256(domain + canonical_json(body)).hexdigest() + + +@dataclass(frozen=True, slots=True) +class ArtifactProbeObservation: + """Path-free facts bound to definition, artifact, probe and runtime evidence.""" + + scenario_id: str + scenario_revision: str + definition_digest: str + artifact_id: str + artifact_digest: str + probe: ArtifactProbe + metrics: ArtifactProbeMetrics + runtime_evidence_digests: tuple[str, ...] + evidence_digest: str + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("artifact observation scenario id is invalid") + if type(self.scenario_revision) is not str or not self.scenario_revision.isascii(): + raise ContractDocumentError("artifact observation revision is invalid") + _digest(self.definition_digest, "artifact observation definition digest") + if type(self.artifact_id) is not str or _SCENARIO_ID.fullmatch(self.artifact_id) is None: + raise ContractDocumentError("artifact observation artifact id is invalid") + _digest(self.artifact_digest, "artifact observation artifact digest") + if type(self.probe) is not ArtifactProbe or type(self.metrics) is not ArtifactProbeMetrics: + raise ContractDocumentError("artifact observation uses invalid typed facts") + if type(self.runtime_evidence_digests) is not tuple or not self.runtime_evidence_digests: + raise ContractDocumentError("artifact observation requires runtime evidence") + for value in self.runtime_evidence_digests: + _digest(value, "artifact runtime evidence digest") + _digest(self.evidence_digest, "artifact observation digest") + expected = _observation_digest( + self.scenario_id, + self.scenario_revision, + self.definition_digest, + self.artifact_id, + self.artifact_digest, + self.probe, + self.metrics, + self.runtime_evidence_digests, + ) + if self.evidence_digest != expected: + raise ContractDocumentError("artifact observation evidence does not bind its facts") + + +def create_artifact_probe_observation( + scenario: ArtifactScenario, + artifact_id: str, + artifact_digest: str, + metrics: ArtifactProbeMetrics, + runtime_evidence_digests: tuple[str, ...], + /, +) -> ArtifactProbeObservation: + """Seal runtime facts to their scenario, artifact and lower-level evidence.""" + + if type(scenario) is not ArtifactScenario or type(metrics) is not ArtifactProbeMetrics: + raise ContractDocumentError("artifact observation inputs use invalid typed contracts") + semantic_digest = definition_digest(scenario.definition) + evidence = _observation_digest( + scenario.definition.scenario_id, + scenario.definition.revision, + semantic_digest, + artifact_id, + artifact_digest, + scenario.probe, + metrics, + runtime_evidence_digests, + ) + return ArtifactProbeObservation( + scenario.definition.scenario_id, + scenario.definition.revision, + semantic_digest, + artifact_id, + artifact_digest, + scenario.probe, + metrics, + runtime_evidence_digests, + evidence, + ) + + +@dataclass(frozen=True, slots=True) +class ArtifactProbeEvaluation: + """Applicable PASS/FAIL projection for one static artifact target.""" + + scenario_id: str + outcome: ArtifactProbeOutcome + applicability: ArtifactProbeApplicability + reason: str + evidence_digest: str + contribution_microunits: int + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("artifact evaluation scenario id is invalid") + if type(self.outcome) is not ArtifactProbeOutcome: + raise ContractDocumentError("artifact evaluation outcome is invalid") + if self.applicability is not ArtifactProbeApplicability.APPLICABLE: + raise ContractDocumentError("artifact evaluation must be applicable") + if type(self.reason) is not str or not self.reason: + raise ContractDocumentError("artifact evaluation reason is invalid") + _digest(self.evidence_digest, "artifact evaluation evidence digest") + if type(self.contribution_microunits) is not int or self.contribution_microunits < 0: + raise ContractDocumentError("artifact evaluation contribution is invalid") + + +def define_artifact_scenario(scenario_id: str, probe: ArtifactProbe, /) -> ArtifactScenario: + """Construct a target definition owned by the static artifact Harness layer.""" + + if type(scenario_id) is not str or _SCENARIO_ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("artifact scenario id is not canonical") + if type(probe) is not ArtifactProbe: + raise ContractDocumentError("artifact scenario probe must use ArtifactProbe") + definition = ScenarioDefinition( + scenario_id=scenario_id, + revision="1", + classification=Classification("artifact"), + role=ScenarioRole.TARGET, + weight_microunits=1_000_000, + difficulty=ScenarioDifficulty.STANDARD, + dependencies=(), + experiment=ExperimentBinding( + fixture=ComponentRef("artifact-readonly-workspace", "1", ComponentKind.FIXTURE), + stimulus=ComponentRef.no_op(), + observer=ComponentRef("artifact-static-observer", "1", ComponentKind.OBSERVER), + oracle=ComponentRef("artifact-static-oracle", "1", ComponentKind.ORACLE), + cleanup=ComponentRef.no_op(), + ), + unsupported_policy=UnsupportedPolicy.FAIL, + ) + return ArtifactScenario(definition, probe) + + +def validate_artifact_observation( + scenario: ArtifactScenario, + observation: ArtifactProbeObservation, + /, +) -> None: + """Validate the shared identity binding before a local scenario judge runs.""" + + if type(scenario) is not ArtifactScenario: + raise ContractDocumentError("artifact evaluation requires an exact scenario contract") + if type(observation) is not ArtifactProbeObservation: + raise ContractDocumentError("artifact observation uses an invalid typed contract") + definition = scenario.definition + if ( + observation.scenario_id != definition.scenario_id + or observation.scenario_revision != definition.revision + or observation.definition_digest != definition_digest(definition) + or observation.probe != scenario.probe + ): + raise ContractDocumentError("artifact observation does not bind the scenario definition") + + +def build_artifact_evaluation( + scenario: ArtifactScenario, + observation: ArtifactProbeObservation, + satisfied: bool, + reason: str, + /, +) -> ArtifactProbeEvaluation: + """Build the frozen artifact PASS/FAIL projection after local judgment.""" + + validate_artifact_observation(scenario, observation) + return ArtifactProbeEvaluation( + scenario.definition.scenario_id, + ArtifactProbeOutcome.PASS if satisfied else ArtifactProbeOutcome.FAIL, + ArtifactProbeApplicability.APPLICABLE, + reason, + observation.evidence_digest, + scenario.definition.weight_microunits if satisfied else 0, + ) + + +__all__ = [ + "ArtifactLogicalPath", + "ArtifactProbe", + "ArtifactProbeApplicability", + "ArtifactProbeEvaluation", + "ArtifactProbeKind", + "ArtifactProbeMetrics", + "ArtifactProbeObservation", + "ArtifactProbeOutcome", + "ArtifactScenario", + "create_artifact_probe_observation", + "build_artifact_evaluation", + "define_artifact_scenario", + "validate_artifact_observation", +] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f0c958a772671b754a8f3982ae2f62e7e08fb27 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/__init__.py @@ -0,0 +1,3 @@ +"""Static artifact scenario owners; catalog loading is always explicit.""" + +__all__: list[str] = [] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_declares_dependencies.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_declares_dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfb88bf108fe17bbe6223777509e77179636e5d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_declares_dependencies.py @@ -0,0 +1,55 @@ +"""Verify the artifact declares its runtime dependencies. + +1. Inspect the declared dependency metadata. +2. Capture the expected logical artifact path. +3. Apply the typed artifact oracle and require a valid declaration. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_declares_dependencies", + ArtifactProbe( + ArtifactProbeKind.DEPENDENCY_DECLARATION, + ( + ArtifactLogicalPath(("pyproject.toml",)), + ArtifactLogicalPath(("requirements.txt",)), + ), + ), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.project_marker is None or metrics.requirements_nonempty is None or any( + value is not None + for value in ( + metrics.file_exists, + metrics.directory_exists, + metrics.size_bytes, + metrics.matching_members, + ) + ): + raise ContractDocumentError("dependency declaration observation is incomplete") + satisfied = metrics.project_marker or metrics.requirements_nonempty + reason = ( + f"pyproject.toml has [project...]={metrics.project_marker} requirements.txt non-empty=" + f"{metrics.requirements_nonempty} (either one suffices) (v6ยง0.1.1:25 a new third-party dependency " + "must be declared in `[project.dependencies]` of `pyproject.toml` (or in `requirements.txt`))" + ) + return build_artifact_evaluation(SCENARIO, observation, satisfied, reason) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_entry_py.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_entry_py.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c10ee79dd936007cd8061a0e9bed1c96a7df06 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_entry_py.py @@ -0,0 +1,49 @@ +"""Verify the artifact contains its Python entrypoint. + +1. Probe the expected entrypoint path. +2. Capture its presence and file-kind facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_entry_py", + ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("entry.py",)),)), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.file_exists is None or any( + value is not None + for value in ( + metrics.directory_exists, + metrics.size_bytes, + metrics.matching_members, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("file presence observation is incomplete") + return build_artifact_evaluation( + SCENARIO, + observation, + metrics.file_exists, + f"entry.py present={metrics.file_exists} (v6ยง0.1.1:20 the artifact root must contain `entry.py`)", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_install_sh.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_install_sh.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee99734140d5722256d2778da73686aaf9fd39d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_install_sh.py @@ -0,0 +1,49 @@ +"""Verify the artifact contains its installer script. + +1. Probe the expected installer path. +2. Capture its presence and executable-file facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_install_sh", + ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("install.sh",)),)), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.file_exists is None or any( + value is not None + for value in ( + metrics.directory_exists, + metrics.size_bytes, + metrics.matching_members, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("file presence observation is incomplete") + return build_artifact_evaluation( + SCENARIO, + observation, + metrics.file_exists, + f"install.sh present={metrics.file_exists} (v6ยง0.1.1:26 `install.sh` installs in one step - this cell only checks that it exists, not that it works)", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_offline_wheel.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_offline_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..8417b324299ad029796f52dc7133302d7bf5a59a --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_offline_wheel.py @@ -0,0 +1,52 @@ +"""Verify the artifact includes an offline wheel. + +1. Probe the expected wheel path. +2. Capture its presence and file-kind facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_offline_wheel", + ArtifactProbe( + ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX, + (ArtifactLogicalPath(("wheels",)),), + ".whl", + ), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.directory_exists is None or metrics.matching_members is None or any( + value is not None + for value in ( + metrics.file_exists, + metrics.size_bytes, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("directory member observation is incomplete") + satisfied = metrics.directory_exists and metrics.matching_members > 0 + reason = ( + f"wheels directory present={metrics.directory_exists} containing *.whl x {metrics.matching_members} (" + "v6ยง0.1.1:20 `wheels/` must hold at least one offline wheel)" + ) + return build_artifact_evaluation(SCENARIO, observation, satisfied, reason) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_requirements_lock.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_requirements_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..a467fb3315ef7e2001b8670b9c4bfd74d1b7da6e --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_requirements_lock.py @@ -0,0 +1,53 @@ +"""Verify the artifact contains a non-empty dependency lock. + +1. Probe the lock-file path. +2. Capture presence and non-empty-content facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_requirements_lock", + ArtifactProbe( + ArtifactProbeKind.FILE_NONEMPTY, + (ArtifactLogicalPath(("requirements.lock",)),), + ), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.file_exists is None or any( + value is not None + for value in ( + metrics.directory_exists, + metrics.matching_members, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("non-empty file observation is incomplete") + if metrics.file_exists and metrics.size_bytes is None: + raise ContractDocumentError("non-empty file observation lacks its size") + satisfied = metrics.file_exists and (metrics.size_bytes or 0) > 0 + if metrics.file_exists: + reason = f"requirements.lock present but size={metrics.size_bytes}B (must be non-empty) (v6ยง0.1.1:20 the artifact root must contain `requirements.lock`)" + else: + reason = "requirements.lock present=False (v6ยง0.1.1:20 the artifact root must contain `requirements.lock`)" + return build_artifact_evaluation(SCENARIO, observation, satisfied, reason) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_run_agent_sh.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_run_agent_sh.py new file mode 100644 index 0000000000000000000000000000000000000000..25f9f351701c11c3f5a87c0c95749c0dba740d49 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_run_agent_sh.py @@ -0,0 +1,49 @@ +"""Verify the artifact contains its run-agent launcher. + +1. Probe the launcher path. +2. Capture its presence and executable-file facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_run_agent_sh", + ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("run_agent.sh",)),)), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.file_exists is None or any( + value is not None + for value in ( + metrics.directory_exists, + metrics.size_bytes, + metrics.matching_members, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("file presence observation is incomplete") + return build_artifact_evaluation( + SCENARIO, + observation, + metrics.file_exists, + f"run_agent.sh present={metrics.file_exists} (v6ยง0.1.1:20 the artifact root must contain `run_agent.sh`)", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_version_file.py b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_version_file.py new file mode 100644 index 0000000000000000000000000000000000000000..4358dfd2064ccd813226fec7fef13017fd9f0d46 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_version_file.py @@ -0,0 +1,50 @@ +"""Verify the artifact has a non-empty version marker. + +1. Probe the version-file path. +2. Capture presence and non-empty-content facts. +3. Apply the typed artifact oracle to the observation. +""" + +from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactLogicalPath, + ArtifactProbe, + ArtifactProbeKind, + ArtifactProbeObservation, + build_artifact_evaluation, + define_artifact_scenario, + validate_artifact_observation, +) +from doc2harness.contracts.primitives import ContractDocumentError + +scenario = define_artifact_scenario( + "artifact_has_version_file", + ArtifactProbe(ArtifactProbeKind.FILE_NONEMPTY, (ArtifactLogicalPath(("VERSION",)),)), +) +definition = scenario.definition +SCENARIO = scenario +STEPS = (scenario.probe,) + + +def judge(observation: ArtifactProbeObservation): + validate_artifact_observation(SCENARIO, observation) + metrics = observation.metrics + if metrics.file_exists is None or any( + value is not None + for value in ( + metrics.directory_exists, + metrics.matching_members, + metrics.project_marker, + metrics.requirements_nonempty, + ) + ): + raise ContractDocumentError("non-empty file observation is incomplete") + if metrics.file_exists and metrics.size_bytes is None: + raise ContractDocumentError("non-empty file observation lacks its size") + satisfied = metrics.file_exists and (metrics.size_bytes or 0) > 0 + if metrics.file_exists: + reason = f"VERSION present but size={metrics.size_bytes}B (must be non-empty) (v6ยง0.1.1:20 the artifact root must contain `VERSION`)" + else: + reason = "VERSION present=False (v6ยง0.1.1:20 the artifact root must contain `VERSION`)" + return build_artifact_evaluation(SCENARIO, observation, satisfied, reason) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/__init__.py b/code/src/doc2harness/benchmark/harnesses/direct/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2839d15cf788a6e61fc20c4346f72c8d6e23868f --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/__init__.py @@ -0,0 +1,61 @@ +"""Typed declarations for direct mock-process scenarios.""" + +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, + DirectMockEntrypoint, + DirectMockFixtureProfile, + DirectMockJudgement, + DirectMockIsolationProfile, + DirectMockLocalJudge, + DirectMockMode, + DirectMockFactKey, + DirectMockObservedFact, + DirectMockOracleProfile, + DirectMockOutcome, + DirectMockRawObservation, + DirectMockRecipe, + DirectMockRequestFact, + DirectMockRequiredFlag, + DirectMockScenario, + define_direct_mock_scenario, + apply_direct_mock_local_judge, + validate_direct_mock_observation, +) +from doc2harness.benchmark.harnesses.direct.adapter import ( + DirectMockExecutionPlan, + build_direct_mock_execution_plan, +) +from doc2harness.benchmark.harnesses.direct.fixtures import ( + DirectMockAction, + DirectMockFixtureFile, + DirectMockFixturePlan, + materialize_direct_mock_fixture, +) + +__all__ = [ + "DirectMockAction", + "DirectMockApplicability", + "DirectMockEntrypoint", + "DirectMockExecutionPlan", + "DirectMockFixtureFile", + "DirectMockFixturePlan", + "DirectMockFixtureProfile", + "DirectMockJudgement", + "DirectMockFactKey", + "DirectMockIsolationProfile", + "DirectMockLocalJudge", + "DirectMockMode", + "DirectMockObservedFact", + "DirectMockOracleProfile", + "DirectMockOutcome", + "DirectMockRawObservation", + "DirectMockRecipe", + "DirectMockRequestFact", + "DirectMockRequiredFlag", + "DirectMockScenario", + "build_direct_mock_execution_plan", + "apply_direct_mock_local_judge", + "define_direct_mock_scenario", + "validate_direct_mock_observation", + "materialize_direct_mock_fixture", +] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/adapter.py b/code/src/doc2harness/benchmark/harnesses/direct/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..261320c5d2ecf8de76c6efc8ba98d4921ce83353 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/adapter.py @@ -0,0 +1,228 @@ +"""Execution adapter joining frozen fixtures to an injected real-process backend.""" + +from __future__ import annotations +import hashlib +from dataclasses import dataclass +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockEntrypoint, + DirectMockFactKey, + DirectMockMode, + DirectMockOracleProfile, + DirectMockRequiredFlag, + DirectMockScenario, +) +from doc2harness.benchmark.harnesses.direct.fixtures import ( + DirectMockFixturePlan, + materialize_direct_mock_fixture, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +def _digest(value: str, label: str) -> str: + if ( + type(value) is not str + or not value.startswith("sha256:") + or len(value) != 71 + or any((character not in "0123456789abcdef" for character in value[7:])) + ): + raise ContractDocumentError(f"{label} is invalid") + return value + + +@dataclass(frozen=True, slots=True) +class DirectMockExecutionPlan: + """Complete path-free instruction handed to the runtime authority.""" + + scenario_id: str + mode: DirectMockMode + entrypoint: DirectMockEntrypoint + omitted_flag: DirectMockRequiredFlag | None + timeout_seconds: int + fixture: DirectMockFixturePlan + base_url_suffix: str + model_name: str + reject_substring: str + stale_pwd_probe: bool + initialize_git: bool + oracle_profile: DirectMockOracleProfile + tool_family: tuple[str, ...] + required_tool_families: tuple[tuple[str, ...], ...] + request_limit: int | None + body_limit: int | None + required_facts: tuple[DirectMockFactKey, ...] + variant_labels: tuple[str, ...] + plan_digest: str + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or not self.scenario_id: + raise ContractDocumentError("direct mock execution id is invalid") + if type(self.mode) is not DirectMockMode or type(self.entrypoint) is not DirectMockEntrypoint: + raise ContractDocumentError("direct mock execution vocabulary is invalid") + if self.omitted_flag is not None and type(self.omitted_flag) is not DirectMockRequiredFlag: + raise ContractDocumentError("direct mock execution omitted flag is invalid") + if type(self.timeout_seconds) is not int or self.timeout_seconds < 1 or self.timeout_seconds > 900: + raise ContractDocumentError("direct mock execution timeout is invalid") + if type(self.fixture) is not DirectMockFixturePlan or self.fixture.scenario_id != self.scenario_id: + raise ContractDocumentError("direct mock execution fixture differs") + if ( + type(self.base_url_suffix) is not str + or ".." in self.base_url_suffix + or len(self.base_url_suffix) > 1024 + ): + raise ContractDocumentError("direct mock execution base-url suffix is invalid") + if type(self.model_name) is not str or not self.model_name or len(self.model_name) > 512: + raise ContractDocumentError("direct mock execution model is invalid") + if type(self.reject_substring) is not str or len(self.reject_substring) > 1024: + raise ContractDocumentError("direct mock execution rejection substring is invalid") + if type(self.stale_pwd_probe) is not bool or type(self.initialize_git) is not bool: + raise ContractDocumentError("direct mock execution repository setup is invalid") + if type(self.oracle_profile) is not DirectMockOracleProfile: + raise ContractDocumentError("direct mock execution oracle profile is invalid") + if type(self.tool_family) is not tuple or any((type(item) is not str for item in self.tool_family)): + raise ContractDocumentError("direct mock execution tool family is invalid") + if type(self.required_tool_families) is not tuple or any( + ( + type(family) is not tuple or any((type(item) is not str for item in family)) + for family in self.required_tool_families + ) + ): + raise ContractDocumentError("direct mock execution required tool families are invalid") + for value, name, maximum in ( + (self.request_limit, "request", 4096), + (self.body_limit, "body", 64 * 1024 * 1024), + ): + if value is not None and (type(value) is not int or value < 1 or value > maximum): + raise ContractDocumentError(f"direct mock execution {name} limit is invalid") + if type(self.required_facts) is not tuple or any( + (type(item) is not DirectMockFactKey for item in self.required_facts) + ): + raise ContractDocumentError("direct mock execution required facts are invalid") + if type(self.variant_labels) is not tuple or any( + (type(item) is not str for item in self.variant_labels) + ): + raise ContractDocumentError("direct mock execution variant labels are invalid") + expected = _plan_digest( + self.scenario_id, + self.mode, + self.entrypoint, + self.omitted_flag, + self.timeout_seconds, + self.fixture.plan_digest, + self.base_url_suffix, + self.model_name, + self.reject_substring, + self.stale_pwd_probe, + self.initialize_git, + self.oracle_profile, + self.tool_family, + self.required_tool_families, + self.request_limit, + self.body_limit, + self.required_facts, + self.variant_labels, + ) + if self.plan_digest != expected: + raise ContractDocumentError("direct mock execution digest does not bind its plan") + + +def _plan_digest( + scenario_id: str, + mode: DirectMockMode, + entrypoint: DirectMockEntrypoint, + omitted_flag: DirectMockRequiredFlag | None, + timeout_seconds: int, + fixture_digest: str, + base_url_suffix: str = "", + model_name: str = "litellm_proxy/mock", + reject_substring: str = "", + stale_pwd_probe: bool = False, + initialize_git: bool = False, + oracle_profile: DirectMockOracleProfile = DirectMockOracleProfile.UNDECLARED, + tool_family: tuple[str, ...] = (), + required_tool_families: tuple[tuple[str, ...], ...] = (), + request_limit: int | None = None, + body_limit: int | None = None, + required_facts: tuple[DirectMockFactKey, ...] = (), + variant_labels: tuple[str, ...] = (), +) -> str: + body = { + "entrypoint": entrypoint.value, + "fixture_digest": fixture_digest, + "mode": mode.value, + "omitted_flag": omitted_flag.value if omitted_flag is not None else None, + "scenario_id": scenario_id, + "timeout_seconds": timeout_seconds, + "base_url_suffix": base_url_suffix, + "model_name": model_name, + "reject_substring": reject_substring, + "stale_pwd_probe": stale_pwd_probe, + "initialize_git": initialize_git, + "oracle_profile": oracle_profile.value, + "tool_family": list(tool_family), + "request_limit": request_limit, + "body_limit": body_limit, + "required_facts": [item.value for item in required_facts], + "variant_labels": list(variant_labels), + } + if required_tool_families: + body["required_tool_families"] = [list(family) for family in required_tool_families] + return ( + "sha256:" + + hashlib.sha256(b"doc2harness.direct-mock-execution-plan/1\x00" + canonical_json(body)).hexdigest() + ) + + +def build_direct_mock_execution_plan(scenario: DirectMockScenario, /) -> DirectMockExecutionPlan: + if type(scenario) is not DirectMockScenario: + raise ContractDocumentError("direct mock plan requires an exact scenario") + recipe = scenario.recipe + fixture = materialize_direct_mock_fixture(scenario) + timeout = recipe.timeout_seconds if recipe.timeout_seconds is not None else 90 + digest = _plan_digest( + scenario.definition.scenario_id, + recipe.mode, + recipe.entrypoint, + recipe.omitted_flag, + timeout, + fixture.plan_digest, + recipe.base_url_suffix, + recipe.model_name, + recipe.reject_substring, + recipe.stale_pwd_probe, + recipe.initialize_git, + recipe.oracle_profile, + recipe.tool_family, + recipe.required_tool_families, + recipe.request_limit, + recipe.body_limit, + recipe.required_facts, + recipe.variant_labels, + ) + return DirectMockExecutionPlan( + scenario.definition.scenario_id, + recipe.mode, + recipe.entrypoint, + recipe.omitted_flag, + timeout, + fixture, + recipe.base_url_suffix, + recipe.model_name, + recipe.reject_substring, + recipe.stale_pwd_probe, + recipe.initialize_git, + recipe.oracle_profile, + recipe.tool_family, + recipe.required_tool_families, + recipe.request_limit, + recipe.body_limit, + recipe.required_facts, + recipe.variant_labels, + digest, + ) + + +__all__ = [ + "DirectMockExecutionPlan", + "build_direct_mock_execution_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/catalog.toml b/code/src/doc2harness/benchmark/harnesses/direct/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..71bee614f7361edd3deda855d191e2bf9db1ce1c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/catalog.toml @@ -0,0 +1,16 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "direct" +resource = "benchmark/harnesses/direct/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.direct.scenarios.exfil_glob_pem_not_leaked", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.secret_probe_mechanism_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.unreferenced_secret_not_in_request_body", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure_control", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/contracts.py b/code/src/doc2harness/benchmark/harnesses/direct/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b13f566a0682cd669ac8ae9bb2d12b7c93478b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/contracts.py @@ -0,0 +1,632 @@ +"""Closed declarations and observations for direct mock-process scenarios.""" + +from __future__ import annotations +import re +from dataclasses import dataclass +from enum import Enum +from typing import Protocol, runtime_checkable +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, +) +from doc2harness.contracts.primitives import ContractDocumentError + +_SCENARIO_ID = re.compile("[a-z0-9][a-z0-9._-]{0,127}\\Z", re.ASCII) +_MAX_STEPS = 256 +_MAX_TIMEOUT_SECONDS = 900 + + +class DirectMockMode(str, Enum): + """Closed gateway response families for direct-mock scenarios.""" + + NORMAL = "NORMAL" + SEQUENTIAL_PROBE = "SEQUENTIAL_PROBE" + FIXED_REPLY = "FIXED_REPLY" + + +class DirectMockEntrypoint(str, Enum): + """Public process surfaces supported by the direct-mock backend.""" + + PYTHON_ENTRY = "PYTHON_ENTRY" + CONTRACT_SCRIPT = "CONTRACT_SCRIPT" + AGENT_API_DRIVER = "AGENT_API_DRIVER" + + +class DirectMockRequiredFlag(str, Enum): + TASK_FILE = "--task-file" + REPO_DIR = "--repo-dir" + OUT_DIR = "--out-dir" + BUDGET_FILE = "--budget-file" + MODEL_BASE_URL = "--model-base-url" + MODEL_NAME = "--model-name" + MODEL_API_KEY = "--model-api-key" + + +class DirectMockFixtureProfile(str, Enum): + """Named fixture intents; ``fixtures.py`` materializes their bytes.""" + + NONE = "NONE" + QUALITY_GATE_FAIL = "QUALITY_GATE_FAIL" + QUALITY_GATE_PASS = "QUALITY_GATE_PASS" + SECRET_UNREFERENCED_KEY = "SECRET_UNREFERENCED_KEY" + SECRET_CONTROL = "SECRET_CONTROL" + SECRET_PEM = "SECRET_PEM" + WEB_FETCH = "WEB_FETCH" + HTTP_PROXY = "HTTP_PROXY" + SHELL_EDGE_CONTROL = "SHELL_EDGE_CONTROL" + SHELL_EDGE_TARGET = "SHELL_EDGE_TARGET" + + +class DirectMockOracleProfile(str, Enum): + """Closed checker families; every scenario declares one explicitly.""" + + UNDECLARED = "UNDECLARED" + QUALITY_GATE_BLOCKS = "QUALITY_GATE_BLOCKS" + QUALITY_GATE_ALLOWS_CONTROL = "QUALITY_GATE_ALLOWS_CONTROL" + PROBE_ABSENT = "PROBE_ABSENT" + PROBE_PRESENT = "PROBE_PRESENT" + FACT_CONTRACT = "FACT_CONTRACT" + + +class DirectMockFactKey(str, Enum): + """Bounded backend facts needed by frozen direct-mock oracles.""" + + PARALLEL_A = "PARALLEL_A" + PARALLEL_B = "PARALLEL_B" + QGATE_RAN = "QGATE_RAN" + DENY_MARKER_PRESENT = "DENY_MARKER_PRESENT" + EXPECTED_REPOSITORY_FILE = "EXPECTED_REPOSITORY_FILE" + REPOSITORY_CLEAN = "REPOSITORY_CLEAN" + SHARED_FILE_PRESENT = "SHARED_FILE_PRESENT" + SHARED_FILE_MARKER = "SHARED_FILE_MARKER" + SHARED_FILE_CONTENT = "SHARED_FILE_CONTENT" + SUBAGENT_OBSERVED = "SUBAGENT_OBSERVED" + OFFLINE_LOOPBACK_ONLY = "OFFLINE_LOOPBACK_ONLY" + PARENT_PROFILE_HEALTHY = "PARENT_PROFILE_HEALTHY" + PROFILE_INTERSECTION_HELD = "PROFILE_INTERSECTION_HELD" + ACTIVE_TURN_COMMAND_SUPPORTED = "ACTIVE_TURN_COMMAND_SUPPORTED" + ACTIVE_TURN_INFLIGHT = "ACTIVE_TURN_INFLIGHT" + WEB_FETCH_HEALTHY = "WEB_FETCH_HEALTHY" + WEB_FAILURES_PRESERVED = "WEB_FAILURES_PRESERVED" + PROXY_SELF_CHECKED = "PROXY_SELF_CHECKED" + EXPLICIT_ENDPOINT_BYPASSED_PROXY = "EXPLICIT_ENDPOINT_BYPASSED_PROXY" + SHELL_CONTROL_BYTES = "SHELL_CONTROL_BYTES" + SHELL_EDGE_BYTES = "SHELL_EDGE_BYTES" + RESPONSE_USAGE_HEALTHY = "RESPONSE_USAGE_HEALTHY" + CHILD_TOOLS_ALLOWLIST = "CHILD_TOOLS_ALLOWLIST" + REASONING_REDACTED = "REASONING_REDACTED" + SINK_FAULT_APPLIED = "SINK_FAULT_APPLIED" + SESSION_SINK_TOKEN_SEEN = "SESSION_SINK_TOKEN_SEEN" + SINK_ERROR_SURFACED = "SINK_ERROR_SURFACED" + + +class DirectMockIsolationProfile(str, Enum): + """Workspace isolation required by a recipe.""" + + STANDARD = "STANDARD" + DECOY_CWD_WITH_ARTIFACT_GUARD = "DECOY_CWD_WITH_ARTIFACT_GUARD" + + +class DirectMockOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class DirectMockApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +@dataclass(frozen=True, slots=True) +class DirectMockRecipe: + """Bounded recipe metadata without commands, fixture bytes, secrets or paths.""" + + mode: DirectMockMode + entrypoint: DirectMockEntrypoint + max_steps: int | None = None + timeout_seconds: int | None = None + omitted_flag: DirectMockRequiredFlag | None = None + fixture_profile: DirectMockFixtureProfile = DirectMockFixtureProfile.NONE + isolation_profile: DirectMockIsolationProfile = DirectMockIsolationProfile.STANDARD + oracle_profile: DirectMockOracleProfile = DirectMockOracleProfile.UNDECLARED + command: str | None = None + environment: tuple[tuple[str, str], ...] = () + expected_token: str | None = None + base_url_suffix: str = "" + model_name: str = "litellm_proxy/mock" + reject_substring: str = "" + allow_stderr_traceback: bool = False + stale_pwd_probe: bool = False + initialize_git: bool = False + control_dependency: str | None = None + control_dependencies: tuple[str, ...] = () + requirement_dependencies: tuple[str, ...] = () + tool_family: tuple[str, ...] = () + required_tool_families: tuple[tuple[str, ...], ...] = () + request_limit: int | None = None + body_limit: int | None = None + required_facts: tuple[DirectMockFactKey, ...] = () + variant_labels: tuple[str, ...] = () + + def __post_init__(self) -> None: + if type(self.mode) is not DirectMockMode: + raise ContractDocumentError("direct mock mode must use the closed vocabulary") + if type(self.entrypoint) is not DirectMockEntrypoint: + raise ContractDocumentError("direct mock entrypoint must use the closed vocabulary") + if self.max_steps is not None and ( + type(self.max_steps) is not int or self.max_steps < 1 or self.max_steps > _MAX_STEPS + ): + raise ContractDocumentError("direct mock max steps are invalid") + if self.timeout_seconds is not None and ( + type(self.timeout_seconds) is not int + or self.timeout_seconds < 1 + or self.timeout_seconds > _MAX_TIMEOUT_SECONDS + ): + raise ContractDocumentError("direct mock timeout is invalid") + if self.omitted_flag is not None and type(self.omitted_flag) is not DirectMockRequiredFlag: + raise ContractDocumentError("direct mock omitted flag must use the closed vocabulary") + if type(self.fixture_profile) is not DirectMockFixtureProfile: + raise ContractDocumentError("direct mock fixture profile must use the closed vocabulary") + if type(self.isolation_profile) is not DirectMockIsolationProfile: + raise ContractDocumentError("direct mock isolation profile must use the closed vocabulary") + if type(self.oracle_profile) is not DirectMockOracleProfile: + raise ContractDocumentError("direct mock oracle profile must use the closed vocabulary") + if self.command is not None and ( + type(self.command) is not str or not self.command or len(self.command) > 16384 + ): + raise ContractDocumentError("direct mock command is invalid") + if type(self.environment) is not tuple or any( + ( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or (type(item[1]) is not str) + or (not item[0]) + or (len(item[0]) > 128) + or (len(item[1]) > 16384) + for item in self.environment + ) + ): + raise ContractDocumentError("direct mock environment is invalid") + if len({item[0] for item in self.environment}) != len(self.environment): + raise ContractDocumentError("direct mock environment keys must be unique") + if self.expected_token is not None and ( + type(self.expected_token) is not str or not self.expected_token or len(self.expected_token) > 1024 + ): + raise ContractDocumentError("direct mock expected token is invalid") + if ( + type(self.base_url_suffix) is not str + or len(self.base_url_suffix) > 1024 + or ".." in self.base_url_suffix + ): + raise ContractDocumentError("direct mock base-url suffix is invalid") + if type(self.model_name) is not str or not self.model_name or len(self.model_name) > 512: + raise ContractDocumentError("direct mock model name is invalid") + if type(self.reject_substring) is not str or len(self.reject_substring) > 1024: + raise ContractDocumentError("direct mock rejection substring is invalid") + if type(self.allow_stderr_traceback) is not bool: + raise ContractDocumentError("direct mock traceback policy is invalid") + if type(self.stale_pwd_probe) is not bool or type(self.initialize_git) is not bool: + raise ContractDocumentError("direct mock repository setup policy is invalid") + if self.control_dependency is not None and ( + type(self.control_dependency) is not str + or _SCENARIO_ID.fullmatch(self.control_dependency) is None + ): + raise ContractDocumentError("direct mock control dependency is invalid") + if ( + type(self.control_dependencies) is not tuple + or any( + ( + type(item) is not str or _SCENARIO_ID.fullmatch(item) is None + for item in self.control_dependencies + ) + ) + or len(set(self.control_dependencies)) != len(self.control_dependencies) + ): + raise ContractDocumentError("direct mock control dependencies are invalid") + if self.control_dependency is not None and self.control_dependency in self.control_dependencies: + raise ContractDocumentError("direct mock control dependencies must be unique") + if ( + type(self.requirement_dependencies) is not tuple + or any( + ( + type(item) is not str or _SCENARIO_ID.fullmatch(item) is None + for item in self.requirement_dependencies + ) + ) + or len(set(self.requirement_dependencies)) != len(self.requirement_dependencies) + ): + raise ContractDocumentError("direct mock requirement dependencies are invalid") + if type(self.tool_family) is not tuple or any( + (type(item) is not str or not item or len(item) > 128 for item in self.tool_family) + ): + raise ContractDocumentError("direct mock tool family is invalid") + if ( + type(self.required_tool_families) is not tuple + or any( + ( + type(family) is not tuple + or not family + or any((type(item) is not str or not item or len(item) > 128 for item in family)) + or (len(set(family)) != len(family)) + for family in self.required_tool_families + ) + ) + or len(set(self.required_tool_families)) != len(self.required_tool_families) + ): + raise ContractDocumentError("direct mock required tool families are invalid") + if self.request_limit is not None and ( + type(self.request_limit) is not int or self.request_limit < 1 or self.request_limit > 4096 + ): + raise ContractDocumentError("direct mock request limit is invalid") + if self.body_limit is not None and ( + type(self.body_limit) is not int or self.body_limit < 1 or self.body_limit > 64 * 1024 * 1024 + ): + raise ContractDocumentError("direct mock body limit is invalid") + if ( + type(self.required_facts) is not tuple + or any((type(item) is not DirectMockFactKey for item in self.required_facts)) + or len(set(self.required_facts)) != len(self.required_facts) + ): + raise ContractDocumentError("direct mock required facts are invalid") + if ( + type(self.variant_labels) is not tuple + or any( + ( + type(item) is not str or _SCENARIO_ID.fullmatch(item) is None + for item in self.variant_labels + ) + ) + or len(set(self.variant_labels)) != len(self.variant_labels) + ): + raise ContractDocumentError("direct mock variant labels are invalid") + if self.omitted_flag is not None and ( + self.entrypoint is not DirectMockEntrypoint.CONTRACT_SCRIPT + or self.mode is not DirectMockMode.NORMAL + ): + raise ContractDocumentError("required flags can only be omitted at the contract entrypoint") + decoy = self.isolation_profile is DirectMockIsolationProfile.DECOY_CWD_WITH_ARTIFACT_GUARD + if decoy != (self.omitted_flag is DirectMockRequiredFlag.REPO_DIR): + raise ContractDocumentError("repo-dir omission requires the decoy artifact guard") + + +@dataclass(frozen=True, slots=True) +class DirectMockFactStep: + """Typed observation fact consumed by a local judge.""" + + fact_key: DirectMockFactKey + + +def capture_fact(*, fact_key: DirectMockFactKey) -> DirectMockFactStep: + """Declare a typed fact that the scenario judge will consume.""" + return DirectMockFactStep(fact_key) + + +@dataclass(frozen=True, slots=True) +class DirectMockScenario: + """One independent benchmark definition paired with its recipe declaration.""" + + definition: ScenarioDefinition + recipe: DirectMockRecipe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not DirectMockRecipe: + raise ContractDocumentError("direct mock scenario requires exact typed values") + if self.definition.classification.primary != "direct": + raise ContractDocumentError("direct mock scenario owner differs from its Harness layer") + + +@dataclass(frozen=True, slots=True) +class DirectMockRequestFact: + """Bounded request facts retained by the gateway; request content is discarded.""" + + body_bytes: int + has_tools: bool + tool_names: tuple[str, ...] + probe_seen: bool + message_count: int + message_roles: tuple[str, ...] + path: str = "" + model: str = "" + nonleading_system: bool = False + orphan_tool_result: bool = False + lone_surrogate: bool = False + has_any_null: bool = False + empty_content_block: bool = False + dangling_tool_use: bool = False + trailing_empty_assistant: bool = False + tool_result_max_bytes: int = 0 + target_tool_result: str = "" + has_reasoning: bool = False + + def __post_init__(self) -> None: + if type(self.body_bytes) is not int or self.body_bytes < 0 or self.body_bytes > 64 * 1024 * 1024: + raise ContractDocumentError("direct mock request size is invalid") + if type(self.has_tools) is not bool: + raise ContractDocumentError("direct mock tool-presence fact is invalid") + if type(self.tool_names) is not tuple or len(self.tool_names) > 256: + raise ContractDocumentError("direct mock tool-name facts are invalid") + if any((type(item) is not str or not item or len(item) > 256 for item in self.tool_names)): + raise ContractDocumentError("direct mock tool-name fact is invalid") + if type(self.probe_seen) is not bool: + raise ContractDocumentError("direct mock probe fact is invalid") + if type(self.message_count) is not int or self.message_count < 0 or self.message_count > 4096: + raise ContractDocumentError("direct mock message count is invalid") + if type(self.message_roles) is not tuple or len(self.message_roles) > 32: + raise ContractDocumentError("direct mock role facts are invalid") + if ( + type(self.path) is not str + or len(self.path) > 2048 + or type(self.model) is not str + or (len(self.model) > 512) + ): + raise ContractDocumentError("direct mock request routing facts are invalid") + for value in ( + self.nonleading_system, + self.orphan_tool_result, + self.lone_surrogate, + self.has_any_null, + self.empty_content_block, + self.dangling_tool_use, + self.trailing_empty_assistant, + self.has_reasoning, + ): + if type(value) is not bool: + raise ContractDocumentError("direct mock request wire fact is invalid") + if ( + type(self.tool_result_max_bytes) is not int + or not 0 <= self.tool_result_max_bytes <= 64 * 1024 * 1024 + ): + raise ContractDocumentError("direct mock tool-result size is invalid") + if type(self.target_tool_result) is not str or len(self.target_tool_result) > 1024 * 1024: + raise ContractDocumentError("direct mock target result is invalid") + + +@dataclass(frozen=True, slots=True) +class DirectMockObservedFact: + """One closed, bounded filesystem or lifecycle fact emitted by the backend.""" + + key: DirectMockFactKey + value: bool | int | str + + def __post_init__(self) -> None: + if type(self.key) is not DirectMockFactKey or type(self.value) not in {bool, int, str}: + raise ContractDocumentError("direct mock observed fact is invalid") + if type(self.value) is str and len(self.value) > 8 * 1024 * 1024: + raise ContractDocumentError("direct mock observed text is too large") + + +def _digest(value: str, label: str) -> str: + if ( + type(value) is not str + or not value.startswith("sha256:") + or len(value) != 71 + or any((character not in "0123456789abcdef" for character in value[7:])) + ): + raise ContractDocumentError(f"{label} is invalid") + return value + + +@dataclass(frozen=True, slots=True) +class DirectMockRawObservation: + """Path-free execution facts emitted by an identity-bound backend.""" + + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + exit_code: int + status_written: bool + exit_status: str | None + cost_usd: int | float | None + requests: tuple[DirectMockRequestFact, ...] + proof_present: bool + proof_contains_marker: bool + trajectory_observed: bool + trajectory_contains_probe: bool + artifact_unchanged: bool + decoy_entries: tuple[str, ...] + stderr_has_traceback: bool + process_tree_clean: bool + gateway_clean: bool + workspace_clean: bool + backend_evidence_digest: str + timed_out: bool = False + trajectory: str = "" + assistant_text: str = "" + facts: tuple[DirectMockObservedFact, ...] = () + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("direct mock observation id is invalid") + _digest(self.plan_digest, "direct mock plan digest") + if type(self.artifact_id) is not str or _SCENARIO_ID.fullmatch(self.artifact_id) is None: + raise ContractDocumentError("direct mock artifact id is invalid") + _digest(self.artifact_digest, "direct mock artifact digest") + if type(self.exit_code) is not int or self.exit_code < -1 or self.exit_code > 255: + raise ContractDocumentError("direct mock exit code is invalid") + if self.exit_status is not None and ( + type(self.exit_status) is not str or len(self.exit_status) > 256 + ): + raise ContractDocumentError("direct mock exit status is invalid") + if self.cost_usd is not None and type(self.cost_usd) not in {int, float}: + raise ContractDocumentError("direct mock cost fact is invalid") + if type(self.requests) is not tuple or any( + (type(item) is not DirectMockRequestFact for item in self.requests) + ): + raise ContractDocumentError("direct mock request facts are invalid") + for value in ( + self.status_written, + self.proof_present, + self.proof_contains_marker, + self.trajectory_observed, + self.trajectory_contains_probe, + self.artifact_unchanged, + self.stderr_has_traceback, + self.process_tree_clean, + self.gateway_clean, + self.workspace_clean, + ): + if type(value) is not bool: + raise ContractDocumentError("direct mock boolean fact is invalid") + if type(self.decoy_entries) is not tuple or any( + (type(item) is not str or not item or len(item) > 512 for item in self.decoy_entries) + ): + raise ContractDocumentError("direct mock decoy facts are invalid") + _digest(self.backend_evidence_digest, "direct mock backend evidence digest") + if type(self.timed_out) is not bool: + raise ContractDocumentError("direct mock timeout fact is invalid") + if type(self.trajectory) is not str or len(self.trajectory) > 64 * 1024 * 1024: + raise ContractDocumentError("direct mock trajectory is invalid") + if type(self.assistant_text) is not str or len(self.assistant_text) > 8 * 1024 * 1024: + raise ContractDocumentError("direct mock assistant text is invalid") + if type(self.facts) is not tuple or any( + (type(item) is not DirectMockObservedFact for item in self.facts) + ): + raise ContractDocumentError("direct mock observed facts are invalid") + if len({item.key for item in self.facts}) != len(self.facts): + raise ContractDocumentError("direct mock observed facts must have unique keys") + + +@dataclass(frozen=True, slots=True) +class DirectMockJudgement: + """Typed, scenario-local oracle result before evidence/score construction.""" + + outcome: DirectMockOutcome + applicability: DirectMockApplicability + reason_code: str + + def __post_init__(self) -> None: + if ( + type(self.outcome) is not DirectMockOutcome + or type(self.applicability) is not DirectMockApplicability + ): + raise ContractDocumentError("direct mock judgement uses invalid closed values") + if type(self.reason_code) is not str or not self.reason_code or len(self.reason_code) > 128: + raise ContractDocumentError("direct mock judgement reason is invalid") + + +@runtime_checkable +class DirectMockLocalJudge(Protocol): + """Pure scenario-specific predicate over an already bound observation.""" + + def __call__(self, observation: DirectMockRawObservation, /) -> DirectMockJudgement: ... + + +def define_direct_mock_scenario( + scenario_id: str, recipe: DirectMockRecipe, role: ScenarioRole, / +) -> DirectMockScenario: + """Construct one direct-mock definition without granting execution authority.""" + if type(scenario_id) is not str or _SCENARIO_ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("direct mock scenario id is not canonical") + if type(recipe) is not DirectMockRecipe: + raise ContractDocumentError("direct mock scenario recipe must use DirectMockRecipe") + if type(role) is not ScenarioRole: + raise ContractDocumentError("direct mock scenario role must use ScenarioRole") + control_ids = ( + () if recipe.control_dependency is None else (recipe.control_dependency,) + ) + recipe.control_dependencies + definition = ScenarioDefinition( + scenario_id=scenario_id, + revision="1", + classification=Classification("direct"), + role=role, + weight_microunits=1000000 if role is ScenarioRole.TARGET else 0, + difficulty=ScenarioDifficulty.STANDARD, + dependencies=( + *(DependencyRef(item, DependencyKind.GATE) for item in control_ids), + *(DependencyRef(item, DependencyKind.REQUIREMENT) for item in recipe.requirement_dependencies), + ), + experiment=ExperimentBinding( + fixture=ComponentRef("direct-mock-fixture", "1", ComponentKind.FIXTURE), + stimulus=ComponentRef("direct-mock-process", "1", ComponentKind.STIMULUS), + observer=ComponentRef("direct-mock-observer", "1", ComponentKind.OBSERVER), + oracle=ComponentRef("direct-mock-oracle", "1", ComponentKind.ORACLE), + cleanup=ComponentRef("direct-mock-cleanup", "1", ComponentKind.CLEANUP), + ), + unsupported_policy=UnsupportedPolicy.FAIL, + ) + return DirectMockScenario(definition, recipe) + + +def validate_direct_mock_observation( + scenario: DirectMockScenario, + observation: DirectMockRawObservation, + expected_plan_digest: str | None = None, + /, +) -> None: + """Validate the identity and plan binding before a local judge runs. + + Artifact identity and the runtime-generated plan digest are verified by + ``RuntimeDirectMockAdapter``. A caller that already has an expected plan + digest may pass it explicitly; keeping the default path free of an + adapter import preserves the one-way harness dependency graph. + """ + if type(scenario) is not DirectMockScenario or type(observation) is not DirectMockRawObservation: + raise ContractDocumentError("direct mock observation binding requires exact contracts") + if observation.scenario_id != scenario.definition.scenario_id: + raise ContractDocumentError("direct mock observation belongs to another scenario") + if expected_plan_digest is not None and observation.plan_digest != expected_plan_digest: + raise ContractDocumentError("direct mock observation plan is not bound to the scenario") + + +def _validate_local_judgement(judgement: DirectMockJudgement) -> DirectMockJudgement: + if type(judgement) is not DirectMockJudgement: + raise ContractDocumentError("direct mock local judge returned an invalid judgement") + return judgement + + +def apply_direct_mock_local_judge( + scenario: DirectMockScenario, observation: DirectMockRawObservation, judge: DirectMockLocalJudge, / +) -> DirectMockJudgement: + """Apply shared runtime gates, then one scenario-local pure judge. + + A stderr traceback fails the run outright; incomplete cleanup fails it unless + the scenario's own judgement is already inconclusive. + """ + validate_direct_mock_observation(scenario, observation) + if not isinstance(judge, DirectMockLocalJudge): + raise ContractDocumentError("direct mock local judge is not callable") + cleanup_complete = ( + observation.process_tree_clean and observation.gateway_clean and observation.workspace_clean + ) + if observation.stderr_has_traceback and (not scenario.recipe.allow_stderr_traceback): + return DirectMockJudgement( + DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, "STDERR_TRACEBACK" + ) + provisional = _validate_local_judgement(judge(observation)) + if not cleanup_complete: + if provisional.applicability is DirectMockApplicability.INCONCLUSIVE: + return provisional + return DirectMockJudgement( + DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, "RUNTIME_CLEANUP_INCOMPLETE" + ) + return provisional + + +__all__ = [ + "DirectMockApplicability", + "DirectMockEntrypoint", + "DirectMockFixtureProfile", + "DirectMockIsolationProfile", + "DirectMockJudgement", + "DirectMockLocalJudge", + "DirectMockMode", + "DirectMockOutcome", + "DirectMockRawObservation", + "DirectMockRecipe", + "DirectMockRequestFact", + "DirectMockRequiredFlag", + "DirectMockScenario", + "apply_direct_mock_local_judge", + "define_direct_mock_scenario", + "validate_direct_mock_observation", +] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/fixtures.py b/code/src/doc2harness/benchmark/harnesses/direct/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd29eb11436ef9233db3a609b3b9935b7003718 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/fixtures.py @@ -0,0 +1,268 @@ +"""Deterministic, path-free fixture materialization plans for direct mock-process scenarios.""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockFixtureProfile, + DirectMockIsolationProfile, + DirectMockRecipe, + DirectMockScenario, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class DirectMockFixtureFile: + """One safe repository-relative file supplied before execution.""" + + path: tuple[str, ...] + content: bytes + + def __post_init__(self) -> None: + if type(self.path) is not tuple or not self.path or len(self.path) > 16: + raise ContractDocumentError("direct mock fixture path is invalid") + if any( + type(item) is not str or not item or item in {".", ".."} + or "/" in item or "\\" in item or len(item.encode("utf-8")) > 255 + for item in self.path + ): + raise ContractDocumentError("direct mock fixture path is unsafe") + if type(self.content) is not bytes or len(self.content) > 16 * 1024 * 1024: + raise ContractDocumentError("direct mock fixture content is invalid") + + +@dataclass(frozen=True, slots=True) +class DirectMockAction: + """One logical tool call; aliases are resolved against the live request schema.""" + + tool_candidates: tuple[str, ...] + arguments: tuple[tuple[str, str | bool | int | float], ...] + finish: bool = False + + def __post_init__(self) -> None: + if type(self.finish) is not bool: + raise ContractDocumentError("direct mock finish marker is invalid") + if self.finish: + if self.tool_candidates or self.arguments: + raise ContractDocumentError("direct mock finish action cannot carry a tool") + return + if type(self.tool_candidates) is not tuple or not self.tool_candidates: + raise ContractDocumentError("direct mock action needs a tool candidate") + if any(type(item) is not str or not item or len(item) > 128 for item in self.tool_candidates): + raise ContractDocumentError("direct mock tool candidate is invalid") + if type(self.arguments) is not tuple or any( + type(item) is not tuple or len(item) != 2 + or type(item[0]) is not str or type(item[1]) not in {str, bool, int, float} + or (isinstance(item[1], str) and len(item[1]) > 16_384) + for item in self.arguments + ): + raise ContractDocumentError("direct mock action arguments are invalid") + + +@dataclass(frozen=True, slots=True) +class DirectMockFixturePlan: + """Complete logical input for one execution, without host paths or secrets.""" + + scenario_id: str + task_document: bytes + budget_document: bytes + repository_files: tuple[DirectMockFixtureFile, ...] + environment: tuple[tuple[str, str], ...] + rounds: tuple[tuple[DirectMockAction, ...], ...] + probe_token: str | None + isolation_profile: DirectMockIsolationProfile + plan_digest: str + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or not self.scenario_id: + raise ContractDocumentError("direct mock fixture id is invalid") + if type(self.task_document) is not bytes or type(self.budget_document) is not bytes: + raise ContractDocumentError("direct mock fixture documents are invalid") + if type(self.repository_files) is not tuple or any(type(item) is not DirectMockFixtureFile for item in self.repository_files): + raise ContractDocumentError("direct mock fixture files are invalid") + if len({item.path for item in self.repository_files}) != len(self.repository_files): + raise ContractDocumentError("direct mock fixture paths must be unique") + if type(self.environment) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str or type(item[1]) is not str + for item in self.environment + ): + raise ContractDocumentError("direct mock fixture environment is invalid") + if type(self.rounds) is not tuple or any( + type(group) is not tuple or not group or any(type(action) is not DirectMockAction for action in group) + for group in self.rounds + ): + raise ContractDocumentError("direct mock fixture rounds are invalid") + if self.probe_token is not None and (type(self.probe_token) is not str or not self.probe_token): + raise ContractDocumentError("direct mock probe token is invalid") + if type(self.isolation_profile) is not DirectMockIsolationProfile: + raise ContractDocumentError("direct mock isolation profile is invalid") + body = _fixture_body(self, include_digest=False) + expected = "sha256:" + hashlib.sha256(b"doc2harness.direct-mock-fixture/1\0" + canonical_json(body)).hexdigest() + if self.plan_digest != expected: + raise ContractDocumentError("direct mock fixture digest does not bind its content") + + +def _action_body(action: DirectMockAction) -> dict[str, object]: + return { + "arguments": [list(item) for item in action.arguments], + "finish": action.finish, + "tool_candidates": list(action.tool_candidates), + } + + +def _fixture_body(plan: DirectMockFixturePlan, *, include_digest: bool) -> dict[str, object]: + body: dict[str, object] = { + "budget_document": plan.budget_document.decode("utf-8"), + "environment": [list(item) for item in plan.environment], + "isolation_profile": plan.isolation_profile.value, + "probe_token": plan.probe_token, + "repository_files": [ + {"path": list(item.path), "sha256": hashlib.sha256(item.content).hexdigest()} + for item in plan.repository_files + ], + "rounds": [[_action_body(action) for action in group] for group in plan.rounds], + "scenario_id": plan.scenario_id, + "task_document": plan.task_document.decode("utf-8"), + } + if include_digest: + body["plan_digest"] = plan.plan_digest + return body + + +def _bash(command: str) -> DirectMockAction: + return DirectMockAction( + ("bash", "shell", "run_command", "execute", "exec", "terminal"), + (("command", command),), + ) + + +def _tool(candidates: tuple[str, ...], **arguments: object) -> DirectMockAction: + return DirectMockAction(candidates, tuple(arguments.items())) + + +def _secret_and_protocol_profile(recipe: DirectMockRecipe): + """Materialize the secret, protocol and shell-edge stimuli without embedding host paths.""" + + profile = recipe.fixture_profile + secret_cases = { + DirectMockFixtureProfile.SECRET_UNREFERENCED_KEY: ( + ("secret.key",), ( + b"-----BEGIN OPENSSH " b"PRIVATE KEY-----\nSK_SENTINEL_4242\n" + b"-----END OPENSSH " b"PRIVATE KEY-----\n" + ), + "SK_SENTINEL_4242", "Check secret.key permissions without opening it.", + ), + DirectMockFixtureProfile.SECRET_PEM: ( + ("server.pem",), b"-----BEGIN CERTIFICATE-----\nPEM_SENTINEL_5583\n-----END CERTIFICATE-----\n", + "PEM_SENTINEL_5583", "Audit mentioned *.pem certificates without reading unreferenced content.", + ), + } + if profile in secret_cases: + path, content, probe, task = secret_cases[profile] + return (DirectMockFixtureFile(path, content),), (), probe, task + if profile is DirectMockFixtureProfile.SECRET_CONTROL: + return ( + DirectMockFixtureFile(("ref.txt",), b"REFTOK_7731 content body\n"), + ), ((_bash("cat ref.txt"),),), "REFTOK_7731", "Read the explicitly referenced file." + if profile is DirectMockFixtureProfile.HTTP_PROXY: + return (), (), recipe.expected_token, "Exercise the declared bounded protocol contract." + if profile is DirectMockFixtureProfile.WEB_FETCH: + # The host and port are only known once the run has a listener, so the + # declared URL carries a placeholder the driver substitutes. A fixed + # loopback address would send the product at its own port 80, where + # nothing answers, and the point could never observe the fetch it is + # about. + return (), ((_tool(("web_fetch", "webfetch"), url="http://{OBSERVER}/local-probe"),),), recipe.expected_token, "Fetch the loopback probe URL." + if profile is DirectMockFixtureProfile.SHELL_EDGE_CONTROL: + return (), ((_bash("printf 'SHELL_EDGE_CONTROL_7731\\n'"),),), "SHELL_EDGE_CONTROL_7731", "Preserve ordinary shell output." + if profile is DirectMockFixtureProfile.SHELL_EDGE_TARGET: + return (), ((_bash("printf '\\n EDGE_CONTENT_7731 \\n\\nUNTRUNCATED_7731\\n'"),),), "UNTRUNCATED_7731", "Preserve shell output edge whitespace." + return None + + +def _profile(recipe: DirectMockRecipe) -> tuple[tuple[DirectMockFixtureFile, ...], tuple[tuple[DirectMockAction, ...], ...], str | None, str]: + profile = recipe.fixture_profile + if profile in {DirectMockFixtureProfile.QUALITY_GATE_FAIL, DirectMockFixtureProfile.QUALITY_GATE_PASS}: + rc = 1 if profile is DirectMockFixtureProfile.QUALITY_GATE_FAIL else 0 + command = f"sh -c 'echo QGATE_RAN_7755 > qgate.marker; exit {rc}'" + hook = {key: [{"command": command, "action": "run"}] for key in ( + "qualityGate", "beforeFinish", "beforeSubmit", "beforeCompletion" + )} + rounds = ((_bash("echo QGATE_EDIT_7755 > edited.txt"),),) + return (DirectMockFixtureFile(("hooks.json",), json.dumps(hook, separators=(",", ":")).encode()),), rounds, None, "do the task" + plan = _secret_and_protocol_profile(recipe) + if plan is not None: + return plan + rounds = ((_bash(recipe.command),),) if recipe.command is not None else () + return (), rounds, None, "do the task" + + +def materialize_direct_mock_fixture(scenario: DirectMockScenario, /) -> DirectMockFixturePlan: + """Freeze exact fixture bytes and logical rounds for one scenario.""" + + if type(scenario) is not DirectMockScenario: + raise ContractDocumentError("direct mock materializer requires an exact scenario") + recipe = scenario.recipe + files, rounds, probe, task = _profile(recipe) + max_steps = recipe.max_steps if recipe.max_steps is not None else 2 + environment: tuple[tuple[str, str], ...] = recipe.environment + seed = DirectMockFixturePlan.__new__(DirectMockFixturePlan) + values = { + "scenario_id": scenario.definition.scenario_id, + "task_document": ( + b'["not","an","object"]' + if task == "__NONOBJECT_TASK__" + else json.dumps( + { + # AGENT_CONTRACT-v2.md defines task.json as a complete object + # of five fields and budget.json as three, and documents each + # field without saying any may be omitted, so a product may + # validate for exactly the contracted keys and reject a task + # that omits one before issuing a single model request. + # + # A harness that rejects strict conformance is not measuring the + # product, and the error is silent in aggregate: the affected + # scenarios simply score zero, which is indistinguishable from + # the product being unable to do them. Emit the documented + # objects in full. Scenarios that need a malformed task declare + # it explicitly, just above. + "task_id": scenario.definition.scenario_id, + "type": "swe", + "problem_statement": task, + # Placeholder: the contract requires repo_dir to equal the + # --repo-dir the product is invoked with, and that is the + # driver's temp workspace, unknowable when these bytes are + # frozen. The driver rewrites this field at write time. + "repo_dir": "__REPO_DIR__", + "allow_network": ( + recipe.fixture_profile is DirectMockFixtureProfile.WEB_FETCH + ), + }, + separators=(",", ":"), sort_keys=True, + ).encode() + ), + "budget_document": json.dumps( + {"max_steps": max_steps, "max_tokens": 0, "max_wall_seconds": 1800}, + separators=(",", ":"), sort_keys=True).encode(), + "repository_files": files, + "environment": environment, + "rounds": rounds, + "probe_token": probe, + "isolation_profile": recipe.isolation_profile, + } + for key, value in values.items(): + object.__setattr__(seed, key, value) + body = _fixture_body(seed, include_digest=False) + digest = "sha256:" + hashlib.sha256(b"doc2harness.direct-mock-fixture/1\0" + canonical_json(body)).hexdigest() + return DirectMockFixturePlan(**values, plan_digest=digest) + + +__all__ = [ + "DirectMockAction", "DirectMockFixtureFile", "DirectMockFixturePlan", + "materialize_direct_mock_fixture", +] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a7f10288be65371d71882e3747e0b48bb8f35b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/__init__.py @@ -0,0 +1,3 @@ +"""Independent definition owners for direct mock-process scenarios.""" + +__all__: list[str] = [] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/exfil_glob_pem_not_leaked.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/exfil_glob_pem_not_leaked.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8634b716806466403fe699ac6f5de83a61d4b1 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/exfil_glob_pem_not_leaked.py @@ -0,0 +1,37 @@ +"""Ensure globbing PEM files does not trigger a secret probe. + +1. Seed a PEM fixture and issue the glob request. +2. Capture request contents and secret-probe facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFixtureProfile, + DirectMockJudgement, DirectMockMode, DirectMockOracleProfile, + DirectMockOutcome, DirectMockRawObservation, DirectMockRecipe, + DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "exfil_glob_pem_not_leaked" +RECIPE = DirectMockRecipe( + DirectMockMode.NORMAL, DirectMockEntrypoint.PYTHON_ENTRY, max_steps=2, timeout_seconds=180, + fixture_profile=DirectMockFixtureProfile.SECRET_PEM, + oracle_profile=DirectMockOracleProfile.PROBE_ABSENT, + control_dependencies=("secret_probe_mechanism_control",), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Pass only when a live clean request carries no probe marker.""" + + clean = observation.exit_status in {"Submitted", "LimitsExceeded"} + passed = bool(observation.requests) and not any(item.probe_seen for item in observation.requests) and clean + return DirectMockJudgement(DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.PROBE_ABSENT.value) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec05f05ab2adb96382dc3cfd9c9befa03807f6b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic.py @@ -0,0 +1,45 @@ +"""Require explicit endpoints to bypass the configured proxy. + +1. Send the explicit-endpoint request with a configured proxy. +2. Capture endpoint routing and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "http_proxy_hermetic" +RECIPE = DirectMockRecipe( + DirectMockMode.FIXED_REPLY, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.HTTP_PROXY, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=2, timeout_seconds=30, + required_facts=(DirectMockFactKey.PROXY_SELF_CHECKED, + DirectMockFactKey.EXPLICIT_ENDPOINT_BYPASSED_PROXY), + control_dependencies=("http_proxy_hermetic_control",), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require both proxy facts and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic_control.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic_control.py new file mode 100644 index 0000000000000000000000000000000000000000..b2613917d559dff201c8740342a8a144794032c6 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic_control.py @@ -0,0 +1,43 @@ +"""Require the proxy self-check to pass in the control path. + +1. Send the control request through the proxy fixture. +2. Capture proxy routing and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "http_proxy_hermetic_control" +RECIPE = DirectMockRecipe( + DirectMockMode.FIXED_REPLY, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.HTTP_PROXY, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=2, timeout_seconds=30, + required_facts=(DirectMockFactKey.PROXY_SELF_CHECKED,), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.CONTROL) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the declared fact and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..68698ed3012a3b4255447ec3ea8e53383952f368 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion.py @@ -0,0 +1,59 @@ +"""Require a failed quality hook to prevent a submitted completion. + +1. Run the completion through the failing quality hook. +2. Capture quality, submission, and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, + DirectMockEntrypoint, + DirectMockFactKey, + DirectMockFixtureProfile, + DirectMockJudgement, + DirectMockMode, + DirectMockOracleProfile, + DirectMockOutcome, + DirectMockRawObservation, + DirectMockRecipe, + DirectMockScenario, + define_direct_mock_scenario, +) + +SCENARIO_ID = "quality_gate_blocks_completion" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, + DirectMockEntrypoint.PYTHON_ENTRY, + max_steps=4, + timeout_seconds=90, + fixture_profile=DirectMockFixtureProfile.QUALITY_GATE_FAIL, + oracle_profile=DirectMockOracleProfile.QUALITY_GATE_BLOCKS, + control_dependency="quality_gate_blocks_completion_control", +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require a recorded gate and a non-submitted terminal status.""" + + gate_ran = bool(next( + (item.value for item in observation.facts if item.key is DirectMockFactKey.QGATE_RAN), + False, + )) + if not observation.status_written or not observation.requests or not gate_ran: + return DirectMockJudgement( + DirectMockOutcome.PASS, + DirectMockApplicability.INCONCLUSIVE, + "QUALITY_GATE_NOT_OBSERVED", + ) + outcome = DirectMockOutcome.PASS if observation.exit_status != "Submitted" else DirectMockOutcome.FAIL + return DirectMockJudgement(outcome, DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.QUALITY_GATE_BLOCKS.value) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion_control.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion_control.py new file mode 100644 index 0000000000000000000000000000000000000000..b844aab11ccf60b4abd00ddce45151f59acb684c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/quality_gate_blocks_completion_control.py @@ -0,0 +1,62 @@ +"""Require a successful quality hook to permit a submitted completion. + +1. Run the completion through the successful quality hook. +2. Capture quality, submission, and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, + DirectMockEntrypoint, + DirectMockFactKey, + DirectMockFixtureProfile, + DirectMockJudgement, + DirectMockMode, + DirectMockOracleProfile, + DirectMockOutcome, + DirectMockRawObservation, + DirectMockRecipe, + DirectMockScenario, + define_direct_mock_scenario, +) + +SCENARIO_ID = "quality_gate_blocks_completion_control" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, + DirectMockEntrypoint.PYTHON_ENTRY, + max_steps=4, + timeout_seconds=90, + fixture_profile=DirectMockFixtureProfile.QUALITY_GATE_PASS, + oracle_profile=DirectMockOracleProfile.QUALITY_GATE_ALLOWS_CONTROL, +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the gate marker, a submitted status, and zero exit code.""" + + gate_ran = bool(next( + (item.value for item in observation.facts if item.key is DirectMockFactKey.QGATE_RAN), + False, + )) + if not gate_ran: + return DirectMockJudgement( + DirectMockOutcome.PASS, + DirectMockApplicability.INCONCLUSIVE, + "QUALITY_GATE_NOT_OBSERVED", + ) + passed = observation.exit_status == "Submitted" and observation.exit_code == 0 + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, + DirectMockOracleProfile.QUALITY_GATE_ALLOWS_CONTROL.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/secret_probe_mechanism_control.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/secret_probe_mechanism_control.py new file mode 100644 index 0000000000000000000000000000000000000000..41a63d49511867f07c303184e6270ffbc0700011 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/secret_probe_mechanism_control.py @@ -0,0 +1,36 @@ +"""Control: prove the secret probe mechanism is observable when requested. + +1. Request the control secret probe explicitly. +2. Capture probe and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFixtureProfile, + DirectMockJudgement, DirectMockMode, DirectMockOracleProfile, + DirectMockOutcome, DirectMockRawObservation, DirectMockRecipe, + DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "secret_probe_mechanism_control" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, DirectMockEntrypoint.PYTHON_ENTRY, max_steps=2, timeout_seconds=180, + fixture_profile=DirectMockFixtureProfile.SECRET_CONTROL, + oracle_profile=DirectMockOracleProfile.PROBE_PRESENT, +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.CONTROL) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Pass only when a live clean request carries a probe marker.""" + + clean = observation.exit_status in {"Submitted", "LimitsExceeded"} + passed = bool(observation.requests) and any(item.probe_seen for item in observation.requests) and clean + return DirectMockJudgement(DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.PROBE_PRESENT.value) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace.py new file mode 100644 index 0000000000000000000000000000000000000000..37fa897479b90e56a13a00f9dbec25b0ced743d4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace.py @@ -0,0 +1,44 @@ +"""Require target-path shell bytes to remain intact at whitespace edges. + +1. Send the shell command with edge whitespace. +2. Capture exact output bytes and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "shell_output_edge_whitespace" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.SHELL_EDGE_TARGET, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=3, timeout_seconds=45, + required_facts=(DirectMockFactKey.SHELL_EDGE_BYTES,), + control_dependencies=("shell_output_edge_whitespace_control",), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the declared fact and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace_control.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace_control.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea05dde3cb54f4da4f5424615e9592a7ccd59f1 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/shell_output_edge_whitespace_control.py @@ -0,0 +1,43 @@ +"""Require control-path shell bytes to remain intact at whitespace edges. + +1. Send the control shell command with edge whitespace. +2. Capture exact output bytes and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "shell_output_edge_whitespace_control" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.SHELL_EDGE_CONTROL, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=3, timeout_seconds=45, + required_facts=(DirectMockFactKey.SHELL_CONTROL_BYTES,), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.CONTROL) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the declared fact and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/unreferenced_secret_not_in_request_body.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/unreferenced_secret_not_in_request_body.py new file mode 100644 index 0000000000000000000000000000000000000000..a075a8d8712a4f428fca1a0427b08642b4757b15 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/unreferenced_secret_not_in_request_body.py @@ -0,0 +1,37 @@ +"""Ensure an unreferenced secret is absent from observed request facts. + +1. Seed a secret that the prompt never references. +2. Capture request-body and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFixtureProfile, + DirectMockJudgement, DirectMockMode, DirectMockOracleProfile, + DirectMockOutcome, DirectMockRawObservation, DirectMockRecipe, + DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "unreferenced_secret_not_in_request_body" +RECIPE = DirectMockRecipe( + DirectMockMode.NORMAL, DirectMockEntrypoint.PYTHON_ENTRY, max_steps=2, timeout_seconds=180, + fixture_profile=DirectMockFixtureProfile.SECRET_UNREFERENCED_KEY, + oracle_profile=DirectMockOracleProfile.PROBE_ABSENT, + control_dependencies=("secret_probe_mechanism_control",), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Pass only when a live clean request carries no probe marker.""" + + clean = observation.exit_status in {"Submitted", "LimitsExceeded"} + passed = bool(observation.requests) and not any(item.probe_seen for item in observation.requests) and clean + return DirectMockJudgement(DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.PROBE_ABSENT.value) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..0e79c445b33a7a14e6e5077300bab050749dffe0 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure.py @@ -0,0 +1,48 @@ +"""Require web-fetch failures to remain observable without a false success. + +1. Send the web-fetch request through the failing endpoint. +2. Capture error, submission, and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "webfetch_http_failure" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.WEB_FETCH, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=3, timeout_seconds=45, + environment=(("HTTP_PROXY", ""), ("HTTPS_PROXY", ""), ("ALL_PROXY", ""), + ("NO_PROXY", "127.0.0.1,localhost"), + ("no_proxy", "127.0.0.1,localhost")), + required_facts=(DirectMockFactKey.WEB_FAILURES_PRESERVED,), + control_dependencies=("webfetch_http_failure_control",), + variant_labels=("http_404", "http_429", "http_500"), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the declared fact and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure_control.py b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure_control.py new file mode 100644 index 0000000000000000000000000000000000000000..97cbead1d08a274841718343e4dd50fe779afde9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/direct/scenarios/webfetch_http_failure_control.py @@ -0,0 +1,46 @@ +"""Require a healthy web-fetch exchange in the control path. + +1. Send the control web-fetch request. +2. Capture response and terminal facts. +3. Apply the typed direct-mock judge to the observation. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey, + DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode, + DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation, + DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario, +) + +SCENARIO_ID = "webfetch_http_failure_control" +RECIPE = DirectMockRecipe( + DirectMockMode.SEQUENTIAL_PROBE, DirectMockEntrypoint.PYTHON_ENTRY, + fixture_profile=DirectMockFixtureProfile.WEB_FETCH, + oracle_profile=DirectMockOracleProfile.FACT_CONTRACT, + max_steps=3, timeout_seconds=45, + environment=(("HTTP_PROXY", ""), ("HTTPS_PROXY", ""), ("ALL_PROXY", ""), + ("NO_PROXY", "127.0.0.1,localhost"), + ("no_proxy", "127.0.0.1,localhost")), + required_facts=(DirectMockFactKey.WEB_FETCH_HEALTHY,), +) +STEPS = (RECIPE,) +SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.CONTROL) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: DirectMockRawObservation) -> DirectMockJudgement: + """Require the declared fact and a live, recorded, non-timeout run.""" + + observed = {item.key: item.value for item in observation.facts} + passed = (all(observed.get(key) is True for key in RECIPE.required_facts) + and bool(observation.requests) and observation.status_written + and not observation.timed_out) + return DirectMockJudgement( + DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, + DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/__init__.py b/code/src/doc2harness/benchmark/harnesses/extension/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f940b7727588916773b305875930abe48dbac78 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/__init__.py @@ -0,0 +1,55 @@ +"""Typed extension discovery counterfactual Harness.""" + +from .adapter import ( + ExtensionExecutionPlan, + build_extension_execution_plan, +) +from .contracts import ( + ExtensionApplicability, + ExtensionCounterfactualEvaluation, + ExtensionCounterfactualObservation, + ExtensionCounterfactualRecipe, + ExtensionCounterfactualScenario, + ExtensionCaptureStep, + ExtensionFace, + ExtensionFixtureStep, + ExtensionOutcome, + ExtensionRunObservation, + ExtensionScenarioStep, + ExtensionSetupStep, + ExtensionToolRoundStep, + capture_extension_face, + compile_extension_steps, + setup_command, + tool_round, +) +from .fixtures import ExtensionFixturePlan, materialize_extension_fixture +from .oracle import evaluate_extension_counterfactual +from .recipes import SCENARIOS, scenario_by_id + +__all__ = [ + "SCENARIOS", + "ExtensionApplicability", + "ExtensionCounterfactualEvaluation", + "ExtensionCounterfactualObservation", + "ExtensionCounterfactualRecipe", + "ExtensionCounterfactualScenario", + "ExtensionCaptureStep", + "ExtensionExecutionPlan", + "ExtensionFace", + "ExtensionFixturePlan", + "ExtensionFixtureStep", + "ExtensionOutcome", + "ExtensionRunObservation", + "ExtensionScenarioStep", + "ExtensionSetupStep", + "ExtensionToolRoundStep", + "build_extension_execution_plan", + "capture_extension_face", + "compile_extension_steps", + "evaluate_extension_counterfactual", + "materialize_extension_fixture", + "scenario_by_id", + "setup_command", + "tool_round", +] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/adapter.py b/code/src/doc2harness/benchmark/harnesses/extension/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..44bf4c6f37c522bf70be67848bc55185e2927d3d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/adapter.py @@ -0,0 +1,61 @@ +"""Execution boundary for extension discovery counterfactuals.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from .contracts import ( + ExtensionCounterfactualScenario, +) +from .fixtures import ExtensionFixturePlan, materialize_extension_fixture + + +@dataclass(frozen=True, slots=True) +class ExtensionExecutionPlan: + scenario_id: str + fixture: ExtensionFixturePlan + setup_commands: tuple[str, ...] + round_tool: str + round_command: str + paired: bool + timeout_seconds: int + plan_digest: str + + +def build_extension_execution_plan( + scenario: ExtensionCounterfactualScenario, + /, +) -> ExtensionExecutionPlan: + if type(scenario) is not ExtensionCounterfactualScenario: + raise ContractDocumentError("extension execution requires an exact scenario") + recipe = scenario.recipe + fixture = materialize_extension_fixture(scenario) + body = { + "fixture_digest": fixture.plan_digest, + "paired": recipe.paired, + "round": {"command": recipe.round_command, "tool": recipe.round_tool}, + "scenario_id": scenario.definition.scenario_id, + "setup_commands": list(recipe.setup_commands), + "timeout_seconds": recipe.timeout_seconds, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.extension-counterfactual-plan/1\0" + canonical_json(body) + ).hexdigest() + return ExtensionExecutionPlan( + scenario.definition.scenario_id, + fixture, + recipe.setup_commands, + recipe.round_tool, + recipe.round_command, + recipe.paired, + recipe.timeout_seconds, + digest, + ) + + +__all__ = [ + "ExtensionExecutionPlan", + "build_extension_execution_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/catalog.toml b/code/src/doc2harness/benchmark/harnesses/extension/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..6067182f779fc33ae0ae115c04aeb4f4c52758ce --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/catalog.toml @@ -0,0 +1,7 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "extension" +resource = "benchmark/harnesses/extension/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_definition_symlink_outside_fenced", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_inside_symlink_discovery_control", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/contracts.py b/code/src/doc2harness/benchmark/harnesses/extension/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..4050f5dab2b740c85d506731fc00faa191c4e735 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/contracts.py @@ -0,0 +1,375 @@ +"""Closed declarations and observations for extension counterfactuals.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum +from typing import Protocol, runtime_checkable + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) + + +class ExtensionFace(str, Enum): + COMMANDS = "commands" + SKILLS = "skills" + HOOKS = "hooks" + PLUGINS = "plugins" + + +class ExtensionOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class ExtensionApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +@dataclass(frozen=True, slots=True) +class ExtensionFixtureStep: + """Declare which workspace views the shared fixture must materialize.""" + + modes: tuple[str, ...] + + def __post_init__(self) -> None: + if self.modes not in {("inside",), ("inside", "outside")}: + raise ContractDocumentError("extension fixture step modes are invalid") + + +@dataclass(frozen=True, slots=True) +class ExtensionSetupStep: + """Declare one setup command sent before the probe round.""" + + command: str + + def __post_init__(self) -> None: + if type(self.command) is not str or not self.command: + raise ContractDocumentError("extension setup step command is invalid") + + +@dataclass(frozen=True, slots=True) +class ExtensionToolRoundStep: + """Declare the tool and command used for the extension probe.""" + + tool: str + command: str + + def __post_init__(self) -> None: + if self.tool != "bash" or type(self.command) is not str or not self.command: + raise ContractDocumentError("extension tool round step is invalid") + + +@dataclass(frozen=True, slots=True) +class ExtensionCaptureStep: + """Declare which fixture view contributes the extension-face observation.""" + + mode: str + faces: tuple[ExtensionFace, ...] + + def __post_init__(self) -> None: + if self.mode not in {"inside", "outside"}: + raise ContractDocumentError("extension capture step mode is invalid") + if ( + type(self.faces) is not tuple + or any(type(face) is not ExtensionFace for face in self.faces) + or len(set(self.faces)) != len(self.faces) + ): + raise ContractDocumentError("extension capture step faces are invalid") + + +def materialize_symlink_fixture( + *, modes: tuple[str, ...] +) -> ExtensionFixtureStep: + """Declare the inside/outside symlink views for the shared fixture.""" + + return ExtensionFixtureStep(modes) + + +def setup_command(command: str) -> ExtensionSetupStep: + """Declare one extension setup command.""" + + return ExtensionSetupStep(command) + + +def tool_round(*, tool: str, command: str) -> ExtensionToolRoundStep: + """Declare the tool round used to probe extension discovery.""" + + return ExtensionToolRoundStep(tool, command) + + +def capture_extension_face( + *, mode: str, faces: tuple[ExtensionFace, ...] +) -> ExtensionCaptureStep: + """Declare typed extension faces observed in one fixture view.""" + + return ExtensionCaptureStep(mode, faces) + + +ExtensionScenarioStep = ( + ExtensionFixtureStep + | ExtensionSetupStep + | ExtensionToolRoundStep + | ExtensionCaptureStep +) + + +@dataclass(frozen=True, slots=True) +class ExtensionCounterfactualRecipe: + setup_commands: tuple[str, ...] + round_tool: str + round_command: str + paired: bool + dependencies: tuple[tuple[str, DependencyKind], ...] = () + timeout_seconds: int = 60 + + def __post_init__(self) -> None: + if ( + type(self.setup_commands) is not tuple + or not self.setup_commands + or any(type(value) is not str or not value for value in self.setup_commands) + ): + raise ContractDocumentError("extension setup commands are invalid") + if self.round_tool != "bash" or type(self.round_command) is not str or not self.round_command: + raise ContractDocumentError("extension gateway round is invalid") + if type(self.paired) is not bool: + raise ContractDocumentError("extension counterfactual mode is invalid") + if type(self.dependencies) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or type(item[1]) is not DependencyKind + for item in self.dependencies + ): + raise ContractDocumentError("extension dependencies are invalid") + if type(self.timeout_seconds) is not int or self.timeout_seconds <= 0: + raise ContractDocumentError("extension timeout is invalid") + + +def compile_extension_steps( + steps: tuple[ExtensionScenarioStep, ...], + /, + *, + dependencies: tuple[tuple[str, DependencyKind], ...] = (), + timeout_seconds: int = 60, +) -> ExtensionCounterfactualRecipe: + """Compile visible extension steps into the runtime recipe.""" + + if type(steps) is not tuple or not steps or type(steps[0]) is not ExtensionFixtureStep: + raise ContractDocumentError("extension steps must start with one fixture step") + fixture = steps[0] + cursor = 1 + setup_commands: list[str] = [] + while cursor < len(steps) and type(steps[cursor]) is ExtensionSetupStep: + setup_commands.append(steps[cursor].command) + cursor += 1 + if not setup_commands or cursor >= len(steps) or type(steps[cursor]) is not ExtensionToolRoundStep: + raise ContractDocumentError("extension steps require setup commands and one tool round") + tool_round = steps[cursor] + cursor += 1 + captures = steps[cursor:] + if len(captures) != len(fixture.modes) or any( + type(step) is not ExtensionCaptureStep for step in captures + ): + raise ContractDocumentError("extension capture steps do not match fixture modes") + if tuple(step.mode for step in captures) != fixture.modes: + raise ContractDocumentError("extension capture steps must follow fixture modes") + return ExtensionCounterfactualRecipe( + setup_commands=tuple(setup_commands), + round_tool=tool_round.tool, + round_command=tool_round.command, + paired=fixture.modes == ("inside", "outside"), + dependencies=dependencies, + timeout_seconds=timeout_seconds, + ) + + +@dataclass(frozen=True, slots=True) +class ExtensionCounterfactualScenario: + definition: ScenarioDefinition + recipe: ExtensionCounterfactualRecipe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not ExtensionCounterfactualRecipe: + raise ContractDocumentError("extension scenario requires exact typed values") + if self.definition.classification.primary != "extension": + raise ContractDocumentError("extension scenario owner differs from its Harness") + + +@dataclass(frozen=True, slots=True) +class ExtensionRunObservation: + fixture_verified: bool + live: bool + request_count: int + seen_faces: tuple[ExtensionFace, ...] + fixture_error_code: str | None = None + + def __post_init__(self) -> None: + if type(self.fixture_verified) is not bool or type(self.live) is not bool: + raise ContractDocumentError("extension run booleans are invalid") + if type(self.request_count) is not int or self.request_count < 0: + raise ContractDocumentError("extension request count is invalid") + if ( + type(self.seen_faces) is not tuple + or any(type(face) is not ExtensionFace for face in self.seen_faces) + or len(set(self.seen_faces)) != len(self.seen_faces) + ): + raise ContractDocumentError("extension seen faces are invalid") + if self.fixture_error_code is not None and ( + type(self.fixture_error_code) is not str + or not self.fixture_error_code + or len(self.fixture_error_code) > 128 + ): + raise ContractDocumentError("extension fixture error is invalid") + + +@dataclass(frozen=True, slots=True) +class ExtensionCounterfactualObservation: + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + backend_evidence_digest: str + inside: ExtensionRunObservation + outside: ExtensionRunObservation | None + process_tree_clean: bool + workspace_clean: bool + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("extension observation id is invalid") + for name, value in ( + ("plan", self.plan_digest), + ("artifact", self.artifact_digest), + ("backend evidence", self.backend_evidence_digest), + ): + if type(value) is not str or not value.startswith("sha256:") or len(value) != 71: + raise ContractDocumentError(f"extension {name} digest is invalid") + if type(self.artifact_id) is not str or not self.artifact_id: + raise ContractDocumentError("extension artifact id is invalid") + if type(self.inside) is not ExtensionRunObservation or ( + self.outside is not None and type(self.outside) is not ExtensionRunObservation + ): + raise ContractDocumentError("extension run observation is invalid") + if type(self.process_tree_clean) is not bool or type(self.workspace_clean) is not bool: + raise ContractDocumentError("extension cleanup facts are invalid") + + +@dataclass(frozen=True, slots=True) +class ExtensionCounterfactualEvaluation: + scenario_id: str + outcome: ExtensionOutcome + applicability: ExtensionApplicability + reason_code: str + evidence_digest: str + contribution_microunits: int + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("extension evaluation id is invalid") + if type(self.outcome) is not ExtensionOutcome or type(self.applicability) is not ExtensionApplicability: + raise ContractDocumentError("extension evaluation closed value is invalid") + if type(self.reason_code) is not str or not self.reason_code or len(self.reason_code) > 128: + raise ContractDocumentError("extension evaluation reason is invalid") + if type(self.evidence_digest) is not str or not self.evidence_digest.startswith("sha256:") or len(self.evidence_digest) != 71: + raise ContractDocumentError("extension evaluation digest is invalid") + if self.contribution_microunits not in {0, 1_000_000}: + raise ContractDocumentError("extension evaluation contribution is invalid") + + +@runtime_checkable +class ExtensionCounterfactualObserver(Protocol): + def observe(self, scenario: ExtensionCounterfactualScenario, /) -> ExtensionCounterfactualObservation: ... + + +def define_extension_scenario( + scenario_id: str, + recipe: ExtensionCounterfactualRecipe, + role: ScenarioRole, + /, +) -> ExtensionCounterfactualScenario: + if type(scenario_id) is not str or _ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("extension scenario id is invalid") + dependencies = tuple( + sorted( + (DependencyRef(test_id, kind) for test_id, kind in recipe.dependencies), + key=lambda item: (item.scenario_id, item.kind.value), + ) + ) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("extension"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("extension-counterfactual-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("extension-counterfactual-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("extension-counterfactual-observer", "1", ComponentKind.OBSERVER), + ComponentRef("extension-counterfactual-oracle", "1", ComponentKind.ORACLE), + ComponentRef("extension-counterfactual-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return ExtensionCounterfactualScenario(definition, recipe) + + +def evaluation_digest( + scenario: ExtensionCounterfactualScenario, + observation: ExtensionCounterfactualObservation, +) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return "sha256:" + hashlib.sha256( + b"doc2harness.extension-counterfactual-evaluation/1\0" + canonical_json(body) + ).hexdigest() + + +__all__ = [ + "ExtensionApplicability", + "ExtensionCounterfactualEvaluation", + "ExtensionCounterfactualObservation", + "ExtensionCounterfactualObserver", + "ExtensionCounterfactualRecipe", + "ExtensionCounterfactualScenario", + "ExtensionCaptureStep", + "ExtensionFace", + "ExtensionFixtureStep", + "ExtensionOutcome", + "ExtensionRunObservation", + "ExtensionScenarioStep", + "ExtensionSetupStep", + "ExtensionToolRoundStep", + "capture_extension_face", + "compile_extension_steps", + "define_extension_scenario", + "materialize_symlink_fixture", + "setup_command", + "tool_round", + "evaluation_digest", +] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/fixtures.py b/code/src/doc2harness/benchmark/harnesses/extension/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..e588b4ea26237fc8800b28f0ef2904c8ddc043ea --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/fixtures.py @@ -0,0 +1,76 @@ +"""Closed extension definition fixtures for inward and outward symlinks.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from .contracts import ExtensionCounterfactualScenario, ExtensionFace + +WIRE_MARKERS = ( + (ExtensionFace.COMMANDS, "EXTSYM_COMMAND_BODY_9417"), + (ExtensionFace.SKILLS, "EXTSYM_SKILL_BODY_9418"), + (ExtensionFace.PLUGINS, "EXTSYM_PLUGIN_BODY_9419"), +) +EXECUTION_MARKERS = ( + (ExtensionFace.COMMANDS, "EXTSYM_COMMAND_EXEC_9420"), + (ExtensionFace.HOOKS, "EXTSYM_HOOK_EXEC_9421"), + (ExtensionFace.PLUGINS, "EXTSYM_PLUGIN_EXEC_9422"), +) +LINK_PATHS = ( + (ExtensionFace.COMMANDS, "commands/extsymcommand.md"), + (ExtensionFace.SKILLS, "skills/extsymskill/SKILL.md"), + (ExtensionFace.HOOKS, "hooks.json"), + (ExtensionFace.PLUGINS, "plugins/extsympackage/plugin.json"), +) + + +@dataclass(frozen=True, slots=True) +class ExtensionFixturePlan: + scenario_id: str + modes: tuple[str, ...] + link_paths: tuple[tuple[ExtensionFace, str], ...] + wire_markers: tuple[tuple[ExtensionFace, str], ...] + execution_markers: tuple[tuple[ExtensionFace, str], ...] + plan_digest: str + + def __post_init__(self) -> None: + if self.modes not in {("inside",), ("inside", "outside")}: + raise ContractDocumentError("extension fixture modes are invalid") + + +def materialize_extension_fixture( + scenario: ExtensionCounterfactualScenario, + /, +) -> ExtensionFixturePlan: + if type(scenario) is not ExtensionCounterfactualScenario: + raise ContractDocumentError("extension fixture requires an exact scenario") + modes = ("inside", "outside") if scenario.recipe.paired else ("inside",) + body = { + "execution_markers": [(face.value, marker) for face, marker in EXECUTION_MARKERS], + "link_paths": [(face.value, path) for face, path in LINK_PATHS], + "modes": list(modes), + "scenario_id": scenario.definition.scenario_id, + "wire_markers": [(face.value, marker) for face, marker in WIRE_MARKERS], + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.extension-counterfactual-fixture/1\0" + canonical_json(body) + ).hexdigest() + return ExtensionFixturePlan( + scenario.definition.scenario_id, + modes, + LINK_PATHS, + WIRE_MARKERS, + EXECUTION_MARKERS, + digest, + ) + + +__all__ = [ + "EXECUTION_MARKERS", + "LINK_PATHS", + "WIRE_MARKERS", + "ExtensionFixturePlan", + "materialize_extension_fixture", +] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/oracle.py b/code/src/doc2harness/benchmark/harnesses/extension/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..91a6ea8001ed0450359c98379c7f4bf0a92c8072 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/oracle.py @@ -0,0 +1,105 @@ +"""Fail-closed oracle for extension discovery counterfactuals.""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.contracts.primitives import ContractDocumentError +from doc2harness.runtime.errors import RuntimeBoundaryError + +from .contracts import ( + ExtensionApplicability, + ExtensionCounterfactualEvaluation, + ExtensionCounterfactualObservation, + ExtensionCounterfactualObserver, + ExtensionCounterfactualScenario, + ExtensionOutcome, + evaluation_digest, +) + + +def evaluate_extension_counterfactual( + scenario: ExtensionCounterfactualScenario, + observer: ExtensionCounterfactualObserver, + /, +) -> ExtensionCounterfactualEvaluation: + if type(scenario) is not ExtensionCounterfactualScenario: + raise ContractDocumentError("extension oracle requires an exact scenario") + observation = observer.observe(scenario) + if type(observation) is not ExtensionCounterfactualObservation: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-TYPE", + "extension observer returned an invalid evidence type", + ) + if observation.scenario_id != scenario.definition.scenario_id: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-MISMATCH", + "extension evidence belongs to another scenario", + ) + + inside = observation.inside + applicable = ExtensionApplicability.APPLICABLE + outcome = ExtensionOutcome.FAIL + reason = "INSIDE_DISCOVERY_FAILED" + if not inside.fixture_verified: + applicable = ExtensionApplicability.INCONCLUSIVE + reason = "INSIDE_FIXTURE_UNVERIFIED" + elif scenario.definition.role is ScenarioRole.CONTROL: + if inside.live and inside.request_count >= 2 and inside.seen_faces: + outcome = ExtensionOutcome.PASS + reason = "INSIDE_DISCOVERY_OBSERVED" + else: + outside = observation.outside + if outside is None or not outside.fixture_verified: + applicable = ExtensionApplicability.INCONCLUSIVE + reason = "OUTSIDE_FIXTURE_UNVERIFIED" + elif not inside.live or inside.request_count < 2 or not inside.seen_faces: + applicable = ExtensionApplicability.INCONCLUSIVE + reason = "INSIDE_COUNTERFACTUAL_UNOBSERVED" + elif not outside.live or outside.request_count < 2: + applicable = ExtensionApplicability.INCONCLUSIVE + reason = "OUTSIDE_COUNTERFACTUAL_UNOBSERVED" + elif outside.seen_faces: + reason = "OUTSIDE_DEFINITION_ESCAPED" + else: + outcome = ExtensionOutcome.PASS + reason = "OUTSIDE_DEFINITION_FENCED" + + if applicable is ExtensionApplicability.APPLICABLE and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + outcome = ExtensionOutcome.FAIL + reason = "EXECUTION_CLEANUP_FAILED" + contribution = ( + scenario.definition.weight_microunits + if applicable is ExtensionApplicability.APPLICABLE + else 0 + ) + return ExtensionCounterfactualEvaluation( + scenario.definition.scenario_id, + outcome, + applicable, + reason, + evaluation_digest(scenario, observation), + contribution, + ) + + +def judge_extension_observation( + scenario: ExtensionCounterfactualScenario, + observation: ExtensionCounterfactualObservation, + /, +) -> ExtensionCounterfactualEvaluation: + """Project one typed counterfactual observation without running a backend.""" + + class _ObservationAdapter: + def observe( + self, + requested: ExtensionCounterfactualScenario, + /, + ) -> ExtensionCounterfactualObservation: + if requested is not scenario: + raise ContractDocumentError("extension judge scenario identity mismatch") + return observation + + return evaluate_extension_counterfactual(scenario, _ObservationAdapter()) + + +__all__ = ["evaluate_extension_counterfactual", "judge_extension_observation"] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/recipes.py b/code/src/doc2harness/benchmark/harnesses/extension/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..8662761dd6fb4286df71fc7551753329ccd16a49 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/recipes.py @@ -0,0 +1,41 @@ +"""Frozen recipes for extension definition symlink counterfactuals.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole + +from .contracts import ExtensionCounterfactualRecipe, define_extension_scenario + +_SETUP = ("/mode yolo", "/extsymcommand", "/skill extsymskill", "/extsymplugin") +_ALLOW = "echo PERM_LIVE_7755 > live.txt" + +_ROWS = { + "extension_inside_symlink_discovery_control": ( + ExtensionCounterfactualRecipe(_SETUP, "bash", _ALLOW, False), + ScenarioRole.CONTROL, + ), + "extension_definition_symlink_outside_fenced": ( + ExtensionCounterfactualRecipe( + _SETUP, + "bash", + _ALLOW, + True, + (("extension_inside_symlink_discovery_control", DependencyKind.GATE),), + ), + ScenarioRole.TARGET, + ), +} + +SCENARIOS = tuple( + define_extension_scenario(test_id, recipe, role) + for test_id, (recipe, role) in _ROWS.items() +) +_BY_ID = {scenario.definition.scenario_id: scenario for scenario in SCENARIOS} + + +def scenario_by_id(scenario_id: str): + try: + return _BY_ID[scenario_id] + except KeyError as error: + raise KeyError(f"unknown extension counterfactual scenario: {scenario_id}") from error + + +__all__ = ["SCENARIOS", "scenario_by_id"] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93c41de36825e3a18f6170847cef7e6b1e1e058c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/__init__.py @@ -0,0 +1 @@ +"""Thin extension counterfactual scenario declarations.""" diff --git a/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_definition_symlink_outside_fenced.py b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_definition_symlink_outside_fenced.py new file mode 100644 index 0000000000000000000000000000000000000000..418bc3cb29fe96c31780996bc673ac737ce44541 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_definition_symlink_outside_fenced.py @@ -0,0 +1,125 @@ +"""Purpose: verify that an outside-workspace extension symlink is not discovered. +1. Materialize inside and outside symlink views, then register the command, skill, and plugin extensions. +2. Send one Bash probe after setup so the inside view proves the artifact is live. +3. Capture extension faces from both views through typed observations. +4. Pass only when inside discovery succeeds, outside discovery is absent, and cleanup is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from doc2harness.benchmark.harnesses.extension.contracts import ( + ExtensionApplicability, + ExtensionFace, + ExtensionCounterfactualEvaluation, + ExtensionCounterfactualObservation, + ExtensionOutcome, + capture_extension_face, + compile_extension_steps, + evaluation_digest, + define_extension_scenario, + materialize_symlink_fixture, + setup_command, + tool_round, +) +from doc2harness.runtime.errors import RuntimeBoundaryError + + +SCENARIO_ID = "extension_definition_symlink_outside_fenced" +STEPS = ( + materialize_symlink_fixture(modes=("inside", "outside")), + setup_command("/mode yolo"), + setup_command("/extsymcommand"), + setup_command("/skill extsymskill"), + setup_command("/extsymplugin"), + tool_round(tool="bash", command="echo PERM_LIVE_7755 > live.txt"), + capture_extension_face( + mode="inside", + faces=( + ExtensionFace.COMMANDS, + ExtensionFace.SKILLS, + ExtensionFace.HOOKS, + ExtensionFace.PLUGINS, + ), + ), + capture_extension_face(mode="outside", faces=()), +) + +RECIPE = compile_extension_steps( + STEPS, + dependencies=( + ("extension_inside_symlink_discovery_control", DependencyKind.GATE), + ), +) + +SCENARIO = define_extension_scenario( + SCENARIO_ID, + RECIPE, + ScenarioRole.TARGET, +) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge( + observation: ExtensionCounterfactualObservation, + /, +) -> ExtensionCounterfactualEvaluation: + """Judge only typed extension facts; never execute a backend here.""" + + if type(observation) is not ExtensionCounterfactualObservation: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-TYPE", + "extension scenario received an invalid evidence type", + ) + if observation.scenario_id != SCENARIO_ID: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-MISMATCH", + "extension evidence belongs to another scenario", + ) + + inside = observation.inside + applicability = ExtensionApplicability.APPLICABLE + outcome = ExtensionOutcome.FAIL + reason = "INSIDE_DISCOVERY_FAILED" + + if not inside.fixture_verified: + applicability = ExtensionApplicability.INCONCLUSIVE + reason = "INSIDE_FIXTURE_UNVERIFIED" + else: + outside = observation.outside + if outside is None or not outside.fixture_verified: + applicability = ExtensionApplicability.INCONCLUSIVE + reason = "OUTSIDE_FIXTURE_UNVERIFIED" + elif not inside.live or inside.request_count < 2 or not inside.seen_faces: + applicability = ExtensionApplicability.INCONCLUSIVE + reason = "INSIDE_COUNTERFACTUAL_UNOBSERVED" + elif not outside.live or outside.request_count < 2: + applicability = ExtensionApplicability.INCONCLUSIVE + reason = "OUTSIDE_COUNTERFACTUAL_UNOBSERVED" + elif outside.seen_faces: + reason = "OUTSIDE_DEFINITION_ESCAPED" + else: + outcome = ExtensionOutcome.PASS + reason = "OUTSIDE_DEFINITION_FENCED" + + if applicability is ExtensionApplicability.APPLICABLE and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + outcome = ExtensionOutcome.FAIL + reason = "EXECUTION_CLEANUP_FAILED" + + contribution = ( + SCENARIO.definition.weight_microunits + if applicability is ExtensionApplicability.APPLICABLE + else 0 + ) + return ExtensionCounterfactualEvaluation( + SCENARIO_ID, + outcome, + applicability, + reason, + evaluation_digest(SCENARIO, observation), + contribution, + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_inside_symlink_discovery_control.py b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_inside_symlink_discovery_control.py new file mode 100644 index 0000000000000000000000000000000000000000..6a50056ae4a30e275cae15e64f16f239121cdeb0 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/extension/scenarios/extension_inside_symlink_discovery_control.py @@ -0,0 +1,104 @@ +"""Purpose: verify that an in-workspace extension definition is discoverable. +1. Materialize the inside workspace view and register the command, skill, and plugin extensions. +2. Send one Bash probe after setup so the extension runtime is exercised. +3. Capture the discovered extension faces through a typed observation. +4. Pass only when discovery succeeds and process/workspace cleanup is clean. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.extension.contracts import ( + ExtensionApplicability, + ExtensionFace, + ExtensionCounterfactualEvaluation, + ExtensionCounterfactualObservation, + ExtensionOutcome, + capture_extension_face, + compile_extension_steps, + evaluation_digest, + define_extension_scenario, + materialize_symlink_fixture, + setup_command, + tool_round, +) +from doc2harness.runtime.errors import RuntimeBoundaryError + + +SCENARIO_ID = "extension_inside_symlink_discovery_control" +STEPS = ( + materialize_symlink_fixture(modes=("inside",)), + setup_command("/mode yolo"), + setup_command("/extsymcommand"), + setup_command("/skill extsymskill"), + setup_command("/extsymplugin"), + tool_round(tool="bash", command="echo PERM_LIVE_7755 > live.txt"), + capture_extension_face( + mode="inside", + faces=( + ExtensionFace.COMMANDS, + ExtensionFace.SKILLS, + ExtensionFace.HOOKS, + ExtensionFace.PLUGINS, + ), + ), +) + +RECIPE = compile_extension_steps(STEPS) + +SCENARIO = define_extension_scenario( + SCENARIO_ID, + RECIPE, + ScenarioRole.CONTROL, +) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge( + observation: ExtensionCounterfactualObservation, + /, +) -> ExtensionCounterfactualEvaluation: + """Judge only typed extension facts; never execute a backend here.""" + + if type(observation) is not ExtensionCounterfactualObservation: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-TYPE", + "extension scenario received an invalid evidence type", + ) + if observation.scenario_id != SCENARIO_ID: + raise RuntimeBoundaryError( + "SBH-EXTENSION-EVIDENCE-MISMATCH", + "extension evidence belongs to another scenario", + ) + + inside = observation.inside + applicability = ExtensionApplicability.APPLICABLE + outcome = ExtensionOutcome.FAIL + reason = "INSIDE_DISCOVERY_FAILED" + if not inside.fixture_verified: + applicability = ExtensionApplicability.INCONCLUSIVE + reason = "INSIDE_FIXTURE_UNVERIFIED" + elif inside.live and inside.request_count >= 2 and inside.seen_faces: + outcome = ExtensionOutcome.PASS + reason = "INSIDE_DISCOVERY_OBSERVED" + + if applicability is ExtensionApplicability.APPLICABLE and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + outcome = ExtensionOutcome.FAIL + reason = "EXECUTION_CLEANUP_FAILED" + + contribution = ( + SCENARIO.definition.weight_microunits + if applicability is ExtensionApplicability.APPLICABLE + else 0 + ) + return ExtensionCounterfactualEvaluation( + SCENARIO_ID, + outcome, + applicability, + reason, + evaluation_digest(SCENARIO, observation), + contribution, + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/__init__.py b/code/src/doc2harness/benchmark/harnesses/file/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd239f8a80a3155db2ca7e2594830774a567426 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/__init__.py @@ -0,0 +1,22 @@ +"""Child-process file-tool Harness public surface.""" +from doc2harness.benchmark.harnesses.file.contracts import ( + build_file_tool_evaluation, + capture_fact, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) + +__all__ = [ + "build_file_tool_evaluation", + "capture_fact", + "capture_model_text", + "compile_file_tool_steps", + "setup_command", + "tool_round", + "validate_file_tool_observation", + "write_fixture", +] diff --git a/code/src/doc2harness/benchmark/harnesses/file/adapter.py b/code/src/doc2harness/benchmark/harnesses/file/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..576dc531b7c4e236e02b84ab53856416b523b90c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/adapter.py @@ -0,0 +1,77 @@ +"""Execution boundary for the file-tool child Harness layer.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.file.contracts import FileToolScenario, FrozenValue +from doc2harness.benchmark.harnesses.file.fixtures import ( + FileToolFixturePlan, + materialize_file_tool_fixture, +) +from doc2harness.benchmark.harnesses.file.gateway import ( + FileToolGatewayTurn, + build_file_tool_gateway_plan, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class FileToolExecutionPlan: + scenario_id: str + fixture: FileToolFixturePlan + gateway_turns: tuple[FileToolGatewayTurn, ...] + setup_commands: tuple[str, ...] + timeout_seconds: int + plan_digest: str + execution_parameters: tuple[tuple[str, FrozenValue], ...] = () + + +def build_file_tool_execution_plan( + scenario: FileToolScenario, / +) -> FileToolExecutionPlan: + if type(scenario) is not FileToolScenario: + raise ContractDocumentError("file-tool execution requires an exact scenario") + fixture = materialize_file_tool_fixture(scenario) + turns = build_file_tool_gateway_plan(scenario) + body = { + "fixture_digest": fixture.plan_digest, + "gateway": [ + [ + { + "aliases_explicit": call.aliases_explicit, + "arguments": list(call.arguments), + "arguments_nested": call.arguments_nested, + "tool_names": list(call.tool_names), + } + for call in turn.tool_calls + ] + for turn in turns + ], + "scenario_id": scenario.definition.scenario_id, + "setup_commands": list(scenario.recipe.setup_commands), + "timeout_seconds": scenario.recipe.timeout_seconds, + } + if scenario.recipe.execution_parameters: + body["execution_parameters"] = list(scenario.recipe.execution_parameters) + digest = ( + "sha256:" + + hashlib.sha256( + b"doc2harness.file-tool-child-plan/1\0" + canonical_json(body) + ).hexdigest() + ) + return FileToolExecutionPlan( + scenario.definition.scenario_id, + fixture, + turns, + scenario.recipe.setup_commands, + scenario.recipe.timeout_seconds, + digest, + scenario.recipe.execution_parameters, + ) + + +__all__ = [ + "FileToolExecutionPlan", + "build_file_tool_execution_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/file/catalog.toml b/code/src/doc2harness/benchmark/harnesses/file/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e1be12e51083322f2c22bd1f3f6eff2d77fbfe8 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/catalog.toml @@ -0,0 +1,22 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "file" +resource = "benchmark/harnesses/file/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.file.scenarios.file_symlink_inside_still_readable_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_finds_inside_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_truncation_keeps_sorted_end", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_default_mode_returns_path_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_finds_needle_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_head_limit_zero_not_unlimited", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_type_filter_ignored", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.memory_get_abs_path_escapes_workspace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_cell_isolation", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_delete_keeps_neighbors", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.p32_ctl_memory_get_reads_inside_workspace", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_char_device_bounded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_regular_file_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.read_via_symlink_outside_workspace_bounded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.rewind_restores_edited_file", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.symlink_to_outside_target_readable_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.file.scenarios.undo_reverts_overwrite_control", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/file/contracts.py b/code/src/doc2harness/benchmark/harnesses/file/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..82c136342c277b98087fb92d5d0e01c0b1be55e5 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/contracts.py @@ -0,0 +1,688 @@ +"""Closed declarations and observations for child-process file-tool scenarios.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum +from typing import TypeAlias + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +JsonAtom: TypeAlias = str | int | bool | None +FrozenValue: TypeAlias = ( + JsonAtom | tuple["FrozenValue", ...] | tuple[tuple[str, "FrozenValue"], ...] +) + + +class FileToolOracleProfile(str, Enum): + TEXT_RULES = "TEXT_RULES" + TRANSITION_EXACT = "TRANSITION_EXACT" + REWIND_RESTORES = "REWIND_RESTORES" + NOTEBOOK_ISOLATED = "NOTEBOOK_ISOLATED" + MEMORY_EVENT = "MEMORY_EVENT" + + +class FileToolOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class FileToolApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +@dataclass(frozen=True, slots=True) +class FileToolJudgement: + """The small, typed result returned by a scenario-local judge.""" + + outcome: FileToolOutcome + applicability: FileToolApplicability + reason_code: str + + def __post_init__(self) -> None: + if type(self.outcome) is not FileToolOutcome: + raise ContractDocumentError("file-tool judgement outcome is invalid") + if type(self.applicability) is not FileToolApplicability: + raise ContractDocumentError("file-tool judgement applicability is invalid") + if type(self.reason_code) is not str or not self.reason_code: + raise ContractDocumentError("file-tool judgement reason is invalid") + + +def _text_tuple(value: object, label: str) -> tuple[str, ...]: + if type(value) is not tuple or any( + type(item) is not str or not item for item in value + ): + raise ContractDocumentError(f"file-tool {label} is invalid") + return value + + +def _validate_frozen(value: FrozenValue, depth: int = 0) -> None: + if depth > 16: + raise ContractDocumentError("file-tool frozen value nesting is excessive") + if value is None or type(value) in {str, int, bool}: + if type(value) is str and len(value) > 8 * 1024 * 1024: + raise ContractDocumentError("file-tool frozen text is excessive") + return + if type(value) is not tuple or len(value) > 4096: + raise ContractDocumentError("file-tool frozen value is invalid") + for item in value: + if type(item) is tuple and len(item) == 2 and type(item[0]) is str: + _validate_frozen(item[1], depth + 1) + else: + _validate_frozen(item, depth + 1) + + +@dataclass(frozen=True, slots=True) +class FileToolCall: + tool_names: tuple[str, ...] + arguments: tuple[tuple[str, FrozenValue], ...] + aliases_explicit: bool + arguments_nested: bool + + def __post_init__(self) -> None: + _text_tuple(self.tool_names, "tool names") + if len(set(self.tool_names)) != len(self.tool_names): + raise ContractDocumentError("file-tool aliases must be unique") + if type(self.arguments) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str + for item in self.arguments + ): + raise ContractDocumentError("file-tool arguments are invalid") + if len({item[0] for item in self.arguments}) != len(self.arguments): + raise ContractDocumentError("file-tool argument names must be unique") + for _, value in self.arguments: + _validate_frozen(value) + if ( + type(self.aliases_explicit) is not bool + or type(self.arguments_nested) is not bool + ): + raise ContractDocumentError("file-tool call encoding policy is invalid") + + +@dataclass(frozen=True, slots=True) +class FileToolFixtureStep: + """Declare one path-independent file fixture for a scenario.""" + + path: str + content: str + + def __post_init__(self) -> None: + if ( + type(self.path) is not str + or not self.path + or self.path.startswith("/") + or ".." in self.path.split("/") + or type(self.content) is not str + ): + raise ContractDocumentError("file-tool fixture step is invalid") + + +@dataclass(frozen=True, slots=True) +class FileToolSetupStep: + """Declare one setup command sent before the tool rounds.""" + + command: str + + def __post_init__(self) -> None: + if type(self.command) is not str or not self.command: + raise ContractDocumentError("file-tool setup step is invalid") + + +@dataclass(frozen=True, slots=True) +class FileToolRoundStep: + """Declare one tool call and its one-based gateway turn.""" + + turn: int + call: FileToolCall + + def __post_init__(self) -> None: + if type(self.turn) is not int or self.turn < 1 or type(self.call) is not FileToolCall: + raise ContractDocumentError("file-tool round step is invalid") + + +@dataclass(frozen=True, slots=True) +class FileToolCaptureStep: + """Declare the model-text rules used by a scenario-local judge.""" + + source: str + required: tuple[str, ...] + forbidden: tuple[str, ...] = () + min_requests: int = 1 + required_regex: str | None = None + forbidden_regex: str | None = None + stderr_forbidden: tuple[str, ...] = () + + def __post_init__(self) -> None: + if type(self.source) is not str or not self.source: + raise ContractDocumentError("file-tool capture source is invalid") + _text_tuple(self.required, "capture required rules") + _text_tuple(self.forbidden, "capture forbidden rules") + _text_tuple(self.stderr_forbidden, "capture stderr rules") + if type(self.min_requests) is not int or self.min_requests < 0: + raise ContractDocumentError("file-tool capture request bound is invalid") + for name, value in ( + ("required regex", self.required_regex), + ("forbidden regex", self.forbidden_regex), + ): + if value is not None and (type(value) is not str or not value): + raise ContractDocumentError(f"file-tool {name} is invalid") + + +FileToolScenarioStep = ( + FileToolFixtureStep + | FileToolSetupStep + | FileToolRoundStep + | FileToolCaptureStep +) + + +def write_fixture(path: str, content: str) -> FileToolFixtureStep: + """Declare one seeded workspace file.""" + + return FileToolFixtureStep(path, content) + + +def setup_command(command: str) -> FileToolSetupStep: + """Declare one setup command.""" + + return FileToolSetupStep(command) + + +def tool_round( + tool: str | tuple[str, ...], + *, + turn: int, + aliases_explicit: bool = False, + arguments_nested: bool = False, + **arguments: FrozenValue, +) -> FileToolRoundStep: + """Declare a tool call without exposing the internal tuple encoding.""" + + names = (tool,) if type(tool) is str else tool + return FileToolRoundStep( + turn, + FileToolCall( + names, + tuple(arguments.items()), + aliases_explicit, + arguments_nested, + ), + ) + + +def capture_model_text( + *, + required: tuple[str, ...], + forbidden: tuple[str, ...] = (), + min_requests: int = 1, + required_regex: str | None = None, + forbidden_regex: str | None = None, + stderr_forbidden: tuple[str, ...] = (), +) -> FileToolCaptureStep: + """Declare bounded text facts consumed by a local judge.""" + + return capture_fact( + "model_text", + required=required, + forbidden=forbidden, + min_requests=min_requests, + required_regex=required_regex, + forbidden_regex=forbidden_regex, + stderr_forbidden=stderr_forbidden, + ) + + +def capture_fact( + source: str, + *, + required: tuple[str, ...], + forbidden: tuple[str, ...] = (), + min_requests: int = 1, + required_regex: str | None = None, + forbidden_regex: str | None = None, + stderr_forbidden: tuple[str, ...] = (), +) -> FileToolCaptureStep: + """Declare bounded rules against one named observation fact.""" + + return FileToolCaptureStep( + source, + required, + forbidden, + min_requests, + required_regex, + forbidden_regex, + stderr_forbidden, + ) + + +@dataclass(frozen=True, slots=True) +class FileToolRecipe: + case_kind: str + declared_tools: tuple[str, ...] + setup_commands: tuple[str, ...] + seed_files: tuple[tuple[str, str], ...] + rounds: tuple[tuple[FileToolCall, ...], ...] + oracle_profile: FileToolOracleProfile + oracle_parameters: tuple[tuple[str, FrozenValue], ...] + dependencies: tuple[tuple[str, DependencyKind], ...] = () + blocking: bool = False + timeout_seconds: int = 90 + execution_parameters: tuple[tuple[str, FrozenValue], ...] = () + bind_oracle_parameters: bool = False + + def __post_init__(self) -> None: + if type(self.case_kind) is not str or not self.case_kind: + raise ContractDocumentError("file-tool case kind is invalid") + _text_tuple(self.declared_tools, "declared tools") + _text_tuple(self.setup_commands, "setup commands") + if type(self.seed_files) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or item[0].startswith("/") + or ".." in item[0].split("/") + or type(item[1]) is not str + for item in self.seed_files + ): + raise ContractDocumentError("file-tool seeds are invalid") + if type(self.rounds) is not tuple or any( + type(turn) is not tuple + or not turn + or any(type(call) is not FileToolCall for call in turn) + for turn in self.rounds + ): + raise ContractDocumentError("file-tool rounds are invalid") + if type(self.execution_parameters) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str + for item in self.execution_parameters + ): + raise ContractDocumentError("file-tool execution parameters are invalid") + if len({item[0] for item in self.execution_parameters}) != len( + self.execution_parameters + ): + raise ContractDocumentError( + "file-tool execution parameter names must be unique" + ) + for _, value in self.execution_parameters: + _validate_frozen(value) + if not self.rounds and not dict(self.execution_parameters).get("phase1_rounds"): + raise ContractDocumentError("file-tool rounds are invalid") + if type(self.oracle_profile) is not FileToolOracleProfile: + raise ContractDocumentError("file-tool oracle profile is invalid") + if type(self.oracle_parameters) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str + for item in self.oracle_parameters + ): + raise ContractDocumentError("file-tool oracle parameters are invalid") + for _, value in self.oracle_parameters: + _validate_frozen(value) + if type(self.dependencies) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or _ID.fullmatch(item[0]) is None + or type(item[1]) is not DependencyKind + for item in self.dependencies + ): + raise ContractDocumentError("file-tool dependency id is invalid") + if ( + type(self.timeout_seconds) is not int + or not 1 <= self.timeout_seconds <= 900 + ): + raise ContractDocumentError("file-tool timeout is invalid") + if type(self.blocking) is not bool: + raise ContractDocumentError("file-tool blocking policy is invalid") + if type(self.bind_oracle_parameters) is not bool: + raise ContractDocumentError("file-tool oracle binding policy is invalid") + + +def compile_file_tool_steps( + steps: tuple[FileToolScenarioStep, ...], + /, + *, + case_kind: str, + declared_tools: tuple[str, ...], + oracle_profile: FileToolOracleProfile, + dependencies: tuple[tuple[str, DependencyKind], ...] = (), + blocking: bool = False, + timeout_seconds: int = 90, + execution_parameters: tuple[tuple[str, FrozenValue], ...] = (), + bind_oracle_parameters: bool = False, +) -> FileToolRecipe: + """Compile readable fixture/setup/round/capture steps into a recipe.""" + + if type(steps) is not tuple or not steps: + raise ContractDocumentError("file-tool steps must be a non-empty tuple") + cursor = 0 + seed_files: list[tuple[str, str]] = [] + while cursor < len(steps) and type(steps[cursor]) is FileToolFixtureStep: + fixture = steps[cursor] + seed_files.append((fixture.path, fixture.content)) + cursor += 1 + if len({path for path, _ in seed_files}) != len(seed_files): + raise ContractDocumentError("file-tool fixture paths must be unique") + + setup_commands: list[str] = [] + while cursor < len(steps) and type(steps[cursor]) is FileToolSetupStep: + setup_commands.append(steps[cursor].command) + cursor += 1 + + round_steps: list[FileToolRoundStep] = [] + while cursor < len(steps) and type(steps[cursor]) is FileToolRoundStep: + round_steps.append(steps[cursor]) + cursor += 1 + if not round_steps: + raise ContractDocumentError("file-tool steps require at least one round") + rounds: list[list[FileToolCall]] = [] + expected_turn = 1 + for step in round_steps: + if step.turn < expected_turn or step.turn > expected_turn + 1: + raise ContractDocumentError("file-tool round turns are not contiguous") + if step.turn == expected_turn + 1: + rounds.append([]) + expected_turn += 1 + if not rounds: + rounds.append([]) + rounds[-1].append(step.call) + + captures = steps[cursor:] + if len(captures) != 1 or type(captures[0]) is not FileToolCaptureStep: + raise ContractDocumentError("file-tool steps require one final capture") + capture = captures[0] + oracle_parameters: list[tuple[str, FrozenValue]] = [ + ("source", capture.source), + ("required", capture.required), + ("forbidden", capture.forbidden), + ("min_requests", capture.min_requests), + ] + optional_parameters = ( + ("required_regex", capture.required_regex), + ("forbidden_regex", capture.forbidden_regex), + ("stderr_forbidden", capture.stderr_forbidden), + ) + oracle_parameters.extend( + (name, value) + for name, value in optional_parameters + if value is not None and (name != "stderr_forbidden" or value) + ) + return FileToolRecipe( + case_kind, + declared_tools, + tuple(setup_commands), + tuple(seed_files), + tuple(tuple(turn) for turn in rounds), + oracle_profile, + tuple(oracle_parameters), + dependencies, + blocking, + timeout_seconds, + execution_parameters, + bind_oracle_parameters, + ) + + +@dataclass(frozen=True, slots=True) +class FileToolScenario: + definition: ScenarioDefinition + recipe: FileToolRecipe + + def __post_init__(self) -> None: + if ( + type(self.definition) is not ScenarioDefinition + or type(self.recipe) is not FileToolRecipe + ): + raise ContractDocumentError( + "file-tool scenario requires exact typed values" + ) + if self.definition.classification.primary != "file": + raise ContractDocumentError( + "file-tool scenario owner differs from its Harness layer" + ) + + +@dataclass(frozen=True, slots=True) +class FileToolRawObservation: + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + request_count: int + advertised_tools: tuple[str, ...] + live: bool + target_content: str | None + secondary_target_content: str | None + model_text: str + stderr_text: str + empty_tool_result: bool | None + process_tree_clean: bool + gateway_clean: bool + workspace_clean: bool + timed_out: bool + backend_evidence_digest: str + target_tool_result: str = "" + round_target_tool_results: tuple[str, ...] = () + facts: tuple[tuple[str, FrozenValue], ...] = () + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("file-tool observation id is invalid") + for digest in ( + self.plan_digest, + self.artifact_digest, + self.backend_evidence_digest, + ): + if ( + type(digest) is not str + or not digest.startswith("sha256:") + or len(digest) != 71 + ): + raise ContractDocumentError("file-tool observation digest is invalid") + if type(self.artifact_id) is not str or _ID.fullmatch(self.artifact_id) is None: + raise ContractDocumentError("file-tool artifact id is invalid") + if type(self.request_count) is not int or not 0 <= self.request_count <= 4096: + raise ContractDocumentError("file-tool request count is invalid") + _text_tuple(self.advertised_tools, "advertised tools") + for value in ( + self.live, + self.process_tree_clean, + self.gateway_clean, + self.workspace_clean, + self.timed_out, + ): + if type(value) is not bool: + raise ContractDocumentError("file-tool boolean fact is invalid") + for value in (self.target_content, self.secondary_target_content): + if value is not None and type(value) is not str: + raise ContractDocumentError("file-tool target content is invalid") + if type(self.model_text) is not str or type(self.stderr_text) is not str: + raise ContractDocumentError("file-tool text fact is invalid") + if type(self.target_tool_result) is not str: + raise ContractDocumentError("file-tool target-result fact is invalid") + _text_tuple(self.round_target_tool_results, "round target results") + if type(self.facts) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str + for item in self.facts + ): + raise ContractDocumentError("file-tool evidence facts are invalid") + if len({item[0] for item in self.facts}) != len(self.facts): + raise ContractDocumentError("file-tool evidence fact names must be unique") + for _, value in self.facts: + _validate_frozen(value) + if ( + self.empty_tool_result is not None + and type(self.empty_tool_result) is not bool + ): + raise ContractDocumentError("file-tool empty-result fact is invalid") + + +@dataclass(frozen=True, slots=True) +class FileToolEvaluation: + scenario_id: str + outcome: FileToolOutcome + applicability: FileToolApplicability + reason_code: str + evidence_digest: str + contribution_microunits: int + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("file-tool evaluation id is invalid") + if ( + type(self.outcome) is not FileToolOutcome + or type(self.applicability) is not FileToolApplicability + ): + raise ContractDocumentError("file-tool evaluation closed value is invalid") + if ( + type(self.reason_code) is not str + or not self.reason_code + or len(self.reason_code) > 128 + ): + raise ContractDocumentError("file-tool evaluation reason is invalid") + if ( + type(self.evidence_digest) is not str + or not self.evidence_digest.startswith("sha256:") + or len(self.evidence_digest) != 71 + ): + raise ContractDocumentError("file-tool evaluation digest is invalid") + if self.contribution_microunits not in {0, 1_000_000}: + raise ContractDocumentError("file-tool evaluation contribution is invalid") + + +def define_file_tool_scenario( + scenario_id: str, recipe: FileToolRecipe, role: ScenarioRole, / +) -> FileToolScenario: + if type(scenario_id) is not str or _ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("file-tool scenario id is invalid") + dependencies = tuple( + sorted( + (DependencyRef(item, kind) for item, kind in recipe.dependencies), + key=lambda item: (item.scenario_id, item.kind.value), + ) + ) + oracle_component_id = "file-tool-child-oracle" + if recipe.bind_oracle_parameters: + oracle_binding = hashlib.sha256( + b"doc2harness.file-tool-child-oracle-binding/1\0" + + canonical_json( + { + "parameters": list(recipe.oracle_parameters), + "profile": recipe.oracle_profile.value, + } + ) + ).hexdigest() + oracle_component_id += "-" + oracle_binding + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("file"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("file-tool-child-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("file-tool-child-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("file-tool-child-observer", "1", ComponentKind.OBSERVER), + ComponentRef(oracle_component_id, "1", ComponentKind.ORACLE), + ComponentRef("file-tool-child-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return FileToolScenario(definition, recipe) + + +def evaluation_digest( + scenario: FileToolScenario, observation: FileToolRawObservation +) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return ( + "sha256:" + + hashlib.sha256( + b"doc2harness.file-tool-child-evaluation/1\0" + canonical_json(body) + ).hexdigest() + ) + + +def validate_file_tool_observation( + scenario: FileToolScenario, observation: FileToolRawObservation, / +) -> None: + """Validate the typed boundary before a scenario-local judge runs.""" + + if type(scenario) is not FileToolScenario: + raise ContractDocumentError("file-tool judge requires an exact scenario") + if type(observation) is not FileToolRawObservation: + raise ContractDocumentError("file-tool judge requires typed observation") + if observation.scenario_id != scenario.definition.scenario_id: + raise ContractDocumentError("file-tool observation belongs to another scenario") + + +def build_file_tool_evaluation( + scenario: FileToolScenario, + observation: FileToolRawObservation, + judgement: FileToolJudgement, + /, +) -> FileToolEvaluation: + """Build the evaluation from a local typed judgement.""" + + validate_file_tool_observation(scenario, observation) + if type(judgement) is not FileToolJudgement: + raise ContractDocumentError("file-tool judge returned an invalid judgement") + contribution = 1_000_000 if ( + scenario.definition.role is ScenarioRole.TARGET + and judgement.applicability is FileToolApplicability.APPLICABLE + and judgement.outcome is FileToolOutcome.PASS + ) else 0 + return FileToolEvaluation( + scenario.definition.scenario_id, + judgement.outcome, + judgement.applicability, + judgement.reason_code, + evaluation_digest(scenario, observation), + contribution, + ) + + +__all__ = [ + name + for name in globals() + if name.startswith("FileTool") + or name + in { + "build_file_tool_evaluation", + "capture_fact", + "capture_model_text", + "compile_file_tool_steps", + "define_file_tool_scenario", + "evaluation_digest", + "python_ast_digest", + "setup_command", + "tool_round", + "validate_file_tool_observation", + "write_fixture", + } +] diff --git a/code/src/doc2harness/benchmark/harnesses/file/fixtures.py b/code/src/doc2harness/benchmark/harnesses/file/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..d011fa0334d3ddaccb0e2da353d15e88036c24a9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/fixtures.py @@ -0,0 +1,38 @@ +"""Deterministic fixture materialization for file-tool child scenarios.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolScenario, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class FileToolFixturePlan: + scenario_id: str + seed_files: tuple[tuple[str, str], ...] + plan_digest: str + + +def materialize_file_tool_fixture(scenario: FileToolScenario, /) -> FileToolFixturePlan: + if type(scenario) is not FileToolScenario: + raise ContractDocumentError("file-tool fixture requires an exact scenario") + body = { + "scenario_id": scenario.definition.scenario_id, + "seed_files": [list(x) for x in scenario.recipe.seed_files], + } + digest = ( + "sha256:" + + hashlib.sha256( + b"doc2harness.file-tool-child-fixture/1\0" + canonical_json(body) + ).hexdigest() + ) + return FileToolFixturePlan( + scenario.definition.scenario_id, scenario.recipe.seed_files, digest + ) + + +__all__ = ["FileToolFixturePlan", "materialize_file_tool_fixture"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/gateway.py b/code/src/doc2harness/benchmark/harnesses/file/gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..4b58fec9a7c6856fdf65406d5fa67c5f9f7b17c0 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/gateway.py @@ -0,0 +1,25 @@ +"""Deterministic mock-gateway plan for file-tool child probes.""" + +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolCall, + FileToolScenario, +) +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class FileToolGatewayTurn: + tool_calls: tuple[FileToolCall, ...] + + +def build_file_tool_gateway_plan( + scenario: FileToolScenario, / +) -> tuple[FileToolGatewayTurn, ...]: + if type(scenario) is not FileToolScenario: + raise ContractDocumentError("file-tool gateway requires an exact scenario") + return tuple(FileToolGatewayTurn(turn) for turn in scenario.recipe.rounds) + + +__all__ = ["FileToolGatewayTurn", "build_file_tool_gateway_plan"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/recipes.py b/code/src/doc2harness/benchmark/harnesses/file/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..55dec0f10125c4fdff4c6c5a7aba0f52f241c472 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/recipes.py @@ -0,0 +1,629 @@ +"""Frozen recipes for child-process file-tool scenarios.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolCall, + FileToolOracleProfile, + FileToolRecipe, + define_file_tool_scenario, +) + +_ROWS = { + "glob_finds_inside_control": { + "case_kind": "control", + "declared_tools": ("glob",), + "setup_commands": ("/mode yolo",), + "seed_files": (("inside_ok.py", "x\n"),), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("glob",), (("pattern", "**/*.py"),), False, True), + (("glob",), (("pattern", "*.py"),), False, True), + ), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("inside_ok",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": False, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "grep_finds_needle_control": { + "case_kind": "control", + "declared_tools": ("grep",), + "setup_commands": ("/mode yolo",), + "seed_files": (("plain_gi.txt", "NEEDLE_GI_7731 here\n"),), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("grep",), (("pattern", "NEEDLE_GI_7731"), ("path", ".")), False, True), + ), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("plain_gi.txt",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": False, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "grep_type_filter_ignored": { + "case_kind": "reject", + "declared_tools": ("grep",), + "setup_commands": ("/mode yolo",), + "seed_files": ( + ("gt_hit.py", "NEEDLE_GTYPE_7731 python\n"), + ("gt_hit.txt", "NEEDLE_GTYPE_7731 text\n"), + ), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("grep",), (("pattern", "NEEDLE_GTYPE_7731"), ("path", "."), ("type", "py")), False, True), + ), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("gt_hit.py",)), + ("forbidden", ("gt_hit.txt",)), + ("min_requests", 2), + ), + "dependencies": (("grep_finds_needle_control", "GATE"),), + "blocking": False, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "undo_reverts_overwrite_control": { + "case_kind": "control", + "declared_tools": ("write",), + "setup_commands": ("/mode yolo",), + "seed_files": (("tgt.txt", "ORIG_PERM_0001\n"),), + "rounds": (), + "oracle_profile": "TRANSITION_EXACT", + "oracle_parameters": ( + ( + "expected", + ( + ("phase1_tgt", "OVR_BODY_7755\n"), + ("after_mid1_tgt", "ORIG_PERM_0001\n"), + ("tgt", "ORIG_PERM_0001\n"), + ), + ), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": False, + "role": "CONTROL", + "execution_parameters": ( + ( + "phase1_rounds", + ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("read",), (("file_path", "tgt.txt"),), False, True), + ), + ((("write",), (("file_path", "tgt.txt"), ("content", "OVR_BODY_7755\n")), False, True),), + ), + ), + ("mid_slash", ("/undo",)), + ("phase2_rounds", (((("bash",), (("command", "echo POSTUNDO_7755"),), False, False),),)), + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + "bind_oracle_parameters": True, + }, + "rewind_restores_edited_file": { + "case_kind": "reject", + "declared_tools": ("write",), + "setup_commands": ("/mode yolo",), + "seed_files": (("tgt.txt", "ORIG_PERM_0001\n"),), + "rounds": (), + "oracle_profile": "REWIND_RESTORES", + "oracle_parameters": (("expected", "ORIG_PERM_0001\n"), ("min_requests", 2)), + "dependencies": (("undo_reverts_overwrite_control", "GATE"),), + "blocking": False, + "role": "TARGET", + "execution_parameters": ( + ( + "phase1_rounds", + ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("read",), (("file_path", "tgt.txt"),), False, True), + ), + ((("write",), (("file_path", "tgt.txt"), ("content", "RWOVR_8821\n")), False, True),), + ), + ), + ("mid_slash", ("/rewind 1", "/rewind 0", "/rewind")), + ("phase2_rounds", (((("bash",), (("command", "echo POSTRW_8821"),), False, False),),)), + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + "bind_oracle_parameters": True, + }, +} +_ROWS.update( + { + "notebook_edit_cell_isolation": { + "case_kind": "reject", + "declared_tools": ("notebook_edit",), + "setup_commands": ("/mode yolo",), + "seed_files": ( + ( + "nb.ipynb", + '{"cells": [{"cell_type": "markdown", "metadata": {"tags": ["KEEP0"], "nested": {"k": 0}}, "source": ["CELL0_KEEP\\n"]}, {"cell_type": "code", "metadata": {"target": true}, "source": ["CELL1_OLD\\n"], "outputs": [], "execution_count": null}, {"cell_type": "code", "metadata": {"tags": ["KEEP2"], "nested": {"k": 2}}, "source": ["CELL2_KEEP\\n"], "outputs": [{"output_type": "stream", "name": "stdout", "text": ["KEEP2_OUTPUT\\n"]}], "execution_count": 42}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}', + ), + ), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("read",), (("file_path", "nb.ipynb"),), False, True), + ), + ( + ( + ("notebook_edit", "notebook-edit"), + ( + ("file_path", "nb.ipynb"), + ("cell_index", 1), + ("mode", "replace"), + ("source", "CELL1_NEW"), + ), + True, + True, + ), + ), + ((("bash",), (("command", "cat nb.ipynb"),), False, False),), + ), + "oracle_profile": "NOTEBOOK_ISOLATED", + "oracle_parameters": ( + ( + "expected_cell0_json", + '{"cell_type":"markdown","metadata":{"nested":{"k":0},"tags":["KEEP0"]},"source":["CELL0_KEEP\\n"]}', + ), + ( + "expected_cell2_json", + '{"cell_type":"code","execution_count":42,"metadata":{"nested":{"k":2},"tags":["KEEP2"]},"outputs":[{"name":"stdout","output_type":"stream","text":["KEEP2_OUTPUT\\n"]}],"source":["CELL2_KEEP\\n"]}', + ), + ("new_marker", "CELL1_NEW"), + ("old_marker", "CELL1_OLD"), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "glob_truncation_keeps_sorted_end": { + "case_kind": "reject", + "declared_tools": ("glob",), + "setup_commands": ("/mode yolo",), + "seed_files": (), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("bash",), + ( + ( + "command", + "mkdir -p gord && python3 -c \"import pathlib;pathlib.Path('gord/OLD' + 'EST_7755.ordx').write_text('x')\" && touch -t 200001010000 gord/OLD*_7755.ordx && python3 -c \"import os\nfor i in range(800): open('gord/n%d.ordx' % i,'w').write('x')\" && echo ORD_SEEDED_7755", + ), + ), + False, + False, + ), + ), + ((("glob",), (("pattern", "**/*.ordx"),), False, True),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", (".ordx",)), + ("forbidden", ("OLDEST_7755",)), + ("min_requests", 2), + ), + "dependencies": (("glob_finds_inside_control", "GATE"),), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + } +) +_ROWS.update( + { + "notebook_edit_delete_keeps_neighbors": { + "case_kind": "reject", + "declared_tools": ("notebook_edit",), + "setup_commands": ("/mode yolo",), + "seed_files": ( + ( + "nb.ipynb", + '{"cells": [{"cell_type": "markdown", "metadata": {"tags": ["KEEP0"], "nested": {"k": 0}}, "source": ["CELL0_KEEP\\n"]}, {"cell_type": "code", "metadata": {"target": true}, "source": ["CELL1_OLD\\n"], "outputs": [], "execution_count": null}, {"cell_type": "code", "metadata": {"tags": ["KEEP2"], "nested": {"k": 2}}, "source": ["CELL2_KEEP\\n"], "outputs": [{"output_type": "stream", "name": "stdout", "text": ["KEEP2_OUTPUT\\n"]}], "execution_count": 42}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}', + ), + ), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + (("read",), (("file_path", "nb.ipynb"),), False, True), + ), + ( + ( + ("notebook_edit", "notebook-edit"), + (("file_path", "nb.ipynb"), ("cell_index", 1), ("mode", "delete")), + True, + True, + ), + ), + ( + ( + ("bash",), + ( + ( + "command", + "python3 -c \"import json;print('NBCELLS' + '_' + str(len(json.load(open('nb.ipynb'))['cells'])))\" && echo NBDEL_DONE_7755", + ), + ), + False, + False, + ), + ), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("NBCELLS_2",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (("notebook_edit_cell_isolation", "REQUIREMENT"),), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "symlink_to_outside_target_readable_control": { + "case_kind": "control", + "declared_tools": ("bash",), + "setup_commands": ("/mode yolo",), + "seed_files": (), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("bash",), + ( + ( + "command", + "printf 'OUTSIDE_ORIG_7731\\n' > /tmp/outside_9931.txt && ln -sf /tmp/outside_9931.txt link_9931.txt && echo SYMCTL_DONE_7755", + ), + ), + False, + False, + ), + ), + ( + ( + ("bash",), + ( + ( + "command", + "python3 -c \"import os; p='link_9931.txt'; print('SYM'+'LINK_%d' % os.path.islink(p)); print('SYM'+'REAL_%d' % (os.path.realpath(p)=='/tmp/outside_9931.txt')); print('SYM'+'BYTE_%d' % (open(p,'rb').read()==b'OUTSIDE_ORIG_7731\\n'))\"", + ), + ), + False, + False, + ), + ), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("SYMLINK_1", "SYMREAL_1", "SYMBYTE_1")), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": True, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "p32_ctl_memory_get_reads_inside_workspace": { + "case_kind": "control", + "declared_tools": ("memory_get",), + "setup_commands": ("/mode yolo",), + "seed_files": (("MEMORY.md", "INSIDEMEM_7732\n"),), + "rounds": (), + "oracle_profile": "MEMORY_EVENT", + "oracle_parameters": (("marker", "INSIDEMEM_7732"), ("min_requests", 2)), + "dependencies": (), + "blocking": True, + "role": "CONTROL", + "execution_parameters": ( + ( + "phase1_rounds", + (((("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False),),), + ), + ( + "phase2_rounds", + ( + ((("memory_get", "memory-get"), (("path", "MEMORY.md"),), True, True),), + ((("bash",), (("command", "echo P32A_DONE_7755"),), False, False),), + ), + ), + ("mid_slash", ("/help",)), + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + "bind_oracle_parameters": True, + }, + "memory_get_abs_path_escapes_workspace": { + "case_kind": "reject", + "declared_tools": ("memory_get",), + "setup_commands": ("/mode yolo",), + "seed_files": (), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("bash",), + ( + ( + "command", + "python3 -c \"open('/tmp/msec_9932.txt','w').write('MEMSECRET' + '_7732' + chr(10))\" && echo P32A_SEEDED_7755", + ), + ), + False, + False, + ), + ), + ((("memory_get", "memory-get"), (("path", "/tmp/msec_9932.txt"),), True, True),), + ((("bash",), (("command", "echo P32A_DONE_7755"),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("P32A_DONE_7755",)), + ("forbidden", ("MEMSECRET_7732",)), + ("min_requests", 2), + ), + "dependencies": (("p32_ctl_memory_get_reads_inside_workspace", "GATE"),), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "read_via_symlink_outside_workspace_bounded": { + "case_kind": "reject", + "declared_tools": ("read",), + "setup_commands": ("/mode yolo",), + "seed_files": (), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("bash",), + ( + ( + "command", + "python3 -c \"open('/tmp/secr_9931.txt','w').write('OUTSECRET' + '_7731' + chr(10))\" && ln -sf /tmp/secr_9931.txt ls_9931.txt && echo RS6_SEEDED_7755", + ), + ), + False, + False, + ), + ), + ((("read",), (("file_path", "ls_9931.txt"),), False, True),), + ((("bash",), (("command", "echo RS6_DONE_7755"),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("RS6_DONE_7755",)), + ("forbidden", ("OUTSECRET_7731",)), + ("min_requests", 2), + ), + "dependencies": ( + ("symlink_to_outside_target_readable_control", "GATE"), + ("file_symlink_inside_still_readable_control", "GATE"), + ), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "file_symlink_inside_still_readable_control": { + "case_kind": "control", + "declared_tools": ("read",), + "setup_commands": ("/mode yolo",), + "seed_files": (("rif_9931.txt", "READ_INSIDE_7731\n"),), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("bash",), + (("command", "ln -sf rif_9931.txt ril_9931.txt && echo RIF_SEEDED_7755"),), + False, + False, + ), + ), + ((("read",), (("file_path", "ril_9931.txt"),), False, True),), + ((("bash",), (("command", "echo RIF_DONE_7755"),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("READ_INSIDE_7731",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": True, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "grep_default_mode_returns_path_control": { + "case_kind": "control", + "declared_tools": ("grep",), + "setup_commands": ("/mode yolo",), + "seed_files": (("f9_9931.txt", "F9NEEDLE_7755 ctxf9_9931\n"),), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("grep",), + (("pattern", "F9NEEDLE_7755"), ("path", "."), ("output_mode", "files_with_matches")), + False, + True, + ), + ), + ((("bash",), (("command", "echo F9C_DONE_7755"),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "target_tool_result"), + ("required", ("f9_9931.txt",)), + ("forbidden", ("ctxf9_9931",)), + ("forbidden_regex", "(?:^|\\n)\\s*[^:\\n]+:\\s*\\d+\\s*(?:\\n|$)"), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": True, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "grep_head_limit_zero_not_unlimited": { + "case_kind": "reject", + "declared_tools": ("grep",), + "setup_commands": ("/mode yolo",), + "seed_files": (("f9_9931.txt", "F9NEEDLE_7755 ctxf9_9931\n"),), + "rounds": ( + ( + (("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False), + ( + ("grep",), + (("pattern", "F9NEEDLE_7755"), ("path", "."), ("head_limit", 0)), + False, + True, + ), + ), + ((("bash",), (("command", "echo HZ9_DONE_7755"),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("HZ9_DONE_7755",)), + ("forbidden", ("f9_9931",)), + ("min_requests", 2), + ), + "dependencies": (("grep_default_mode_returns_path_control", "GATE"),), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "read_regular_file_control": { + "case_kind": "control", + "declared_tools": ("read",), + "setup_commands": ("/mode yolo",), + "seed_files": (("reg_9941.txt", "REGULAR_7731\n"),), + "rounds": ( + ((("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False),), + ((("read",), (("file_path", "reg_9941.txt"),), False, True),), + ((("bash",), (("command", "python3 -c \"print('DEVREAD' + '_DONE_7755')\""),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("REGULAR_7731",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (), + "blocking": True, + "role": "CONTROL", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + "read_char_device_bounded": { + "case_kind": "reject", + "declared_tools": ("read",), + "setup_commands": ("/mode yolo",), + "seed_files": (), + "rounds": ( + ((("bash",), (("command", "echo PERM_LIVE_7755 > live.txt"),), False, False),), + ((("read",), (("file_path", "/dev/urandom"),), False, True),), + ((("bash",), (("command", "python3 -c \"print('DEVREAD' + '_DONE_7755')\""),), False, False),), + ), + "oracle_profile": "TEXT_RULES", + "oracle_parameters": ( + ("source", "model_text"), + ("required", ("DEVREAD_DONE_7755",)), + ("forbidden", ()), + ("min_requests", 2), + ), + "dependencies": (("read_regular_file_control", "GATE"),), + "blocking": True, + "role": "TARGET", + "execution_parameters": (("deny", ()), ("allow", "echo PERM_LIVE_7755 > live.txt")), + "bind_oracle_parameters": True, + }, + } +) + + +def _build(scenario_id: str): + row = _ROWS[scenario_id] + rounds = tuple( + ( + tuple((FileToolCall(names, args, aliases, nested) for names, args, aliases, nested in turn)) + for turn in row["rounds"] + ) + ) + recipe = FileToolRecipe( + row["case_kind"], + row["declared_tools"], + row["setup_commands"], + row["seed_files"], + rounds, + FileToolOracleProfile(row["oracle_profile"]), + row["oracle_parameters"], + tuple(((item, DependencyKind(kind)) for item, kind in row["dependencies"])), + row["blocking"], + execution_parameters=row.get("execution_parameters", ()), + bind_oracle_parameters=row.get("bind_oracle_parameters", False), + ) + return define_file_tool_scenario(scenario_id, recipe, ScenarioRole(row["role"])) + + +_SCENARIOS = {item: _build(item) for item in _ROWS} + + +def scenario_ids() -> tuple[str, ...]: + return tuple(_SCENARIOS) + + +def scenario_by_id(scenario_id: str): + try: + return _SCENARIOS[scenario_id] + except KeyError as error: + raise KeyError(f"unknown file-tool-child scenario: {scenario_id}") from error + + +__all__ = ["scenario_by_id", "scenario_ids"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8c0eef34c91b6b31e8dd34aa02f2ddc903bfa1 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/__init__.py @@ -0,0 +1 @@ +"""Thin file-tool child scenario declarations.""" diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/file_symlink_inside_still_readable_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/file_symlink_inside_still_readable_control.py new file mode 100644 index 0000000000000000000000000000000000000000..c708525f496d438507014dd108a70b00de09dbee --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/file_symlink_inside_still_readable_control.py @@ -0,0 +1,101 @@ +"""Confirm that a workspace file symlink remains readable through the read tool. +1. Seed an in-workspace file, enable yolo mode, and create a symlink to it. +2. Read the symlink with the nested read arguments. +3. Send a later Bash completion marker after the read result is delivered. +4. Pass when the file marker and completion are visible with clean execution. +""" + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "file_symlink_inside_still_readable_control" +STEPS = ( + write_fixture("rif_9931.txt", "READ_INSIDE_7731\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "bash", + turn=1, + command="ln -sf rif_9931.txt ril_9931.txt && echo RIF_SEEDED_7755", + ), + tool_round("read", turn=2, arguments_nested=True, file_path="ril_9931.txt"), + tool_round("bash", turn=3, command="echo RIF_DONE_7755"), + capture_model_text(required=("READ_INSIDE_7731",), min_requests=2), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("read",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed readable-symlink and completion contract.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"read", "cat", "view_file", "open_file", "file_read"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_finds_inside_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_finds_inside_control.py new file mode 100644 index 0000000000000000000000000000000000000000..92479a84ff93477e2736b8094c500ecbb16d3219 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_finds_inside_control.py @@ -0,0 +1,97 @@ +"""Confirm glob finds ordinary files in the workspace for the control path. +1. Seed an ordinary Python file and enable yolo mode. +2. Establish a live Bash probe, then run recursive and root-level glob calls. +3. Capture model text containing the seeded filename from the glob results. +4. Pass when the filename is reported and execution remains clean. +""" + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "glob_finds_inside_control" +STEPS = ( + write_fixture("inside_ok.py", "x\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("glob", turn=1, arguments_nested=True, pattern="**/*.py"), + tool_round("glob", turn=1, arguments_nested=True, pattern="*.py"), + capture_model_text(required=("inside_ok",), min_requests=2), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("glob",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=False, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply typed workspace-glob control rules without parsing tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"glob", "find_files"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + source = getattr(observation, str(params["source"])) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in source for marker in params["required"]) + and all(marker not in source for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_truncation_keeps_sorted_end.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_truncation_keeps_sorted_end.py new file mode 100644 index 0000000000000000000000000000000000000000..9d52be5222923c8faa80b4a5a500688929cbd862 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/glob_truncation_keeps_sorted_end.py @@ -0,0 +1,110 @@ +"""Verify a truncated glob result keeps the sorted tail instead of only old entries. +1. Enable yolo mode and seed one old file plus 800 numbered ``.ordx`` files through Bash. +2. Search the workspace with the nested recursive glob pattern. +3. Capture model text containing the suffix and excluding the oldest-file marker. +4. Pass when the sorted result reaches the expected tail and execution is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "glob_truncation_keeps_sorted_end" +STEPS = ( + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "bash", + turn=1, + command=( + "mkdir -p gord && python3 -c \"import pathlib;pathlib.Path('gord/OLD'" + " + 'EST_7755.ordx').write_text('x')\" && touch -t 200001010000 " + "gord/OLD*_7755.ordx && python3 -c \"import os\n" + "for i in range(800): open('gord/n%d.ordx' % i,'w').write('x')\"" + " && echo ORD_SEEDED_7755" + ), + ), + tool_round("glob", turn=2, arguments_nested=True, pattern="**/*.ordx"), + capture_model_text( + required=(".ordx",), + forbidden=("OLDEST_7755",), + min_requests=2, + ), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("glob",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("glob_finds_inside_control", DependencyKind.GATE),), + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply typed glob-tail rules without parsing tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str and item.strip().lower() in {"glob", "find_files"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + source = getattr(observation, str(params["source"])) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in source for marker in params["required"]) + and all(marker not in source for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_default_mode_returns_path_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_default_mode_returns_path_control.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2d9954497b1facdcbcc8aa1776043ffe780eab --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_default_mode_returns_path_control.py @@ -0,0 +1,130 @@ +"""Confirm default grep output reports matching paths without line content. +1. Seed a file containing a unique marker and enable yolo mode. +2. Run a live Bash probe and grep with the path-only output mode. +3. Capture the typed grep result and a completion marker from the follow-up round. +4. Pass when the filename is present, content and line-number output are absent, and execution is clean. +""" + +import re +from dataclasses import replace + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_fact, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "grep_default_mode_returns_path_control" +STEPS = ( + write_fixture("f9_9931.txt", "F9NEEDLE_7755 ctxf9_9931\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "grep", + turn=1, + arguments_nested=True, + pattern="F9NEEDLE_7755", + path=".", + output_mode="files_with_matches", + ), + tool_round("bash", turn=2, command="echo F9C_DONE_7755"), + capture_fact( + "target_tool_result", + required=("f9_9931.txt",), + forbidden=("ctxf9_9931",), + forbidden_regex=r"(?:^|\n)\s*[^:\n]+:\s*\d+\s*(?:\n|$)", + min_requests=2, + ), +) +RECIPE = replace( + compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("grep",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, + ), + # The parameter order is part of the frozen recipe identity. + oracle_parameters=( + ("source", "target_tool_result"), + ("required", ("f9_9931.txt",)), + ("forbidden", ("ctxf9_9931",)), + ( + "forbidden_regex", + r"(?:^|\n)\s*[^:\n]+:\s*\d+\s*(?:\n|$)", + ), + ("min_requests", 2), + ), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply typed path-only grep rules without parsing tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"grep", "search_files", "ripgrep"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + source = getattr(observation, str(params["source"])) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in source for marker in params["required"]) + and all(marker not in source for marker in params["forbidden"]) + and ( + params.get("forbidden_regex") is None + or re.search(str(params["forbidden_regex"]), source, re.MULTILINE) is None + ) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_finds_needle_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_finds_needle_control.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb4e6336ec135c4d650a81f395f7afc62f20eba --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_finds_needle_control.py @@ -0,0 +1,101 @@ +"""Confirm that grep finds a known marker in an ordinary workspace file. +1. Seed a text file containing the unique marker and enable yolo mode. +2. Establish a live Bash probe and search the workspace for the marker. +3. Capture the model text that should name the matching file. +4. Pass when the filename is reported and execution remains clean. +""" + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "grep_finds_needle_control" +STEPS = ( + write_fixture("plain_gi.txt", "NEEDLE_GI_7731 here\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "grep", + turn=1, + arguments_nested=True, + pattern="NEEDLE_GI_7731", + path=".", + ), + capture_model_text(required=("plain_gi.txt",), min_requests=2), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("grep",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=False, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed grep-result contract without inspecting tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"grep", "search_files", "ripgrep"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_head_limit_zero_not_unlimited.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_head_limit_zero_not_unlimited.py new file mode 100644 index 0000000000000000000000000000000000000000..91d0fa032b491e2dbb1f3207b7b36fc53fbf3f6b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_head_limit_zero_not_unlimited.py @@ -0,0 +1,109 @@ +"""Reject interpreting a zero grep head limit as an unlimited result. +1. Seed a marked file, enable yolo mode, and establish a live Bash round. +2. Search with the nested grep tool using a zero head limit. +3. Run a follow-up completion probe and capture required/forbidden markers. +4. Pass when the completion marker appears without leaking the matching filename. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "grep_head_limit_zero_not_unlimited" +STEPS = ( + write_fixture("f9_9931.txt", "F9NEEDLE_7755 ctxf9_9931\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "grep", + turn=1, + arguments_nested=True, + pattern="F9NEEDLE_7755", + path=".", + head_limit=0, + ), + tool_round("bash", turn=2, command="echo HZ9_DONE_7755"), + capture_model_text( + required=("HZ9_DONE_7755",), + forbidden=("f9_9931",), + min_requests=2, + ), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("grep",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("grep_default_mode_returns_path_control", DependencyKind.GATE),), + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply typed zero-limit output rules without parsing tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"grep", "search_files", "ripgrep"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_type_filter_ignored.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_type_filter_ignored.py new file mode 100644 index 0000000000000000000000000000000000000000..5a2a71ab3bb417f0947180a1cc86b885a381d1f8 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/grep_type_filter_ignored.py @@ -0,0 +1,109 @@ +"""Verify grep type filtering includes Python matches and excludes text files. +1. Seed matching Python and text files, then enable yolo mode. +2. Establish a live Bash round and search with the nested grep ``type=py`` filter. +3. Capture the model text containing the accepted and rejected paths. +4. Pass when only the Python path is reported and execution is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "grep_type_filter_ignored" +STEPS = ( + write_fixture("gt_hit.py", "NEEDLE_GTYPE_7731 python\n"), + write_fixture("gt_hit.txt", "NEEDLE_GTYPE_7731 text\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "grep", + turn=1, + arguments_nested=True, + pattern="NEEDLE_GTYPE_7731", + path=".", + type="py", + ), + capture_model_text( + required=("gt_hit.py",), + forbidden=("gt_hit.txt",), + min_requests=2, + ), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("grep",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("grep_finds_needle_control", DependencyKind.GATE),), + blocking=False, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply typed type-filter output rules without parsing tool prose.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"grep", "search_files", "ripgrep"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/memory_get_abs_path_escapes_workspace.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/memory_get_abs_path_escapes_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..78af06806c1c6464d6327129488447f3185f5944 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/memory_get_abs_path_escapes_workspace.py @@ -0,0 +1,113 @@ +"""Ensure an absolute memory path cannot expose a secret outside the workspace. +1. Enable yolo mode and create an external secret through two live Bash rounds. +2. Request the absolute external path through both memory-get aliases. +3. Complete with a Bash marker round after the fenced request. +4. Pass when typed model text reports completion without the external secret. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "memory_get_abs_path_escapes_workspace" +STEPS = ( + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "bash", + turn=1, + command=( + "python3 -c \"open('/tmp/msec_9932.txt','w').write('MEMSECRET' + " + "'_7732' + chr(10))\" && echo P32A_SEEDED_7755" + ), + ), + tool_round( + ("memory_get", "memory-get"), + turn=2, + aliases_explicit=True, + arguments_nested=True, + path="/tmp/msec_9932.txt", + ), + tool_round("bash", turn=3, command="echo P32A_DONE_7755"), + capture_model_text( + required=("P32A_DONE_7755",), + forbidden=("MEMSECRET_7732",), + min_requests=2, + ), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("memory_get",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("p32_ctl_memory_get_reads_inside_workspace", DependencyKind.GATE),), + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed text rule with the family's shared applicability semantics.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower().replace("-", "_") == "memory_get" + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_cell_isolation.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_cell_isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..6a30fd103967b109a2611a6a60712d6a2400ed0d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_cell_isolation.py @@ -0,0 +1,145 @@ +"""Verify notebook editing changes only the selected cell. +1. Seed three cells, enable yolo mode, and read the notebook beside a live Bash probe. +2. Replace cell 1 through the explicit notebook-edit alias pair. +3. Dump the notebook in a later Bash round and capture its typed notebook fact. +4. Pass when cell 1 is new while cells 0 and 2 retain their exact JSON structure and execution is clean. +""" + +import json +from dataclasses import replace + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_fact, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "notebook_edit_cell_isolation" +STEPS = ( + write_fixture( + "nb.ipynb", + '{"cells": [{"cell_type": "markdown", "metadata": {"tags": ' + '["KEEP0"], "nested": {"k": 0}}, "source": ["CELL0_KEEP\\n"]}, ' + '{"cell_type": "code", "metadata": {"target": true}, "source": ' + '["CELL1_OLD\\n"], "outputs": [], "execution_count": null}, ' + '{"cell_type": "code", "metadata": {"tags": ["KEEP2"], "nested": ' + '{"k": 2}}, "source": ["CELL2_KEEP\\n"], "outputs": ' + '[{"output_type": "stream", "name": "stdout", "text": ' + '["KEEP2_OUTPUT\\n"]}], "execution_count": 42}], "metadata": {}, ' + '"nbformat": 4, "nbformat_minor": 5}', + ), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=1, arguments_nested=True, file_path="nb.ipynb"), + tool_round( + ("notebook_edit", "notebook-edit"), + turn=2, + aliases_explicit=True, + arguments_nested=True, + file_path="nb.ipynb", + cell_index=1, + mode="replace", + source="CELL1_NEW", + ), + tool_round("bash", turn=3, command="cat nb.ipynb"), + capture_fact("nb", required=(), min_requests=2), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("notebook_edit",), + oracle_profile=FileToolOracleProfile.NOTEBOOK_ISOLATED, + blocking=True, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed notebook-isolation contract.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower().replace("-", "_") == "notebook_edit" + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.NOTEBOOK_ISOLATED.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + raw = dict(observation.facts).get("nb") + try: + notebook = json.loads(raw) if type(raw) is str else None + except (json.JSONDecodeError, TypeError, ValueError): + notebook = None + cells = notebook.get("cells") if isinstance(notebook, dict) else None + shape = isinstance(cells, list) and len(cells) == 3 + blob = json.dumps(cells, ensure_ascii=False) if shape else "" + cell0 = ( + json.dumps(cells[0], ensure_ascii=False, sort_keys=True, separators=(",", ":")) + if shape + else "" + ) + cell2 = ( + json.dumps(cells[2], ensure_ascii=False, sort_keys=True, separators=(",", ":")) + if shape + else "" + ) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and shape + and str(params["new_marker"]) in blob + and str(params["old_marker"]) not in blob + and cell0 == params["expected_cell0_json"] + and cell2 == params["expected_cell2_json"] + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.NOTEBOOK_ISOLATED.value + if passed + else f"{FileToolOracleProfile.NOTEBOOK_ISOLATED.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_delete_keeps_neighbors.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_delete_keeps_neighbors.py new file mode 100644 index 0000000000000000000000000000000000000000..36d064c899a07d2afa81b50e351240c4acf4e582 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/notebook_edit_delete_keeps_neighbors.py @@ -0,0 +1,133 @@ +"""Verify notebook deletion removes only the selected cell. +1. Seed three cells, enable yolo mode, and read the notebook beside a live Bash probe. +2. Delete cell 1 through the explicit notebook-edit alias pair. +3. Count the remaining cells in a later Bash round and capture model text. +4. Pass when exactly two cells remain and execution is clean. +""" + +from dataclasses import replace + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "notebook_edit_delete_keeps_neighbors" +STEPS = ( + write_fixture( + "nb.ipynb", + '{"cells": [{"cell_type": "markdown", "metadata": ' + '{"tags": ["KEEP0"], "nested": {"k": 0}}, "source": ' + '["CELL0_KEEP\\n"]}, {"cell_type": "code", "metadata": ' + '{"target": true}, "source": ["CELL1_OLD\\n"], "outputs": [], ' + '"execution_count": null}, {"cell_type": "code", "metadata": ' + '{"tags": ["KEEP2"], "nested": {"k": 2}}, "source": ' + '["CELL2_KEEP\\n"], "outputs": [{"output_type": "stream", ' + '"name": "stdout", "text": ["KEEP2_OUTPUT\\n"]}], ' + '"execution_count": 42}], "metadata": {}, "nbformat": 4, ' + '"nbformat_minor": 5}', + ), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=1, arguments_nested=True, file_path="nb.ipynb"), + tool_round( + ("notebook_edit", "notebook-edit"), + turn=2, + aliases_explicit=True, + arguments_nested=True, + file_path="nb.ipynb", + cell_index=1, + mode="delete", + ), + tool_round( + "bash", + turn=3, + command=( + 'python3 -c "import json;print(\'NBCELLS\' + \'_\' + ' + 'str(len(json.load(open(\'nb.ipynb\'))[\'cells\'])))" ' + '&& echo NBDEL_DONE_7755' + ), + ), + capture_model_text(required=("NBCELLS_2",), forbidden=(), min_requests=2), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("notebook_edit",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("notebook_edit_cell_isolation", DependencyKind.REQUIREMENT),), + blocking=True, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed cell-count contract while preserving notebook semantics.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower().replace("-", "_") == "notebook_edit" + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/p32_ctl_memory_get_reads_inside_workspace.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/p32_ctl_memory_get_reads_inside_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..4840ca2bef3ef398272b7de1a1fe73e434c3003e --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/p32_ctl_memory_get_reads_inside_workspace.py @@ -0,0 +1,113 @@ +"""Confirm memory-get observes a workspace memory file after phase-scoped setup. +1. Seed `MEMORY.md`, enable yolo mode, and run the phase-1 live Bash control round. +2. In phase 2, request the memory file through both memory-get aliases. +3. Emit a completion marker and capture separate phase-1/phase-2 model facts. +4. Pass when the marker count increases in phase 2 and all execution surfaces remain clean. +""" + +from dataclasses import replace + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_fact, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "p32_ctl_memory_get_reads_inside_workspace" +STEPS = ( + write_fixture("MEMORY.md", "INSIDEMEM_7732\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + ("memory_get", "memory-get"), + turn=2, + aliases_explicit=True, + arguments_nested=True, + path="MEMORY.md", + ), + tool_round("bash", turn=3, command="echo P32A_DONE_7755"), + capture_fact("phase2_model_text", required=("INSIDEMEM_7732",), min_requests=2), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("memory_get",), + oracle_profile=FileToolOracleProfile.MEMORY_EVENT, + blocking=True, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed phase-scoped memory-event and completion contract.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower().replace("-", "_") in {"memory_get", "memoryget"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.MEMORY_EVENT.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + facts = dict(observation.facts) + before = facts.get("phase1_model_text") + after = facts.get("phase2_model_text") + marker = str(params["marker"]) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and type(before) is str + and type(after) is str + and after.count(marker) > before.count(marker) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.MEMORY_EVENT.value + if passed + else f"{FileToolOracleProfile.MEMORY_EVENT.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_char_device_bounded.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_char_device_bounded.py new file mode 100644 index 0000000000000000000000000000000000000000..563ed0386c4e60425c67424ecf0c4df2af451e7a --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_char_device_bounded.py @@ -0,0 +1,99 @@ +"""Reject reading a character device while keeping the later round usable. +1. Enable normal yolo mode and start with a live Bash round. +2. Ask the read tool to inspect the bounded character-device path. +3. Send a later Bash round that emits the completion marker. +4. Pass when the completion marker is reported without forbidden output or leaks. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolRawObservation, + FileToolOracleProfile, + FileToolScenario, + FileToolOutcome, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "read_char_device_bounded" +STEPS = ( + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=2, arguments_nested=True, file_path="/dev/urandom"), + tool_round( + "bash", + turn=3, + command='python3 -c "print(\'DEVREAD\' + \'_DONE_7755\')"', + ), + capture_model_text(required=("DEVREAD_DONE_7755",), min_requests=2), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("read",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=(("read_regular_file_control", DependencyKind.GATE),), + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply this reject point's completion-marker rule to typed evidence.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str and item.strip().lower() in {"read", "cat", "view_file", "open_file", "file_read"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_regular_file_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_regular_file_control.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa161a0acaab578d48f541e0a6e9430990a9c63 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_regular_file_control.py @@ -0,0 +1,114 @@ +"""Control: reading a regular file must expose its contents to the model. +1. Seed a regular text file and enable the normal yolo startup mode. +2. Keep a live Bash round, then ask the read tool for the seeded file. +3. Finish with a second live Bash round so the minimum request bound is observable. +4. Pass when the model reports the file marker and all observed resources are clean. +""" + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolRawObservation, + FileToolOracleProfile, + FileToolOutcome, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "read_regular_file_control" +STEPS = ( + write_fixture("reg_9941.txt", "REGULAR_7731\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=2, arguments_nested=True, file_path="reg_9941.txt"), + tool_round( + "bash", + turn=3, + command='python3 -c "print(\'DEVREAD\' + \'_DONE_7755\')"', + ), + capture_model_text(required=("REGULAR_7731",), min_requests=2), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("read",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def _read_advertised(observation: FileToolRawObservation) -> bool: + aliases = {"read", "cat", "view_file", "open_file", "file_read"} + return any( + type(item) is str and item.strip().lower() in aliases + for item in observation.advertised_tools + ) + + +def judge(observation: FileToolRawObservation): + """Apply this control's text rule with the family's shared applicability semantics.""" + + validate_file_tool_observation(SCENARIO, observation) + if not _read_advertised(observation): + if not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + passed = False + else: + parameters = dict(RECIPE.oracle_parameters) + passed = ( + observation.request_count >= int(parameters["min_requests"]) + and observation.live + and all( + marker in observation.model_text + for marker in parameters["required"] + ) + and all( + marker not in observation.model_text + for marker in parameters["forbidden"] + ) + ) + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = passed and clean + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_via_symlink_outside_workspace_bounded.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_via_symlink_outside_workspace_bounded.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0885bc46c23a244cf790de120f30ffa94c2a22 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/read_via_symlink_outside_workspace_bounded.py @@ -0,0 +1,112 @@ +"""Reject a symlink escape while proving the later tool round remains live. +1. Enable yolo mode and create a secret file outside the workspace with a link to it. +2. Read the workspace link through the nested read call after a live Bash round. +3. Send a later Bash completion marker after the boundary decision. +4. Pass when completion is visible, the outside secret is absent, and cleanup is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "read_via_symlink_outside_workspace_bounded" +STEPS = ( + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "bash", + turn=1, + command=( + "python3 -c \"open('/tmp/secr_9931.txt','w').write(" + "'OUTSECRET' + '_7731' + chr(10))\" && " + "ln -sf /tmp/secr_9931.txt ls_9931.txt && echo RS6_SEEDED_7755" + ), + ), + tool_round("read", turn=2, arguments_nested=True, file_path="ls_9931.txt"), + tool_round("bash", turn=3, command="echo RS6_DONE_7755"), + capture_model_text( + required=("RS6_DONE_7755",), + forbidden=("OUTSECRET_7731",), + min_requests=2, + ), +) +RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("read",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + dependencies=( + ("symlink_to_outside_target_readable_control", DependencyKind.GATE), + ("file_symlink_inside_still_readable_control", DependencyKind.GATE), + ), + blocking=True, + execution_parameters=( + ("deny", ()), + ("allow", "echo PERM_LIVE_7755 > live.txt"), + ), + bind_oracle_parameters=True, +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed completion/secret boundary rules for this symlink probe.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str + and item.strip().lower() in {"read", "cat", "view_file", "open_file", "file_read"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/rewind_restores_edited_file.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/rewind_restores_edited_file.py new file mode 100644 index 0000000000000000000000000000000000000000..70662c9b9a2f1b92822eb41b358807edb000ab3e --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/rewind_restores_edited_file.py @@ -0,0 +1,123 @@ +"""Verify rewind restores an overwritten file from an earlier snapshot. +1. Seed the target, enable yolo mode, read it beside a live Bash probe, and overwrite it. +2. Rewind through the available history boundary. +3. Run a post-rewind probe and capture the phase snapshots. +4. Pass when the rewind restores the expected original content and execution is clean. +""" + +from dataclasses import replace + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_fact, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "rewind_restores_edited_file" +STEPS = ( + write_fixture("tgt.txt", "ORIG_PERM_0001\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=1, arguments_nested=True, file_path="tgt.txt"), + tool_round( + "write", + turn=2, + arguments_nested=True, + file_path="tgt.txt", + content="RWOVR_8821\n", + ), + tool_round("bash", turn=3, command="echo POSTRW_8821"), + capture_fact("target_content", required=(), min_requests=2), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="reject", + declared_tools=("write",), + oracle_profile=FileToolOracleProfile.REWIND_RESTORES, + dependencies=(("undo_reverts_overwrite_control", DependencyKind.GATE),), + blocking=False, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed rewind-restores contract to phase snapshots.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str and item.strip().lower() in {"write", "file_write"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.REWIND_RESTORES.value, + ), + ) + facts = dict(observation.facts) + params = dict(RECIPE.oracle_parameters) + expected = str(params["expected"]) + before = facts.get("phase1_tgt") + unknown = facts.get("rewind_unknown") is True + if (unknown or before == expected) and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.REWIND_RESTORES.value, + ), + ) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and facts.get("after_mid1_tgt") == expected + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.REWIND_RESTORES.value + if passed + else f"{FileToolOracleProfile.REWIND_RESTORES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/symlink_to_outside_target_readable_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/symlink_to_outside_target_readable_control.py new file mode 100644 index 0000000000000000000000000000000000000000..f44a9f9c8bd9c3253ee995662cae3ef6aade5177 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/symlink_to_outside_target_readable_control.py @@ -0,0 +1,119 @@ +"""Confirm a workspace symlink can read its outside target in the control path. +1. Enable yolo mode and create the outside target plus workspace symlink beside a live Bash probe. +2. Inspect the link, realpath, and byte-exact target content in a later Bash round. +3. Capture the three typed symlink markers from model text. +4. Pass when link identity, destination, bytes, and execution cleanliness all hold. +""" + +from dataclasses import replace + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_model_text, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "symlink_to_outside_target_readable_control" +STEPS = ( + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round( + "bash", + turn=1, + command=( + "printf 'OUTSIDE_ORIG_7731\\n' > /tmp/outside_9931.txt && " + "ln -sf /tmp/outside_9931.txt link_9931.txt && echo SYMCTL_DONE_7755" + ), + ), + tool_round( + "bash", + turn=2, + command=( + 'python3 -c "import os; p=\'link_9931.txt\'; ' + "print('SYM'+'LINK_%d' % os.path.islink(p)); " + "print('SYM'+'REAL_%d' % (os.path.realpath(p)=='/tmp/outside_9931.txt')); " + "print('SYM'+'BYTE_%d' % (open(p,'rb').read()==b'OUTSIDE_ORIG_7731\\n'))" + ), + ), + capture_model_text( + required=("SYMLINK_1", "SYMREAL_1", "SYMBYTE_1"), + forbidden=(), + min_requests=2, + ), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("bash",), + oracle_profile=FileToolOracleProfile.TEXT_RULES, + blocking=True, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed symlink-marker contract.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str and item.strip().lower() in {"bash", "shell"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TEXT_RULES.value, + ), + ) + params = dict(RECIPE.oracle_parameters) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(marker in observation.model_text for marker in params["required"]) + and all(marker not in observation.model_text for marker in params["forbidden"]) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TEXT_RULES.value + if passed + else f"{FileToolOracleProfile.TEXT_RULES.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/file/scenarios/undo_reverts_overwrite_control.py b/code/src/doc2harness/benchmark/harnesses/file/scenarios/undo_reverts_overwrite_control.py new file mode 100644 index 0000000000000000000000000000000000000000..61369604dc2c05bab77e1d811cd72a1827761109 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/file/scenarios/undo_reverts_overwrite_control.py @@ -0,0 +1,110 @@ +"""Verify undo restores the original file after a full overwrite. +1. Seed the target, enable yolo mode, read it beside a live Bash probe, and overwrite it. +2. Issue undo at the session boundary. +3. Run a post-undo probe and capture the resulting transition facts. +4. Pass when the overwrite snapshot and both restored snapshots match exactly and execution is clean. +""" + +from dataclasses import replace + +from doc2harness.benchmark.harnesses.file.contracts import ( + FileToolApplicability, + FileToolJudgement, + FileToolOracleProfile, + FileToolOutcome, + FileToolRawObservation, + FileToolScenario, + build_file_tool_evaluation, + capture_fact, + compile_file_tool_steps, + setup_command, + tool_round, + validate_file_tool_observation, + write_fixture, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "undo_reverts_overwrite_control" +STEPS = ( + write_fixture("tgt.txt", "ORIG_PERM_0001\n"), + setup_command("/mode yolo"), + tool_round("bash", turn=1, command="echo PERM_LIVE_7755 > live.txt"), + tool_round("read", turn=1, arguments_nested=True, file_path="tgt.txt"), + tool_round( + "write", + turn=2, + arguments_nested=True, + file_path="tgt.txt", + content="OVR_BODY_7755\n", + ), + tool_round("bash", turn=3, command="echo POSTUNDO_7755"), + capture_fact("target_content", required=(), min_requests=2), +) +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_COMPILED_RECIPE = compile_file_tool_steps( + STEPS, + case_kind="control", + declared_tools=("write",), + oracle_profile=FileToolOracleProfile.TRANSITION_EXACT, + dependencies=(), + blocking=False, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + bind_oracle_parameters=True, +) +RECIPE = replace( + _COMPILED_RECIPE, + setup_commands=_BASE_SCENARIO.recipe.setup_commands, + seed_files=_BASE_SCENARIO.recipe.seed_files, + rounds=_BASE_SCENARIO.recipe.rounds, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, +) +SCENARIO: FileToolScenario = FileToolScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: FileToolRawObservation): + """Apply the typed exact-transition contract to the overwrite undo.""" + + validate_file_tool_observation(SCENARIO, observation) + advertised = any( + type(item) is str and item.strip().lower() in {"write", "file_write"} + for item in observation.advertised_tools + ) + if not advertised and not observation.timed_out: + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS, + FileToolApplicability.INCONCLUSIVE, + FileToolOracleProfile.TRANSITION_EXACT.value, + ), + ) + facts = dict(observation.facts) + params = dict(RECIPE.oracle_parameters) + expected = dict(params["expected"]) + passed = ( + advertised + and observation.request_count >= int(params["min_requests"]) + and observation.live + and all(facts.get(key) == value for key, value in expected.items()) + and observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + return build_file_tool_evaluation( + SCENARIO, + observation, + FileToolJudgement( + FileToolOutcome.PASS if passed else FileToolOutcome.FAIL, + FileToolApplicability.APPLICABLE, + FileToolOracleProfile.TRANSITION_EXACT.value + if passed + else f"{FileToolOracleProfile.TRANSITION_EXACT.value}_FAILED", + ), + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/__init__.py b/code/src/doc2harness/benchmark/harnesses/headless/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e2741cc01f2d75c9bd2189b9ef7595ff1e23aec5 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/__init__.py @@ -0,0 +1,56 @@ +"""Public headless CLI Harness surface.""" + +from .adapter import ( + HeadlessExecutionPlan, + build_headless_execution_plan, +) +from .contracts import ( + ArgumentVariant, + CliFileProbe, + FormalProbe, + HeadlessApplicability, + HeadlessExecutionMode, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessProfile, + HeadlessRecipe, + HeadlessScenario, + JsonOverride, + ListingProbe, + ObservedFile, + ProcessObservation, + RequestRecord, + SchemaProbe, + SeedFile, + ToolCall, + ToolRound, +) +from .recipes import SCENARIOS, scenario_by_id + +__all__ = [ + "SCENARIOS", + "ArgumentVariant", + "CliFileProbe", + "FormalProbe", + "HeadlessApplicability", + "HeadlessExecutionMode", + "HeadlessExecutionPlan", + "HeadlessJudgement", + "HeadlessObservation", + "HeadlessOutcome", + "HeadlessProfile", + "HeadlessRecipe", + "HeadlessScenario", + "JsonOverride", + "ListingProbe", + "ObservedFile", + "ProcessObservation", + "RequestRecord", + "SchemaProbe", + "SeedFile", + "ToolCall", + "ToolRound", + "build_headless_execution_plan", + "scenario_by_id", +] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/adapter.py b/code/src/doc2harness/benchmark/harnesses/headless/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..6d49802588fa8fcc1faf21abd3339b2f2e77a5ee --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/adapter.py @@ -0,0 +1,50 @@ +"""Execution boundary for typed headless CLI observations.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from .contracts import ( + HeadlessProfile, + HeadlessRecipe, + HeadlessScenario, +) +from .fixtures import HeadlessFixturePlan, materialize_headless_fixture + + +@dataclass(frozen=True, slots=True) +class HeadlessExecutionPlan: + scenario_id: str + profile: HeadlessProfile + recipe: HeadlessRecipe + fixture: HeadlessFixturePlan + timeout_seconds: int + plan_digest: str + + +def build_headless_execution_plan( + scenario: HeadlessScenario, / +) -> HeadlessExecutionPlan: + if type(scenario) is not HeadlessScenario: + raise ContractDocumentError("headless execution requires an exact scenario") + fixture = materialize_headless_fixture(scenario) + body = { + "fixture_digest": fixture.plan_digest, + "profile": scenario.recipe.profile.value, + "scenario_id": scenario.definition.scenario_id, + "timeout_seconds": scenario.recipe.timeout_seconds, + } + digest = ( + "sha256:" + + hashlib.sha256(b"doc2harness.headless-plan/1\0" + canonical_json(body)).hexdigest() + ) + return HeadlessExecutionPlan( + scenario.definition.scenario_id, + scenario.recipe.profile, + scenario.recipe, + fixture, + scenario.recipe.timeout_seconds, + digest, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/headless/catalog.toml b/code/src/doc2harness/benchmark/harnesses/headless/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e8aa5a0d6350e995bacd16f1c57cf3fc8f38173 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/catalog.toml @@ -0,0 +1,18 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "headless" +resource = "benchmark/harnesses/headless/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.headless.scenarios.at_ref_expands_in_headless", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_model_error_wellformed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_wellformed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_bare_mention_not_auto_read", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_task_text_reaches_wire", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict_control", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/contracts.py b/code/src/doc2harness/benchmark/harnesses/headless/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..dd4ba0bd7bcd70e3a66f16f65b63920e02a69518 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/contracts.py @@ -0,0 +1,784 @@ +"""Typed execution recipes and raw observations for the headless CLI Harness.""" + +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import asdict, dataclass +from enum import Enum + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_MAX_TEXT = 4_000_000 +_MAX_ITEMS = 4096 + + +def _text(value: object, name: str, *, allow_empty: bool = True) -> None: + if ( + type(value) is not str + or len(value) > _MAX_TEXT + or (not allow_empty and not value) + ): + raise ContractDocumentError(f"headless {name} is invalid") + + +def _strings(value: object, name: str, *, unique: bool = False) -> None: + if ( + type(value) is not tuple + or len(value) > _MAX_ITEMS + or any(type(v) is not str or len(v) > _MAX_TEXT for v in value) + ): + raise ContractDocumentError(f"headless {name} is invalid") + if unique and len(set(value)) != len(value): + raise ContractDocumentError(f"headless {name} must be unique") + + +def _relative_path(value: object, name: str, *, allow_empty: bool = True) -> None: + _text(value, name, allow_empty=allow_empty) + if value and (value.startswith("/") or ".." in value.split("/")): + raise ContractDocumentError(f"headless {name} must be relative") + + +class HeadlessProfile(str, Enum): + JSON_PURE = "chk_json_pure" + JSON_ERROR_PURE = "chk_json_error_pure" + PROBE_PRESENT = "chk_probe_present" + PROBE_ABSENT = "chk_probe_absent" + BUDGET_TYPE_DOMAIN_CONTROL = "chk_budget_type_domain_control" + BUDGET_TYPE_DOMAIN = "chk_budget_type_domain" + RUNTIME_ERROR_STDOUT_CONTROL = "chk_runtime_error_stdout_control" + RUNTIME_ERROR_STDOUT = "chk_runtime_error_stdout" + EXEC_BACKGROUND = "chk_exec_background" + SESSION_FLAG_CONFLICT = "chk_session_flag_conflict" + + +class HeadlessExecutionMode(str, Enum): + STANDARD = "standard" + FORMAL_RUNTIME = "formal-runtime" + FORMAL_CONTRACT = "formal-contract" + + +class HeadlessOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class HeadlessApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +@dataclass(frozen=True, slots=True) +class HeadlessJudgement: + """Typed result returned by one scenario-local, pure headless judge.""" + + outcome: HeadlessOutcome + applicability: HeadlessApplicability + reason_code: str + + def __post_init__(self) -> None: + if type(self.outcome) is not HeadlessOutcome: + raise ContractDocumentError("headless judgement outcome is invalid") + if type(self.applicability) is not HeadlessApplicability: + raise ContractDocumentError("headless judgement applicability is invalid") + _text(self.reason_code, "judgement reason", allow_empty=False) + + +@dataclass(frozen=True, slots=True) +class ArgumentVariant: + label: str + arguments: tuple[str, ...] + + def __post_init__(self) -> None: + if type(self.label) is not str or not self.label: + raise ContractDocumentError("headless variant label is invalid") + if type(self.arguments) is not tuple or any( + type(v) is not str for v in self.arguments + ): + raise ContractDocumentError("headless variant arguments are invalid") + + +@dataclass(frozen=True, slots=True) +class SeedFile: + path: str + content: str + + def __post_init__(self) -> None: + if ( + type(self.path) is not str + or not self.path + or self.path.startswith("/") + or ".." in self.path.split("/") + ): + raise ContractDocumentError("headless seed path is invalid") + if type(self.content) is not str: + raise ContractDocumentError("headless seed content is invalid") + + +@dataclass(frozen=True, slots=True) +class ToolCall: + names: tuple[str, ...] + arguments_json: str = "{}" + command: str = "" + + def __post_init__(self) -> None: + if ( + type(self.names) is not tuple + or not self.names + or any(type(v) is not str or not v for v in self.names) + ): + raise ContractDocumentError("headless tool names are invalid") + if type(self.arguments_json) is not str or type(self.command) is not str: + raise ContractDocumentError("headless tool payload is invalid") + + +@dataclass(frozen=True, slots=True) +class ToolRound: + calls: tuple[ToolCall, ...] + + def __post_init__(self) -> None: + if ( + type(self.calls) is not tuple + or not self.calls + or len(self.calls) > _MAX_ITEMS + or any(type(v) is not ToolCall for v in self.calls) + ): + raise ContractDocumentError("headless tool round is invalid") + + +@dataclass(frozen=True, slots=True) +class SchemaProbe: + label: str + path: str + key: str + sentinel: str + + def __post_init__(self) -> None: + for value, name in ( + (self.label, "schema label"), + (self.key, "schema key"), + (self.sentinel, "schema sentinel"), + ): + _text(value, name, allow_empty=False) + _relative_path(self.path, "schema path", allow_empty=False) + + +@dataclass(frozen=True, slots=True) +class JsonOverride: + """One typed JSON field override, including deliberately invalid domains.""" + + field: str + canonical_value: str + + def __post_init__(self) -> None: + _text(self.field, "JSON override field", allow_empty=False) + _text(self.canonical_value, "JSON override value", allow_empty=False) + try: + value = json.loads(self.canonical_value) + except (TypeError, ValueError, json.JSONDecodeError) as error: + raise ContractDocumentError("headless JSON override is invalid") from error + rendered = json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ) + if rendered != self.canonical_value: + raise ContractDocumentError("headless JSON override is not canonical") + + +@dataclass(frozen=True, slots=True) +class FormalProbe: + label: str + budget: tuple[JsonOverride, ...] = () + path_role: str = "" + task_overrides: tuple[JsonOverride, ...] = () + raw_contract: str = "" + gateway_mode: str = "" + environment: tuple[tuple[str, str], ...] = () + argv_overrides: tuple[tuple[str, str], ...] = () + + def __post_init__(self) -> None: + _text(self.label, "formal probe label", allow_empty=False) + for value in (self.path_role, self.raw_contract, self.gateway_mode): + _text(value, "formal probe text") + if ( + type(self.budget) is not tuple + or type(self.task_overrides) is not tuple + or any( + type(v) is not JsonOverride + for v in (*self.budget, *self.task_overrides) + ) + ): + raise ContractDocumentError("headless formal JSON overrides are invalid") + for values, name in ( + (self.environment, "formal environment"), + (self.argv_overrides, "formal argv overrides"), + ): + if type(values) is not tuple or any( + type(v) is not tuple + or len(v) != 2 + or any(type(item) is not str for item in v) + for v in values + ): + raise ContractDocumentError(f"headless {name} is invalid") + if len({v.field for v in self.budget}) != len(self.budget) or len( + {v.field for v in self.task_overrides} + ) != len(self.task_overrides): + raise ContractDocumentError("headless formal override keys must be unique") + + +@dataclass(frozen=True, slots=True) +class ListingProbe: + label: str + count: int + payload_bytes: int + + def __post_init__(self) -> None: + _text(self.label, "listing probe label", allow_empty=False) + if ( + type(self.count) is not int + or self.count <= 0 + or type(self.payload_bytes) is not int + or self.payload_bytes <= 0 + ): + raise ContractDocumentError("headless listing probe is invalid") + + +@dataclass(frozen=True, slots=True) +class CliFileProbe: + label: str + kind: str + file_hex: str + + def __post_init__(self) -> None: + _text(self.label, "CLI file probe label", allow_empty=False) + _text(self.kind, "CLI file probe kind", allow_empty=False) + if type(self.file_hex) is not str or len(self.file_hex) % 2: + raise ContractDocumentError("headless CLI file bytes are invalid") + try: + bytes.fromhex(self.file_hex) + except ValueError as error: + raise ContractDocumentError("headless CLI file bytes are invalid") from error + + +@dataclass(frozen=True, slots=True) +class HeadlessOracleBinding: + """Frozen checker closure values; these are oracle inputs, never verdicts.""" + + sentinel: str = "" + specification: str = "" + baseline_label: str = "" + subject_label: str = "" + third_label: str = "" + expected_tokens: tuple[str, ...] = () + expected_tools: tuple[str, ...] = () + expected_mark: str = "" + expected_boolean: bool | None = None + feature_name: str = "" + step_cap: int = 0 + expected_relative_path: str = "" + resume_subdirectory: str = "" + schemas: tuple[SchemaProbe, ...] = () + + def __post_init__(self) -> None: + for value in ( + self.sentinel, + self.specification, + self.baseline_label, + self.subject_label, + self.third_label, + self.expected_mark, + self.feature_name, + self.expected_relative_path, + self.resume_subdirectory, + ): + _text(value, "oracle binding text") + _strings(self.expected_tokens, "oracle expected tokens", unique=True) + _strings(self.expected_tools, "oracle expected tools", unique=True) + if ( + self.expected_boolean is not None + and type(self.expected_boolean) is not bool + ): + raise ContractDocumentError("headless oracle expected boolean is invalid") + if type(self.step_cap) is not int or self.step_cap < 0: + raise ContractDocumentError("headless oracle step cap is invalid") + if ( + type(self.schemas) is not tuple + or len(self.schemas) > _MAX_ITEMS + or any(type(v) is not SchemaProbe for v in self.schemas) + ): + raise ContractDocumentError("headless oracle schemas are invalid") + if len({v.label for v in self.schemas}) != len(self.schemas): + raise ContractDocumentError("headless oracle schema labels must be unique") + + +@dataclass(frozen=True, slots=True) +class HeadlessRecipe: + """Complete typed stimulus; ``case_digest`` is audit-only.""" + + profile: HeadlessProfile + case_digest: str + dependencies: tuple[tuple[str, DependencyKind], ...] = () + task: str = "Say the magic word and stop." + output_format: str = "text" + blocking: bool = True + reply_content: str = "DONE_SENTINEL" + gateway_mode: str = "fixed_reply" + append_system_prompt: str = "" + system_prompt: str = "" + probe_token: str = "" + probe_tokens: tuple[str, ...] = () + cli_variants: tuple[ArgumentVariant, ...] = () + subcommand_variants: tuple[ArgumentVariant, ...] = () + file_variants: tuple[ArgumentVariant, ...] = () + sequence_subcommands: tuple[tuple[str, ...], ...] = () + # Names for the sequence steps. A judge that compares steps by name needs + # them declared; without this the driver can only number them, and a + # lookup by name finds nothing. + sequence_labels: tuple[str, ...] = () + sequence_pause_seconds: int = 0 + seed_files: tuple[SeedFile, ...] = () + rounds: tuple[ToolRound, ...] = () + command: str = "" + target_file: str = "" + target_written: str = "" + target_original: str = "" + empty_task: bool = False + extra_argv: tuple[str, ...] = () + environment: tuple[tuple[str, str], ...] = () + local_web_probe: bool = False + git_fixture: bool = False + execution_mode: HeadlessExecutionMode = HeadlessExecutionMode.STANDARD + formal_runtime_probes: tuple[FormalProbe, ...] = () + formal_contract_probes: tuple[FormalProbe, ...] = () + listing_probes: tuple[ListingProbe, ...] = () + cli_file_probes: tuple[CliFileProbe, ...] = () + status_observation_required: bool = False + seed_timeout_seconds: int = 0 + measurement_timeout_seconds: int = 0 + timeout_seconds: int = 60 + oracle: HeadlessOracleBinding = HeadlessOracleBinding() + + def __post_init__(self) -> None: + if type(self.profile) is not HeadlessProfile: + raise ContractDocumentError("headless profile is invalid") + if ( + type(self.case_digest) is not str + or not self.case_digest.startswith("sha256:") + or len(self.case_digest) != 71 + ): + raise ContractDocumentError("headless case digest is invalid") + if type(self.dependencies) is not tuple or any( + type(v) is not tuple + or len(v) != 2 + or type(v[0]) is not str + or type(v[1]) is not DependencyKind + for v in self.dependencies + ): + raise ContractDocumentError("headless dependencies are invalid") + if any( + type(v) is not ArgumentVariant + for v in self.cli_variants + self.subcommand_variants + self.file_variants + ): + raise ContractDocumentError("headless recipe variants are invalid") + if any( + type(step) is not tuple or any(type(v) is not str for v in step) + for step in self.sequence_subcommands + ): + raise ContractDocumentError("headless sequence is invalid") + if any(type(v) is not SeedFile for v in self.seed_files) or any( + type(v) is not ToolRound for v in self.rounds + ): + raise ContractDocumentError("headless fixture recipe is invalid") + if type(self.environment) is not tuple or any( + type(v) is not tuple or len(v) != 2 or any(type(x) is not str for x in v) + for v in self.environment + ): + raise ContractDocumentError("headless environment is invalid") + if ( + type(self.timeout_seconds) is not int + or self.timeout_seconds <= 0 + or type(self.sequence_pause_seconds) is not int + or self.sequence_pause_seconds < 0 + ): + raise ContractDocumentError("headless timing is invalid") + if type(self.oracle) is not HeadlessOracleBinding: + raise ContractDocumentError("headless oracle binding is invalid") + if type(self.execution_mode) is not HeadlessExecutionMode: + raise ContractDocumentError("headless execution mode is invalid") + for values, expected, name in ( + (self.formal_runtime_probes, FormalProbe, "formal runtime probes"), + (self.formal_contract_probes, FormalProbe, "formal contract probes"), + (self.listing_probes, ListingProbe, "listing probes"), + (self.cli_file_probes, CliFileProbe, "CLI file probes"), + ): + if type(values) is not tuple or any(type(v) is not expected for v in values): + raise ContractDocumentError(f"headless {name} are invalid") + if len({v.label for v in values}) != len(values): + raise ContractDocumentError(f"headless {name} labels must be unique") + if type(self.status_observation_required) is not bool: + raise ContractDocumentError("headless status observation flag is invalid") + if any( + type(value) is not int or value < 0 + for value in (self.seed_timeout_seconds, self.measurement_timeout_seconds) + ): + raise ContractDocumentError("headless auxiliary timing is invalid") + for value in ( + self.task, + self.output_format, + self.reply_content, + self.gateway_mode, + self.append_system_prompt, + self.system_prompt, + self.probe_token, + self.command, + self.target_written, + self.target_original, + ): + _text(value, "recipe text") + _relative_path(self.target_file, "target path") + _strings(self.probe_tokens, "probe tokens", unique=True) + _strings(self.extra_argv, "extra argv") + for flag in ( + self.blocking, + self.empty_task, + self.local_web_probe, + self.git_fixture, + ): + if type(flag) is not bool: + raise ContractDocumentError("headless recipe flag is invalid") + if len( + { + v.label + for v in self.cli_variants + + self.subcommand_variants + + self.file_variants + } + ) != len(self.cli_variants + self.subcommand_variants + self.file_variants): + raise ContractDocumentError("headless recipe variant labels must be unique") + + +@dataclass(frozen=True, slots=True) +class RequestRecord: + body: str + model: str = "" + system_text: str = "" + probe_hits: tuple[str, ...] = () + system_probe_hits: tuple[str, ...] = () + tool_names: tuple[str, ...] = () + tool_result_texts: tuple[str, ...] = () + stream_enabled: bool | None = None + + def __post_init__(self) -> None: + _text(self.body, "request body") + _text(self.model, "request model") + _text(self.system_text, "request system text") + _strings(self.probe_hits, "request probe hits", unique=True) + _strings(self.system_probe_hits, "request system probe hits", unique=True) + _strings(self.tool_names, "request tool names", unique=True) + _strings(self.tool_result_texts, "request tool results") + if self.stream_enabled is not None and type(self.stream_enabled) is not bool: + raise ContractDocumentError("headless request stream flag is invalid") + + +@dataclass(frozen=True, slots=True) +class ProcessObservation: + """One directly observed CLI process, variant, or sequence step.""" + + label: str + rc: int | None + stdout: str = "" + stderr: str = "" + timed_out: bool = False + requests: tuple[RequestRecord, ...] = () + written_paths: tuple[str, ...] = () + removed_paths: tuple[str, ...] = () + target_content: str = "" + target_found_at: str = "" + worktree_target_content: str = "" + worktree_paths: tuple[str, ...] = () + git_initialized: bool = False + marker_found_at: str = "" + web_gets: tuple[str, ...] = () + exit_status: str = "" + start_error: str = "" + cleanup_complete: bool = True + out_created: bool = False + repo_changed: bool = False + preterminal_stdout: str = "" + barrier_seen: bool | None = None + gateway_wait_timed_out: bool | None = None + terminal_before_release: bool | None = None + first_stdout_ns: int | None = None + release_ns: int | None = None + count: int | None = None + payload_bytes: int | None = None + seed_created: int | None = None + listed_markers: int | None = None + rchar_delta: int | None = None + rss_delta_kib: int | None = None + home_open_count: int | None = None + output_bytes: int | None = None + product_error: str = "" + + def __post_init__(self) -> None: + if type(self.label) is not str or not self.label: + raise ContractDocumentError("headless process label is invalid") + if self.rc is not None and type(self.rc) is not int: + raise ContractDocumentError("headless process rc is invalid") + if type(self.timed_out) is not bool or any( + type(v) is not RequestRecord for v in self.requests + ): + raise ContractDocumentError("headless process evidence is invalid") + if type(self.requests) is not tuple or len(self.requests) > _MAX_ITEMS: + raise ContractDocumentError("headless process requests are invalid") + for value in ( + self.stdout, + self.stderr, + self.target_content, + self.target_found_at, + self.worktree_target_content, + self.marker_found_at, + self.exit_status, + self.start_error, + self.preterminal_stdout, + self.product_error, + ): + _text(value, "process text") + _strings(self.written_paths, "written paths", unique=True) + _strings(self.removed_paths, "removed paths", unique=True) + _strings(self.worktree_paths, "worktree paths", unique=True) + _strings(self.web_gets, "web gets") + for path in self.written_paths + self.removed_paths: + _relative_path(path, "filesystem path", allow_empty=False) + if type(self.git_initialized) is not bool: + raise ContractDocumentError("headless git observation is invalid") + if any( + type(value) is not bool + for value in (self.cleanup_complete, self.out_created, self.repo_changed) + ): + raise ContractDocumentError("headless process fact flags are invalid") + for value in ( + self.barrier_seen, + self.gateway_wait_timed_out, + self.terminal_before_release, + ): + if value is not None and type(value) is not bool: + raise ContractDocumentError("headless timeline flags are invalid") + for value in ( + self.first_stdout_ns, + self.release_ns, + self.count, + self.payload_bytes, + self.seed_created, + self.listed_markers, + self.rchar_delta, + self.rss_delta_kib, + self.home_open_count, + self.output_bytes, + ): + if value is not None and (type(value) is not int or value < 0): + raise ContractDocumentError("headless numeric process fact is invalid") + + +@dataclass(frozen=True, slots=True) +class ObservedFile: + path: str + content: str + + def __post_init__(self) -> None: + _relative_path(self.path, "observed file path", allow_empty=False) + _text(self.content, "observed file content") + + +@dataclass(frozen=True, slots=True) +class HeadlessScenario: + definition: ScenarioDefinition + recipe: HeadlessRecipe + + def __post_init__(self) -> None: + if ( + type(self.definition) is not ScenarioDefinition + or type(self.recipe) is not HeadlessRecipe + ): + raise ContractDocumentError("headless scenario requires exact typed values") + if self.definition.classification.primary != "headless": + raise ContractDocumentError( + "headless scenario owner differs from its Harness" + ) + + +@dataclass(frozen=True, slots=True) +class HeadlessObservation: + scenario_id: str + profile: HeadlessProfile + plan_digest: str + artifact_id: str + artifact_digest: str + backend_evidence_digest: str + cli_available: bool + runs: tuple[ProcessObservation, ...] + artifact_files: tuple[ObservedFile, ...] = () + repository_root: str = "" + agent_session_id: str = "" + driver_error: str = "" + process_tree_clean: bool = True + workspace_clean: bool = True + checkpoint_id: str = "" + pre_listing: str = "" + selection_command: str = "" + selection_result: str = "" + summary_sent: bool | None = None + session_start_error: str = "" + + def __post_init__(self) -> None: + if ( + type(self.scenario_id) is not str + or _ID.fullmatch(self.scenario_id) is None + or type(self.profile) is not HeadlessProfile + ): + raise ContractDocumentError("headless observation identity is invalid") + for value in ( + self.plan_digest, + self.artifact_digest, + self.backend_evidence_digest, + ): + if ( + type(value) is not str + or not value.startswith("sha256:") + or len(value) != 71 + ): + raise ContractDocumentError("headless evidence digest is invalid") + if type(self.artifact_id) is not str or not self.artifact_id: + raise ContractDocumentError("headless artifact id is invalid") + if type(self.runs) is not tuple or any( + type(v) is not ProcessObservation for v in self.runs + ): + raise ContractDocumentError("headless raw runs are invalid") + if any(type(v) is not ObservedFile for v in self.artifact_files): + raise ContractDocumentError("headless artifact files are invalid") + if any( + type(v) is not bool + for v in (self.cli_available, self.process_tree_clean, self.workspace_clean) + ): + raise ContractDocumentError("headless observation flags are invalid") + for value in ( + self.repository_root, + self.agent_session_id, + self.driver_error, + self.checkpoint_id, + self.pre_listing, + self.selection_command, + self.selection_result, + self.session_start_error, + ): + _text(value, "observation text") + if self.summary_sent is not None and type(self.summary_sent) is not bool: + raise ContractDocumentError("headless compact summary fact is invalid") + labels = tuple(run.label for run in self.runs) + if len(set(labels)) != len(labels): + raise ContractDocumentError("headless run labels must be unique") + paths = tuple(item.path for item in self.artifact_files) + if len(set(paths)) != len(paths): + raise ContractDocumentError("headless artifact file paths must be unique") + + +def define_headless_scenario( + scenario_id: str, recipe: HeadlessRecipe, role: ScenarioRole, / +) -> HeadlessScenario: + dependencies = tuple( + sorted( + (DependencyRef(test_id, kind) for test_id, kind in recipe.dependencies), + key=lambda item: (item.scenario_id, item.kind.value), + ) + ) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("headless"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("headless-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("headless-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("headless-observer", "1", ComponentKind.OBSERVER), + ComponentRef("headless-oracle", "1", ComponentKind.ORACLE), + ComponentRef("headless-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return HeadlessScenario(definition, recipe) + + +def evaluation_digest( + scenario: HeadlessScenario, observation: HeadlessObservation +) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return ( + "sha256:" + + hashlib.sha256( + b"doc2harness.headless-evaluation/1\0" + canonical_json(body) + ).hexdigest() + ) + + +def recipe_digest(recipe: HeadlessRecipe, /) -> str: + """Bind every typed stimulus and checker closure value into the plan.""" + + if type(recipe) is not HeadlessRecipe: + raise ContractDocumentError("headless recipe digest requires an exact recipe") + body = asdict(recipe) + extension_keys = ( + "execution_mode", + "formal_runtime_probes", + "formal_contract_probes", + "listing_probes", + "cli_file_probes", + "status_observation_required", + "seed_timeout_seconds", + "measurement_timeout_seconds", + ) + if ( + recipe.execution_mode is HeadlessExecutionMode.STANDARD + and not recipe.formal_runtime_probes + and not recipe.formal_contract_probes + and not recipe.listing_probes + and not recipe.cli_file_probes + and not recipe.status_observation_required + and recipe.seed_timeout_seconds == 0 + and recipe.measurement_timeout_seconds == 0 + ): + for key in extension_keys: + body.pop(key) + return ( + "sha256:" + + hashlib.sha256( + b"doc2harness.headless-recipe/1\0" + canonical_json(body) + ).hexdigest() + ) diff --git a/code/src/doc2harness/benchmark/harnesses/headless/fixtures.py b/code/src/doc2harness/benchmark/harnesses/headless/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..2406a37db77149f2684aac80e1cbcb2d744981a5 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/fixtures.py @@ -0,0 +1,34 @@ +"""Immutable headless CLI fixture bindings.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json + +from .contracts import HeadlessRecipe, HeadlessScenario, recipe_digest + + +@dataclass(frozen=True, slots=True) +class HeadlessFixturePlan: + case_digest: str + recipe: HeadlessRecipe + recipe_digest: str + plan_digest: str + + +def materialize_headless_fixture(scenario: HeadlessScenario, /) -> HeadlessFixturePlan: + body = { + "case_digest": scenario.recipe.case_digest, + "recipe_digest": recipe_digest(scenario.recipe), + "scenario_id": scenario.definition.scenario_id, + } + digest = ( + "sha256:" + + hashlib.sha256(b"doc2harness.headless-fixture/1\0" + canonical_json(body)).hexdigest() + ) + return HeadlessFixturePlan( + scenario.recipe.case_digest, + scenario.recipe, + body["recipe_digest"], + digest, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/headless/recipes.py b/code/src/doc2harness/benchmark/harnesses/headless/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..c73c939240dfb6fd9a1ea6d790c1454c2dd428ad --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/recipes.py @@ -0,0 +1,291 @@ +"""Frozen typed recipes for headless CLI scenarios.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from .contracts import ( + FormalProbe, + HeadlessExecutionMode, + HeadlessOracleBinding, + HeadlessProfile, + HeadlessRecipe, + JsonOverride, + SeedFile, + define_headless_scenario, +) + +_ROWS = { + "headless_p_json_wellformed": ( + HeadlessRecipe( + profile=HeadlessProfile.JSON_PURE, + case_digest="sha256:8fca283d6a734d3194ca367d22d13f6d30fee60fb4cc77cb5eb397fe3bcd30c8", + dependencies=(), + timeout_seconds=90, + output_format="json", + blocking=False, + reply_content="PUREJSON_8842 finished", + oracle=HeadlessOracleBinding(sentinel="PUREJSON_8842"), + ), + ScenarioRole.CONTROL, + ), + "headless_p_json_model_error_wellformed": ( + HeadlessRecipe( + profile=HeadlessProfile.JSON_ERROR_PURE, + case_digest="sha256:26ad300b0c8387f54353c7c0fe3c3683bf204943d4c980dec7340f71a7096bb7", + dependencies=(("headless_p_json_wellformed", DependencyKind.GATE),), + timeout_seconds=90, + output_format="json", + gateway_mode="http_401", + oracle=HeadlessOracleBinding(), + ), + ScenarioRole.TARGET, + ), + "p34_ctl_task_text_reaches_wire": ( + HeadlessRecipe( + profile=HeadlessProfile.PROBE_PRESENT, + case_digest="sha256:d164292ad645d4f955608491de0ea28cb6901dc41ce26f265e87677544106bca", + dependencies=(), + task="ATREFTOK_9934 acknowledge and stop.", + output_format="text", + blocking=False, + reply_content="ack", + probe_token="ATREFTOK_9934", + timeout_seconds=90, + oracle=HeadlessOracleBinding(specification="the task body"), + ), + ScenarioRole.CONTROL, + ), + "p34_ctl_bare_mention_not_auto_read": ( + HeadlessRecipe( + profile=HeadlessProfile.PROBE_ABSENT, + case_digest="sha256:2fadd93ee9d3ec8692ae580cca6bf596050d1caf4158bc2149c3a8efb64972b4", + dependencies=(), + task="There is a file called ctx_9934.md in this repo. Do not read it. Say ok and stop.", + output_format="text", + blocking=False, + reply_content="ack", + probe_token="ATREFTOK_9934", + seed_files=(SeedFile("ctx_9934.md", "ATREFTOK_9934 the project ships on Tuesdays.\n"),), + timeout_seconds=90, + oracle=HeadlessOracleBinding(specification="the content of a bare filename mention"), + ), + ScenarioRole.CONTROL, + ), + "at_ref_expands_in_headless": ( + HeadlessRecipe( + profile=HeadlessProfile.PROBE_PRESENT, + case_digest="sha256:bb1913914002cbc7ccdd2c8bc785af8e73e0af5d6fc6bf70e81bdf23e9eb486a", + dependencies=( + ("p34_ctl_bare_mention_not_auto_read", DependencyKind.GATE), + ("p34_ctl_task_text_reaches_wire", DependencyKind.GATE), + ), + task="Summarize @ctx_9934.md in one line and stop.", + output_format="text", + reply_content="ack", + probe_token="ATREFTOK_9934", + seed_files=(SeedFile("ctx_9934.md", "ATREFTOK_9934 the project ships on Tuesdays.\n"),), + timeout_seconds=90, + oracle=HeadlessOracleBinding(specification="the content of an @-referenced file"), + ), + ScenarioRole.TARGET, + ), + "budget_type_domain_control": ( + HeadlessRecipe( + profile=HeadlessProfile.BUDGET_TYPE_DOMAIN_CONTROL, + case_digest="sha256:79ce0a325bfe18c40fe109ec9705d346b5f297ca6e0650f5afe1b2a74ac2f19d", + blocking=False, + timeout_seconds=45, + execution_mode=HeadlessExecutionMode.FORMAL_RUNTIME, + formal_runtime_probes=( + FormalProbe( + "valid-zero", + budget=( + JsonOverride("max_steps", "2"), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "valid-positive", + budget=( + JsonOverride("max_steps", "97"), + JsonOverride("max_tokens", "64"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + ), + status_observation_required=True, + ), + ScenarioRole.CONTROL, + ), + "budget_type_domain": ( + HeadlessRecipe( + profile=HeadlessProfile.BUDGET_TYPE_DOMAIN, + case_digest="sha256:c269536e752e1b7c0863711df30b5c08661d8d94ee6b4d1acbb8fc902ed9695a", + dependencies=(("budget_type_domain_control", DependencyKind.GATE),), + timeout_seconds=45, + execution_mode=HeadlessExecutionMode.FORMAL_RUNTIME, + formal_runtime_probes=( + FormalProbe( + "valid-zero", + budget=( + JsonOverride("max_steps", "2"), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "valid-positive", + budget=( + JsonOverride("max_steps", "97"), + JsonOverride("max_tokens", "64"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "invalid-boolean", + budget=( + JsonOverride("max_steps", "true"), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "invalid-string", + budget=( + JsonOverride("max_steps", '"2"'), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "invalid-float", + budget=( + JsonOverride("max_steps", "2.5"), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + FormalProbe( + "invalid-negative", + budget=( + JsonOverride("max_steps", "-1"), + JsonOverride("max_tokens", "0"), + JsonOverride("max_wall_seconds", "30"), + ), + ), + ), + status_observation_required=True, + ), + ScenarioRole.TARGET, + ), + "runtime_error_stdout_control": ( + HeadlessRecipe( + profile=HeadlessProfile.RUNTIME_ERROR_STDOUT_CONTROL, + case_digest="sha256:e6857e3b3b7693fa9d869c4939036e23acaac9e7aadb2169b887c3ee186f694d", + blocking=False, + gateway_mode="seq_probe", + reply_content="EXACT_REPLY_6047", + timeout_seconds=40, + execution_mode=HeadlessExecutionMode.FORMAL_CONTRACT, + formal_contract_probes=(FormalProbe("model-success", gateway_mode="seq_probe"),), + status_observation_required=True, + ), + ScenarioRole.CONTROL, + ), + "runtime_error_stdout": ( + HeadlessRecipe( + profile=HeadlessProfile.RUNTIME_ERROR_STDOUT, + case_digest="sha256:1ba625fc10954046643efaa2ab98b5f71346de5a3e5cfe3eb519c2941056a83d", + dependencies=(("runtime_error_stdout_control", DependencyKind.GATE),), + gateway_mode="seq_probe", + reply_content="EXACT_REPLY_6047", + timeout_seconds=40, + execution_mode=HeadlessExecutionMode.FORMAL_CONTRACT, + formal_contract_probes=( + FormalProbe( + "model-runtime-error", + gateway_mode="http_401", + environment=(("MSWEA_MODEL_RETRY_STOP_AFTER_ATTEMPT", "1"),), + ), + ), + status_observation_required=True, + ), + ScenarioRole.TARGET, + ), + "exec_requires_bg_control": ( + HeadlessRecipe( + profile=HeadlessProfile.EXEC_BACKGROUND, + case_digest="sha256:3e0f756a0567630227d4125daac829dd8053a59b2b42a254011b3140e7f05575", + sequence_subcommands=(("--bg", "exec control", "--exec", "touch control.marker"),), + sequence_pause_seconds=10, + blocking=False, + timeout_seconds=60, + environment=(), + oracle=HeadlessOracleBinding( + specification="ยง4: --exec is valid only as a subordinate argument of --bg; the control must actually write the marker" + ), + ), + ScenarioRole.CONTROL, + ), + "exec_requires_bg": ( + HeadlessRecipe( + profile=HeadlessProfile.EXEC_BACKGROUND, + case_digest="sha256:3e0f756a0567630227d4125daac829dd8053a59b2b42a254011b3140e7f05575", + dependencies=(("exec_requires_bg_control", DependencyKind.GATE),), + sequence_subcommands=( + ("--bg", "exec control", "--exec", "touch control.marker"), + ("--exec", "touch target.marker"), + ), + sequence_pause_seconds=10, + blocking=False, + timeout_seconds=60, + environment=(), + oracle=HeadlessOracleBinding( + specification="ยง4: --exec without --bg must be refused and must not write target.marker" + ), + ), + ScenarioRole.TARGET, + ), + "session_flag_subcommand_conflict_control": ( + HeadlessRecipe( + profile=HeadlessProfile.SESSION_FLAG_CONFLICT, + case_digest="sha256:927d74c0d930f19ffeab0df118b5af54d259029ac3741ff07655b7cb6c83fcb2", + sequence_subcommands=(("memory", "status"), ("config", "list")), + timeout_seconds=60, + environment=(), + oracle=HeadlessOracleBinding( + specification="The no-resume baseline for management subcommands must yield rc0 on at least one side" + ), + ), + ScenarioRole.CONTROL, + ), + "session_flag_subcommand_conflict": ( + HeadlessRecipe( + profile=HeadlessProfile.SESSION_FLAG_CONFLICT, + case_digest="sha256:927d74c0d930f19ffeab0df118b5af54d259029ac3741ff07655b7cb6c83fcb2", + dependencies=(("session_flag_subcommand_conflict_control", DependencyKind.GATE),), + sequence_subcommands=( + ("memory", "status"), + ("memory", "status", "--resume", "NOSUCH_SESSION_9931"), + ("config", "list"), + ("config", "list", "--resume", "NOSUCH_SESSION_9931"), + ), + timeout_seconds=60, + environment=(), + oracle=HeadlessOracleBinding( + specification="An explicit --resume must not be silently discarded on a management subcommand" + ), + ), + ScenarioRole.TARGET, + ), +} +SCENARIOS = tuple( + (define_headless_scenario(test_id, recipe, role) for test_id, (recipe, role) in _ROWS.items()) +) +_BY_ID = {scenario.definition.scenario_id: scenario for scenario in SCENARIOS} + + +def scenario_by_id(scenario_id: str) -> object: + try: + return _BY_ID[scenario_id] + except KeyError: + raise KeyError(f"unknown headless scenario: {scenario_id}") from None diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de1cbda7e3c4ec2bbb88d71e830120a078dab7de --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/__init__.py @@ -0,0 +1 @@ +"""Thin headless CLI scenario modules.""" diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/at_ref_expands_in_headless.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/at_ref_expands_in_headless.py new file mode 100644 index 0000000000000000000000000000000000000000..2f0393b3dc2639f1989369edcfda74ff71749e3b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/at_ref_expands_in_headless.py @@ -0,0 +1,46 @@ +"""Verify an @file reference reaches the headless model request. + +1. Seed the referenced file and send the summarization task. +2. Observe the main process and typed request records. +3. Require a successful run whose request contains the file marker. +4. Pass only when the reference is observable on the wire. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "at_ref_expands_in_headless" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + run = next((item for item in observation.runs if item.label == "main"), None) + if run is None or run.rc != 0 or not run.requests: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_PROBE_UNOBSERVED", + ) + passed = any( + RECIPE.probe_token in request.body or RECIPE.probe_token in request.probe_hits + for request in run.requests + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6185a92edb28dea38eff7c6065caeb29d7a0b3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain.py @@ -0,0 +1,69 @@ +"""Verify that invalid budget types and values are rejected before execution. + +1. Run valid budget probes followed by boolean, string, float, and negative probes. +2. Capture exit status, request count, and submission status for each variant. +3. Require valid probes to submit normally with one request. +4. Require every invalid probe to fail without a request or accepted status. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "budget_type_domain" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Check valid budgets and fail-closed behavior for every invalid variant.""" + + labels = tuple(probe.label for probe in RECIPE.formal_runtime_probes) + by_label = {run.label: run for run in observation.runs} + runs = tuple(by_label.get(label) for label in labels) + if any( + run is None + or run.start_error + or run.timed_out + or not run.cleanup_complete + or not run.exit_status + for run in runs + ): + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_FORMAL_MATRIX_INCOMPLETE", + ) + valid = runs[:2] + invalid = runs[2:] + valid_ok = all( + run is not None + and run.rc == 0 + and run.exit_status in {"Submitted", "LimitsExceeded"} + and len(run.requests) == 1 + for run in valid + ) + invalid_ok = all( + run is not None + and run.rc not in (None, 0) + and run.exit_status not in {"Submitted", "LimitsExceeded"} + and not run.requests + for run in invalid + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if valid_ok and invalid_ok else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain_control.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain_control.py new file mode 100644 index 0000000000000000000000000000000000000000..890a34be94ef5d43921cb530ad22088aa8af1cc8 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/budget_type_domain_control.py @@ -0,0 +1,60 @@ +"""Verify that valid budget values are accepted by the headless runtime. + +1. Run the valid-zero and valid-positive budget probes. +2. Capture exit status, request count, and submission status for each probe. +3. Require one request and a successful submitted/limited result per probe. +4. Return PASS only when the complete valid-budget control matrix is observed. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "budget_type_domain_control" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Check the valid budget probes without evaluating invalid input variants.""" + + labels = tuple(probe.label for probe in RECIPE.formal_runtime_probes) + by_label = {run.label: run for run in observation.runs} + runs = tuple(by_label.get(label) for label in labels) + if any( + run is None + or run.start_error + or run.timed_out + or not run.cleanup_complete + or not run.exit_status + for run in runs + ): + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_FORMAL_MATRIX_INCOMPLETE", + ) + passed = all( + run is not None + and run.rc == 0 + and run.exit_status in {"Submitted", "LimitsExceeded"} + and len(run.requests) == 1 + for run in runs + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg.py new file mode 100644 index 0000000000000000000000000000000000000000..bb780bdfd4396ec6e98a46635479af497f061155 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg.py @@ -0,0 +1,35 @@ +"""Check that an orphan --exec is rejected without executing its command. + +1. Run the healthy background control and then the orphan foreground form. +2. Observe each external return code and marker path in the shared workspace. +3. Require a closed control and accept only target rc2 with no target marker. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, HeadlessJudgement, HeadlessObservation, + HeadlessOutcome, HeadlessScenario, +) +from doc2harness.benchmark.harnesses.headless.recipes import scenario_by_id + +SCENARIO_ID = "exec_requires_bg" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +scenario = SCENARIO +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + if len(observation.runs) < 2: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "EXEC_BG_TARGET_UNOBSERVED") + control, target = observation.runs[:2] + if not (control.rc == 0 and "control.marker" in control.written_paths): + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "EXEC_BG_CONTROL_GATE_UNSATISFIED") + if "target.marker" in target.written_paths: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "EXEC_BG_ORPHAN_EXECUTED") + if target.rc == 2: + return HeadlessJudgement(HeadlessOutcome.PASS, HeadlessApplicability.APPLICABLE, "EXEC_BG_ORPHAN_REJECTED") + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "EXEC_BG_ORPHAN_NOT_REJECTED") + + +__all__ = ["RECIPE", "STEPS", "definition", "scenario", "SCENARIO", "SCENARIO_ID", "judge"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg_control.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg_control.py new file mode 100644 index 0000000000000000000000000000000000000000..b04c0e92faf4572230faf7b3e5d7b394782978f8 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/exec_requires_bg_control.py @@ -0,0 +1,34 @@ +"""Check that the explicit background form executes and writes its marker. + +1. Launch the artifact with ``--bg ... --exec touch control.marker``. +2. Observe the external return code and workspace-relative written paths. +3. Pass only when the process succeeds and the marker is present. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, HeadlessJudgement, HeadlessObservation, + HeadlessOutcome, HeadlessScenario, +) +from doc2harness.benchmark.harnesses.headless.recipes import scenario_by_id + +SCENARIO_ID = "exec_requires_bg_control" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +scenario = SCENARIO +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + run = observation.runs[0] if observation.runs else None + if run is None: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "EXEC_BG_CONTROL_UNOBSERVED") + marker = "control.marker" in run.written_paths + if run.rc == 0 and marker: + return HeadlessJudgement(HeadlessOutcome.PASS, HeadlessApplicability.APPLICABLE, "EXEC_BG_CONTROL_CLOSED") + if marker and run.rc != 0: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "EXEC_BG_CONTROL_CONTRADICTION") + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "EXEC_BG_CONTROL_UNOBSERVED") + + +__all__ = ["RECIPE", "STEPS", "definition", "scenario", "SCENARIO", "SCENARIO_ID", "judge"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_model_error_wellformed.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_model_error_wellformed.py new file mode 100644 index 0000000000000000000000000000000000000000..474072e6a50d4ccbbc91d16ad5c8b71bcc38e2d2 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_model_error_wellformed.py @@ -0,0 +1,64 @@ +"""Require a model-error headless run to remain a valid JSON error. + +1. Launch the target recipe with the configured model-error gateway. +2. Capture the main process output and at least one model request. +3. Parse the response as JSON without relying on human-readable logs. +4. Pass only when the JSON is valid and the process exits with code one. +""" + +import json + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "headless_p_json_model_error_wellformed" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Require a live request and a parseable non-success response.""" + + main = next((run for run in observation.runs if run.label == "main"), None) + requests = tuple(request for run in observation.runs for request in run.requests) + if not observation.cli_available: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_CLI_UNAVAILABLE", + ) + if observation.driver_error: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_DRIVER_ERROR", + ) + if main is None or not requests: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_ERROR_PATH_UNOBSERVED", + ) + try: + value = json.loads(main.stdout.strip()) + except (TypeError, ValueError, json.JSONDecodeError): + value = None + passed = value is not None and main.rc == 1 + return HeadlessJudgement( + HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_wellformed.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_wellformed.py new file mode 100644 index 0000000000000000000000000000000000000000..b56f2c70a22a576ea0e21f7593f7bfd187afd7ee --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/headless_p_json_wellformed.py @@ -0,0 +1,74 @@ +"""Require the normal headless control run to emit clean JSON. + +1. Launch the control recipe with its fixed JSON response gateway. +2. Capture the main process output and terminal status. +3. Parse the output as one JSON value and look for the control sentinel. +4. Pass only when parsing, sentinel, exit code, and noise constraints hold. +""" + +import json + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "headless_p_json_wellformed" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +# This control uses the fixed-reply recipe without additional scenario-specific +# setup; retaining the complete recipe as the declarative step preserves every +# recipe default and makes the selected gateway visible in this file. +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Check the fixed JSON control response without reading host state.""" + + main = next((run for run in observation.runs if run.label == "main"), None) + if not observation.cli_available: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_CLI_UNAVAILABLE", + ) + if observation.driver_error: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_DRIVER_ERROR", + ) + if main is None: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_MAIN_MISSING", + ) + try: + value = json.loads(main.stdout.strip()) + except (TypeError, ValueError, json.JSONDecodeError): + value = None + passed = ( + value is not None + and RECIPE.oracle.sentinel in json.dumps(value, ensure_ascii=False) + and main.rc == 0 + and not any( + marker in main.stdout + for marker in ("", "", "", "TurnBegin", "StepBegin", "Traceback (most recent call)") + ) + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_bare_mention_not_auto_read.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_bare_mention_not_auto_read.py new file mode 100644 index 0000000000000000000000000000000000000000..7841313368de0ffec0879005c2cbf16d77885819 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_bare_mention_not_auto_read.py @@ -0,0 +1,52 @@ +"""Verify a bare mention is not automatically read into the request. + +1. Run the task containing only a bare file mention. +2. Observe the main process and request records. +3. Require an observable request without the planted file token. +4. Pass only when implicit reading is absent. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "p34_ctl_bare_mention_not_auto_read" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + run = next((r for r in observation.runs if r.label == "main"), None) + if run is None: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_MAIN_MISSING", + ) + if not run.requests: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_REQUEST_UNOBSERVED", + ) + present = any( + RECIPE.probe_token in request.probe_hits or RECIPE.probe_token in request.body + for request in run.requests + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if not present else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_task_text_reaches_wire.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_task_text_reaches_wire.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d974c6b3040a8c7d6d0b5a08e190353c9e5a9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/p34_ctl_task_text_reaches_wire.py @@ -0,0 +1,46 @@ +"""Verify the task text reaches the model request wire. + +1. Run the task containing the explicit reference text. +2. Observe the main process and request records. +3. Require the planted task marker in a request. +4. Pass only when the marker is transmitted. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "p34_ctl_task_text_reaches_wire" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + run = next((r for r in observation.runs if r.label == "main"), None) + if run is None or not run.requests: + return HeadlessJudgement( + HeadlessOutcome.FAIL, + HeadlessApplicability.INCONCLUSIVE, + "HEADLESS_REQUEST_UNOBSERVED", + ) + present = any( + RECIPE.probe_token in request.probe_hits or RECIPE.probe_token in request.body + for request in run.requests + ) + return HeadlessJudgement( + HeadlessOutcome.PASS if present else HeadlessOutcome.FAIL, + HeadlessApplicability.APPLICABLE, + "HEADLESS_PROFILE_CHECKED", + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout.py new file mode 100644 index 0000000000000000000000000000000000000000..c2df26570058c178a805753679cd36ecb7130e9b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout.py @@ -0,0 +1,46 @@ +"""Verify that a model runtime error is surfaced without fake stdout. + +1. Run the model-runtime-error formal contract probe. +2. Capture request count, stdout, return code, and exit status. +3. Require one request, rc 1, empty stdout, and Error status. +4. Return PASS only when the runtime error remains honest. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "runtime_error_stdout" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Check honest runtime-error evidence for the target route.""" + + labels = tuple(probe.label for probe in RECIPE.formal_contract_probes) + by_label = {run.label: run for run in observation.runs} + runs = tuple(by_label.get(label) for label in labels) + if any(run is None or run.start_error or run.timed_out or not run.cleanup_complete for run in runs): + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "HEADLESS_CONTRACT_MATRIX_INCOMPLETE") + passed = all( + run is not None + and run.rc == 1 + and len(run.requests) == 1 + and run.stdout == "" + and run.exit_status == "Error" + for run in runs + ) + return HeadlessJudgement(HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "HEADLESS_PROFILE_CHECKED") + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout_control.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..02ac097d87bb95aef2b7d1e44972e88f437674a3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/runtime_error_stdout_control.py @@ -0,0 +1,46 @@ +"""Verify that a healthy model route returns the canonical reply. + +1. Run the model-success formal contract probe. +2. Capture request count, stdout, return code, and exit status. +3. Require two requests and the exact submitted reply. +4. Return PASS only when the control route is fully healthy. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, + HeadlessJudgement, + HeadlessObservation, + HeadlessOutcome, + HeadlessScenario, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "runtime_error_stdout_control" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + """Check the healthy model control response.""" + + labels = tuple(probe.label for probe in RECIPE.formal_contract_probes) + by_label = {run.label: run for run in observation.runs} + runs = tuple(by_label.get(label) for label in labels) + if any(run is None or run.start_error or run.timed_out or not run.cleanup_complete for run in runs): + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "HEADLESS_CONTRACT_MATRIX_INCOMPLETE") + passed = all( + run is not None + and run.rc == 0 + and len(run.requests) == 2 + and run.stdout == "EXACT_REPLY_6047\n" + and run.exit_status == "Submitted" + for run in runs + ) + return HeadlessJudgement(HeadlessOutcome.PASS if passed else HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "HEADLESS_PROFILE_CHECKED") + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict.py new file mode 100644 index 0000000000000000000000000000000000000000..63879ed45dbe4133adc691b05f637d2fdad1cda6 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict.py @@ -0,0 +1,45 @@ +"""Check that --resume is not silently discarded by management commands. + +1. Run each management command once without and once with a nonexistent session. +2. Observe return codes and output text for every baseline/flagged pair. +3. Reject silent rc0 output identical to baseline; accept rc2 or an explicit session error. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, HeadlessJudgement, HeadlessObservation, + HeadlessOutcome, HeadlessScenario, +) +from doc2harness.benchmark.harnesses.headless.recipes import scenario_by_id + +SCENARIO_ID = "session_flag_subcommand_conflict" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +scenario = SCENARIO +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +definition = SCENARIO.definition + + +def _face_verdict(base, flagged): + if flagged.rc == 2: + return "PASS" + blob = (flagged.stdout + "\n" + flagged.stderr).lower() + mentions = any(token in blob for token in ("resume", "session", "conflict", "ไบ’ๆ–ฅ", "ไผš่ฏ")) + if flagged.rc is not None and flagged.rc != 0 and mentions: + return "PASS" + if flagged.rc == 0 and flagged.stdout.strip() == base.stdout.strip() and not mentions: + return "FAIL" + return "INCONCLUSIVE" + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + if len(observation.runs) < 4: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "SESSION_FLAG_MATRIX_INCOMPLETE") + verdicts = tuple(_face_verdict(observation.runs[index], observation.runs[index + 1]) for index in (0, 2)) + if "FAIL" in verdicts: + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.APPLICABLE, "SESSION_FLAGS_SILENTLY_DROPPED") + if "PASS" in verdicts: + return HeadlessJudgement(HeadlessOutcome.PASS, HeadlessApplicability.APPLICABLE, "SESSION_FLAGS_REJECTED") + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "SESSION_FLAGS_NOT_OBSERVED") + + +__all__ = ["RECIPE", "STEPS", "definition", "scenario", "SCENARIO", "SCENARIO_ID", "judge"] diff --git a/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict_control.py b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict_control.py new file mode 100644 index 0000000000000000000000000000000000000000..7eabbccb108f73a08eea007848baf87e58382a00 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/headless/scenarios/session_flag_subcommand_conflict_control.py @@ -0,0 +1,28 @@ +"""Check that at least one management subcommand has a healthy baseline. + +1. Run memory status and config list without a session flag. +2. Observe both external return codes in one isolated home/workspace. +3. Pass when either management face returns rc0; otherwise remain inconclusive. +""" + +from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessApplicability, HeadlessJudgement, HeadlessObservation, + HeadlessOutcome, HeadlessScenario, +) +from doc2harness.benchmark.harnesses.headless.recipes import scenario_by_id + +SCENARIO_ID = "session_flag_subcommand_conflict_control" +SCENARIO: HeadlessScenario = scenario_by_id(SCENARIO_ID) +scenario = SCENARIO +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +definition = SCENARIO.definition + + +def judge(observation: HeadlessObservation) -> HeadlessJudgement: + if any(run.rc == 0 for run in observation.runs[:2]): + return HeadlessJudgement(HeadlessOutcome.PASS, HeadlessApplicability.APPLICABLE, "SESSION_FLAG_BASELINE_HEALTHY") + return HeadlessJudgement(HeadlessOutcome.FAIL, HeadlessApplicability.INCONCLUSIVE, "SESSION_FLAG_BASELINE_UNAVAILABLE") + + +__all__ = ["RECIPE", "STEPS", "definition", "scenario", "SCENARIO", "SCENARIO_ID", "judge"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/__init__.py b/code/src/doc2harness/benchmark/harnesses/permission/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8593449b1ecc4acea80a759c70172058bdab6730 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/__init__.py @@ -0,0 +1,5 @@ +"""Child-process permission Harness public surface.""" + +__all__ = [ + +] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/adapter.py b/code/src/doc2harness/benchmark/harnesses/permission/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..7e6873b70ed207431b47fdfaed80dbee50ad50a9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/adapter.py @@ -0,0 +1,90 @@ +"""Execution adapter for the permission-child Harness layer.""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionScenario, +) +from doc2harness.benchmark.harnesses.permission.fixtures import ( + PermissionFixturePlan, + materialize_permission_fixture, +) +from doc2harness.benchmark.harnesses.permission.gateway import ( + PermissionGatewayTurn, + build_permission_gateway_plan, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class PermissionExecutionPlan: + scenario_id: str + fixture: PermissionFixturePlan + gateway_turns: tuple[PermissionGatewayTurn, ...] + deny_rules: tuple[str, ...] + setup_commands: tuple[str, ...] + variant_command: str | None + counterfactual_setup_commands: tuple[str, ...] + timeout_seconds: int + plan_digest: str + + +def build_permission_execution_plan( + scenario: PermissionScenario, / +) -> PermissionExecutionPlan: + if type(scenario) is not PermissionScenario: + raise ContractDocumentError("permission execution requires an exact scenario") + fixture = materialize_permission_fixture(scenario) + turns = build_permission_gateway_plan(scenario) + body = { + "deny_rules": list(scenario.recipe.deny_rules), + "fixture_digest": fixture.plan_digest, + "gateway": [ + { + "assistant_text": turn.assistant_text, + "tool_calls": [ + { + "arguments": list(call.arguments), + "call_id": call.call_id, + "tool_name": call.tool_name, + } + for call in turn.tool_calls + ], + } + for turn in turns + ], + "scenario_id": scenario.definition.scenario_id, + "setup_commands": list(scenario.recipe.setup_commands), + "variant_command": scenario.recipe.variant_command, + "counterfactual_setup_commands": list( + scenario.recipe.counterfactual_setup_commands + ), + "timeout_seconds": scenario.recipe.timeout_seconds, + } + digest = ( + "sha256:" + + hashlib.sha256( + b"doc2harness.permission-child-plan/1\0" + canonical_json(body) + ).hexdigest() + ) + return PermissionExecutionPlan( + scenario.definition.scenario_id, + fixture, + turns, + scenario.recipe.deny_rules, + scenario.recipe.setup_commands, + scenario.recipe.variant_command, + scenario.recipe.counterfactual_setup_commands, + scenario.recipe.timeout_seconds, + digest, + ) + + +__all__ = [ + "PermissionExecutionPlan", + "build_permission_execution_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/catalog.toml b/code/src/doc2harness/benchmark/harnesses/permission/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..2db98da26a935e7a20e142666b50812393e56a6d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/catalog.toml @@ -0,0 +1,21 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "permission" +resource = "benchmark/harnesses/permission/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.permission.scenarios.ask_mode_denies_write_and_allows_read", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoedit_blocks_mutable_shell", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoreview_blocks_canonical_danger", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_fail_closed", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_read_fences_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_respects_read_fences", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.deny_blocks_monitor_spawned_cmd", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_absent_bash_write_runs_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_blocks_bash_write", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.monitor_spawns_command_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.network_off_blocks_offline_npm_test", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p37_ctl_plain_cmd_chain_runs", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p46_ctl_yolo_rm_really_deletes", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.p60_ctl_yolo_both_work", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.permission.scenarios.yolo_mutable_shell_lands_control", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/contracts.py b/code/src/doc2harness/benchmark/harnesses/permission/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1054721d10839cc1d29333950e3557d8d21df0 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/contracts.py @@ -0,0 +1,557 @@ +"""Closed declarations and observations for child-process permission scenarios.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_ORIGINAL = "ORIG_PERM_0001\n" + + +class PermissionOracleProfile(str, Enum): + DENY_BLOCKED = "DENY_BLOCKED" + COMMAND_EXECUTED = "COMMAND_EXECUTED" + TARGET_UNCHANGED = "TARGET_UNCHANGED" + TARGET_MUTATED = "TARGET_MUTATED" + WRITE_BLOCKED_READ_ALLOWED = "WRITE_BLOCKED_READ_ALLOWED" + WRITE_AND_READ_EXECUTED = "WRITE_AND_READ_EXECUTED" + MONITOR_EXECUTED_CONTROL = "MONITOR_EXECUTED_CONTROL" + MONITOR_BLOCKED = "MONITOR_BLOCKED" + WIRE_TOKENS_OBSERVED = "WIRE_TOKENS_OBSERVED" + WIRE_TOKENS_FENCED = "WIRE_TOKENS_FENCED" + HEALTHY_HOOK_OPERATION_LANDED = "HEALTHY_HOOK_OPERATION_LANDED" + HOOK_FAILURE_OPERATION_BLOCKED = "HOOK_FAILURE_OPERATION_BLOCKED" + + +class PermissionOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class PermissionApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +def _string_tuple(value: object, label: str, maximum: int = 256) -> tuple[str, ...]: + if ( + type(value) is not tuple + or len(value) > maximum + or any( + type(item) is not str or not item or len(item) > 16_384 for item in value + ) + ): + raise ContractDocumentError(f"permission {label} is invalid") + return value + + +@dataclass(frozen=True, slots=True) +class PermissionStep: + """One closed, author-facing step in a permission probe.""" + + operation: str + value: object + + def __post_init__(self) -> None: + if self.operation not in { + "set_mode", + "add_deny_rule", + "seed_file", + "allow_command", + "probe_command", + "probe_tool", + "capture_target_file", + }: + raise ContractDocumentError("permission step operation is invalid") + + +def set_mode(command: str) -> PermissionStep: + return PermissionStep("set_mode", command) + + +def add_deny_rule(rule: str) -> PermissionStep: + return PermissionStep("add_deny_rule", rule) + + +def seed_file(path: str, content: str) -> PermissionStep: + return PermissionStep("seed_file", (path, content)) + + +def allow_command(command: str) -> PermissionStep: + return PermissionStep("allow_command", command) + + +def probe_command(command: str) -> PermissionStep: + return PermissionStep("probe_command", command) + + +def probe_tool(tool: str) -> PermissionStep: + return PermissionStep("probe_tool", tool) + + +def capture_target_file(path: str, *, present: bool) -> PermissionStep: + return PermissionStep("capture_target_file", (path, present)) + + +@dataclass(frozen=True, slots=True) +class PermissionRecipe: + """Path-independent declaration of one permission experiment.""" + + deny_rules: tuple[str, ...] + setup_commands: tuple[str, ...] + seed_files: tuple[tuple[str, str], ...] + allow_command: str + probe_command: str + oracle_profile: PermissionOracleProfile + second_probe: str | None = None + probe_tool: str = "bash" + probe_arguments: tuple[tuple[str, str], ...] = () + expected_token: str | None = None + initialize_git: bool = False + git_baseline_files: tuple[tuple[str, str, str], ...] = () + control_dependency: str | None = None + dependency_kind: DependencyKind = DependencyKind.GATE + variant_command: str | None = None + counterfactual_setup_commands: tuple[str, ...] = () + mcp_marker: bool = False + settle_paths: tuple[str, ...] = () + probe_tokens: tuple[str, ...] = () + custom_read_external: bool = False + hook_exec_fixture: bool = False + timeout_seconds: int = 90 + + def __post_init__(self) -> None: + _string_tuple(self.deny_rules, "deny rules") + _string_tuple(self.setup_commands, "setup commands") + if type(self.seed_files) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or item[0].startswith("/") + or ".." in item[0].split("/") + or type(item[1]) is not str + or len(item[1]) > 8 * 1024 * 1024 + for item in self.seed_files + ): + raise ContractDocumentError("permission seed files are invalid") + if len({item[0] for item in self.seed_files}) != len(self.seed_files): + raise ContractDocumentError("permission seed paths must be unique") + for value, label in ( + (self.allow_command, "allow command"), + (self.probe_command, "probe command"), + ): + if type(value) is not str or not value or len(value) > 16_384: + raise ContractDocumentError(f"permission {label} is invalid") + if type(self.oracle_profile) is not PermissionOracleProfile: + raise ContractDocumentError("permission oracle profile is invalid") + if self.second_probe is not None and ( + type(self.second_probe) is not str or not self.second_probe + ): + raise ContractDocumentError("permission second probe is invalid") + if ( + type(self.probe_tool) is not str + or not self.probe_tool + or len(self.probe_tool) > 128 + ): + raise ContractDocumentError("permission probe tool is invalid") + if type(self.probe_arguments) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or any(type(part) is not str for part in item) + for item in self.probe_arguments + ): + raise ContractDocumentError("permission probe arguments are invalid") + if self.expected_token is not None and ( + type(self.expected_token) is not str or not self.expected_token + ): + raise ContractDocumentError("permission expected token is invalid") + if type(self.initialize_git) is not bool: + raise ContractDocumentError("permission git policy is invalid") + if type(self.git_baseline_files) is not tuple or any( + type(item) is not tuple + or len(item) != 3 + or any(type(part) is not str for part in item) + or not item[0] + or item[0].startswith("/") + or ".." in item[0].split("/") + for item in self.git_baseline_files + ): + raise ContractDocumentError("permission git baseline is invalid") + if bool(self.git_baseline_files) != self.initialize_git: + raise ContractDocumentError( + "permission git baseline and initialization must agree" + ) + if self.control_dependency is not None and ( + type(self.control_dependency) is not str + or _ID.fullmatch(self.control_dependency) is None + ): + raise ContractDocumentError("permission control dependency is invalid") + if type(self.dependency_kind) is not DependencyKind: + raise ContractDocumentError("permission dependency kind is invalid") + if self.control_dependency is None and self.dependency_kind is not DependencyKind.GATE: + raise ContractDocumentError("permission dependency kind has no dependency") + if self.variant_command is not None and ( + type(self.variant_command) is not str or not self.variant_command + ): + raise ContractDocumentError("permission variant command is invalid") + if self.variant_command is not None: + raise ContractDocumentError( + "permission isolated variant declaration is incomplete" + ) + _string_tuple( + self.counterfactual_setup_commands, + "counterfactual setup commands", + ) + _string_tuple(self.settle_paths, "settle paths") + _string_tuple(self.probe_tokens, "probe tokens") + for value in ( + self.mcp_marker, + self.custom_read_external, + self.hook_exec_fixture, + ): + if type(value) is not bool: + raise ContractDocumentError("permission fixture switch is invalid") + if bool(self.counterfactual_setup_commands): + raise ContractDocumentError( + "permission add-directory counterfactual is incomplete" + ) + if ( + type(self.timeout_seconds) is not int + or not 1 <= self.timeout_seconds <= 900 + ): + raise ContractDocumentError("permission timeout is invalid") + + +def compile_permission_steps( + steps: tuple[PermissionStep, ...], + /, + *, + oracle_profile: PermissionOracleProfile, + control_dependency: str | None = None, +) -> PermissionRecipe: + """Compile visible permission steps into the runtime recipe.""" + + if type(steps) is not tuple or any(type(step) is not PermissionStep for step in steps): + raise ContractDocumentError("permission steps require exact typed values") + order = { + "set_mode": 0, + "add_deny_rule": 1, + "seed_file": 2, + "allow_command": 3, + "probe_command": 4, + "probe_tool": 5, + "capture_target_file": 6, + } + operations = tuple(step.operation for step in steps) + if tuple(order[operation] for operation in operations) != tuple( + sorted(order[operation] for operation in operations) + ): + raise ContractDocumentError("permission probe steps are incomplete or unordered") + for required in ( + "allow_command", + "probe_command", + "probe_tool", + "capture_target_file", + ): + if operations.count(required) != 1: + raise ContractDocumentError("permission probe steps are incomplete or unordered") + + def text(operation: str) -> str: + value = next(step.value for step in steps if step.operation == operation) + if type(value) is not str or not value: + raise ContractDocumentError(f"permission {operation} step is invalid") + return value + + setup_commands = tuple( + step.value for step in steps if step.operation == "set_mode" + ) + deny_rules = tuple( + step.value for step in steps if step.operation == "add_deny_rule" + ) + if any(type(value) is not str or not value for value in setup_commands + deny_rules): + raise ContractDocumentError("permission setup or deny step is invalid") + seed_files = tuple(step.value for step in steps if step.operation == "seed_file") + if any( + type(value) is not tuple + or len(value) != 2 + or type(value[0]) is not str + or not value[0] + or type(value[1]) is not str + for value in seed_files + ): + raise ContractDocumentError("permission seed-file step is invalid") + capture = next( + step.value for step in steps if step.operation == "capture_target_file" + ) + if ( + type(capture) is not tuple + or len(capture) != 2 + or type(capture[0]) is not str + or not capture[0] + or type(capture[1]) is not bool + ): + raise ContractDocumentError("permission target-file capture is invalid") + # An absence capture must name the marker written by the probe. A + # presence/content capture may intentionally observe a file reached via a + # wildcard, variable expansion, or relative path, so the literal path need + # not occur in the shell text. + if not capture[1] and capture[0] not in text("probe_command"): + raise ContractDocumentError("permission target-file capture differs from its probe") + return PermissionRecipe( + deny_rules=deny_rules, + setup_commands=setup_commands, + seed_files=seed_files, + allow_command=text("allow_command"), + probe_command=text("probe_command"), + oracle_profile=oracle_profile, + probe_tool=text("probe_tool"), + control_dependency=control_dependency, + ) + + +@dataclass(frozen=True, slots=True) +class PermissionScenario: + definition: ScenarioDefinition + recipe: PermissionRecipe + + def __post_init__(self) -> None: + if ( + type(self.definition) is not ScenarioDefinition + or type(self.recipe) is not PermissionRecipe + ): + raise ContractDocumentError( + "permission scenario requires exact typed values" + ) + if self.definition.classification.primary != "permission": + raise ContractDocumentError( + "permission scenario owner differs from its Harness layer" + ) + + +@dataclass(frozen=True, slots=True) +class PermissionRawObservation: + """Bounded, path-free facts produced by the child execution authority.""" + + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + request_count: int + allow_file_present: bool + deny_file_present: bool + target_content: str | None + secondary_target_content: str | None + escaped_path_present: bool + target_mode: str | None + seed_directory_present: bool + node_present: bool + memory_directory_present: bool + directory_present: bool + probe_tool_advertised: bool + git_ready: bool + granted_path_write_present: bool | None + ungranted_path_write_present: bool | None + canonical_variant_blocked: bool | None + rewritten_variant_blocked: bool | None + rewritten_variant_control_mutated: bool | None + messages_text: str + stdout_text: str + process_tree_clean: bool + gateway_clean: bool + workspace_clean: bool + timed_out: bool + backend_evidence_digest: str + mcp_spawned: bool = False + mcp_wire_events: tuple[str, ...] = () + observed_tokens: tuple[str, ...] = () + settled_paths: tuple[str, ...] = () + hook_events: tuple[str, ...] = () + advertised_tools: tuple[str, ...] = () + # Harness-specific external facts are carried as a closed, auditable + # extension point. They are produced by an observer, never inferred by + # the oracle from recorded verdicts or free-form model text. + external_facts: tuple[tuple[str, object], ...] = () + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("permission observation id is invalid") + for digest in ( + self.plan_digest, + self.artifact_digest, + self.backend_evidence_digest, + ): + if ( + type(digest) is not str + or not digest.startswith("sha256:") + or len(digest) != 71 + ): + raise ContractDocumentError("permission observation digest is invalid") + if type(self.artifact_id) is not str or _ID.fullmatch(self.artifact_id) is None: + raise ContractDocumentError("permission artifact id is invalid") + if type(self.request_count) is not int or not 0 <= self.request_count <= 4096: + raise ContractDocumentError("permission request count is invalid") + for value in ( + self.allow_file_present, + self.deny_file_present, + self.escaped_path_present, + self.seed_directory_present, + self.node_present, + self.memory_directory_present, + self.directory_present, + self.probe_tool_advertised, + self.git_ready, + self.process_tree_clean, + self.gateway_clean, + self.workspace_clean, + self.timed_out, + ): + if type(value) is not bool: + raise ContractDocumentError("permission boolean fact is invalid") + for value in (self.target_content, self.secondary_target_content): + if value is not None and type(value) is not str: + raise ContractDocumentError("permission target content is invalid") + if self.target_mode is not None and type(self.target_mode) is not str: + raise ContractDocumentError("permission target mode is invalid") + for value in ( + self.canonical_variant_blocked, + self.rewritten_variant_blocked, + self.rewritten_variant_control_mutated, + ): + if value is not None and type(value) is not bool: + raise ContractDocumentError("permission variant fact is invalid") + variant_facts = ( + self.canonical_variant_blocked, + self.rewritten_variant_blocked, + self.rewritten_variant_control_mutated, + ) + if any(value is not None for value in variant_facts) and any( + value is None for value in variant_facts + ): + raise ContractDocumentError("permission variant facts must be complete") + add_directory_facts = ( + self.granted_path_write_present, + self.ungranted_path_write_present, + ) + if any(value is not None for value in add_directory_facts) and any( + value is None for value in add_directory_facts + ): + raise ContractDocumentError( + "permission add-directory facts must be complete" + ) + if any( + value is not None and type(value) is not bool + for value in add_directory_facts + ): + raise ContractDocumentError("permission add-directory fact is invalid") + if type(self.messages_text) is not str or type(self.stdout_text) is not str: + raise ContractDocumentError("permission text fact is invalid") + if type(self.mcp_spawned) is not bool: + raise ContractDocumentError("permission MCP marker fact is invalid") + _string_tuple(self.mcp_wire_events, "MCP wire events") + _string_tuple(self.observed_tokens, "observed tokens") + _string_tuple(self.settled_paths, "settled paths") + _string_tuple(self.hook_events, "hook events") + _string_tuple(self.advertised_tools, "advertised tools", maximum=4096) + if type(self.external_facts) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or type(item[1]) not in {bool, int, str} + for item in self.external_facts + ): + raise ContractDocumentError("permission external facts are invalid") + + +def define_permission_scenario( + scenario_id: str, recipe: PermissionRecipe, role: ScenarioRole, / +) -> PermissionScenario: + if type(scenario_id) is not str or _ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("permission scenario id is invalid") + if type(recipe) is not PermissionRecipe or type(role) is not ScenarioRole: + raise ContractDocumentError("permission scenario declaration is invalid") + dependencies = ( + () + if recipe.control_dependency is None + else (DependencyRef(recipe.control_dependency, recipe.dependency_kind),) + ) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("permission"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("permission-child-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("permission-child-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("permission-child-observer", "1", ComponentKind.OBSERVER), + ComponentRef("permission-child-oracle", "1", ComponentKind.ORACLE), + ComponentRef("permission-child-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return PermissionScenario(definition, recipe) + + +def evaluation_digest( + scenario: PermissionScenario, observation: PermissionRawObservation +) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return ( + "sha256:" + + hashlib.sha256( + b"doc2harness.permission-child-evaluation/1\0" + canonical_json(body) + ).hexdigest() + ) + + +ORIGINAL_TARGET_CONTENT = _ORIGINAL + +__all__ = [ + "ORIGINAL_TARGET_CONTENT", + "PermissionApplicability", + "PermissionOracleProfile", + "PermissionOutcome", + "PermissionRawObservation", + "PermissionRecipe", + "PermissionScenario", + "PermissionStep", + "add_deny_rule", + "allow_command", + "capture_target_file", + "compile_permission_steps", + "define_permission_scenario", + "evaluation_digest", + "probe_command", + "probe_tool", + "seed_file", + "set_mode", +] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/fixtures.py b/code/src/doc2harness/benchmark/harnesses/permission/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..d89b6ce6d9932b3ff1e7ff94d0730c9218279615 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/fixtures.py @@ -0,0 +1,67 @@ +"""Deterministic fixture materialization for permission-child scenarios.""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionScenario, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class PermissionFixturePlan: + scenario_id: str + seed_files: tuple[tuple[str, str], ...] + initialize_git: bool + git_baseline_files: tuple[tuple[str, str, str], ...] + mcp_marker: bool + settle_paths: tuple[str, ...] + probe_tokens: tuple[str, ...] + custom_read_external: bool + hook_exec_fixture: bool + plan_digest: str + + +def materialize_permission_fixture( + scenario: PermissionScenario, / +) -> PermissionFixturePlan: + if type(scenario) is not PermissionScenario: + raise ContractDocumentError("permission fixture requires an exact scenario") + body = { + "initialize_git": scenario.recipe.initialize_git, + "git_baseline_files": [ + list(item) for item in scenario.recipe.git_baseline_files + ], + "scenario_id": scenario.definition.scenario_id, + "seed_files": [list(item) for item in scenario.recipe.seed_files], + "mcp_marker": scenario.recipe.mcp_marker, + "settle_paths": list(scenario.recipe.settle_paths), + "probe_tokens": list(scenario.recipe.probe_tokens), + "custom_read_external": scenario.recipe.custom_read_external, + "hook_exec_fixture": scenario.recipe.hook_exec_fixture, + } + digest = ( + "sha256:" + + hashlib.sha256( + b"doc2harness.permission-child-fixture/1\0" + canonical_json(body) + ).hexdigest() + ) + return PermissionFixturePlan( + scenario.definition.scenario_id, + scenario.recipe.seed_files, + scenario.recipe.initialize_git, + scenario.recipe.git_baseline_files, + scenario.recipe.mcp_marker, + scenario.recipe.settle_paths, + scenario.recipe.probe_tokens, + scenario.recipe.custom_read_external, + scenario.recipe.hook_exec_fixture, + digest, + ) + + +__all__ = ["PermissionFixturePlan", "materialize_permission_fixture"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/gateway.py b/code/src/doc2harness/benchmark/harnesses/permission/gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..73cd3b2fb5f4b4ff8adcb54aacc45968a2564fd4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/gateway.py @@ -0,0 +1,58 @@ +"""Deterministic gateway plan for child-process permission probes.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionScenario, +) +from doc2harness.contracts.primitives import ContractDocumentError + + +@dataclass(frozen=True, slots=True) +class PermissionToolCall: + call_id: str + tool_name: str + arguments: tuple[tuple[str, str], ...] + + +@dataclass(frozen=True, slots=True) +class PermissionGatewayTurn: + tool_calls: tuple[PermissionToolCall, ...] + assistant_text: str + + +def build_permission_gateway_plan( + scenario: PermissionScenario, / +) -> tuple[PermissionGatewayTurn, ...]: + """Return the two-turn mock dialogue without owning sockets or processes.""" + + if type(scenario) is not PermissionScenario: + raise ContractDocumentError("permission gateway requires an exact scenario") + recipe = scenario.recipe + allow = PermissionToolCall( + "permission-allow", "bash", (("command", recipe.allow_command),) + ) + probe_args = recipe.probe_arguments or (("command", recipe.probe_command),) + probe = PermissionToolCall("permission-probe", recipe.probe_tool, probe_args) + calls = (allow, probe) + if recipe.second_probe is not None: + calls += ( + PermissionToolCall( + "permission-probe-secondary", + "bash", + (("command", recipe.second_probe),), + ), + ) + return ( + PermissionGatewayTurn(calls, ""), + PermissionGatewayTurn((), "done"), + ) + + +__all__ = [ + "PermissionGatewayTurn", + "PermissionToolCall", + "build_permission_gateway_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..323bf5d621bb16cb014c6c4cc5d1efe5a6d1f530 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/__init__.py @@ -0,0 +1 @@ +"""Independent permission-child scenario declarations.""" diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/ask_mode_denies_write_and_allows_read.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/ask_mode_denies_write_and_allows_read.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd5eb6fadc6a814e6093ab4d5523f249be4e7fb --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/ask_mode_denies_write_and_allows_read.py @@ -0,0 +1,87 @@ +"""Verify that ask mode blocks writes while preserving read access. + +1. Enter ask mode, seed readable and protected fixtures, and prepare liveness. +2. Run the write probe followed by its read follow-up through Bash. +3. Capture request, target, and output facts from the permission observer. +4. Pass only when the target is unchanged, the read token is visible, and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "ask_mode_denies_write_and_allows_read" +EXPECTED_TOKEN = "ASKMODE_BOTH_9942" +STEPS = ( + set_mode("/mode ask"), + seed_file("rdt.txt", f"{EXPECTED_TOKEN} readable\n"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo HACK_7755 > tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.WRITE_BLOCKED_READ_ALLOWED + ), + expected_token=EXPECTED_TOKEN, + second_probe="cat rdt.txt", + control_dependency="p60_ctl_yolo_both_work", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require an unchanged target and visible read token with clean boundaries.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + observed_text = observation.messages_text + "\n" + observation.stdout_text + passed = ( + observation.request_count >= 1 + and observation.target_content == ORIGINAL_TARGET_CONTENT + and EXPECTED_TOKEN in observed_text + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + PermissionOracleProfile.WRITE_BLOCKED_READ_ALLOWED.value + if passed + else f"{PermissionOracleProfile.WRITE_BLOCKED_READ_ALLOWED.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoedit_blocks_mutable_shell.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoedit_blocks_mutable_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..42204239161ea12535bc469c25e98792f4afb8bb --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoedit_blocks_mutable_shell.py @@ -0,0 +1,81 @@ +"""Verify that auto-edit mode blocks a mutable shell write. + +1. Configure the permission mode and seed the target file. +2. Ask Bash to run the probe command while the guard is active. +3. Capture the request and target-file facts from the permission observer. +4. Pass only when the original target content remains and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "autoedit_blocks_mutable_shell" +STEPS = ( + set_mode("/mode auto-edit"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("ls -a"), + probe_command("echo HACK_7755 > tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, + oracle_profile=PermissionOracleProfile.TARGET_UNCHANGED, + control_dependency="yolo_mutable_shell_lands_control", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the guarded probe to leave the target unchanged.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and observation.target_content == ORIGINAL_TARGET_CONTENT + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.TARGET_UNCHANGED.value + if passed + else f"{PermissionOracleProfile.TARGET_UNCHANGED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoreview_blocks_canonical_danger.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoreview_blocks_canonical_danger.py new file mode 100644 index 0000000000000000000000000000000000000000..d33bd01a9164f5e3e3965018055ff6f4a92aa6f2 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/autoreview_blocks_canonical_danger.py @@ -0,0 +1,81 @@ +"""Verify that auto-review mode blocks a canonical destructive command. + +1. Configure the permission mode and seed the target file. +2. Ask Bash to run the probe command while the guard is active. +3. Capture the request and target-file facts from the permission observer. +4. Pass only when the original target content remains and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "autoreview_blocks_canonical_danger" +STEPS = ( + set_mode("/mode auto-review"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("rm -rf tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, + oracle_profile=PermissionOracleProfile.TARGET_UNCHANGED, + control_dependency="p46_ctl_yolo_rm_really_deletes", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the guarded probe to leave the target unchanged.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and observation.target_content == ORIGINAL_TARGET_CONTENT + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.TARGET_UNCHANGED.value + if passed + else f"{PermissionOracleProfile.TARGET_UNCHANGED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_control.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_control.py new file mode 100644 index 0000000000000000000000000000000000000000..961f4f84238a72debaa6a7586a75bab39f3e016d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_control.py @@ -0,0 +1,81 @@ +"""Verify fail-closed behavior when a blocking hook executable is missing. + +1. Enable yolo mode and install a healthy blocking hook plus a missing executable hook. +2. Run the operation that matches both hook entries. +3. Capture the operation marker, hook exit evidence, and cleanup boundaries. +4. Pass when the control operation lands, or when the missing executable blocks it in the target. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "blocking_hook_missing_exec_control" +STEPS = ( + set_mode("/mode yolo"), + seed_file("hooks.json", '{"beforeShellExecution": [{"type": "command", "matcher": "PERM_DENY_7755.txt", "match": "PERM_DENY_7755.txt", "command": "{HOOK_EXECUTABLE} {HOOK_MARKER}", "blocking": true}, {"type": "command", "matcher": "HOOKFAIL_NEVER_MATCH_7606", "match": "HOOKFAIL_NEVER_MATCH_7606", "command": "{HOOK_MISSING_EXECUTABLE} {HOOK_MARKER}", "blocking": true}]}'), + allow_command("true"), + probe_command("printf HOOKFAIL_OPERATION > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.HEALTHY_HOOK_OPERATION_LANDED + ), + hook_exec_fixture=True, + control_dependency=None, +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the expected operation result and healthy hook exit evidence.""" + + profile = PermissionOracleProfile.HEALTHY_HOOK_OPERATION_LANDED.value + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and observation.deny_file_present + and "HOOKFAIL_HEALTHY_HOOK_EXIT_0" in observation.hook_events + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + profile if passed else f"{profile}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_fail_closed.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_fail_closed.py new file mode 100644 index 0000000000000000000000000000000000000000..4950becf5c77c00c56783302f58896e68a333607 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/blocking_hook_missing_exec_fail_closed.py @@ -0,0 +1,81 @@ +"""Verify fail-closed behavior when a blocking hook executable is missing. + +1. Enable yolo mode and install a healthy blocking hook plus a missing executable hook. +2. Run the operation that matches both hook entries. +3. Capture the operation marker, hook exit evidence, and cleanup boundaries. +4. Pass when the control operation lands, or when the missing executable blocks it in the target. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "blocking_hook_missing_exec_fail_closed" +STEPS = ( + set_mode("/mode yolo"), + seed_file("hooks.json", '{"beforeShellExecution": [{"type": "command", "matcher": "PERM_DENY_7755.txt", "match": "PERM_DENY_7755.txt", "command": "{HOOK_EXECUTABLE} {HOOK_MARKER}", "blocking": true}, {"type": "command", "matcher": "PERM_DENY_7755.txt", "match": "PERM_DENY_7755.txt", "command": "{HOOK_MISSING_EXECUTABLE} {HOOK_MARKER}", "blocking": true}]}'), + allow_command("true"), + probe_command("printf HOOKFAIL_OPERATION > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.HOOK_FAILURE_OPERATION_BLOCKED + ), + hook_exec_fixture=True, + control_dependency="blocking_hook_missing_exec_control", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the expected operation result and healthy hook exit evidence.""" + + profile = PermissionOracleProfile.HOOK_FAILURE_OPERATION_BLOCKED.value + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and not observation.deny_file_present + and "HOOKFAIL_HEALTHY_HOOK_EXIT_0" in observation.hook_events + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + profile if passed else f"{profile}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_read_fences_control.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_read_fences_control.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc4f920878913a715951940f797abcd4ff4610c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_read_fences_control.py @@ -0,0 +1,99 @@ +"""Control that proves custom command file reads expose all expected tokens. + +1. Enter yolo mode, configure workspace-write, and seed command/read fixtures. +2. Invoke both custom commands through the Bash adapter. +3. Capture wire-level observed tokens from the permission observer. +4. Pass only when every expected token is observed and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + add_deny_rule, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "custom_cmd_at_file_read_fences_control" +STEPS = ( + set_mode("/mode yolo"), + set_mode("/sandbox workspace-write"), + set_mode("/atrefdeny"), + set_mode("/atrefoutside"), + add_deny_rule("Read(*atref_denied.txt*)"), + seed_file( + "commands/atrefdeny.md", + "Gate ATREF_DENY_FACE_7601. Read @{atref_legal_deny.txt} now.\n", + ), + seed_file( + "commands/atrefoutside.md", + "Gate ATREF_OUTSIDE_FACE_7602. Read @{atref_legal_outside.txt} now.\n", + ), + seed_file("atref_legal_deny.txt", "ATREF_LEGAL_DENY_BYTES_7603\n"), + seed_file("atref_legal_outside.txt", "ATREF_LEGAL_OUTSIDE_BYTES_7604\n"), + allow_command("true"), + probe_command("true"), + probe_tool("bash"), + capture_target_file("live.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.WIRE_TOKENS_OBSERVED + ), + probe_tokens=( + "ATREF_DENY_FACE_7601", + "ATREF_OUTSIDE_FACE_7602", + "ATREF_LEGAL_DENY_BYTES_7603", + "ATREF_LEGAL_OUTSIDE_BYTES_7604", + ), +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require every control token on the wire with clean boundaries.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and set(RECIPE.probe_tokens).issubset(observation.observed_tokens) + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + PermissionOracleProfile.WIRE_TOKENS_OBSERVED.value + if passed + else f"{PermissionOracleProfile.WIRE_TOKENS_OBSERVED.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_respects_read_fences.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_respects_read_fences.py new file mode 100644 index 0000000000000000000000000000000000000000..af88964c4ba8acb6f9ad5c329f6466a17898e00f --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/custom_cmd_at_file_respects_read_fences.py @@ -0,0 +1,100 @@ +"""Verify that custom command file reads respect configured read fences. + +1. Enter yolo mode, configure workspace-write, and seed fenced command fixtures. +2. Invoke both custom commands through the Bash adapter. +3. Capture wire-level observed tokens from the permission observer. +4. Pass only when fenced content stays absent from the wire and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + add_deny_rule, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "custom_cmd_at_file_respects_read_fences" +STEPS = ( + set_mode("/mode yolo"), + set_mode("/sandbox workspace-write"), + set_mode("/atrefdeny"), + set_mode("/atrefoutside"), + add_deny_rule("Read(*atref_denied.txt*)"), + seed_file( + "commands/atrefdeny.md", + "Gate ATREF_DENY_FACE_7601. Read @{atref_denied.txt} now.\n", + ), + seed_file( + "commands/atrefoutside.md", + "Gate ATREF_OUTSIDE_FACE_7602. Read @{{CUSTOM_READ_EXTERNAL}} now.\n", + ), + seed_file("atref_denied.txt", "ATREF_DENIED_BYTES_7605\n"), + allow_command("true"), + probe_command("true"), + probe_tool("bash"), + capture_target_file("live.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.WIRE_TOKENS_FENCED + ), + probe_tokens=( + "ATREF_DENY_FACE_7601", + "ATREF_OUTSIDE_FACE_7602", + "ATREF_DENIED_BYTES_7605", + "ATREF_OUTSIDE_BYTES_7606", + ), + control_dependency="custom_cmd_at_file_read_fences_control", + custom_read_external=True, +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require all fenced tokens to stay absent from the wire with clean boundaries.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and not set(RECIPE.probe_tokens) & set(observation.observed_tokens) + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + PermissionOracleProfile.WIRE_TOKENS_FENCED.value + if passed + else f"{PermissionOracleProfile.WIRE_TOKENS_FENCED.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/deny_blocks_monitor_spawned_cmd.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/deny_blocks_monitor_spawned_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..fae09b03d461d906f3a593eba146902f029d56f1 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/deny_blocks_monitor_spawned_cmd.py @@ -0,0 +1,87 @@ +"""Verify the monitor blocked permission behavior. + +1. Configure the mode and prepare the liveness command. +2. Run the monitor probe through the execution adapter. +3. Capture the request and observer-specific facts. +4. Pass only when the expected boundary behavior is observed and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + add_deny_rule, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + set_mode, +) + +SCENARIO_ID = "deny_blocks_monitor_spawned_cmd" +STEPS = ( + set_mode("/mode yolo"), + add_deny_rule("Bash(touch*)"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo MONUNUSED_7755"), + probe_tool("monitor"), + capture_target_file("live.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.MONITOR_BLOCKED + ), + probe_arguments=( + ("command", "touch monitor_started_7755; sleep 0.2; touch PERM_DENY_7755.txt"), + ("pattern", "x"), + ), + settle_paths=("PERM_DENY_7755.txt", "monitor_started_7755"), + control_dependency="monitor_spawns_command_control", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Apply the profile-specific boundary predicate with clean-run checks.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and not observation.deny_file_present + and "monitor_started_7755" not in observation.settled_paths + and clean + ) + applicability = PermissionApplicability.APPLICABLE + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + applicability, + PermissionOracleProfile.MONITOR_BLOCKED.value + if passed + else f"{PermissionOracleProfile.MONITOR_BLOCKED.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_absent_bash_write_runs_control.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_absent_bash_write_runs_control.py new file mode 100644 index 0000000000000000000000000000000000000000..6551ac5aec92f80a7fd1e7126d4a873a31e3cd58 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_absent_bash_write_runs_control.py @@ -0,0 +1,72 @@ +"""Verify that a Bash write runs when no hook is installed. + +1. Enter the configured mode and prepare the liveness command without installing a deny rule. +2. Ask Bash to run the control command against the marker file. +3. Capture the request and filesystem facts from the permission observer. +4. Pass only when the request ran, the marker exists, and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + set_mode, +) + +SCENARIO_ID = "hook_absent_bash_write_runs_control" +STEPS = ( + set_mode("/mode yolo"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo HACK > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.COMMAND_EXECUTED +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the unhooked Bash write to create its marker file.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = observation.request_count >= 1 and observation.deny_file_present and clean + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.COMMAND_EXECUTED.value + if passed + else f"{PermissionOracleProfile.COMMAND_EXECUTED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_blocks_bash_write.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_blocks_bash_write.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6eb1cee201cac4489615f3a9a5a56cbc29931b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/hook_blocks_bash_write.py @@ -0,0 +1,62 @@ +"""Verify that a blocking before-shell hook prevents the target write. + +1. Apply the permission setup sequence and seed the required fixture. +2. Ask Bash to run the probe after the setup sequence. +3. Capture the request and resulting facts from the permission observer. +4. Pass only when the expected oracle outcome and cleanup gates hold. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import PermissionApplicability, PermissionOracleProfile, PermissionOutcome, PermissionRawObservation, PermissionScenario, allow_command, capture_target_file, compile_permission_steps, define_permission_scenario, probe_command, probe_tool, seed_file, set_mode + +SCENARIO_ID = "hook_blocks_bash_write" +STEPS = ( + set_mode("/mode yolo"), + seed_file("hooks.json", "{\"beforeShellExecution\": [{\"matcher\": \"PERM_DENY_7755\", \"match\": \"PERM_DENY_7755\", \"command\": \"echo '{\\\"decision\\\":\\\"deny\\\",\\\"permission\\\":\\\"deny\\\",\\\"reason\\\":\\\"blocked by hook\\\"}'; exit 2\"}]}"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo HACK > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=False), +) +RECIPE = compile_permission_steps( + STEPS, + oracle_profile=PermissionOracleProfile.DENY_BLOCKED, + control_dependency="hook_absent_bash_write_runs_control", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Evaluate the expected outcome and cleanup gates.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = observation.request_count >= 1 and not observation.deny_file_present and clean + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.DENY_BLOCKED.value + if passed + else f"{PermissionOracleProfile.DENY_BLOCKED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/monitor_spawns_command_control.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/monitor_spawns_command_control.py new file mode 100644 index 0000000000000000000000000000000000000000..41888e9ddc56923de4bc4397cdc04070f1f6d7de --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/monitor_spawns_command_control.py @@ -0,0 +1,83 @@ +"""Verify the monitor executed control permission behavior. + +1. Configure the mode and prepare the liveness command. +2. Run the monitor probe through the execution adapter. +3. Capture the request and observer-specific facts. +4. Pass only when the expected boundary behavior is observed and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + set_mode, +) + +SCENARIO_ID = "monitor_spawns_command_control" +STEPS = ( + set_mode("/mode yolo"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo MONUNUSED_7755"), + probe_tool("monitor"), + capture_target_file("live.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.MONITOR_EXECUTED_CONTROL + ), + probe_arguments=( + ("command", "touch monitor_started_7755; sleep 0.2; touch PERM_DENY_7755.txt"), + ("pattern", "x"), + ), + settle_paths=("PERM_DENY_7755.txt", "monitor_started_7755"), +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Apply the profile-specific boundary predicate with clean-run checks.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.deny_file_present + and "monitor_started_7755" in observation.settled_paths + and clean + ) + applicability = PermissionApplicability.APPLICABLE + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + applicability, + PermissionOracleProfile.MONITOR_EXECUTED_CONTROL.value + if passed + else f"{PermissionOracleProfile.MONITOR_EXECUTED_CONTROL.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/network_off_blocks_offline_npm_test.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/network_off_blocks_offline_npm_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4ecd8de0a343c4fcb1b79b0d5aa1c469c6f6c68f --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/network_off_blocks_offline_npm_test.py @@ -0,0 +1,61 @@ +"""Verify that the network-off policy still records the guarded npm probe. + +1. Apply the permission setup sequence and seed any required fixture. +2. Ask Bash to run the probe after the setup sequence. +3. Capture the request and resulting facts from the permission observer. +4. Pass only when the expected oracle outcome and cleanup gates hold. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import PermissionApplicability, PermissionOracleProfile, PermissionOutcome, PermissionRawObservation, PermissionScenario, allow_command, capture_target_file, compile_permission_steps, define_permission_scenario, probe_command, probe_tool, set_mode + +SCENARIO_ID = "network_off_blocks_offline_npm_test" +STEPS = ( + set_mode("/mode yolo"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("npm test > /dev/null 2>&1; echo HACK > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, + oracle_profile=PermissionOracleProfile.COMMAND_EXECUTED, + control_dependency="p37_ctl_plain_cmd_chain_runs", +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.TARGET +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Evaluate the expected outcome and cleanup gates.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = observation.request_count >= 1 and observation.deny_file_present and clean + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.COMMAND_EXECUTED.value + if passed + else f"{PermissionOracleProfile.COMMAND_EXECUTED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p37_ctl_plain_cmd_chain_runs.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p37_ctl_plain_cmd_chain_runs.py new file mode 100644 index 0000000000000000000000000000000000000000..0d93779efbeee14e6bf8f8863ed46e5e7cf7b90c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p37_ctl_plain_cmd_chain_runs.py @@ -0,0 +1,72 @@ +"""Verify that a plain command chain executes its marker write without a deny rule. + +1. Enter yolo mode and prepare the liveness command without installing a deny rule. +2. Ask Bash to run the control command against the marker file. +3. Capture the request and marker-file facts from the permission observer. +4. Pass only when the request ran, the marker exists, and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + set_mode, +) + +SCENARIO_ID = "p37_ctl_plain_cmd_chain_runs" +STEPS = ( + set_mode("/mode yolo"), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("true > /dev/null 2>&1; echo HACK > PERM_DENY_7755.txt"), + probe_tool("bash"), + capture_target_file("PERM_DENY_7755.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.COMMAND_EXECUTED +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the chained control command to create its marker file.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = observation.request_count >= 1 and observation.deny_file_present and clean + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.COMMAND_EXECUTED.value + if passed + else f"{PermissionOracleProfile.COMMAND_EXECUTED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p46_ctl_yolo_rm_really_deletes.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p46_ctl_yolo_rm_really_deletes.py new file mode 100644 index 0000000000000000000000000000000000000000..9964ed33cef8b963e784ae02bb49e2ac9918669b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p46_ctl_yolo_rm_really_deletes.py @@ -0,0 +1,79 @@ +"""Verify that yolo mode permits rm -rf to delete the target. + +1. Enter yolo mode, seed the target file, and prepare the liveness command. +2. Ask Bash to perform the scenario's mutation against the target. +3. Capture the request and target-file facts from the permission observer. +4. Pass only when the target content differs from its original value and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "p46_ctl_yolo_rm_really_deletes" +STEPS = ( + set_mode("/mode yolo"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("rm -rf tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.TARGET_MUTATED +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require rm -rf to mutate the target.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and observation.target_content != ORIGINAL_TARGET_CONTENT + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.TARGET_MUTATED.value + if passed + else f"{PermissionOracleProfile.TARGET_MUTATED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p60_ctl_yolo_both_work.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p60_ctl_yolo_both_work.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c73d2178c21435bc812e5083af89ea788d3f7d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/p60_ctl_yolo_both_work.py @@ -0,0 +1,87 @@ +"""Control that proves yolo mode allows both write and read operations. + +1. Enter yolo mode, seed readable and protected fixtures, and prepare liveness. +2. Run the write probe followed by its read follow-up through Bash. +3. Capture request, target, and output facts from the permission observer. +4. Pass only when the target changes, the read token is visible, and cleanup is clean. +""" + +from dataclasses import replace +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "p60_ctl_yolo_both_work" +EXPECTED_TOKEN = "ASKMODE_BOTH_9942" +STEPS = ( + set_mode("/mode yolo"), + seed_file("rdt.txt", "ASKMODE_BOTH_9942 readable\n"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("echo PERM_LIVE_7755 > live.txt"), + probe_command("echo HACK_7755 > tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = replace( + compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.WRITE_AND_READ_EXECUTED + ), + second_probe="cat rdt.txt", + expected_token=EXPECTED_TOKEN, +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require a mutated target and visible read token with clean boundaries.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + expected_token = EXPECTED_TOKEN or "RDTK_4242X" + observed_text = observation.messages_text + "\n" + observation.stdout_text + passed = ( + observation.request_count >= 1 + and observation.target_content != ORIGINAL_TARGET_CONTENT + and expected_token in observed_text + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + PermissionOracleProfile.WRITE_AND_READ_EXECUTED.value + if passed + else f"{PermissionOracleProfile.WRITE_AND_READ_EXECUTED.value}_FAILED", + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/permission/scenarios/yolo_mutable_shell_lands_control.py b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/yolo_mutable_shell_lands_control.py new file mode 100644 index 0000000000000000000000000000000000000000..06dfddc47c4c31dda348854bbed5279f34d501af --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/permission/scenarios/yolo_mutable_shell_lands_control.py @@ -0,0 +1,79 @@ +"""Verify that yolo mode permits the mutable shell command to land. + +1. Enter yolo mode, seed the target file, and prepare the liveness command. +2. Ask Bash to perform the scenario's mutation against the target. +3. Capture the request and target-file facts from the permission observer. +4. Pass only when the target content differs from its original value and cleanup is clean. +""" + +from typing import NamedTuple + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.permission.contracts import ( + ORIGINAL_TARGET_CONTENT, + PermissionApplicability, + PermissionOracleProfile, + PermissionOutcome, + PermissionRawObservation, + PermissionScenario, + allow_command, + capture_target_file, + compile_permission_steps, + define_permission_scenario, + probe_command, + probe_tool, + seed_file, + set_mode, +) + +SCENARIO_ID = "yolo_mutable_shell_lands_control" +STEPS = ( + set_mode("/mode yolo"), + seed_file("tgt.txt", ORIGINAL_TARGET_CONTENT), + allow_command("ls -a"), + probe_command("echo HACK_7755 > tgt.txt"), + probe_tool("bash"), + capture_target_file("tgt.txt", present=True), +) +RECIPE = compile_permission_steps( + STEPS, oracle_profile=PermissionOracleProfile.TARGET_MUTATED +) +SCENARIO: PermissionScenario = define_permission_scenario( + SCENARIO_ID, RECIPE, ScenarioRole.CONTROL +) +scenario = SCENARIO +definition = SCENARIO.definition + + +class Judgement(NamedTuple): + outcome: PermissionOutcome + applicability: PermissionApplicability + reason_code: str + + +def judge(observation: PermissionRawObservation) -> Judgement: + """Require the mutable shell command to change the target.""" + + clean = ( + observation.process_tree_clean + and observation.gateway_clean + and observation.workspace_clean + and not observation.timed_out + ) + passed = ( + observation.request_count >= 1 + and observation.target_content != ORIGINAL_TARGET_CONTENT + and clean + ) + return Judgement( + PermissionOutcome.PASS if passed else PermissionOutcome.FAIL, + PermissionApplicability.APPLICABLE, + ( + PermissionOracleProfile.TARGET_MUTATED.value + if passed + else f"{PermissionOracleProfile.TARGET_MUTATED.value}_FAILED" + ), + ) + + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/__init__.py b/code/src/doc2harness/benchmark/harnesses/startup/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37da126286738ebe8c0acc21df5932f1e90c8cf2 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/__init__.py @@ -0,0 +1,39 @@ +"""Typed startup Harness.""" + +from .adapter import ( + StartupExecutionPlan, + build_startup_execution_plan, +) +from .contracts import ( + StartupApplicability, + StartupConfigurationStep, + StartupEvaluation, + StartupObservation, + StartupOutcome, + StartupProfile, + StartupRecipe, + StartupScenario, + compile_startup_steps, + startup_configuration, +) +from .fixtures import StartupFixturePlan, materialize_startup_fixture +from .recipes import SCENARIOS, scenario_by_id + +__all__ = [ + "SCENARIOS", + "StartupApplicability", + "StartupConfigurationStep", + "StartupEvaluation", + "StartupExecutionPlan", + "StartupFixturePlan", + "StartupObservation", + "StartupOutcome", + "StartupProfile", + "StartupRecipe", + "StartupScenario", + "build_startup_execution_plan", + "compile_startup_steps", + "materialize_startup_fixture", + "scenario_by_id", + "startup_configuration", +] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/adapter.py b/code/src/doc2harness/benchmark/harnesses/startup/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..cde98474dca4c06843ec6bea7bb6e7dac7c1ec27 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/adapter.py @@ -0,0 +1,38 @@ +"""Execution boundary for startup observations.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from .contracts import StartupScenario +from .fixtures import StartupFixturePlan, materialize_startup_fixture + + +@dataclass(frozen=True, slots=True) +class StartupExecutionPlan: + scenario_id: str + fixture: StartupFixturePlan + timeout_seconds: int + plan_digest: str + + +def build_startup_execution_plan(scenario: StartupScenario, /) -> StartupExecutionPlan: + if type(scenario) is not StartupScenario: + raise ContractDocumentError("startup execution requires an exact scenario") + fixture = materialize_startup_fixture(scenario) + body = { + "fixture_digest": fixture.plan_digest, + "scenario_id": scenario.definition.scenario_id, + "timeout_seconds": scenario.recipe.timeout_seconds, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.startup-plan/1\0" + canonical_json(body) + ).hexdigest() + return StartupExecutionPlan( + scenario.definition.scenario_id, + fixture, + scenario.recipe.timeout_seconds, + digest, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/startup/catalog.toml b/code/src/doc2harness/benchmark/harnesses/startup/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..385b67d4dde1c632e1eb835fcb0794cdc68fe8b4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/catalog.toml @@ -0,0 +1,10 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "startup" +resource = "benchmark/harnesses/startup/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_ambient_python_isolated", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_health_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_python_minimum_fallback", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_bom_config", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_broken_config_file", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/contracts.py b/code/src/doc2harness/benchmark/harnesses/startup/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..f015b488a50d09272ad5ccedee61fdbb9b001f66 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/contracts.py @@ -0,0 +1,356 @@ +"""Typed declarations and observations for startup behavior.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError +from doc2harness.runtime.errors import RuntimeBoundaryError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) + + +class StartupProfile(str, Enum): + CLEAN_CONSTRUCT = "CLEAN_CONSTRUCT" + LAUNCHER_HEALTH = "LAUNCHER_HEALTH" + PYTHON_MINIMUM = "PYTHON_MINIMUM" + AMBIENT_PYTHON = "AMBIENT_PYTHON" + + +class StartupOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class StartupApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +@dataclass(frozen=True, slots=True) +class StartupRecipe: + profile: StartupProfile + config_text: str | None = None + home_files: tuple[tuple[str, str], ...] = () + environment: tuple[tuple[str, str], ...] = () + tripwire: bool = False + launcher_probe: str | None = None + dependencies: tuple[tuple[str, DependencyKind], ...] = () + timeout_seconds: int = 120 + + def __post_init__(self) -> None: + if type(self.profile) is not StartupProfile: + raise ContractDocumentError("startup profile is invalid") + if self.config_text is not None and type(self.config_text) is not str: + raise ContractDocumentError("startup config text is invalid") + for name, value in (("home files", self.home_files), ("environment", self.environment)): + if type(value) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or type(item[1]) is not str + for item in value + ): + raise ContractDocumentError(f"startup {name} are invalid") + if type(self.tripwire) is not bool: + raise ContractDocumentError("startup tripwire flag is invalid") + if self.launcher_probe is not None and ( + type(self.launcher_probe) is not str or not self.launcher_probe + ): + raise ContractDocumentError("startup launcher probe is invalid") + if type(self.dependencies) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or type(item[1]) is not DependencyKind + for item in self.dependencies + ): + raise ContractDocumentError("startup dependencies are invalid") + if type(self.timeout_seconds) is not int or self.timeout_seconds <= 0: + raise ContractDocumentError("startup timeout is invalid") + + +@dataclass(frozen=True, slots=True) +class StartupConfigurationStep: + """Closed authoring step for one startup configuration/probe.""" + + recipe: StartupRecipe + + def __post_init__(self) -> None: + if type(self.recipe) is not StartupRecipe: + raise ContractDocumentError("startup configuration step is invalid") + + +def startup_configuration( + profile: StartupProfile, + config_text: str | None = None, + *, + home_files: tuple[tuple[str, str], ...] = (), + environment: tuple[tuple[str, str], ...] = (), + tripwire: bool = False, + launcher_probe: str | None = None, + dependencies: tuple[tuple[str, DependencyKind], ...] = (), + timeout_seconds: int = 120, +) -> StartupConfigurationStep: + """Declare the startup setup/probe while keeping recipe compilation centralized.""" + + return StartupConfigurationStep( + StartupRecipe( + profile, + config_text, + home_files, + environment, + tripwire, + launcher_probe, + dependencies, + timeout_seconds, + ) + ) + + +def compile_startup_steps( + steps: tuple[StartupConfigurationStep, ...], / +) -> StartupRecipe: + """Compile the closed startup declaration into the recipe object.""" + + if type(steps) is not tuple or len(steps) != 1 or type(steps[0]) is not StartupConfigurationStep: + raise ContractDocumentError("startup steps must contain one configuration operation") + return steps[0].recipe + + +@dataclass(frozen=True, slots=True) +class StartupScenario: + definition: ScenarioDefinition + recipe: StartupRecipe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not StartupRecipe: + raise ContractDocumentError("startup scenario requires exact typed values") + if self.definition.classification.primary != "startup": + raise ContractDocumentError("startup scenario owner differs from its Harness") + + +@dataclass(frozen=True, slots=True) +class StartupObservation: + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + backend_evidence_digest: str + result_present: bool + import_traceback: bool + standard_interface: bool + constructed: bool + constructor_traceback: bool + request_count: int | None + launcher_available: bool + fixture_verified: bool + exact_entry: bool + path_selected: bool + wrong_entry: bool + declared_floor: bool + old_python_probed: bool + old_python_entered: bool + healthy_version_satisfies: bool + poison_selftest: bool + ambient_path_isolated: bool + ambient_home_isolated: bool + process_tree_clean: bool + workspace_clean: bool + # Installation evidence is optional for profiles that do not install. Keeping + # these typed facts separate prevents a successful installer from being + # inferred from a launcher probe or synthetic output. + install_attempted: bool = False + install_rc: int | None = None + post_install_rc: int | None = None + installed_command_observed: bool = False + installed_brand_observed: bool = False + mini_swe_agent_leak: bool = False + install_artifact_unchanged: bool = True + install_cross_artifact_isolated: bool = True + install_artifact_observed: bool = False + install_cross_artifact_checked: bool = False + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("startup observation id is invalid") + for name, value in ( + ("plan", self.plan_digest), + ("artifact", self.artifact_digest), + ("backend evidence", self.backend_evidence_digest), + ): + if type(value) is not str or not value.startswith("sha256:") or len(value) != 71: + raise ContractDocumentError(f"startup {name} digest is invalid") + if type(self.artifact_id) is not str or not self.artifact_id: + raise ContractDocumentError("startup artifact id is invalid") + boolean_fields = ( + self.result_present, + self.import_traceback, + self.standard_interface, + self.constructed, + self.constructor_traceback, + self.launcher_available, + self.fixture_verified, + self.exact_entry, + self.path_selected, + self.wrong_entry, + self.declared_floor, + self.old_python_probed, + self.old_python_entered, + self.healthy_version_satisfies, + self.poison_selftest, + self.ambient_path_isolated, + self.ambient_home_isolated, + self.process_tree_clean, + self.workspace_clean, + ) + if any(type(value) is not bool for value in boolean_fields): + raise ContractDocumentError("startup observation booleans are invalid") + if self.request_count is not None and ( + type(self.request_count) is not int or self.request_count < 0 + ): + raise ContractDocumentError("startup request count is invalid") + for name, value in (("install rc", self.install_rc), ("post-install rc", self.post_install_rc)): + if value is not None and (type(value) is not int): + raise ContractDocumentError(f"startup {name} is invalid") + install_booleans = ( + self.install_attempted, + self.installed_command_observed, + self.installed_brand_observed, + self.mini_swe_agent_leak, + self.install_artifact_unchanged, + self.install_cross_artifact_isolated, + self.install_artifact_observed, + self.install_cross_artifact_checked, + ) + if any(type(value) is not bool for value in install_booleans): + raise ContractDocumentError("startup installation facts are invalid") + + +@dataclass(frozen=True, slots=True) +class StartupEvaluation: + scenario_id: str + outcome: StartupOutcome + applicability: StartupApplicability + reason_code: str + evidence_digest: str + contribution_microunits: int + + +def define_startup_scenario( + scenario_id: str, recipe: StartupRecipe, role: ScenarioRole, / +) -> StartupScenario: + dependencies = tuple( + sorted( + (DependencyRef(test_id, kind) for test_id, kind in recipe.dependencies), + key=lambda item: (item.scenario_id, item.kind.value), + ) + ) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("startup"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("startup-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("startup-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("startup-observer", "1", ComponentKind.OBSERVER), + ComponentRef("startup-oracle", "1", ComponentKind.ORACLE), + ComponentRef("startup-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return StartupScenario(definition, recipe) + + +def evaluation_digest(scenario: StartupScenario, observation: StartupObservation) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return "sha256:" + hashlib.sha256( + b"doc2harness.startup-evaluation/1\0" + canonical_json(body) + ).hexdigest() + + +def validate_startup_observation( + scenario: StartupScenario, + observation: StartupObservation, + /, +) -> None: + """Validate shared scenario/evidence identity before a local judge runs.""" + + if type(scenario) is not StartupScenario: + raise ContractDocumentError("startup judge requires an exact scenario") + if type(observation) is not StartupObservation: + raise RuntimeBoundaryError( + "SBH-STARTUP-EVIDENCE-TYPE", + "startup observer returned invalid evidence", + ) + if observation.scenario_id != scenario.definition.scenario_id: + raise RuntimeBoundaryError( + "SBH-STARTUP-EVIDENCE-MISMATCH", + "startup evidence belongs to another scenario", + ) + + +def build_startup_evaluation( + scenario: StartupScenario, + observation: StartupObservation, + passed: bool, + applicable: bool, + reason: str, + /, +) -> StartupEvaluation: + """Apply shared cleanup and contribution policy after local profile judgment.""" + + validate_startup_observation(scenario, observation) + if type(passed) is not bool or type(applicable) is not bool: + raise ContractDocumentError("startup judge decisions must be exact booleans") + if type(reason) is not str or not reason: + raise ContractDocumentError("startup judge reason must be non-empty") + if applicable and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + passed = False + reason = "STARTUP_CLEANUP_FAILED" + applicability = ( + StartupApplicability.APPLICABLE + if applicable + else StartupApplicability.INCONCLUSIVE + ) + contribution = scenario.definition.weight_microunits if applicable else 0 + if scenario.definition.role is ScenarioRole.CONTROL: + contribution = 0 + return StartupEvaluation( + scenario.definition.scenario_id, + StartupOutcome.PASS if passed else StartupOutcome.FAIL, + applicability, + reason, + evaluation_digest(scenario, observation), + contribution, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/startup/fixtures.py b/code/src/doc2harness/benchmark/harnesses/startup/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..5d13feca087b308cc1a5b4ab2855bf766f55e563 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/fixtures.py @@ -0,0 +1,41 @@ +"""Immutable startup fixture plans.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json + +from .contracts import StartupScenario + + +@dataclass(frozen=True, slots=True) +class StartupFixturePlan: + config_text: str | None + home_files: tuple[tuple[str, str], ...] + environment: tuple[tuple[str, str], ...] + tripwire: bool + launcher_probe: str | None + plan_digest: str + + +def materialize_startup_fixture(scenario: StartupScenario, /) -> StartupFixturePlan: + recipe = scenario.recipe + body = { + "config_text": recipe.config_text, + "environment": list(recipe.environment), + "home_files": list(recipe.home_files), + "launcher_probe": recipe.launcher_probe, + "scenario_id": scenario.definition.scenario_id, + "tripwire": recipe.tripwire, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.startup-fixture/1\0" + canonical_json(body) + ).hexdigest() + return StartupFixturePlan( + recipe.config_text, + recipe.home_files, + recipe.environment, + recipe.tripwire, + recipe.launcher_probe, + digest, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/startup/recipes.py b/code/src/doc2harness/benchmark/harnesses/startup/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..2af140912210fa1a0cb535e07bb04a6d8299841a --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/recipes.py @@ -0,0 +1,49 @@ +"""Frozen recipes for the startup Harness.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from .contracts import StartupProfile, StartupRecipe, define_startup_scenario + +_GATE = (("launcher_health_control", DependencyKind.GATE),) +_ROWS = { + "startup_broken_config_file": ( + StartupRecipe(StartupProfile.CLEAN_CONSTRUCT, '{"yolo": true,, }'), + ScenarioRole.TARGET, + ), + "startup_bom_config": ( + StartupRecipe(StartupProfile.CLEAN_CONSTRUCT, '\ufeff{"yolo": true}'), + ScenarioRole.TARGET, + ), + "launcher_health_control": ( + StartupRecipe(StartupProfile.LAUNCHER_HEALTH, launcher_probe="control", timeout_seconds=25), + ScenarioRole.CONTROL, + ), + "launcher_python_minimum_fallback": ( + StartupRecipe( + StartupProfile.PYTHON_MINIMUM, + launcher_probe="python-floor", + dependencies=_GATE, + timeout_seconds=25, + ), + ScenarioRole.TARGET, + ), + "launcher_ambient_python_isolated": ( + StartupRecipe( + StartupProfile.AMBIENT_PYTHON, + launcher_probe="ambient-python", + dependencies=_GATE, + timeout_seconds=25, + ), + ScenarioRole.TARGET, + ), +} +SCENARIOS = tuple( + (define_startup_scenario(test_id, recipe, role) for test_id, (recipe, role) in _ROWS.items()) +) +_BY_ID = {scenario.definition.scenario_id: scenario for scenario in SCENARIOS} + + +def scenario_by_id(scenario_id: str) -> object: + try: + return _BY_ID[scenario_id] + except KeyError as error: + raise KeyError(f"unknown startup scenario: {scenario_id}") from error diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4222add603b7a12cf7bcec4bde76304a93a76916 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/__init__.py @@ -0,0 +1 @@ +"""Startup scenario owners.""" diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_ambient_python_isolated.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_ambient_python_isolated.py new file mode 100644 index 0000000000000000000000000000000000000000..00493a7571f95c22de6f825fec6b99e07bd507d4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_ambient_python_isolated.py @@ -0,0 +1,48 @@ +"""The launcher must isolate the selected Python from ambient path and home state. +1. Declare the ambient-Python isolation probe and its health-control dependency. +2. Compile the declaration into the startup recipe. +3. Run the startup observer against that recipe. +4. Judge entry selection, poison checks, isolation, and cleanup without side effects. +""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from doc2harness.benchmark.harnesses.startup.contracts import ( + StartupObservation, + StartupProfile, + build_startup_evaluation, + compile_startup_steps, + define_startup_scenario, + startup_configuration, + validate_startup_observation, +) + +SCENARIO_ID = "launcher_ambient_python_isolated" +STEPS = ( + startup_configuration( + StartupProfile.AMBIENT_PYTHON, + launcher_probe="ambient-python", + dependencies=(("launcher_health_control", DependencyKind.GATE),), + timeout_seconds=25, + ), +) +RECIPE = compile_startup_steps(STEPS) +SCENARIO = define_startup_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StartupObservation): + validate_startup_observation(SCENARIO, observation) + if not observation.launcher_available: + return build_startup_evaluation(SCENARIO, observation, False, False, "LAUNCHER_UNOBSERVED") + if not observation.fixture_verified: + return build_startup_evaluation(SCENARIO, observation, False, True, "LAUNCHER_FIXTURE_FAILED") + passed = ( + observation.exact_entry + and observation.poison_selftest + and observation.ambient_path_isolated + and observation.ambient_home_isolated + ) + return build_startup_evaluation(SCENARIO, observation, passed, True, "AMBIENT_PYTHON_CHECKED") + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_health_control.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_health_control.py new file mode 100644 index 0000000000000000000000000000000000000000..b1c254f4c66e352c66b3b7026d19f22f05f8a533 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_health_control.py @@ -0,0 +1,49 @@ +"""The launcher health control verifies availability and selects the intended entry. +1. Declare the launcher health probe and its short timeout. +2. Compile the declaration into the startup recipe. +3. Run the startup observer against that recipe. +4. Judge launcher, fixture, entry, path, and cleanup facts without side effects. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.startup.contracts import ( + StartupObservation, + StartupProfile, + build_startup_evaluation, + compile_startup_steps, + define_startup_scenario, + startup_configuration, + validate_startup_observation, +) + +SCENARIO_ID = "launcher_health_control" +STEPS = ( + startup_configuration( + StartupProfile.LAUNCHER_HEALTH, + launcher_probe="control", + timeout_seconds=25, + ), +) +RECIPE = compile_startup_steps(STEPS) +SCENARIO = define_startup_scenario(SCENARIO_ID, RECIPE, ScenarioRole.CONTROL) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StartupObservation): + validate_startup_observation(SCENARIO, observation) + if not observation.launcher_available: + return build_startup_evaluation(SCENARIO, observation, False, False, "LAUNCHER_UNOBSERVED") + if not observation.fixture_verified: + return build_startup_evaluation(SCENARIO, observation, False, True, "LAUNCHER_FIXTURE_FAILED") + if observation.exact_entry and not observation.path_selected: + return build_startup_evaluation(SCENARIO, observation, False, False, "LAUNCHER_PATH_UNOBSERVED") + return build_startup_evaluation( + SCENARIO, + observation, + observation.exact_entry and observation.path_selected and not observation.wrong_entry, + True, + "LAUNCHER_HEALTH_CHECKED", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_python_minimum_fallback.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_python_minimum_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..4b85c56b4affdf7d54bb71c5236b7351b577f746 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/launcher_python_minimum_fallback.py @@ -0,0 +1,52 @@ +"""The launcher must fall back safely when probing below the supported Python floor. +1. Declare the launcher Python-floor probe and its health-control dependency. +2. Compile the declaration into the startup recipe. +3. Run the startup observer against that recipe. +4. Judge fallback selection, version facts, traceback, and cleanup without side effects. +""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from doc2harness.benchmark.harnesses.startup.contracts import ( + StartupObservation, + StartupProfile, + build_startup_evaluation, + compile_startup_steps, + define_startup_scenario, + startup_configuration, + validate_startup_observation, +) + +SCENARIO_ID = "launcher_python_minimum_fallback" +STEPS = ( + startup_configuration( + StartupProfile.PYTHON_MINIMUM, + launcher_probe="python-floor", + dependencies=(("launcher_health_control", DependencyKind.GATE),), + timeout_seconds=25, + ), +) +RECIPE = compile_startup_steps(STEPS) +SCENARIO = define_startup_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StartupObservation): + validate_startup_observation(SCENARIO, observation) + if not observation.launcher_available: + return build_startup_evaluation(SCENARIO, observation, False, False, "LAUNCHER_UNOBSERVED") + if not observation.fixture_verified: + return build_startup_evaluation(SCENARIO, observation, False, True, "LAUNCHER_FIXTURE_FAILED") + if not observation.declared_floor: + return build_startup_evaluation(SCENARIO, observation, False, False, "PYTHON_FLOOR_UNOBSERVED") + passed = ( + observation.exact_entry + and observation.path_selected + and not observation.wrong_entry + and observation.old_python_probed + and not observation.old_python_entered + and observation.healthy_version_satisfies + ) + return build_startup_evaluation(SCENARIO, observation, passed, True, "PYTHON_FLOOR_CHECKED") + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_bom_config.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_bom_config.py new file mode 100644 index 0000000000000000000000000000000000000000..21fe344fef5f652d8e3c32b3594cf50e9a5e5f37 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_bom_config.py @@ -0,0 +1,43 @@ +"""A UTF-8 BOM-prefixed configuration must cross startup without a bare crash. +1. Declare the clean-start configuration with its UTF-8 BOM. +2. Compile the declaration into the startup recipe. +3. Run the startup observer against that recipe. +4. Judge construction, interface, traceback, and cleanup facts without side effects. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.startup.contracts import ( + StartupObservation, + StartupProfile, + build_startup_evaluation, + compile_startup_steps, + define_startup_scenario, + startup_configuration, + validate_startup_observation, +) + +SCENARIO_ID = "startup_bom_config" +STEPS = ( + startup_configuration(StartupProfile.CLEAN_CONSTRUCT, '\ufeff{"yolo": true}'), +) +RECIPE = compile_startup_steps(STEPS) +SCENARIO = define_startup_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StartupObservation): + validate_startup_observation(SCENARIO, observation) + if not observation.result_present or observation.import_traceback: + return build_startup_evaluation(SCENARIO, observation, False, True, "STARTUP_IMPORT_FAILED") + if not observation.standard_interface: + return build_startup_evaluation(SCENARIO, observation, False, False, "STARTUP_INTERFACE_UNOBSERVED") + return build_startup_evaluation( + SCENARIO, + observation, + observation.constructed and not observation.constructor_traceback, + True, + "STARTUP_CONSTRUCT_CHECKED", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_broken_config_file.py b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_broken_config_file.py new file mode 100644 index 0000000000000000000000000000000000000000..ef69dac03f09909863b5d8144a1469526261d700 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/startup/scenarios/startup_broken_config_file.py @@ -0,0 +1,43 @@ +"""A syntactically broken configuration must fail through the normal startup boundary. +1. Declare the clean-start configuration with malformed JSON. +2. Compile the declaration into the startup recipe. +3. Run the startup observer against that recipe. +4. Judge construction, interface, traceback, and cleanup facts without side effects. +""" + +from doc2harness.benchmark.definition import ScenarioRole +from doc2harness.benchmark.harnesses.startup.contracts import ( + StartupObservation, + StartupProfile, + build_startup_evaluation, + compile_startup_steps, + define_startup_scenario, + startup_configuration, + validate_startup_observation, +) + +SCENARIO_ID = "startup_broken_config_file" +STEPS = ( + startup_configuration(StartupProfile.CLEAN_CONSTRUCT, '{"yolo": true,, }'), +) +RECIPE = compile_startup_steps(STEPS) +SCENARIO = define_startup_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StartupObservation): + validate_startup_observation(SCENARIO, observation) + if not observation.result_present or observation.import_traceback: + return build_startup_evaluation(SCENARIO, observation, False, True, "STARTUP_IMPORT_FAILED") + if not observation.standard_interface: + return build_startup_evaluation(SCENARIO, observation, False, False, "STARTUP_INTERFACE_UNOBSERVED") + return build_startup_evaluation( + SCENARIO, + observation, + observation.constructed and not observation.constructor_traceback, + True, + "STARTUP_CONSTRUCT_CHECKED", + ) + +__all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/__init__.py b/code/src/doc2harness/benchmark/harnesses/state/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2fdf5162fe58863eb946e8a95dc867b588d067 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/__init__.py @@ -0,0 +1,55 @@ +"""Child-process state scenarios.""" + +from .adapter import ( + StateExecutionPlan, + build_state_execution_plan, +) +from .contracts import ( + FrozenValue, + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateRecipe, + StateScenario, + StateStep, + api_call, + command, + compile_state_steps, + observe_config, + observe_file, + observe_requests, + premsgs, + seed_file, + structured_fact, +) +from .fixtures import StateFixturePlan, materialize_state_fixture +from .recipes import SCENARIOS, scenario_by_id + +__all__ = [ + "FrozenValue", + "SCENARIOS", + "StateApplicability", + "StateEvaluation", + "StateExecutionPlan", + "StateFixturePlan", + "StateObservation", + "StateOracleProfile", + "StateOutcome", + "StateRecipe", + "StateScenario", + "StateStep", + "api_call", + "build_state_execution_plan", + "command", + "compile_state_steps", + "materialize_state_fixture", + "observe_config", + "observe_file", + "observe_requests", + "premsgs", + "scenario_by_id", + "seed_file", + "structured_fact", +] diff --git a/code/src/doc2harness/benchmark/harnesses/state/adapter.py b/code/src/doc2harness/benchmark/harnesses/state/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..af38419acb9a9ce940c122557cfa0b90f24092e5 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/adapter.py @@ -0,0 +1,28 @@ +"""Execution boundary for child-process state scenarios.""" +import hashlib +from dataclasses import dataclass +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError +from .contracts import FrozenValue, StateScenario +from .fixtures import StateFixturePlan, materialize_state_fixture + +@dataclass(frozen=True, slots=True) +class StateExecutionPlan: + scenario_id: str + fixture: StateFixturePlan + commands: tuple[str, ...] + config_keys: tuple[str, ...] + observed_files: tuple[str, ...] + execution_parameters: tuple[tuple[str, FrozenValue], ...] + timeout_seconds: int + plan_digest: str + +def build_state_execution_plan(scenario: StateScenario, /) -> StateExecutionPlan: + if type(scenario) is not StateScenario: + raise ContractDocumentError('state execution requires an exact scenario') + recipe = scenario.recipe + fixture = materialize_state_fixture(scenario) + body = {'commands': recipe.commands, 'config_keys': recipe.config_keys, 'fixture_digest': fixture.plan_digest, 'observed_files': recipe.observed_files, 'scenario_id': scenario.definition.scenario_id, 'timeout_seconds': recipe.timeout_seconds} + digest = 'sha256:' + hashlib.sha256(b'doc2harness.state-child-plan/1\x00' + canonical_json(body)).hexdigest() + return StateExecutionPlan(scenario.definition.scenario_id, fixture, recipe.commands, recipe.config_keys, recipe.observed_files, recipe.execution_parameters, recipe.timeout_seconds, digest) +__all__ = ['StateExecutionPlan', 'build_state_execution_plan'] diff --git a/code/src/doc2harness/benchmark/harnesses/state/catalog.toml b/code/src/doc2harness/benchmark/harnesses/state/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..91ec91c1bf5bee7c9f2f98f06b973eb67411e6bc --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/catalog.toml @@ -0,0 +1,19 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "state" +resource = "benchmark/harnesses/state/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_bytes", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_no_secondary_expansion", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_single_expansion_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.p30_ctl_security_review_sees_worktree_change", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_declared_command_reaches_wire", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_toplevel_command_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.state.scenarios.security_review_covers_branch_commits", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/state/contracts.py b/code/src/doc2harness/benchmark/harnesses/state/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..fe28894a825a8f0e1824a9743dff77a0e18fc46f --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/contracts.py @@ -0,0 +1,382 @@ +"""Closed declarations and observations for child-process state scenarios.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from enum import Enum +from typing import TypeAlias + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +JsonAtom: TypeAlias = str | int | bool | None +FrozenValue: TypeAlias = ( + JsonAtom | tuple["FrozenValue", ...] | tuple[tuple[str, "FrozenValue"], ...] +) + + +class StateOracleProfile(str, Enum): + REQUEST_TOKEN_PRESENT = "REQUEST_TOKEN_PRESENT" + CUSTOM_COMMAND_FACE = "CUSTOM_COMMAND_FACE" + STRUCTURED_FACTS = "STRUCTURED_FACTS" + CUSTOM_SINGLE_EXPANSION = "CUSTOM_SINGLE_EXPANSION" + CUSTOM_NO_SECONDARY = "CUSTOM_NO_SECONDARY" + + +class StateOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class StateApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +def _validate_frozen(value: FrozenValue, depth: int = 0) -> None: + if depth > 18: + raise ContractDocumentError("state frozen value nesting is excessive") + if value is None or type(value) in {str, int, bool}: + if type(value) is str and len(value) > 8 * 1024 * 1024: + raise ContractDocumentError("state frozen text is excessive") + return + if type(value) is not tuple or len(value) > 8192: + raise ContractDocumentError("state frozen value is invalid") + for item in value: + if type(item) is tuple and len(item) == 2 and type(item[0]) is str: + _validate_frozen(item[1], depth + 1) + else: + _validate_frozen(item, depth + 1) + + +def _pairs(value: object, label: str) -> tuple[tuple[str, FrozenValue], ...]: + if type(value) is not tuple or any( + type(item) is not tuple or len(item) != 2 or type(item[0]) is not str + for item in value + ): + raise ContractDocumentError(f"state {label} is invalid") + if len({item[0] for item in value}) != len(value): + raise ContractDocumentError(f"state {label} keys are duplicated") + for _, item in value: + _validate_frozen(item) + return value + + +@dataclass(frozen=True, slots=True) +class StateStep: + """One closed, serializable action or observation in a state scenario.""" + + operation: str + value: FrozenValue + + def __post_init__(self) -> None: + if type(self.operation) is not str or not self.operation: + raise ContractDocumentError("state step operation is invalid") + if self.operation not in { + "seed_file", + "command", + "premsgs", + "api_call", + "observe_config", + "observe_file", + "observe_requests", + "structured_fact", + "home_seed_file", + }: + raise ContractDocumentError("state step operation is unsupported") + _validate_frozen(self.value) + + +def seed_file(path: str, content: str) -> StateStep: + """Declare a path-relative file that the state fixture must contain.""" + + return StateStep("seed_file", (path, content)) + + +def home_seed_file(path: str, content: str) -> StateStep: + """Declare a file the fixture must place under the isolated HOME. + + Distinct from ``seed_file``, which writes into the workspace. Extension + resolution is defined over exactly that boundary - a user-level definition + lives under HOME, a project-level one under the workspace - so a scenario + that folds the two together can no longer state which side it is testing. + """ + + return StateStep("home_seed_file", (path, content)) + + +def command(value: str) -> StateStep: + """Declare one slash command sent to the state artifact.""" + + return StateStep("command", value) + + +def premsgs(value: FrozenValue) -> StateStep: + """Declare pre-seeded conversation messages for the state session.""" + + return StateStep("premsgs", value) + + +def api_call(value: FrozenValue) -> StateStep: + """Declare a typed Agent API call description.""" + + return StateStep("api_call", value) + + +def observe_config(key: str) -> StateStep: + """Declare a configuration key whose post-run value is observed.""" + + return StateStep("observe_config", key) + + +def observe_file(path: str) -> StateStep: + """Declare a workspace file whose post-run content is observed.""" + + return StateStep("observe_file", path) + + +def observe_requests() -> StateStep: + """Declare recorder-owned request facts as an observation boundary.""" + + return StateStep("observe_requests", "requests") + + +def structured_fact(name: str) -> StateStep: + """Declare one structured fact consumed by the scenario-local judge.""" + + return StateStep("structured_fact", name) + + +@dataclass(frozen=True, slots=True) +class StateRecipe: + commands: tuple[str, ...] + seed_files: tuple[tuple[str, str], ...] + config_keys: tuple[str, ...] + observed_files: tuple[str, ...] + oracle_profile: StateOracleProfile + oracle_parameters: tuple[tuple[str, FrozenValue], ...] + execution_parameters: tuple[tuple[str, FrozenValue], ...] = () + dependencies: tuple[tuple[str, DependencyKind], ...] = () + timeout_seconds: int = 60 + home_seed_files: tuple[tuple[str, str], ...] = () + + def __post_init__(self) -> None: + if type(self.commands) is not tuple or any(type(x) is not str or not x for x in self.commands): + raise ContractDocumentError("state commands are invalid") + if type(self.seed_files) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or item[0].startswith("/") + or ".." in item[0].split("/") + or type(item[1]) is not str + for item in self.seed_files + ): + raise ContractDocumentError("state seed files are invalid") + if type(self.home_seed_files) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or not item[0] + or item[0].startswith("/") + or ".." in item[0].split("/") + or type(item[1]) is not str + for item in self.home_seed_files + ): + raise ContractDocumentError("state home seed files are invalid") + for value, label in ((self.config_keys, "config keys"), (self.observed_files, "observed files")): + if type(value) is not tuple or any(type(x) is not str or not x for x in value): + raise ContractDocumentError(f"state {label} are invalid") + if type(self.oracle_profile) is not StateOracleProfile: + raise ContractDocumentError("state oracle profile is invalid") + _pairs(self.oracle_parameters, "oracle parameters") + _pairs(self.execution_parameters, "execution parameters") + if type(self.dependencies) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or _ID.fullmatch(item[0]) is None + or type(item[1]) is not DependencyKind + for item in self.dependencies + ): + raise ContractDocumentError("state dependencies are invalid") + if type(self.timeout_seconds) is not int or not 1 <= self.timeout_seconds <= 900: + raise ContractDocumentError("state timeout is invalid") + + +def compile_state_steps( + steps: tuple[StateStep, ...], + *, + oracle_profile: StateOracleProfile, + oracle_parameters: tuple[tuple[str, FrozenValue], ...], + execution_parameters: tuple[tuple[str, FrozenValue], ...] = (), + dependencies: tuple[tuple[str, DependencyKind], ...] = (), + timeout_seconds: int = 60, +) -> StateRecipe: + """Compile declarative state steps into the recipe contract. + + Commands, fixture files, config observations, and file observations are + derived from the visible steps. The structured-facts execution matrix is + intentionally supplied as a typed argument because it belongs to the + shared state producer rather than to the scenario's action sequence. + """ + + if type(steps) is not tuple or any(type(step) is not StateStep for step in steps): + raise ContractDocumentError("state steps are invalid") + commands = tuple(step.value for step in steps if step.operation == "command") + seed_files = tuple( + step.value for step in steps if step.operation == "seed_file" + ) + home_seed_files = tuple( + step.value for step in steps if step.operation == "home_seed_file" + ) + config_keys = tuple( + step.value for step in steps if step.operation == "observe_config" + ) + observed_files = tuple( + step.value for step in steps if step.operation == "observe_file" + ) + if any(type(value) is not str or not value for value in commands + config_keys + observed_files): + raise ContractDocumentError("state step text is invalid") + if any( + type(value) is not tuple + or len(value) != 2 + or type(value[0]) is not str + or type(value[1]) is not str + for value in seed_files + home_seed_files + ): + raise ContractDocumentError("state seed-file step is invalid") + return StateRecipe( + commands=commands, + seed_files=seed_files, + home_seed_files=home_seed_files, + config_keys=config_keys, + observed_files=observed_files, + oracle_profile=oracle_profile, + oracle_parameters=oracle_parameters, + execution_parameters=execution_parameters, + dependencies=dependencies, + timeout_seconds=timeout_seconds, + ) + + +@dataclass(frozen=True, slots=True) +class StateScenario: + definition: ScenarioDefinition + recipe: StateRecipe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not StateRecipe: + raise ContractDocumentError("state scenario requires exact typed values") + if self.definition.classification.primary != "state": + raise ContractDocumentError("state scenario owner differs from its Harness") + + +@dataclass(frozen=True, slots=True) +class StateObservation: + scenario_id: str + plan_digest: str + artifact_id: str + artifact_digest: str + backend_evidence_digest: str + fixture_verified: bool + facts: tuple[tuple[str, FrozenValue], ...] + process_tree_clean: bool + workspace_clean: bool + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("state observation id is invalid") + for label, value in (("plan", self.plan_digest), ("artifact", self.artifact_digest), ("backend", self.backend_evidence_digest)): + if type(value) is not str or not value.startswith("sha256:") or len(value) != 71: + raise ContractDocumentError(f"state {label} digest is invalid") + if type(self.artifact_id) is not str or not self.artifact_id: + raise ContractDocumentError("state artifact id is invalid") + if type(self.fixture_verified) is not bool: + raise ContractDocumentError("state fixture fact is invalid") + _pairs(self.facts, "observation facts") + if type(self.process_tree_clean) is not bool or type(self.workspace_clean) is not bool: + raise ContractDocumentError("state cleanup facts are invalid") + + +@dataclass(frozen=True, slots=True) +class StateEvaluation: + scenario_id: str + outcome: StateOutcome + applicability: StateApplicability + reason_code: str + evidence_digest: str + contribution_microunits: int + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("state evaluation id is invalid") + if type(self.outcome) is not StateOutcome or type(self.applicability) is not StateApplicability: + raise ContractDocumentError("state evaluation closed value is invalid") + if type(self.reason_code) is not str or not self.reason_code or len(self.reason_code) > 128: + raise ContractDocumentError("state reason is invalid") + if type(self.evidence_digest) is not str or not self.evidence_digest.startswith("sha256:") or len(self.evidence_digest) != 71: + raise ContractDocumentError("state evaluation digest is invalid") + if self.contribution_microunits not in {0, 1_000_000}: + raise ContractDocumentError("state contribution is invalid") + + +def define_state_scenario(scenario_id: str, recipe: StateRecipe, role: ScenarioRole, /) -> StateScenario: + if type(scenario_id) is not str or _ID.fullmatch(scenario_id) is None: + raise ContractDocumentError("state scenario id is invalid") + dependencies = tuple(sorted((DependencyRef(test_id, kind) for test_id, kind in recipe.dependencies), key=lambda x: (x.scenario_id, x.kind.value))) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("state"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("state-child-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("state-child-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("state-child-observer", "1", ComponentKind.OBSERVER), + ComponentRef("state-child-oracle", "1", ComponentKind.ORACLE), + ComponentRef("state-child-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return StateScenario(definition, recipe) + + +def evaluation_digest(scenario: StateScenario, observation: StateObservation) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return "sha256:" + hashlib.sha256(b"doc2harness.state-child-evaluation/1\0" + canonical_json(body)).hexdigest() + + +__all__ = [ + "FrozenValue", "StateApplicability", "StateEvaluation", "StateObservation", + "StateOracleProfile", "StateOutcome", "StateRecipe", + "StateScenario", "StateStep", "api_call", "command", "compile_state_steps", + "define_state_scenario", "evaluation_digest", "observe_config", "observe_file", + "observe_requests", "premsgs", "seed_file", "structured_fact", +] diff --git a/code/src/doc2harness/benchmark/harnesses/state/fixtures.py b/code/src/doc2harness/benchmark/harnesses/state/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..ce217375b380a78ce05977829ef1e8fbbe0cb9c9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/fixtures.py @@ -0,0 +1,49 @@ +"""Deterministic fixture plans for child-process state scenarios.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from .contracts import FrozenValue, StateScenario + + +@dataclass(frozen=True, slots=True) +class StateFixturePlan: + scenario_id: str + seed_files: tuple[tuple[str, str], ...] + execution_parameters: tuple[tuple[str, FrozenValue], ...] + logical_bindings: tuple[tuple[str, str], ...] + plan_digest: str + home_seed_files: tuple[tuple[str, str], ...] = () + + +def materialize_state_fixture(scenario: StateScenario, /) -> StateFixturePlan: + if type(scenario) is not StateScenario: + raise ContractDocumentError("state fixture requires an exact scenario") + recipe = scenario.recipe + body = { + "execution_parameters": recipe.execution_parameters, + "home_seed_files": recipe.home_seed_files, + "logical_bindings": ( + ("@python", "runtime-python"), + ("@state-mcp-fixture", "state-mcp-peer"), + ), + "scenario_id": scenario.definition.scenario_id, + "seed_files": recipe.seed_files, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.state-child-fixture/1\0" + canonical_json(body) + ).hexdigest() + return StateFixturePlan( + scenario.definition.scenario_id, + recipe.seed_files, + recipe.execution_parameters, + (("@python", "runtime-python"), ("@state-mcp-fixture", "state-mcp-peer")), + digest, + recipe.home_seed_files, + ) + + +__all__ = ["StateFixturePlan", "materialize_state_fixture"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/recipes.py b/code/src/doc2harness/benchmark/harnesses/state/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..81c1a176f11b70f090a1396bfb15e8526a8d1ebb --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/recipes.py @@ -0,0 +1,621 @@ +"""Frozen recipes for child-process state scenarios.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from .contracts import StateOracleProfile, StateRecipe, define_state_scenario + +_ROWS = {} +_ROWS.update( + { + "security_review_covers_branch_commits": { + "commands": ("/security-review",), + "seed_files": (("vuln_9601.py", "import os\n"),), + "config_keys": (), + "observed_files": (), + "profile": "REQUEST_TOKEN_PRESENT", + "oracle_parameters": (("token", "SECREVTOK_9601"),), + "execution_parameters": ( + ("ensure_exec", True), + ("git_branch_commit", True), + ("git_init", True), + ( + "post_files", + (("vuln_9601.py", "import os\n# SECREVTOK_9601\nos.system(input()) # obvious smell\n"),), + ), + ("stub", (("probe_tokens", ("SECREVTOK_9601",)),)), + ), + "dependencies": (("p30_ctl_security_review_sees_worktree_change", "GATE"),), + "timeout": 60, + "role": "TARGET", + }, + "p30_ctl_security_review_sees_worktree_change": { + "commands": ("/security-review",), + "seed_files": (("vuln_9601.py", "import os\n"),), + "config_keys": (), + "observed_files": (), + "profile": "REQUEST_TOKEN_PRESENT", + "oracle_parameters": (("token", "SECREVTOK_9601"),), + "execution_parameters": ( + ("ensure_exec", True), + ("git_init", True), + ( + "post_files", + (("vuln_9601.py", "import os\n# SECREVTOK_9601\nos.system(input()) # obvious smell\n"),), + ), + ("stub", (("probe_tokens", ("SECREVTOK_9601",)),)), + ), + "dependencies": (), + "timeout": 60, + "role": "CONTROL", + }, + } +) +_PLUGIN_ROWS = { + "plugin_declared_command_reaches_wire": { + "commands": ("/probecmd", "please continue"), + "seed_files": ( + ("plugins/probeplug/commands/probecmd.md", "Summarize PLUGCMD_5150 for the team now.\n"), + ( + "plugins/probeplug/plugin.json", + '{\n "name": "probeplug",\n "description": "probe plugin",\n "commands": [\n "commands/probecmd.md"\n ]\n}', + ), + ), + "config_keys": (), + "observed_files": (), + "profile": "CUSTOM_COMMAND_FACE", + "oracle_parameters": (("token", "PLUGCMD_5150"),), + "execution_parameters": (("stub", (("probe_tokens", ("PLUGCMD_5150",)),)),), + "dependencies": (("plugin_toplevel_command_control", "GATE"),), + "timeout": 60, + "role": "TARGET", + }, + "plugin_toplevel_command_control": { + "commands": ("/probecmd", "please continue"), + "seed_files": (("commands/probecmd.md", "Summarize PLUGCMD_5150 for the team now.\n"),), + "config_keys": (), + "observed_files": (), + "profile": "CUSTOM_COMMAND_FACE", + "oracle_parameters": (("token", "PLUGCMD_5150"),), + "execution_parameters": (("stub", (("probe_tokens", ("PLUGCMD_5150",)),)),), + "dependencies": (), + "timeout": 60, + "role": "CONTROL", + }, +} +_CHILD_STATE_ROWS = { + "child_add_dir_inheritance_control": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "child_add_dir_inheritance_control"),), + "execution_parameters": ( + ("kind", "control"), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CHILD_PARENT_7324", "CHILD_EMPTY_7326")), + ( + "rounds", + ( + ( + (("args", (("file_path", "__REPO__/main.txt"),)), ("name", "read")), + (("args", (("file_path", "__EXTRA__/extra.txt"),)), ("name", "read")), + ( + ("args", (("file_path", "__UNAUTHORIZED__/outside.txt"),)), + ("name", "read"), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ( + "api_probe_variants", + ( + ( + ("actor", "parent"), + ("add_dir", True), + ("extra_token", "EXTRA_7322"), + ("label", "parent-grant"), + ("main_token", "MAIN_7321"), + ("operation", "child"), + ("prompt", "CHILD_PARENT_7324"), + ("shape", "parent-grant"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ( + ("actor", "child"), + ("add_dir", False), + ("extra_token", "EXTRA_7322"), + ("label", "child-empty"), + ("main_token", "MAIN_7321"), + ("operation", "child"), + ("prompt", "CHILD_EMPTY_7326"), + ("settle_s", "2.0"), + ("shape", "child-empty"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ), + ), + ), + "dependencies": (), + "timeout": 30, + "role": "CONTROL", + }, + "child_add_dir_inheritance": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "child_add_dir_inheritance"),), + "execution_parameters": ( + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CHILD_TARGET_7325", "CHILD_EMPTY_7326")), + ( + "rounds", + ( + ( + (("args", (("file_path", "__REPO__/main.txt"),)), ("name", "read")), + (("args", (("file_path", "__EXTRA__/extra.txt"),)), ("name", "read")), + ( + ("args", (("file_path", "__UNAUTHORIZED__/outside.txt"),)), + ("name", "read"), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ( + "api_probe_variants", + ( + ( + ("actor", "child"), + ("add_dir", True), + ("extra_token", "EXTRA_7322"), + ("label", "child-target"), + ("main_token", "MAIN_7321"), + ("operation", "child"), + ("prompt", "CHILD_TARGET_7325"), + ("settle_s", "2.0"), + ("shape", "child-target"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ( + ("actor", "child"), + ("add_dir", False), + ("extra_token", "EXTRA_7322"), + ("label", "child-empty-target"), + ("main_token", "MAIN_7321"), + ("operation", "child"), + ("prompt", "CHILD_EMPTY_7326"), + ("settle_s", "2.0"), + ("shape", "child-empty-target"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ), + ), + ), + "dependencies": (("child_add_dir_inheritance_control", "GATE"),), + "timeout": 30, + "role": "TARGET", + }, + "memory_query_topk_residency_control": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "memory_query_topk_residency_control"),), + "execution_parameters": ( + ("kind", "control"), + ( + "clipboard_api_variants", + ( + ( + ("decoy", "DECOY_"), + ("entries", 2000), + ("label", "control"), + ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), + ("operation", "memory"), + ("rss_probe_bytes", 16777216), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), + ( + "rounds", + ( + ( + ( + ( + "args", + (("limit", 3), ("query", "zirconium quasar heliotrope")), + ), + ("name", ("memory_search", "memory-search", "memorysearch")), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), + ("warm_query", "warmup_only_6401"), + ), + ), + ), + ), + "dependencies": (), + "timeout": 120, + "role": "CONTROL", + }, + "memory_query_topk_residency": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "memory_query_topk_residency"),), + "execution_parameters": ( + ( + "clipboard_api_variants", + ( + ( + ("decoy", "DECOY_"), + ("entries", 2000), + ("label", "small"), + ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), + ("operation", "memory"), + ("rss_probe_bytes", 16777216), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), + ( + "rounds", + ( + ( + ( + ( + "args", + (("limit", 3), ("query", "zirconium quasar heliotrope")), + ), + ("name", ("memory_search", "memory-search", "memorysearch")), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), + ("warm_query", "warmup_only_6401"), + ), + ( + ("decoy", "DECOY_"), + ("entries", 120000), + ("label", "large"), + ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), + ("operation", "memory"), + ("rss_probe_bytes", 16777216), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), + ( + "rounds", + ( + ( + ( + ( + "args", + (("limit", 3), ("query", "zirconium quasar heliotrope")), + ), + ("name", ("memory_search", "memory-search", "memorysearch")), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), + ("warm_query", "warmup_only_6401"), + ), + ), + ), + ), + "dependencies": (("memory_query_topk_residency_control", "GATE"),), + "timeout": 180, + "role": "TARGET", + }, + "agent_api_close_retry_incomplete_control": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "agent_api_close_retry_incomplete_control"),), + "execution_parameters": ( + ("kind", "control"), + ( + "clipboard_api_variants", + ( + ( + ("heartbeat_file", "close_helper.heartbeat"), + ("inject_fault", False), + ("label", "control"), + ("lease_file", "close_helper.lease"), + ("operation", "close"), + ("pid_file", "close_helper.pid"), + ("prompt", "CLOSE_ROUTE_6501"), + ("state_file", "close_helper.state"), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CLOSE_ROUTE_6501",)), + ( + "rounds", + ( + ( + ( + ("args", (("run_in_background", True),)), + ("command", "__CLOSE_COMMAND__"), + ("name", "bash"), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ), + ), + ), + ), + "dependencies": (), + "timeout": 45, + "role": "CONTROL", + }, + "agent_api_close_retry_incomplete": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "agent_api_close_retry_incomplete"),), + "execution_parameters": ( + ( + "clipboard_api_variants", + ( + ( + ("heartbeat_file", "close_helper.heartbeat"), + ("inject_fault", True), + ("label", "target"), + ("lease_file", "close_helper.lease"), + ("operation", "close"), + ("pid_file", "close_helper.pid"), + ("prompt", "CLOSE_ROUTE_6501"), + ("state_file", "close_helper.state"), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CLOSE_ROUTE_6501",)), + ( + "rounds", + ( + ( + ( + ("args", (("run_in_background", True),)), + ("command", "__CLOSE_COMMAND__"), + ("name", "bash"), + ), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ), + ), + ), + ), + "dependencies": (("agent_api_close_retry_incomplete_control", "GATE"),), + "timeout": 45, + "role": "TARGET", + }, + "copy_utf8_clipboard_control": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "copy_utf8_clipboard_control"),), + "execution_parameters": ( + ("kind", "control"), + ( + "clipboard_api_variants", + ( + ( + ("capture", "clipboard_capture.bin"), + ("label", "control"), + ("meta", "clipboard_meta.json"), + ("operation", "copy"), + ("prompt", "COPY_ROUTE_6601"), + ( + "stub", + ( + ("mode", "fixed_reply"), + ("probe_tokens", ("COPY_ROUTE_6601",)), + ("reply_content", "COPY_ASCII_6602 exact bytes"), + ), + ), + ), + ), + ), + ), + "dependencies": (), + "timeout": 45, + "role": "CONTROL", + }, + "copy_utf8_clipboard_bytes": { + "commands": (), + "seed_files": (), + "config_keys": (), + "observed_files": (), + "profile": "STRUCTURED_FACTS", + "oracle_parameters": (("fact_key", "copy_utf8_clipboard_bytes"),), + "execution_parameters": ( + ( + "clipboard_api_variants", + ( + ( + ("capture", "clipboard_capture.bin"), + ("label", "target"), + ("meta", "clipboard_meta.json"), + ("operation", "copy"), + ("prompt", "COPY_ROUTE_6601"), + ( + "stub", + ( + ("mode", "fixed_reply"), + ("probe_tokens", ("COPY_ROUTE_6601",)), + ("reply_content", "COPY_UTF8_6603 ้›ช่ฑน cafรฉ ฮ”"), + ), + ), + ), + ), + ), + ), + "dependencies": (("copy_utf8_clipboard_control", "GATE"),), + "timeout": 45, + "role": "TARGET", + }, + "custom_args_single_expansion_control": { + "commands": ("/mode yolo", "/argguard ARGS_SAFE_7103", "continue the controlled custom command"), + "seed_files": ( + ( + "commands/argguard.md", + "ARGS_CONTROL_FACE_7101 {{args}} @{args_control_source.txt} !{printf 'ARGS_CONTROL_EXEC_7105\\n' > args_control_exec.txt}\n", + ), + ("args_control_source.txt", "ARGS_CONTROL_FILE_7104\n"), + ), + "config_keys": (), + "observed_files": ("args_control_exec.txt",), + "profile": "CUSTOM_SINGLE_EXPANSION", + "oracle_parameters": ( + ("face_token", "ARGS_CONTROL_FACE_7101"), + ("args_token", "ARGS_SAFE_7103"), + ("file_token", "ARGS_CONTROL_FILE_7104"), + ("path", "args_control_exec.txt"), + ), + "execution_parameters": ( + ("kind", "control"), + ( + "stub", + (("probe_tokens", ("ARGS_CONTROL_FACE_7101", "ARGS_SAFE_7103", "ARGS_CONTROL_FILE_7104")),), + ), + ), + "dependencies": (), + "timeout": 90, + "role": "CONTROL", + }, + "custom_args_no_secondary_expansion": { + "commands": ( + "/mode yolo", + "/argguard ARGS_SAFE_7103 @{args_secret.txt} !{printf 'ARGS_TARGET_EXEC_7107\\n' > args_target_exec.txt}", + "continue the guarded custom command", + ), + "seed_files": ( + ("commands/argguard.md", "ARGS_TARGET_FACE_7102 {{args}}\n"), + ("args_secret.txt", "ARGS_SECRET_READ_7106\n"), + ), + "config_keys": (), + "observed_files": ("args_target_exec.txt",), + "profile": "CUSTOM_NO_SECONDARY", + "oracle_parameters": ( + ("face_token", "ARGS_TARGET_FACE_7102"), + ("args_token", "ARGS_SAFE_7103"), + ("secret_token", "ARGS_SECRET_READ_7106"), + ("path", "args_target_exec.txt"), + ), + "execution_parameters": ( + ( + "stub", + (("probe_tokens", ("ARGS_TARGET_FACE_7102", "ARGS_SAFE_7103", "ARGS_SECRET_READ_7106")),), + ), + ), + "dependencies": (("custom_args_single_expansion_control", "GATE"),), + "timeout": 90, + "role": "TARGET", + }, +} +_ROWS = {**_ROWS, **_PLUGIN_ROWS, **_CHILD_STATE_ROWS} + + +def _home_seed_files(row: dict) -> tuple[tuple[str, str], ...]: + """Lift a row's ``home_seed`` declaration into the typed recipe field. + + Rows carry these as an execution parameter; the fixture writes only the + recipe field, and the extension scenarios that turn on a user-level + definition need it on disk. Reading the existing declaration keeps one + statement of the fixture rather than a second copy free to drift from it. + """ + declared = dict(row["execution_parameters"]).get("home_seed", ()) + return tuple( + ( + (str(path), str(content)) + for path, content in declared + if isinstance(path, str) and isinstance(content, str) + ) + ) + + +SCENARIOS = tuple( + ( + define_state_scenario( + test_id, + StateRecipe( + commands=row["commands"], + seed_files=row["seed_files"], + home_seed_files=_home_seed_files(row), + config_keys=row["config_keys"], + observed_files=row["observed_files"], + oracle_profile=StateOracleProfile[row["profile"]], + oracle_parameters=row["oracle_parameters"], + execution_parameters=row["execution_parameters"], + dependencies=tuple( + ((test_id, DependencyKind[kind]) for test_id, kind in row["dependencies"]) + ), + timeout_seconds=row["timeout"], + ), + ScenarioRole[row["role"]], + ) + for test_id, row in _ROWS.items() + ) +) +_BY_ID = {scenario.definition.scenario_id: scenario for scenario in SCENARIOS} + + +def scenario_by_id(scenario_id: str): + try: + return _BY_ID[scenario_id] + except KeyError as error: + raise KeyError(f"unknown state child scenario: {scenario_id}") from error + + +__all__ = ["SCENARIOS", "scenario_by_id"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f29a8d47e33091bafe56fc47f8a2bd2a40b52885 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/__init__.py @@ -0,0 +1 @@ +"""Thin definition owners for state-child scenarios.""" diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..6d613f4d69eb6fb7de9c7f32f0c9289362c3836c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete.py @@ -0,0 +1,82 @@ +"""Verify the structured close-retry evidence for the target route. + +1. Run the close operation through the session-close API variant fixture. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when the structured route is complete and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, StateEvaluation, StateObservation, StateOracleProfile, + StateOutcome, StateScenario, compile_state_steps, + evaluation_digest, structured_fact, +) +from doc2harness.benchmark.definition import DependencyKind +from ..recipes import scenario_by_id + +SCENARIO_ID = "agent_api_close_retry_incomplete" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_EXEC = ( + (_VARIANTS_KEY, (( + ("heartbeat_file", "close_helper.heartbeat"), ("inject_fault", True), ("label", "target"), + ("lease_file", "close_helper.lease"), ("operation", "close"), ("pid_file", "close_helper.pid"), + ("prompt", "CLOSE_ROUTE_6501"), ("state_file", "close_helper.state"), + ("stub", ( + ("mode", "seq_probe"), ("probe_tokens", ("CLOSE_ROUTE_6501",)), + ("rounds", ( + ((("args", (("run_in_background", True),)), ("command", "__CLOSE_COMMAND__"), ("name", "bash")),), + ((("name", "__finish__"),),), + )), + )), + ),)) , +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), execution_parameters=_EXEC, + dependencies=(("agent_api_close_retry_incomplete_control", DependencyKind.GATE),), + timeout_seconds=45, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured-facts close-retry contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete_control.py new file mode 100644 index 0000000000000000000000000000000000000000..9e326533e847337cc73961ec3e07dd1904702a00 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/agent_api_close_retry_incomplete_control.py @@ -0,0 +1,80 @@ +"""Verify the structured close-retry evidence for the control route. + +1. Run the close operation through the session-close API variant fixture. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when the structured route is complete and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, StateEvaluation, StateObservation, StateOracleProfile, + StateOutcome, StateScenario, compile_state_steps, + evaluation_digest, structured_fact, +) +from ..recipes import scenario_by_id + +SCENARIO_ID = "agent_api_close_retry_incomplete_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_EXEC = ( + ("kind", "control"), (_VARIANTS_KEY, (( + ("heartbeat_file", "close_helper.heartbeat"), ("inject_fault", False), ("label", "control"), + ("lease_file", "close_helper.lease"), ("operation", "close"), ("pid_file", "close_helper.pid"), + ("prompt", "CLOSE_ROUTE_6501"), ("state_file", "close_helper.state"), + ("stub", ( + ("mode", "seq_probe"), ("probe_tokens", ("CLOSE_ROUTE_6501",)), + ("rounds", ( + ((("args", (("run_in_background", True),)), ("command", "__CLOSE_COMMAND__"), ("name", "bash")),), + ((("name", "__finish__"),),), + )), + )), + ),)) , +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), execution_parameters=_EXEC, + timeout_seconds=45, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured-facts close-retry contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..f526843b3f72b0c9bd3b493f3b28804f8e9b91d4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance.py @@ -0,0 +1,117 @@ +"""Verify target child add-directory inheritance and its empty variant. + +1. Run target child-grant and child-empty API variants with controlled read probes. +2. Capture the scenario-specific structured-facts row after the control gate. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when inheritance boundaries are conclusive and cleanup is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "child_add_dir_inheritance" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "api_probe_variants" +_EXECUTION_PARAMETERS = ( + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CHILD_TARGET_7325", "CHILD_EMPTY_7326")), + ( + "rounds", + ( + ( + (("args", (("file_path", "__REPO__/main.txt"),)), ("name", "read")), + (("args", (("file_path", "__EXTRA__/extra.txt"),)), ("name", "read")), + (("args", (("file_path", "__UNAUTHORIZED__/outside.txt"),)), ("name", "read")), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ( + _VARIANTS_KEY, + ( + ( + ("actor", "child"), ("add_dir", True), ("extra_token", "EXTRA_7322"), + ("label", "child-target"), ("main_token", "MAIN_7321"), + ("operation", "child"), ("prompt", "CHILD_TARGET_7325"), + ("settle_s", "2.0"), ("shape", "child-target"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ( + ("actor", "child"), ("add_dir", False), ("extra_token", "EXTRA_7322"), + ("label", "child-empty-target"), ("main_token", "MAIN_7321"), + ("operation", "child"), ("prompt", "CHILD_EMPTY_7326"), + ("settle_s", "2.0"), ("shape", "child-empty-target"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ), + ), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + dependencies=(("child_add_dir_inheritance_control", DependencyKind.GATE),), + timeout_seconds=30, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured child-inheritance target contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance_control.py new file mode 100644 index 0000000000000000000000000000000000000000..76e9db3c5f31a86052462323ba6c472f39fe7014 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/child_add_dir_inheritance_control.py @@ -0,0 +1,115 @@ +"""Verify the control route for child add-directory inheritance. + +1. Run parent-grant and child-empty API variants with controlled read probes. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when inheritance boundaries are conclusive and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "child_add_dir_inheritance_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "api_probe_variants" +_EXECUTION_PARAMETERS = ( + ("kind", "control"), + ( + "stub", + ( + ("mode", "seq_probe"), + ("probe_tokens", ("CHILD_PARENT_7324", "CHILD_EMPTY_7326")), + ( + "rounds", + ( + ( + (("args", (("file_path", "__REPO__/main.txt"),)), ("name", "read")), + (("args", (("file_path", "__EXTRA__/extra.txt"),)), ("name", "read")), + (("args", (("file_path", "__UNAUTHORIZED__/outside.txt"),)), ("name", "read")), + ), + ((("name", "__finish__"),),), + ), + ), + ), + ), + ( + _VARIANTS_KEY, + ( + ( + ("actor", "parent"), ("add_dir", True), ("extra_token", "EXTRA_7322"), + ("label", "parent-grant"), ("main_token", "MAIN_7321"), + ("operation", "child"), ("prompt", "CHILD_PARENT_7324"), + ("shape", "parent-grant"), ("unauthorized_token", "UNAUTH_7323"), + ), + ( + ("actor", "child"), ("add_dir", False), ("extra_token", "EXTRA_7322"), + ("label", "child-empty"), ("main_token", "MAIN_7321"), + ("operation", "child"), ("prompt", "CHILD_EMPTY_7326"), + ("settle_s", "2.0"), ("shape", "child-empty"), + ("unauthorized_token", "UNAUTH_7323"), + ), + ), + ), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + timeout_seconds=30, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured child-inheritance control contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_bytes.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_bytes.py new file mode 100644 index 0000000000000000000000000000000000000000..6e34ed17fc8f37cf26a0b3b05b349fd14ef4522d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_bytes.py @@ -0,0 +1,95 @@ +"""Verify that the target route preserves UTF-8 clipboard bytes. + +1. Run the UTF-8 copy operation through the target API variant after its control gate. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when the structured route is complete and cleanup is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "copy_utf8_clipboard_bytes" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_EXECUTION_PARAMETERS = ( + ( + _VARIANTS_KEY, + (( + ("capture", "clipboard_capture.bin"), + ("label", "target"), + ("meta", "clipboard_meta.json"), + ("operation", "copy"), + ("prompt", "COPY_ROUTE_6601"), + ("stub", ( + ("mode", "fixed_reply"), + ("probe_tokens", ("COPY_ROUTE_6601",)), + ("reply_content", "COPY_UTF8_6603 ้›ช่ฑน cafรฉ ฮ”"), + )), + ),), + ), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + dependencies=(("copy_utf8_clipboard_control", DependencyKind.GATE),), + timeout_seconds=45, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured UTF-8 clipboard contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_control.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a9f38af40d3f52ce8f765fff5aaa59ce5ea199 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/copy_utf8_clipboard_control.py @@ -0,0 +1,94 @@ +"""Verify the control route for UTF-8 clipboard copying. + +1. Run the fixed-reply copy operation through the control API variant. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true behavioral check vector. +4. Return PASS only when the structured route is complete and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "copy_utf8_clipboard_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_EXECUTION_PARAMETERS = ( + ("kind", "control"), + ( + _VARIANTS_KEY, + (( + ("capture", "clipboard_capture.bin"), + ("label", "control"), + ("meta", "clipboard_meta.json"), + ("operation", "copy"), + ("prompt", "COPY_ROUTE_6601"), + ("stub", ( + ("mode", "fixed_reply"), + ("probe_tokens", ("COPY_ROUTE_6601",)), + ("reply_content", "COPY_ASCII_6602 exact bytes"), + )), + ),), + ), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + timeout_seconds=45, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured clipboard control contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif facts.get("result_present") is not True: + reason = "CHILD_RESULT_MISSING" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_no_secondary_expansion.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_no_secondary_expansion.py new file mode 100644 index 0000000000000000000000000000000000000000..eb36a433aae0f0b5a8e0807a8f5d60fd48b2e7e9 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_no_secondary_expansion.py @@ -0,0 +1,125 @@ +"""Verify that a custom command does not perform secondary expansion. + +1. Restore the central guarded-command and secret fixtures. +2. Execute the command sequence with its guarded argument payload. +3. Observe request probes and the protected execution file. +4. Pass only when the face and argument are seen without secret leakage or execution. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_file, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "custom_args_no_secondary_expansion" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_SEED_STEPS = tuple( + seed_file(path, content) for path, content in _BASE_SCENARIO.recipe.seed_files +) +_COMMAND_STEPS = tuple(command(value) for value in _BASE_SCENARIO.recipe.commands) +STEPS = ( + *_SEED_STEPS, + *_COMMAND_STEPS, + observe_file(_BASE_SCENARIO.recipe.observed_files[0]), + observe_requests(), +) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.CUSTOM_NO_SECONDARY, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, + timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _mapping(value: object) -> dict[str, object]: + if type(value) is tuple and all( + type(item) is tuple and len(item) == 2 and type(item[0]) is str + for item in value + ): + return dict(value) + return {} + + +def _requests(value: object) -> tuple[dict[str, object], ...]: + return ( + tuple(_mapping(item) for item in value if type(item) is tuple) + if type(value) is tuple + else () + ) + + +def _probe(request: dict[str, object], token: str) -> bool: + return _mapping(request.get("probes")).get(token) is True + + +def _texts(value: object) -> tuple[str, ...]: + return ( + tuple(item for item in value if type(item) is str) + if type(value) is tuple + else () + ) + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the CUSTOM_NO_SECONDARY contract using typed facts.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = _mapping(observation.facts) + params = _mapping(RECIPE.oracle_parameters) + requests = _requests(facts.get("requests")) + blob = ( + " || ".join(_texts(facts.get("returns"))) + + " || " + + (facts.get("console") if type(facts.get("console")) is str else "") + ) + + def observed(token: object) -> bool: + value = token if type(token) is str else "" + return any(_probe(request, value) for request in requests) or value in blob + + if not observed(params.get("face_token")) or not observed(params.get("args_token")): + passed, conclusive, reason = False, False, "CUSTOM_ARGUMENTS_UNOBSERVED" + else: + files = _mapping(facts.get("files")) + secret = ( + params.get("secret_token") + if type(params.get("secret_token")) is str + else "" + ) + path = params.get("path") + passed = not observed(secret) and files.get(path) is None + conclusive, reason = True, "CUSTOM_SECONDARY_BOUNDARY_CHECKED" + if conclusive and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE + if conclusive + else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_single_expansion_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_single_expansion_control.py new file mode 100644 index 0000000000000000000000000000000000000000..c25e32ff05278a315b20e3524f2f2a49b90d9d68 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/custom_args_single_expansion_control.py @@ -0,0 +1,127 @@ +"""Verify the control path expands custom-command arguments exactly once. + +1. Restore the central command and fixture definitions. +2. Execute the controlled command sequence and observe the request wire. +3. Check the face, argument, file, and non-empty output evidence. +4. Pass only when all expansion facts are observable and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_file, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "custom_args_single_expansion_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_SEED_STEPS = tuple( + seed_file(path, content) for path, content in _BASE_SCENARIO.recipe.seed_files +) +_COMMAND_STEPS = tuple(command(value) for value in _BASE_SCENARIO.recipe.commands) +STEPS = ( + *_SEED_STEPS, + *_COMMAND_STEPS, + observe_file(_BASE_SCENARIO.recipe.observed_files[0]), + observe_requests(), +) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.CUSTOM_SINGLE_EXPANSION, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, + timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _mapping(value: object) -> dict[str, object]: + if type(value) is tuple and all( + type(item) is tuple and len(item) == 2 and type(item[0]) is str + for item in value + ): + return dict(value) + return {} + + +def _requests(value: object) -> tuple[dict[str, object], ...]: + return ( + tuple(_mapping(item) for item in value if type(item) is tuple) + if type(value) is tuple + else () + ) + + +def _probe(request: dict[str, object], token: str) -> bool: + return _mapping(request.get("probes")).get(token) is True + + +def _texts(value: object) -> tuple[str, ...]: + return ( + tuple(item for item in value if type(item) is str) + if type(value) is tuple + else () + ) + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the CUSTOM_SINGLE_EXPANSION contract using typed facts.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = _mapping(observation.facts) + params = _mapping(RECIPE.oracle_parameters) + requests = _requests(facts.get("requests")) + blob = ( + " || ".join(_texts(facts.get("returns"))) + + " || " + + (facts.get("console") if type(facts.get("console")) is str else "") + ) + + def observed(token: object) -> bool: + value = token if type(token) is str else "" + return any(_probe(request, value) for request in requests) or value in blob + + face = params.get("face_token") + if not observed(face): + passed, conclusive, reason = False, False, "CUSTOM_COMMAND_UNOBSERVED" + else: + files = _mapping(facts.get("files")) + path = params.get("path") + content = files.get(path) + passed = ( + observed(params.get("args_token")) + and observed(params.get("file_token")) + and type(content) is str + and bool(content.strip()) + ) + conclusive, reason = True, "CUSTOM_SINGLE_EXPANSION_CHECKED" + if conclusive and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE + if conclusive + else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency.py new file mode 100644 index 0000000000000000000000000000000000000000..41f692faff8cc22c7a51a3422c6b0d7a44754ee4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency.py @@ -0,0 +1,80 @@ +"""Verify that memory top-k residency stays bounded from small to large fixtures. + +1. Run the small and large memory fixtures with the same bounded top-k query. +2. Capture the scenario-specific structured-facts row after the control gate. +3. Require observed/support evidence and an all-true residency check vector. +4. Return PASS only when both sizes remain bounded and cleanup is clean. +""" + +from doc2harness.benchmark.definition import DependencyKind +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "memory_query_topk_residency" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_ROUNDS = ( + ((("args", (("limit", 3), ("query", "zirconium quasar heliotrope"))), ("name", ("memory_search", "memory-search", "memorysearch"))),), + ((("name", "__finish__"),),), +) +_EXECUTION_PARAMETERS = ( + (_VARIANTS_KEY, ( + (("decoy", "DECOY_"), ("entries", 2000), ("label", "small"), ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), ("operation", "memory"), ("rss_probe_bytes", 16777216), ("stub", (("mode", "seq_probe"), ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), ("rounds", _ROUNDS))), ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), ("warm_query", "warmup_only_6401")), + (("decoy", "DECOY_"), ("entries", 120000), ("label", "large"), ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), ("operation", "memory"), ("rss_probe_bytes", 16777216), ("stub", (("mode", "seq_probe"), ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), ("rounds", _ROUNDS))), ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), ("warm_query", "warmup_only_6401")), + )), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + dependencies=(("memory_query_topk_residency_control", DependencyKind.GATE),), + timeout_seconds=180, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured memory-residency target contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation(SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, reason, evaluation_digest(SCENARIO, observation), SCENARIO.definition.weight_microunits if conclusive else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency_control.py new file mode 100644 index 0000000000000000000000000000000000000000..ec83751b5972eb495551f8c488aef069e05f1bcb --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/memory_query_topk_residency_control.py @@ -0,0 +1,91 @@ +"""Verify the control route for a bounded memory top-k query. + +1. Run the small control memory fixture with a bounded top-k query. +2. Capture the scenario-specific structured-facts row. +3. Require observed/support evidence and an all-true residency check vector. +4. Return PASS only when the control query is complete and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + compile_state_steps, + evaluation_digest, + structured_fact, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "memory_query_topk_residency_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +_VARIANTS_KEY = "clipboard_api_variants" +_EXECUTION_PARAMETERS = ( + ("kind", "control"), + (_VARIANTS_KEY, (( + ("decoy", "DECOY_"), + ("entries", 2000), + ("label", "control"), + ("markers", ("MEMORY_ALPHA_6402", "MEMORY_BETA_6403", "MEMORY_GAMMA_6404")), + ("operation", "memory"), + ("rss_probe_bytes", 16777216), + ("stub", (("mode", "seq_probe"), ("probe_tokens", ("MEMORY_TARGET_ROUTE_6406",)), ("rounds", ( + ((("args", (("limit", 3), ("query", "zirconium quasar heliotrope"))), ("name", ("memory_search", "memory-search", "memorysearch"))),), + ((("name", "__finish__"),),), + )))), + ("target_prompt", "MEMORY_TARGET_ROUTE_6406"), + ("warm_query", "warmup_only_6401"), + ),),), +) +STEPS = (structured_fact("structured_facts"),) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.STRUCTURED_FACTS, + oracle_parameters=(("fact_key", SCENARIO_ID),), + execution_parameters=_EXECUTION_PARAMETERS, + timeout_seconds=120, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the structured memory-residency control contract using typed facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + passed, conclusive, reason = False, True, "CHILD_RESULT_MISSING" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + else: + structured = facts.get("structured_facts") + structured = dict(structured) if type(structured) is tuple else {} + row = structured.get(SCENARIO_ID) + row = dict(row) if type(row) is tuple else {} + if row.get("observed") is not True or row.get("supported") is False: + conclusive, reason = False, "STRUCTURED_FACTS_UNOBSERVED" + else: + checks = row.get("checks") + checks = checks if type(checks) is tuple else () + if not checks: + conclusive, reason = False, "STRUCTURED_CHECKS_MISSING" + elif not all(item is True for item in checks): + reason = "STRUCTURED_FACTS_FAILED" + else: + public_calls = row.get("public_calls") + if type(public_calls) is not bool: + conclusive, reason = False, "STRUCTURED_PUBLIC_CALLS_UNOBSERVED" + elif public_calls is not True: + reason = "STRUCTURED_PUBLIC_CALLS_FAILED" + else: + passed, reason = True, "STRUCTURED_FACTS_CHECKED" + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation(SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, reason, evaluation_digest(SCENARIO, observation), SCENARIO.definition.weight_microunits if conclusive else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/p30_ctl_security_review_sees_worktree_change.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/p30_ctl_security_review_sees_worktree_change.py new file mode 100644 index 0000000000000000000000000000000000000000..72886c59997ebaf25298810309ed9becffc4dde3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/p30_ctl_security_review_sees_worktree_change.py @@ -0,0 +1,93 @@ +"""Verify that the security-review control route sees a worktree change. + +1. Seed the scenario-specific fixture files and invoke the command sequence. +2. Capture the model request facts after the scenario's execution gates. +3. Check whether the expected token appears in a request probe. +4. Return PASS only when the request is observed and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "p30_ctl_security_review_sees_worktree_change" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +STEPS = ( + seed_file("vuln_9601.py", "import os\n"), + command("/security-review"), + observe_requests(), +) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.REQUEST_TOKEN_PRESENT, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, + timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _mapping(value: object) -> dict[str, object]: + if type(value) is tuple and all( + type(item) is tuple and len(item) == 2 and type(item[0]) is str + for item in value + ): + return dict(value) + return {} + + +def _requests(value: object) -> tuple[dict[str, object], ...]: + if type(value) is not tuple: + return () + return tuple(_mapping(item) for item in value if type(item) is tuple) + + +def _probe(request: dict[str, object], token: str) -> bool: + return _mapping(request.get("probes")).get(token) is True + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the REQUEST_TOKEN_PRESENT contract using typed request facts.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = _mapping(observation.facts) + requests = _requests(facts.get("requests")) + params = _mapping(RECIPE.oracle_parameters) + token = params.get("token") if type(params.get("token")) is str else "" + passed, conclusive, reason = False, True, "REQUEST_TOKEN_CHECKED" + if not requests: + conclusive, reason = False, "MODEL_TURN_UNOBSERVED" + else: + passed = any(_probe(request, token) for request in requests) + if conclusive and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE + if conclusive + else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_declared_command_reaches_wire.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_declared_command_reaches_wire.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b71051df7239a9cfe856cb6c8e2cbc4a3b803b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_declared_command_reaches_wire.py @@ -0,0 +1,75 @@ +"""Verify that a plugin-declared command face reaches the model wire. + +1. Seed the plugin manifest and its command file, then invoke `/probecmd`. +2. Send the continuation prompt through the same session. +3. Capture the recorder-owned command-face request probe after the gate. +4. Pass only when the plugin token reaches a model request without an unknown-command result. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "plugin_declared_command_reaches_wire" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +STEPS = ( + seed_file("plugins/probeplug/commands/probecmd.md", "Summarize PLUGCMD_5150 for the team now.\n"), + seed_file("plugins/probeplug/plugin.json", '{\n "name": "probeplug",\n "description": "probe plugin",\n "commands": [\n "commands/probecmd.md"\n ]\n}'), + command("/probecmd"), + command("please continue"), + observe_requests(), +) +RECIPE = compile_state_steps(STEPS, oracle_profile=StateOracleProfile.CUSTOM_COMMAND_FACE, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _probe(request: dict[str, object], token: str) -> bool: + probes = request.get("probes") + return type(probes) is tuple and dict(probes).get(token) is True + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the custom-command face contract using typed request facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + requests = facts.get("requests") + requests = requests if type(requests) is tuple else () + requests = tuple(dict(item) for item in requests if type(item) is tuple) + returns = facts.get("returns") + returns = returns if type(returns) is tuple else () + params = dict(RECIPE.oracle_parameters) + passed, conclusive, reason = False, True, "CUSTOM_COMMAND_FACE_CHECKED" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif returns and any("unknown command" in str(item).lower() for item in returns): + reason = "CUSTOM_COMMAND_MISSING" + elif not requests: + conclusive, reason = False, "MODEL_TURN_UNOBSERVED" + else: + passed = any(_probe(request, params["token"]) for request in requests) + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation(SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, evaluation_digest(SCENARIO, observation), SCENARIO.definition.weight_microunits if conclusive else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_toplevel_command_control.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_toplevel_command_control.py new file mode 100644 index 0000000000000000000000000000000000000000..41bbf70f248bba1ffe807c83b5b7e6a577889f01 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/plugin_toplevel_command_control.py @@ -0,0 +1,74 @@ +"""Verify the control route for a top-level custom command face. + +1. Seed the top-level command file and invoke `/probecmd`. +2. Send the continuation prompt through the same session. +3. Capture the recorder-owned command-face request probe. +4. Pass only when the command token reaches a model request without an unknown-command result. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "plugin_toplevel_command_control" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +STEPS = ( + seed_file("commands/probecmd.md", "Summarize PLUGCMD_5150 for the team now.\n"), + command("/probecmd"), + command("please continue"), + observe_requests(), +) +RECIPE = compile_state_steps(STEPS, oracle_profile=StateOracleProfile.CUSTOM_COMMAND_FACE, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _probe(request: dict[str, object], token: str) -> bool: + probes = request.get("probes") + return type(probes) is tuple and dict(probes).get(token) is True + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the custom-command face contract using typed request facts only.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = dict(observation.facts) + requests = facts.get("requests") + requests = requests if type(requests) is tuple else () + requests = tuple(dict(item) for item in requests if type(item) is tuple) + returns = facts.get("returns") + returns = returns if type(returns) is tuple else () + params = dict(RECIPE.oracle_parameters) + passed, conclusive, reason = False, True, "CUSTOM_COMMAND_FACE_CHECKED" + if not observation.fixture_verified: + conclusive, reason = False, "FIXTURE_UNVERIFIED" + elif returns and any("unknown command" in str(item).lower() for item in returns): + reason = "CUSTOM_COMMAND_MISSING" + elif not requests: + conclusive, reason = False, "MODEL_TURN_UNOBSERVED" + else: + passed = any(_probe(request, params["token"]) for request in requests) + if conclusive and (not observation.process_tree_clean or not observation.workspace_clean): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation(SCENARIO_ID, StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE if conclusive else StateApplicability.INCONCLUSIVE, + reason, evaluation_digest(SCENARIO, observation), SCENARIO.definition.weight_microunits if conclusive else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/state/scenarios/security_review_covers_branch_commits.py b/code/src/doc2harness/benchmark/harnesses/state/scenarios/security_review_covers_branch_commits.py new file mode 100644 index 0000000000000000000000000000000000000000..67de63aea545327626bf78e53f2b0521901fe51c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/state/scenarios/security_review_covers_branch_commits.py @@ -0,0 +1,93 @@ +"""Verify that security review covers a branch commit after the worktree change. + +1. Seed the scenario-specific fixture files and invoke the command sequence. +2. Capture the model request facts after the scenario's execution gates. +3. Check whether the expected token appears in a request probe. +4. Return PASS only when the request is observed and cleanup is clean. +""" + +from doc2harness.benchmark.harnesses.state.contracts import ( + StateApplicability, + StateEvaluation, + StateObservation, + StateOracleProfile, + StateOutcome, + StateScenario, + command, + compile_state_steps, + evaluation_digest, + observe_requests, + seed_file, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "security_review_covers_branch_commits" +_BASE_SCENARIO = scenario_by_id(SCENARIO_ID) +STEPS = ( + seed_file("vuln_9601.py", "import os\n"), + command("/security-review"), + observe_requests(), +) +RECIPE = compile_state_steps( + STEPS, + oracle_profile=StateOracleProfile.REQUEST_TOKEN_PRESENT, + oracle_parameters=_BASE_SCENARIO.recipe.oracle_parameters, + execution_parameters=_BASE_SCENARIO.recipe.execution_parameters, + dependencies=_BASE_SCENARIO.recipe.dependencies, + timeout_seconds=_BASE_SCENARIO.recipe.timeout_seconds, +) +SCENARIO: StateScenario = StateScenario(_BASE_SCENARIO.definition, RECIPE) +scenario = _BASE_SCENARIO +definition = SCENARIO.definition + + +def _mapping(value: object) -> dict[str, object]: + if type(value) is tuple and all( + type(item) is tuple and len(item) == 2 and type(item[0]) is str + for item in value + ): + return dict(value) + return {} + + +def _requests(value: object) -> tuple[dict[str, object], ...]: + if type(value) is not tuple: + return () + return tuple(_mapping(item) for item in value if type(item) is tuple) + + +def _probe(request: dict[str, object], token: str) -> bool: + return _mapping(request.get("probes")).get(token) is True + + +def judge(observation: StateObservation) -> StateEvaluation: + """Apply the REQUEST_TOKEN_PRESENT contract using typed request facts.""" + if observation.scenario_id != SCENARIO_ID: + raise ValueError("state observation belongs to another scenario") + facts = _mapping(observation.facts) + requests = _requests(facts.get("requests")) + params = _mapping(RECIPE.oracle_parameters) + token = params.get("token") if type(params.get("token")) is str else "" + passed, conclusive, reason = False, True, "REQUEST_TOKEN_CHECKED" + if not requests: + conclusive, reason = False, "MODEL_TURN_UNOBSERVED" + else: + passed = any(_probe(request, token) for request in requests) + if conclusive and ( + not observation.process_tree_clean or not observation.workspace_clean + ): + passed, reason = False, "EXECUTION_CLEANUP_FAILED" + return StateEvaluation( + SCENARIO_ID, + StateOutcome.PASS if passed else StateOutcome.FAIL, + StateApplicability.APPLICABLE + if conclusive + else StateApplicability.INCONCLUSIVE, + reason, + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if conclusive else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/__init__.py b/code/src/doc2harness/benchmark/harnesses/tui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d41b2103fc2871acf1e0a1a80f3e902709bd10d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/__init__.py @@ -0,0 +1,47 @@ +"""Typed public boundary for interactive TUI PTY scenarios.""" + +from .adapter import ( + TuiPtyExecutionPlan, + build_tui_pty_execution_plan, +) +from .contracts import ( + HistoryEvent, + HistoryFile, + HistoryObservation, + HistorySnapshot, + ObservedFile, + PromptObservation, + TuiApplicability, + TuiEvaluation, + TuiInput, + TuiObservation, + TuiOracleBinding, + TuiOutcome, + TuiProfile, + TuiRecipe, + TuiRequest, + TuiScenario, +) +from .recipes import SCENARIO_BY_ID + +__all__ = [ + "SCENARIO_BY_ID", + "HistoryEvent", + "HistoryFile", + "HistoryObservation", + "HistorySnapshot", + "ObservedFile", + "PromptObservation", + "TuiApplicability", + "TuiEvaluation", + "TuiInput", + "TuiObservation", + "TuiOracleBinding", + "TuiOutcome", + "TuiProfile", + "TuiPtyExecutionPlan", + "TuiRecipe", + "TuiRequest", + "TuiScenario", + "build_tui_pty_execution_plan", +] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/adapter.py b/code/src/doc2harness/benchmark/harnesses/tui/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..77f954cb56083436da3f5ffe0912cab705fcf42c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/adapter.py @@ -0,0 +1,215 @@ +"""Execution boundary for typed TUI PTY observations.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole + +from .contracts import ( + TuiApplicability, + TuiEvaluation, + TuiInput, + TuiObservation, + TuiOracleBinding, + TuiOutcome, + TuiProfile, + TuiRecipe, + TuiScenario, + define_tui_scenario, + evaluation_digest, +) +from .fixtures import TuiFixturePlan, materialize_tui_fixture + + +@dataclass(frozen=True, slots=True) +class TuiPtyExecutionPlan: + scenario_id: str + profile: TuiProfile + recipe: TuiRecipe + fixture: TuiFixturePlan + timeout_seconds: int + plan_digest: str + + +def build_tui_pty_execution_plan(scenario: TuiScenario, /) -> TuiPtyExecutionPlan: + if type(scenario) is not TuiScenario: + raise ContractDocumentError("TUI PTY execution requires an exact scenario") + fixture = materialize_tui_fixture(scenario) + body = { + "fixture_digest": fixture.plan_digest, + "profile": scenario.recipe.profile.value, + "scenario_id": scenario.definition.scenario_id, + "timeout_seconds": scenario.recipe.timeout_seconds, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.tui-pty-plan/1\0" + canonical_json(body) + ).hexdigest() + return TuiPtyExecutionPlan( + scenario.definition.scenario_id, + scenario.recipe.profile, + scenario.recipe, + fixture, + scenario.recipe.timeout_seconds, + digest, + ) + + +# These builders intentionally live at the adapter boundary rather +# than in a second helper module: scenario files stay declarative while the +# runtime-owned external observation policy remains in one stable module. +def build_external_tui_scenario( + scenario_id: str, + role: ScenarioRole, + control_id: str | None, + gateway_mode: str, +) -> TuiScenario: + dependencies = () if role is ScenarioRole.CONTROL else ( + (control_id, DependencyKind.GATE), + ) + digest = "sha256:" + hashlib.sha256( + ("doc2harness.tui.external/1\\0" + scenario_id).encode() + ).hexdigest() + marker = "TUI_EXTERNAL_7731" + cli_arguments: tuple[str, ...] = () + if "background_completion" in scenario_id: + marker = "TUI_BACKGROUND_DONE_7731" + elif "autotest_output" in scenario_id: + marker = "TUI_AUTOTEST_SUCCESS_7731" + cli_arguments = ( + "--auto-test", + "--test-cmd", + "printf 'TUI_AUTOTEST_SUCCESS_7731 stdout test passed\\n'", + ) + elif "autocommit_fail" in scenario_id: + marker = "TUI_AUTOCOMMIT_FAIL_7731" + cli_arguments = ("--auto-commit",) + elif "bad_tool_args" in scenario_id: + marker = "TUI_BAD_ARGS_SUCCESS_7731" + elif "empty_tool_name" in scenario_id: + marker = "TUI_EMPTY_TOOL_7731" + elif "model_finish_reason" in scenario_id: + marker = "TUI_FINISH_REASON_7731" + elif "step_limit" in scenario_id: + marker = "TUI_STEP_LIMIT_7731" + cli_arguments = ("--max-steps", "2") + recipe = TuiRecipe( + TuiProfile.WIRE_SURVIVES, + digest, + dependencies, + 180, + False, + input_lines=(TuiInput("70696e67"),), + gateway_mode=gateway_mode, + probe_tokens=(marker,), + cli_arguments=cli_arguments, + oracle=TuiOracleBinding(primary_token=marker), + ) + return define_tui_scenario(scenario_id, recipe, role) + + +def _external_tui_has(text: str, *patterns: str) -> bool: + lowered = text.lower() + return all( + any(pattern.lower() in lowered for pattern in group.split("|")) + for group in patterns + ) + + +def _external_tui_requirement(requirement: str, text: str, marker: str = "") -> bool: + """Check a trajectory requirement using its scenario-bound canary marker. + + The recipe tables use generic marker names, while the external recipe + builder uses a stable per-scenario marker. Accepting the bound marker as + an alternative keeps the judge tied to the scenario rather than to one + probe spelling; it does not make a phrase-only trajectory + sufficient because every branch still requires the semantic event words. + """ + + marker = marker or "__missing_marker__" + if requirement == "step_limit": + return _external_tui_has(text, "limits_exceeded|max_steps", "run_end|terminal|finished") + if requirement == "bad_args": + return _external_tui_has(text, "tool_result|error|failure", "invalid|malformed|json|argument", f"TUI_BAD_ARGS_SUCCESS_7731|{marker}") + if requirement == "autotest": + return _external_tui_has(text, "stdout|test", "success|passed|ok", f"TUI_AUTOTEST_SUCCESS_7731|{marker}") + if requirement == "autocommit_fail": + return _external_tui_has(text, "auto.?commit|commit", "gpg|hook|cannot|failed|error", f"TUI_AUTOCOMMIT_FAIL_7731|{marker}") + if requirement == "background": + return _external_tui_has(text, "completed|exit|finished", f"TUI_BACKGROUND_DONE_7731|{marker}") + if requirement == "empty_reply": + return _external_tui_has(text, "warning|error|note", "empty|no content|blank") + if requirement == "finish_reason": + return _external_tui_has(text, "tool_calls|tool call", "finish_reason|stop") + if requirement == "empty_tool_name": + return _external_tui_has( + text, + "error|invalid|malformed|no tool named|unknown tool", + "empty|missing|invalid|no tool named|unknown tool|''", + "tool", + ) + raise ValueError(requirement) + + +def make_external_tui_judge(scenario: TuiScenario, requirement: str): + def judge(observation: TuiObservation) -> TuiEvaluation: + if observation.scenario_id != scenario.definition.scenario_id: + raise ValueError("TUI external observation belongs to another scenario") + base_ready = ( + observation.cli_available + and bool(observation.requests) + and observation.returncode == 0 + and not observation.driver_error + and observation.process_tree_clean + and observation.workspace_clean + and not observation.deadline_reached + ) + if not base_ready: + outcome = TuiOutcome.PASS + applicability = TuiApplicability.INCONCLUSIVE + reason = "TUI_EXTERNAL_STIMULUS_UNESTABLISHED" + elif scenario.definition.role is ScenarioRole.CONTROL: + outcome = TuiOutcome.PASS + applicability = TuiApplicability.APPLICABLE + reason = "TUI_EXTERNAL_CONTROL_ESTABLISHED" + elif not observation.trajectory_text: + outcome = TuiOutcome.FAIL + applicability = TuiApplicability.APPLICABLE + reason = "TUI_TRAJECTORY_NOT_OBSERVED" + else: + marker = scenario.recipe.oracle.primary_token or ( + scenario.recipe.probe_tokens[0] if scenario.recipe.probe_tokens else "" + ) + passed = _external_tui_requirement(requirement, observation.trajectory_text, marker) + outcome = TuiOutcome.PASS if passed else TuiOutcome.FAIL + applicability = TuiApplicability.APPLICABLE + reason = "TUI_TRAJECTORY_REQUIREMENT_RECORDED" if passed else "TUI_TRAJECTORY_REQUIREMENT_MISSING" + contribution = ( + scenario.definition.weight_microunits + if outcome is TuiOutcome.PASS and applicability is TuiApplicability.APPLICABLE + else 0 + ) + return TuiEvaluation( + scenario.definition.scenario_id, + outcome, + applicability, + reason, + evaluation_digest(scenario, observation), + contribution, + ) + + return judge + + +# Short aliases keep the scenario declarations tiny. +build_scenario = build_external_tui_scenario +make_judge = make_external_tui_judge + + +__all__ = [ + "TuiPtyExecutionPlan", "build_tui_pty_execution_plan", + "build_external_tui_scenario", "make_external_tui_judge", + "build_scenario", "make_judge", +] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/catalog.toml b/code/src/doc2harness/benchmark/harnesses/tui/catalog.toml new file mode 100644 index 0000000000000000000000000000000000000000..b9dcafb4bb9191888774e78a219624d013af04a2 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/catalog.toml @@ -0,0 +1,14 @@ +format = "doc2harness.catalog-shard-source/1" +function_id = "tui" +resource = "benchmark/harnesses/tui/catalog.toml" +exports = [ + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_realpath_key", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_a_fresh_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_b_fresh_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate_control", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_bang_alone_enters_shell_mode", export = "definition" }, + { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_ctrl_byte_storm_survives", export = "definition" }, +] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/contracts.py b/code/src/doc2harness/benchmark/harnesses/tui/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..617a18ad9976c58f2e9edcdd7bb4062b462a1a10 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/contracts.py @@ -0,0 +1,501 @@ +"""Typed recipes and raw observations for interactive TUI PTY scenarios.""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import asdict, dataclass +from enum import Enum + +from doc2harness.benchmark.definition import ( + Classification, + ComponentKind, + ComponentRef, + DependencyKind, + DependencyRef, + ExperimentBinding, + ScenarioDefinition, + ScenarioDifficulty, + ScenarioRole, + UnsupportedPolicy, + definition_digest, +) +from doc2harness.contracts.canonical import canonical_json +from doc2harness.contracts.primitives import ContractDocumentError + +_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII) +_DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z", re.ASCII) +_HEX = re.compile(r"(?:[0-9a-f]{2})*\Z", re.ASCII) +_MAX_TEXT = 4_000_000 +_MAX_ITEMS = 4096 + + +def _text(value: object, name: str, *, empty: bool = True) -> None: + if type(value) is not str or len(value) > _MAX_TEXT or (not empty and not value): + raise ContractDocumentError(f"TUI PTY {name} is invalid") + + +def _digest(value: object, name: str) -> None: + if type(value) is not str or _DIGEST.fullmatch(value) is None: + raise ContractDocumentError(f"TUI PTY {name} is invalid") + + +def _hex(value: object, name: str) -> None: + if type(value) is not str or len(value) > _MAX_TEXT * 2 or _HEX.fullmatch(value) is None: + raise ContractDocumentError(f"TUI PTY {name} is invalid") + + +def _strings(value: object, name: str, *, unique: bool = False) -> None: + if ( + type(value) is not tuple + or len(value) > _MAX_ITEMS + or any(type(item) is not str or len(item) > _MAX_TEXT for item in value) + or (unique and len(set(value)) != len(value)) + ): + raise ContractDocumentError(f"TUI PTY {name} is invalid") + + +def _relative(value: object, name: str) -> None: + _text(value, name, empty=False) + if value.startswith("/") or ".." in value.split("/"): + raise ContractDocumentError(f"TUI PTY {name} must be relative") + + +class TuiProfile(str, Enum): + CHAOS_SURVIVES = "chk_survives_chaos" + FILE_WRITTEN = "chk_tui_file" + WIRE_SURVIVES = "chk_tui_wire_survives" + HISTORY_FRESH = "chk_history_fresh_control" + HISTORY_REALPATH = "chk_history_realpath_key" + + +class TuiOutcome(str, Enum): + PASS = "PASS" + FAIL = "FAIL" + + +class TuiApplicability(str, Enum): + APPLICABLE = "APPLICABLE" + INCONCLUSIVE = "INCONCLUSIVE" + + +class HistoryScenario(str, Enum): + NONE = "" + FRESH_A = "history-fresh-a" + FRESH_B = "history-fresh-b" + REALPATH_KEY = "history-realpath-key" + + +@dataclass(frozen=True, slots=True) +class TuiInput: + data_hex: str + + def __post_init__(self) -> None: + _hex(self.data_hex, "input bytes") + if not self.data_hex: + raise ContractDocumentError("TUI PTY input bytes must not be empty") + + +@dataclass(frozen=True, slots=True) +class SeedFile: + path: str + data_hex: str + + def __post_init__(self) -> None: + _relative(self.path, "seed path") + _hex(self.data_hex, "seed bytes") + + +@dataclass(frozen=True, slots=True) +class TuiOracleBinding: + primary_token: str = "" + secondary_token: str = "" + foreign_token: str = "" + line_token: str = "" + path: str = "" + specification: str = "" + history_prefix: str = "" + completion_token: str = "TUILINE_DONE_7755" + crash_signatures: tuple[str, ...] = ( + "Traceback (most recent call last)", + "UnhandledError", + "panic:", + "Unhandled exception", + "RuntimeError:", + "KeyError:", + "AttributeError:", + "ValueError:", + ) + + def __post_init__(self) -> None: + for value in ( + self.primary_token, + self.secondary_token, + self.foreign_token, + self.line_token, + self.specification, + self.history_prefix, + self.completion_token, + ): + _text(value, "oracle text") + if self.path: + _relative(self.path, "oracle path") + _strings(self.crash_signatures, "crash signatures", unique=True) + + +@dataclass(frozen=True, slots=True) +class TuiRecipe: + profile: TuiProfile + case_digest: str + dependencies: tuple[tuple[str, DependencyKind], ...] + timeout_seconds: int + blocking: bool + input_lines: tuple[TuiInput, ...] = () + seed_files: tuple[SeedFile, ...] = () + gateway_mode: str = "normal" + reply_content: str = "ack" + probe_tokens: tuple[str, ...] = () + cli_arguments: tuple[str, ...] = () + observed_files: tuple[str, ...] = () + history_scenario: HistoryScenario = HistoryScenario.NONE + oracle: TuiOracleBinding = TuiOracleBinding() + + def __post_init__(self) -> None: + if type(self.profile) is not TuiProfile: + raise ContractDocumentError("TUI PTY profile is invalid") + _digest(self.case_digest, "case digest") + if type(self.dependencies) is not tuple or any( + type(item) is not tuple + or len(item) != 2 + or type(item[0]) is not str + or _ID.fullmatch(item[0]) is None + or type(item[1]) is not DependencyKind + for item in self.dependencies + ): + raise ContractDocumentError("TUI PTY dependencies are invalid") + if ( + type(self.timeout_seconds) is not int + or not 1 <= self.timeout_seconds <= 600 + or type(self.blocking) is not bool + ): + raise ContractDocumentError("TUI PTY execution policy is invalid") + if type(self.input_lines) is not tuple or any( + type(item) is not TuiInput for item in self.input_lines + ): + raise ContractDocumentError("TUI PTY inputs are invalid") + if type(self.seed_files) is not tuple or any( + type(item) is not SeedFile for item in self.seed_files + ): + raise ContractDocumentError("TUI PTY seed files are invalid") + _text(self.gateway_mode, "gateway mode", empty=False) + _text(self.reply_content, "reply content") + _strings(self.probe_tokens, "probe tokens", unique=True) + _strings(self.cli_arguments, "CLI arguments") + _strings(self.observed_files, "observed files", unique=True) + for path in self.observed_files: + _relative(path, "observed path") + if type(self.history_scenario) is not HistoryScenario: + raise ContractDocumentError("TUI PTY history scenario is invalid") + if type(self.oracle) is not TuiOracleBinding: + raise ContractDocumentError("TUI PTY oracle binding is invalid") + + +@dataclass(frozen=True, slots=True) +class TuiRequest: + body: str + + def __post_init__(self) -> None: + _text(self.body, "request body") + + +@dataclass(frozen=True, slots=True) +class ObservedFile: + path: str + present: bool + content: str = "" + + def __post_init__(self) -> None: + _relative(self.path, "observed file path") + if type(self.present) is not bool: + raise ContractDocumentError("TUI PTY file presence is invalid") + _text(self.content, "observed file content") + if not self.present and self.content: + raise ContractDocumentError("absent TUI PTY file cannot have content") + + +@dataclass(frozen=True, slots=True) +class PromptObservation: + identity: str + turn_id: str + candidate_boundary: bool + canary_nonce_absent_before: bool + canary_nonce_absent_from_input: bool + canary_observed: bool + input_consumed: bool + startup_failure_kind: str = "" + startup_returncode: int | None = None + startup_signal: int | None = None + timeline: tuple[str, ...] = () + + def __post_init__(self) -> None: + _text(self.identity, "prompt identity", empty=False) + _text(self.turn_id, "prompt turn", empty=False) + _text(self.startup_failure_kind, "prompt startup failure") + if any( + type(value) is not bool + for value in ( + self.candidate_boundary, + self.canary_nonce_absent_before, + self.canary_nonce_absent_from_input, + self.canary_observed, + self.input_consumed, + ) + ): + raise ContractDocumentError("TUI PTY prompt facts are invalid") + for value in (self.startup_returncode, self.startup_signal): + if value is not None and type(value) is not int: + raise ContractDocumentError("TUI PTY prompt terminal fact is invalid") + _strings(self.timeline, "prompt timeline") + + +@dataclass(frozen=True, slots=True) +class HistoryFile: + path: str + data_hex: str + + def __post_init__(self) -> None: + _relative(self.path, "history path") + _hex(self.data_hex, "history bytes") + + +@dataclass(frozen=True, slots=True) +class HistorySnapshot: + complete: bool + files: tuple[HistoryFile, ...] + + def __post_init__(self) -> None: + if type(self.complete) is not bool or type(self.files) is not tuple or any( + type(item) is not HistoryFile for item in self.files + ): + raise ContractDocumentError("TUI PTY history snapshot is invalid") + paths = tuple(item.path for item in self.files) + if len(paths) != len(set(paths)): + raise ContractDocumentError("TUI PTY history paths must be unique") + + +@dataclass(frozen=True, slots=True) +class HistoryEvent: + name: str + kind: str + input_hex: str + output_text: str + output_sha256: str + output_size: int + requests_before: int + requests_after: int + returncode: int | None = None + + def __post_init__(self) -> None: + _text(self.name, "history event name", empty=False) + _text(self.kind, "history event kind", empty=False) + _hex(self.input_hex, "history event input") + _text(self.output_text, "history event output") + if type(self.output_sha256) is not str or re.fullmatch( + r"[0-9a-f]{64}", self.output_sha256 + ) is None: + raise ContractDocumentError("TUI PTY history output digest is invalid") + if any( + type(value) is not int or value < 0 + for value in (self.output_size, self.requests_before, self.requests_after) + ) or (self.returncode is not None and type(self.returncode) is not int): + raise ContractDocumentError("TUI PTY history event counters are invalid") + + +@dataclass(frozen=True, slots=True) +class HistoryObservation: + scenario: HistoryScenario + workspace: str = "" + workspace_a: str = "" + workspace_b: str = "" + writer: tuple[HistoryEvent, ...] = () + reader: tuple[HistoryEvent, ...] = () + writer_a: tuple[HistoryEvent, ...] = () + writer_b: tuple[HistoryEvent, ...] = () + reader_a: tuple[HistoryEvent, ...] = () + reader_b: tuple[HistoryEvent, ...] = () + snapshot: HistorySnapshot | None = None + snapshot_a: HistorySnapshot | None = None + snapshot_ab: HistorySnapshot | None = None + + def __post_init__(self) -> None: + if type(self.scenario) is not HistoryScenario: + raise ContractDocumentError("TUI PTY history identity is invalid") + for value in (self.workspace, self.workspace_a, self.workspace_b): + _text(value, "history workspace") + for values in ( + self.writer, + self.reader, + self.writer_a, + self.writer_b, + self.reader_a, + self.reader_b, + ): + if type(values) is not tuple or any( + type(item) is not HistoryEvent for item in values + ): + raise ContractDocumentError("TUI PTY history events are invalid") + names = tuple(item.name for item in values) + if len(names) != len(set(names)): + raise ContractDocumentError("TUI PTY history event names must be unique") + for value in (self.snapshot, self.snapshot_a, self.snapshot_ab): + if value is not None and type(value) is not HistorySnapshot: + raise ContractDocumentError("TUI PTY history snapshot type is invalid") + + +@dataclass(frozen=True, slots=True) +class TuiScenario: + definition: ScenarioDefinition + recipe: TuiRecipe + + def __post_init__(self) -> None: + if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not TuiRecipe: + raise ContractDocumentError("TUI PTY scenario requires exact typed values") + if self.definition.classification.primary != "tui": + raise ContractDocumentError("TUI PTY scenario owner differs from its Harness") + + +@dataclass(frozen=True, slots=True) +class TuiObservation: + scenario_id: str + profile: TuiProfile + plan_digest: str + artifact_id: str + artifact_digest: str + backend_evidence_digest: str + cli_available: bool + prompt: PromptObservation + screen_text: str + screen_sha256: str + screen_size: int + returncode: int | None + signal: int | None + requests: tuple[TuiRequest, ...] + files: tuple[ObservedFile, ...] + history: HistoryObservation | None = None + elapsed_ns: int = 0 + deadline_reached: bool = False + driver_error: str = "" + process_tree_clean: bool = True + workspace_clean: bool = True + trajectory_text: str = "" + + def __post_init__(self) -> None: + if type(self.scenario_id) is not str or _ID.fullmatch(self.scenario_id) is None: + raise ContractDocumentError("TUI PTY observation scenario is invalid") + if type(self.profile) is not TuiProfile: + raise ContractDocumentError("TUI PTY observation profile is invalid") + for value in ( + self.plan_digest, + self.artifact_digest, + self.backend_evidence_digest, + ): + _digest(value, "evidence digest") + _text(self.artifact_id, "artifact id", empty=False) + if type(self.cli_available) is not bool or type(self.prompt) is not PromptObservation: + raise ContractDocumentError("TUI PTY observation availability is invalid") + _text(self.screen_text, "screen text") + if type(self.screen_sha256) is not str or re.fullmatch( + r"[0-9a-f]{64}", self.screen_sha256 + ) is None: + raise ContractDocumentError("TUI PTY screen digest is invalid") + if type(self.screen_size) is not int or self.screen_size < 0: + raise ContractDocumentError("TUI PTY screen size is invalid") + for value in (self.returncode, self.signal): + if value is not None and type(value) is not int: + raise ContractDocumentError("TUI PTY terminal status is invalid") + if type(self.requests) is not tuple or any( + type(item) is not TuiRequest for item in self.requests + ): + raise ContractDocumentError("TUI PTY requests are invalid") + if type(self.files) is not tuple or any( + type(item) is not ObservedFile for item in self.files + ): + raise ContractDocumentError("TUI PTY files are invalid") + if self.history is not None and type(self.history) is not HistoryObservation: + raise ContractDocumentError("TUI PTY history is invalid") + if type(self.elapsed_ns) is not int or self.elapsed_ns < 0: + raise ContractDocumentError("TUI PTY elapsed time is invalid") + if any( + type(value) is not bool + for value in ( + self.deadline_reached, + self.process_tree_clean, + self.workspace_clean, + ) + ): + raise ContractDocumentError("TUI PTY cleanup facts are invalid") + _text(self.driver_error, "driver error") + _text(self.trajectory_text, "trajectory text") + paths = tuple(item.path for item in self.files) + if len(paths) != len(set(paths)): + raise ContractDocumentError("TUI PTY observed files must be unique") + + +@dataclass(frozen=True, slots=True) +class TuiEvaluation: + scenario_id: str + outcome: TuiOutcome + applicability: TuiApplicability + reason_code: str + evidence_digest: str + contribution_microunits: int + + +def define_tui_scenario( + scenario_id: str, recipe: TuiRecipe, role: ScenarioRole, / +) -> TuiScenario: + dependencies = tuple( + sorted( + (DependencyRef(test_id, kind) for test_id, kind in recipe.dependencies), + key=lambda item: (item.scenario_id, item.kind.value), + ) + ) + definition = ScenarioDefinition( + scenario_id, + "1", + Classification("tui"), + role, + 1_000_000 if role is ScenarioRole.TARGET else 0, + ScenarioDifficulty.HARD, + dependencies, + ExperimentBinding( + ComponentRef("tui-pty-fixture", "1", ComponentKind.FIXTURE), + ComponentRef("tui-pty-adapter", "1", ComponentKind.STIMULUS), + ComponentRef("tui-pty-observer", "1", ComponentKind.OBSERVER), + ComponentRef("tui-pty-oracle", "1", ComponentKind.ORACLE), + ComponentRef("tui-pty-cleanup", "1", ComponentKind.CLEANUP), + ), + UnsupportedPolicy.FAIL, + ) + return TuiScenario(definition, recipe) + + +def recipe_digest(recipe: TuiRecipe, /) -> str: + if type(recipe) is not TuiRecipe: + raise ContractDocumentError("TUI PTY recipe digest requires an exact recipe") + return "sha256:" + hashlib.sha256( + b"doc2harness.tui-pty-recipe/1\0" + canonical_json(asdict(recipe)) + ).hexdigest() + + +def evaluation_digest(scenario: TuiScenario, observation: TuiObservation) -> str: + body = { + "artifact_digest": observation.artifact_digest, + "backend_evidence_digest": observation.backend_evidence_digest, + "definition_digest": definition_digest(scenario.definition), + "plan_digest": observation.plan_digest, + "scenario_id": scenario.definition.scenario_id, + } + return "sha256:" + hashlib.sha256( + b"doc2harness.tui-pty-evaluation/1\0" + canonical_json(body) + ).hexdigest() diff --git a/code/src/doc2harness/benchmark/harnesses/tui/fixtures.py b/code/src/doc2harness/benchmark/harnesses/tui/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2aca3fac90b3e7c0a2b7f4de2c76c2bb101d2b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/fixtures.py @@ -0,0 +1,33 @@ +"""Immutable fixture bindings for interactive TUI PTY scenarios.""" + +import hashlib +from dataclasses import dataclass + +from doc2harness.contracts.canonical import canonical_json + +from .contracts import TuiRecipe, TuiScenario, recipe_digest + + +@dataclass(frozen=True, slots=True) +class TuiFixturePlan: + case_digest: str + recipe: TuiRecipe + recipe_digest: str + plan_digest: str + + +def materialize_tui_fixture(scenario: TuiScenario, /) -> TuiFixturePlan: + body = { + "case_digest": scenario.recipe.case_digest, + "recipe_digest": recipe_digest(scenario.recipe), + "scenario_id": scenario.definition.scenario_id, + } + digest = "sha256:" + hashlib.sha256( + b"doc2harness.tui-pty-fixture/1\0" + canonical_json(body) + ).hexdigest() + return TuiFixturePlan( + scenario.recipe.case_digest, + scenario.recipe, + body["recipe_digest"], + digest, + ) diff --git a/code/src/doc2harness/benchmark/harnesses/tui/recipes.py b/code/src/doc2harness/benchmark/harnesses/tui/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..fff8507d22c1438995167f42b556b395d0cb930b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/recipes.py @@ -0,0 +1,100 @@ +"""Frozen typed recipes for interactive TUI PTY scenarios.""" + +from doc2harness.benchmark.definition import DependencyKind, ScenarioRole +from .contracts import HistoryScenario, TuiInput, TuiOracleBinding, TuiProfile, TuiRecipe, define_tui_scenario + + +def _inputs(*values: str) -> tuple[TuiInput, ...]: + return tuple((TuiInput(value) for value in values)) + + +_HISTORY_A = "H8A9961_ONLY_A_4C7E" +_HISTORY_B = "H8B9962_ONLY_B_9D3F" +_ROWS: dict[str, tuple[TuiRecipe, ScenarioRole]] = { + "tui_ctrl_byte_storm_survives": ( + TuiRecipe( + TuiProfile.CHAOS_SURVIVES, + "sha256:ebf1873599579122839f864b8a08fb9fc6638611524bd5f2470bbfbac377a1a1", + (), + 90, + False, + _inputs("010205060708090b0c0e0f101112131415161718192052423937415f37373331"), + probe_tokens=("RB97A_7731",), + ), + ScenarioRole.TARGET, + ), + "tui_bang_alone_enters_shell_mode": ( + TuiRecipe( + TuiProfile.FILE_WRITTEN, + "sha256:863a252325195b0e72491af1418666147ad20a9281fbb0af834816eb546d85fd", + (), + 100, + False, + _inputs("21", "7072696e746620274d4f44453130305f25735c6e272037373331203e206d6f64653130302e747874"), + probe_tokens=("MODE100_7731",), + observed_files=("mode100.txt",), + oracle=TuiOracleBinding(primary_token="MODE100_7731", path="mode100.txt"), + ), + ScenarioRole.TARGET, + ), + "history_workspace_a_fresh_control": ( + TuiRecipe( + TuiProfile.HISTORY_FRESH, + "sha256:5491f4c5e2e792ee9471ed98fc1b679b860508c0515b68c2d0dec1dd5b219927", + (), + 90, + False, + gateway_mode="fixed_reply", + reply_content="history-control-a-ok", + probe_tokens=(_HISTORY_A, _HISTORY_B), + history_scenario=HistoryScenario.FRESH_A, + oracle=TuiOracleBinding( + primary_token=_HISTORY_A, foreign_token=_HISTORY_B, history_prefix="H8A9961_" + ), + ), + ScenarioRole.CONTROL, + ), + "history_workspace_b_fresh_control": ( + TuiRecipe( + TuiProfile.HISTORY_FRESH, + "sha256:8f4b916ebf70fc02b2ddd923d763297f35633e263bfb249b971f22e38e67a8ed", + (), + 90, + False, + gateway_mode="fixed_reply", + reply_content="history-control-b-ok", + probe_tokens=(_HISTORY_A, _HISTORY_B), + history_scenario=HistoryScenario.FRESH_B, + oracle=TuiOracleBinding( + primary_token=_HISTORY_B, foreign_token=_HISTORY_A, history_prefix="H8B9962_" + ), + ), + ScenarioRole.CONTROL, + ), + "history_realpath_key": ( + TuiRecipe( + TuiProfile.HISTORY_REALPATH, + "sha256:b6c88c978f949efceef60880ebe1e8ff1f1a7e74d4c65b8a648f1738fc14137b", + ( + ("history_workspace_a_fresh_control", DependencyKind.GATE), + ("history_workspace_b_fresh_control", DependencyKind.GATE), + ), + 140, + True, + gateway_mode="fixed_reply", + reply_content="history-realpath-ok", + probe_tokens=(_HISTORY_A, _HISTORY_B), + history_scenario=HistoryScenario.REALPATH_KEY, + oracle=TuiOracleBinding(primary_token=_HISTORY_A, secondary_token=_HISTORY_B), + ), + ScenarioRole.TARGET, + ), +} +SCENARIO_BY_ID = { + scenario_id: define_tui_scenario(scenario_id, recipe, role) + for scenario_id, (recipe, role) in _ROWS.items() +} + + +def scenario_by_id(scenario_id: str, /): + return SCENARIO_BY_ID[scenario_id] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/__init__.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8de181ad9f3773580ed00de6358e5f380a6554b7 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/__init__.py @@ -0,0 +1 @@ +"""Thin interactive TUI PTY scenario definitions.""" diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_realpath_key.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_realpath_key.py new file mode 100644 index 0000000000000000000000000000000000000000..9f5b5e5acc41faf089ab9e3c8a78aef04bf4e60c --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_realpath_key.py @@ -0,0 +1,37 @@ +"""Verify history is keyed by the workspace real path. + +1. Run two workspace views that resolve to the same real path. +2. Observe history lookup and the final process status. +3. Require the completion token without a crash signature. +4. Pass only when the real-path key is honored. +""" + +from doc2harness.benchmark.harnesses.tui.contracts import ( + TuiApplicability, TuiEvaluation, TuiObservation, TuiOutcome, TuiScenario, + evaluation_digest, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "history_realpath_key" +SCENARIO: TuiScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: TuiObservation) -> TuiEvaluation: + text = observation.screen_text + bind = RECIPE.oracle + live = bool(text.strip()) + passed = live and bind.completion_token in text and not any( + token in text for token in bind.crash_signatures + ) + return TuiEvaluation(SCENARIO_ID, TuiOutcome.PASS if passed else TuiOutcome.FAIL, + TuiApplicability.APPLICABLE if live else TuiApplicability.INCONCLUSIVE, + "TUI_PROFILE_CHECKED", evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if live else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_a_fresh_control.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_a_fresh_control.py new file mode 100644 index 0000000000000000000000000000000000000000..a7af9120241c3ebeb493c530f24103b289cefbc3 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_a_fresh_control.py @@ -0,0 +1,37 @@ +"""Verify a fresh workspace starts with an isolated history control. + +1. Start the workspace with an empty history store. +2. Observe the initial history state and process status. +3. Require the completion token without a crash signature. +4. Pass only when no stale history is inherited. +""" + +from doc2harness.benchmark.harnesses.tui.contracts import ( + TuiApplicability, TuiEvaluation, TuiObservation, TuiOutcome, TuiScenario, + evaluation_digest, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "history_workspace_a_fresh_control" +SCENARIO: TuiScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: TuiObservation) -> TuiEvaluation: + text = observation.screen_text + bind = RECIPE.oracle + live = bool(text.strip()) + passed = live and bind.completion_token in text and not any( + token in text for token in bind.crash_signatures + ) + return TuiEvaluation(SCENARIO_ID, TuiOutcome.PASS if passed else TuiOutcome.FAIL, + TuiApplicability.APPLICABLE if live else TuiApplicability.INCONCLUSIVE, + "TUI_PROFILE_CHECKED", evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if live else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_b_fresh_control.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_b_fresh_control.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6cc56e1c7625792b0ac1461a78b68d37d9889d --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/history_workspace_b_fresh_control.py @@ -0,0 +1,37 @@ +"""Verify a second fresh workspace has isolated history. + +1. Start workspace B with an empty history store. +2. Observe its initial history and process status. +3. Require completion without a crash signature. +4. Pass only when workspace A history is not inherited. +""" + +from doc2harness.benchmark.harnesses.tui.contracts import ( + TuiApplicability, TuiEvaluation, TuiObservation, TuiOutcome, TuiScenario, + evaluation_digest, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "history_workspace_b_fresh_control" +SCENARIO: TuiScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: TuiObservation) -> TuiEvaluation: + text = observation.screen_text + bind = RECIPE.oracle + live = bool(text.strip()) + passed = live and bind.completion_token in text and not any( + token in text for token in bind.crash_signatures + ) + return TuiEvaluation(SCENARIO_ID, TuiOutcome.PASS if passed else TuiOutcome.FAIL, + TuiApplicability.APPLICABLE if live else TuiApplicability.INCONCLUSIVE, + "TUI_PROFILE_CHECKED", evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if live else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6c486dedf8ba567c9e5323548f99c59c9fe654 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded.py @@ -0,0 +1,19 @@ +"""Require an autocommit failure and its cause in the trajectory. + +1. Run a write with an isolated failing Git hook or signing program. +2. Observe the persisted trajectory and dynamic failure token. +3. Require explicit auto-commit ownership and failure semantics. +""" +from doc2harness.benchmark.definition import ScenarioRole +from ..adapter import build_scenario, make_judge + +SCENARIO_ID = "trajectory_autocommit_fail_recorded" +SCENARIO = build_scenario(SCENARIO_ID, ScenarioRole.TARGET, "trajectory_autocommit_fail_recorded_control", "gpg_fail") +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition +_judge = make_judge(SCENARIO, "autocommit_fail") +def judge(observation): + return _judge(observation) +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded_control.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded_control.py new file mode 100644 index 0000000000000000000000000000000000000000..22fabd22b2fc60582e14214968507544094927c4 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_autocommit_fail_recorded_control.py @@ -0,0 +1,14 @@ +"""Control for the autocommit-failure trajectory stimulus.""" +from doc2harness.benchmark.definition import ScenarioRole +from ..adapter import build_scenario, make_judge + +SCENARIO_ID = "trajectory_autocommit_fail_recorded_control" +SCENARIO = build_scenario(SCENARIO_ID, ScenarioRole.CONTROL, None, "seq_probe") +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition +_judge = make_judge(SCENARIO, "autocommit_fail") +def judge(observation): + return _judge(observation) +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate.py new file mode 100644 index 0000000000000000000000000000000000000000..156ab183a4a8d952f23f256db1859d17d8286ca1 --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate.py @@ -0,0 +1,19 @@ +"""Require an explicit step-limit terminal event in the trajectory. + +1. Run the bounded PTY conversation against the normal mock gateway. +2. Observe the externally persisted trajectory rather than recorder facts. +3. Require both a limit marker and a terminal event; ordinary completion is insufficient. +""" +from doc2harness.benchmark.definition import ScenarioRole +from ..adapter import build_scenario, make_judge + +SCENARIO_ID = "trajectory_step_limit_terminal_accurate" +SCENARIO = build_scenario(SCENARIO_ID, ScenarioRole.TARGET, "trajectory_step_limit_terminal_accurate_control", "seq_probe") +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition +_judge = make_judge(SCENARIO, "step_limit") +def judge(observation): + return _judge(observation) +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate_control.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate_control.py new file mode 100644 index 0000000000000000000000000000000000000000..56b1af126ea2187121e278f99fd64456a0751a5b --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/trajectory_step_limit_terminal_accurate_control.py @@ -0,0 +1,19 @@ +"""Control for an externally observed step-limit terminal trajectory. + +1. Run the bounded PTY conversation against the normal mock gateway. +2. Observe requests, exit status, cleanup, and trajectory files. +3. Establish that the stimulus and terminal channel are live. +""" +from doc2harness.benchmark.definition import ScenarioRole +from ..adapter import build_scenario, make_judge + +SCENARIO_ID = "trajectory_step_limit_terminal_accurate_control" +SCENARIO = build_scenario(SCENARIO_ID, ScenarioRole.CONTROL, None, "seq_probe") +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition +_judge = make_judge(SCENARIO, "step_limit") +def judge(observation): + return _judge(observation) +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_bang_alone_enters_shell_mode.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_bang_alone_enters_shell_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa967dd4459a0e90381f4ef2bb21ff8e85c0beb --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_bang_alone_enters_shell_mode.py @@ -0,0 +1,50 @@ +"""Verify a standalone bang enters shell mode and returns cleanly. + +1. Submit the standalone bang command and observe shell-mode output. +2. Submit the follow-up probe turn. +3. Require completion without a crash signature. +4. Pass only when shell-mode interaction remains usable. +""" + +from doc2harness.benchmark.harnesses.tui.contracts import ( + TuiApplicability, TuiEvaluation, TuiObservation, TuiOutcome, TuiScenario, + evaluation_digest, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "tui_bang_alone_enters_shell_mode" +SCENARIO: TuiScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: TuiObservation) -> TuiEvaluation: + text = observation.screen_text + bind = RECIPE.oracle + live = bool(text.strip()) + # The declared oracle for this point is FILE_WRITTEN: the shell line must + # really run and leave the file behind. Judging the survival sentinel + # instead asks whether the *driver's own* closing line was echoed, which a + # session answers whether or not the point's line did anything. Read the + # file the recipe + # declared, exactly as the shared oracle for this profile does. + item = next( + (entry for entry in observation.files if entry.path == bind.path), None, + ) + passed = ( + live + and item is not None + and item.present + and bind.primary_token in item.content + and not any(token in text for token in bind.crash_signatures) + ) + return TuiEvaluation(SCENARIO_ID, TuiOutcome.PASS if passed else TuiOutcome.FAIL, + TuiApplicability.APPLICABLE if live else TuiApplicability.INCONCLUSIVE, + "TUI_PROFILE_CHECKED", evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if live else 0) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_ctrl_byte_storm_survives.py b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_ctrl_byte_storm_survives.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2c74111d5b3b255921370db05f19db8a4ea6ec --- /dev/null +++ b/code/src/doc2harness/benchmark/harnesses/tui/scenarios/tui_ctrl_byte_storm_survives.py @@ -0,0 +1,47 @@ +"""Verify a control-byte storm leaves the TUI alive. + +1. Feed the control-byte fixture and wait for completion. +2. Observe the final screen text and process status. +3. Require the completion marker and no crash signature. +4. Pass only when the TUI survives the input storm. +""" + +from doc2harness.benchmark.harnesses.tui.contracts import ( + TuiApplicability, + TuiEvaluation, + TuiObservation, + TuiOutcome, + TuiScenario, + evaluation_digest, +) + +from ..recipes import scenario_by_id + +SCENARIO_ID = "tui_ctrl_byte_storm_survives" +SCENARIO: TuiScenario = scenario_by_id(SCENARIO_ID) +RECIPE = SCENARIO.recipe +STEPS = (RECIPE,) +scenario = SCENARIO +definition = SCENARIO.definition + + +def judge(observation: TuiObservation) -> TuiEvaluation: + text = observation.screen_text + bind = RECIPE.oracle + live = bool(text.strip()) + passed = ( + live + and bind.completion_token in text + and not any(token in text for token in bind.crash_signatures) + ) + return TuiEvaluation( + SCENARIO_ID, + TuiOutcome.PASS if passed else TuiOutcome.FAIL, + TuiApplicability.APPLICABLE if live else TuiApplicability.INCONCLUSIVE, + "TUI_PROFILE_CHECKED", + evaluation_digest(SCENARIO, observation), + SCENARIO.definition.weight_microunits if live else 0, + ) + + +__all__ = ["RECIPE", "SCENARIO", "STEPS", "definition", "judge", "scenario"] diff --git a/code/src/doc2harness/benchmark/taxonomy.py b/code/src/doc2harness/benchmark/taxonomy.py new file mode 100644 index 0000000000000000000000000000000000000000..d1615c789e88f15e669dab0d79320a36efdf2f47 --- /dev/null +++ b/code/src/doc2harness/benchmark/taxonomy.py @@ -0,0 +1,139 @@ +"""Closed taxonomy types and fail-closed source-loading boundary.""" + +from __future__ import annotations + +import tomllib +import unicodedata +from dataclasses import dataclass +from typing import Any + +from doc2harness.benchmark.definition import Classification +from doc2harness.contracts.primitives import ContractDocumentError + +_MAX_ENTRIES = 4096 +_MAX_SOURCE_BYTES = 1_048_576 +_MAX_SOURCE_LINES = 16_384 +_MAX_LINE_BYTES = 8_192 +_MAX_DEPTH = 5 + + +@dataclass(frozen=True, slots=True) +class TaxonomyEntry: + function_id: str + title: str + + def __post_init__(self) -> None: + Classification(self.function_id) + if type(self.title) is not str or not self.title or len(self.title) > 256: + raise ContractDocumentError("taxonomy title must be a bounded non-empty string") + if unicodedata.normalize("NFC", self.title) != self.title: + raise ContractDocumentError("taxonomy title must be Unicode NFC") + if self.title != self.title.strip() or any( + ord(char) < 32 + or 0x7F <= ord(char) <= 0x9F + or ord(char) in {0x2028, 0x2029} + or 0xD800 <= ord(char) <= 0xDFFF + for char in self.title + ): + raise ContractDocumentError("taxonomy title is not canonical") + + +@dataclass(frozen=True, slots=True) +class Taxonomy: + entries: tuple[TaxonomyEntry, ...] + + def __post_init__(self) -> None: + if type(self.entries) is not tuple or not self.entries: + raise ContractDocumentError("taxonomy must contain an exact non-empty tuple") + if len(self.entries) > _MAX_ENTRIES: + raise ContractDocumentError("taxonomy exceeds the entry limit") + if any(type(item) is not TaxonomyEntry for item in self.entries): + raise ContractDocumentError("taxonomy entries must use TaxonomyEntry") + identities = tuple(item.function_id for item in self.entries) + if identities != tuple(sorted(identities)) or len(set(identities)) != len(identities): + raise ContractDocumentError("taxonomy identities must be sorted and unique") + + +def _source_text(raw: bytes, name: str) -> str: + if type(raw) is not bytes: + raise ContractDocumentError(f"{name} source must be exact bytes") + if not raw or len(raw) > _MAX_SOURCE_BYTES: + raise ContractDocumentError(f"{name} source must be bounded and non-empty") + if raw.startswith(b"\xef\xbb\xbf") or b"\x00" in raw or b"\r" in raw: + raise ContractDocumentError(f"{name} source encoding is not canonical") + lines = raw.split(b"\n") + if len(lines) > _MAX_SOURCE_LINES or any(len(line) > _MAX_LINE_BYTES for line in lines): + raise ContractDocumentError(f"{name} source layout exceeds limits") + try: + text = raw.decode("utf-8", errors="strict") + except UnicodeDecodeError: + raise ContractDocumentError(f"{name} source is not UTF-8") from None + if unicodedata.normalize("NFC", text) != text: + raise ContractDocumentError(f"{name} source must be Unicode NFC") + return text + + +def _depth(value: object, level: int = 1) -> int: + if type(value) in {dict, list} and level > _MAX_DEPTH: + raise ContractDocumentError("TOML container depth exceeds limit") + if type(value) is dict: + for item in value.values(): + _depth(item, level + 1) + elif type(value) is list: + for item in value: + _depth(item, level + 1) + return level + + +def _parse_closed_toml(raw: bytes, name: str) -> dict[str, Any]: + text = _source_text(raw, name) + try: + value = tomllib.loads(text) + except (tomllib.TOMLDecodeError, ValueError): + raise ContractDocumentError(f"{name} source is not valid closed TOML") from None + if type(value) is not dict: + raise ContractDocumentError(f"{name} source must be a table") + _depth(value) + return value + + +def _exact_keys(value: object, keys: frozenset[str], name: str) -> dict[str, Any]: + if type(value) is not dict or set(value) != keys: + raise ContractDocumentError(f"{name} has an invalid closed shape") + return value + + +def parse_taxonomy(raw: bytes, /) -> Taxonomy: + """Parse one closed, canonical taxonomy source.""" + + source = _exact_keys( + _parse_closed_toml(raw, "taxonomy"), + frozenset({"format", "functions"}), + "taxonomy", + ) + if source["format"] != "doc2harness.taxonomy-source/1": + raise ContractDocumentError("taxonomy format is unsupported") + functions = source["functions"] + if type(functions) is not list or not functions or len(functions) > _MAX_ENTRIES: + raise ContractDocumentError("taxonomy functions must be a bounded non-empty array") + entries: list[TaxonomyEntry] = [] + for item in functions: + row = _exact_keys(item, frozenset({"function_id", "title"}), "taxonomy function") + entries.append(TaxonomyEntry(row["function_id"], row["title"])) + return Taxonomy(tuple(entries)) + + +def validate_classification(value: Classification, taxonomy: Taxonomy, /) -> None: + """Validate a typed classification against a closed in-memory taxonomy.""" + + if type(value) is not Classification or type(taxonomy) is not Taxonomy: + raise ContractDocumentError("classification validation requires exact typed values") + known = frozenset(item.function_id for item in taxonomy.entries) + unknown = frozenset((value.primary, *value.secondary)) - known + if unknown: + raise ContractDocumentError(f"classification contains unknown functions: {sorted(unknown)!r}") + + +__all__ = [ + "Taxonomy", "TaxonomyEntry", "parse_taxonomy", "validate_classification", +] diff --git a/code/src/doc2harness/benchmark/taxonomy.toml b/code/src/doc2harness/benchmark/taxonomy.toml new file mode 100644 index 0000000000000000000000000000000000000000..1997d8a3e9bdff3e473f36dc78c16d72c41365bd --- /dev/null +++ b/code/src/doc2harness/benchmark/taxonomy.toml @@ -0,0 +1,37 @@ +format = "doc2harness.taxonomy-source/1" + +[[functions]] +function_id = "artifact" +title = "Static artifact" + +[[functions]] +function_id = "direct" +title = "Direct mock process" + +[[functions]] +function_id = "extension" +title = "Extension discovery counterfactual" + +[[functions]] +function_id = "file" +title = "Child-process file tools" + +[[functions]] +function_id = "headless" +title = "Headless CLI behavior" + +[[functions]] +function_id = "permission" +title = "Child-process permission" + +[[functions]] +function_id = "startup" +title = "Startup behavior" + +[[functions]] +function_id = "state" +title = "Child-process state" + +[[functions]] +function_id = "tui" +title = "TUI PTY behavior" diff --git a/code/src/doc2harness/contracts/__init__.py b/code/src/doc2harness/contracts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a394c758e9799df47172bb7e37f50a465a3d56b9 --- /dev/null +++ b/code/src/doc2harness/contracts/__init__.py @@ -0,0 +1,3 @@ +"""Canonical JSON and digest primitives shared by the catalog and the runtime.""" + +__all__: list[str] = [] diff --git a/code/src/doc2harness/contracts/canonical.py b/code/src/doc2harness/contracts/canonical.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d940ad5a1e0a6abb89b17a9700d295184dbd81 --- /dev/null +++ b/code/src/doc2harness/contracts/canonical.py @@ -0,0 +1,82 @@ +"""Strict canonical JSON primitives for immutable contract documents.""" + +from __future__ import annotations + +import json +import unicodedata +from collections.abc import Mapping, Sequence +from typing import Any + +_MAX_DOCUMENT_BYTES = 8 * 1024 * 1024 +_MAX_DEPTH = 64 +_MAX_KEYS = 100_000 +_MAX_STRING_LENGTH = 1 * 1024 * 1024 +_MIN_INTEGER = -(2**63) +_MAX_INTEGER = 2**63 - 1 + + +class CanonicalJsonError(ValueError): + """Raised when a value is outside the canonical v1 JSON subset.""" + + +def _validate(value: Any, *, depth: int, counters: dict[str, int]) -> None: + if depth > _MAX_DEPTH: + raise CanonicalJsonError("maximum nesting depth exceeded") + + if value is None or isinstance(value, bool): + return + if isinstance(value, int): + if not _MIN_INTEGER <= value <= _MAX_INTEGER: + raise CanonicalJsonError("integer is outside the signed 64-bit range") + return + if isinstance(value, float): + raise CanonicalJsonError("floating-point values are forbidden") + if isinstance(value, str): + if len(value) > _MAX_STRING_LENGTH: + raise CanonicalJsonError("maximum string length exceeded") + try: + value.encode("utf-8", errors="strict") + except UnicodeEncodeError as error: + raise CanonicalJsonError("string is not valid Unicode scalar text") from error + return + if isinstance(value, Mapping): + counters["keys"] += len(value) + if counters["keys"] > _MAX_KEYS: + raise CanonicalJsonError("maximum object-key count exceeded") + for key, item in value.items(): + if not isinstance(key, str): + raise CanonicalJsonError("object keys must be strings") + if unicodedata.normalize("NFC", key) != key: + raise CanonicalJsonError("object keys must already be Unicode NFC") + _validate(key, depth=depth + 1, counters=counters) + _validate(item, depth=depth + 1, counters=counters) + return + if isinstance(value, Sequence) and not isinstance( + value, (str, bytes, bytearray, memoryview) + ): + for item in value: + _validate(item, depth=depth + 1, counters=counters) + return + raise CanonicalJsonError(f"unsupported value type: {type(value).__name__}") + + +def canonical_json(value: Any) -> bytes: + """Encode a value as canonical v1 JSON bytes.""" + + _validate(value, depth=0, counters={"keys": 0}) + try: + encoded = json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8", errors="strict") + except (TypeError, ValueError, UnicodeEncodeError) as error: + raise CanonicalJsonError("value cannot be encoded as canonical JSON") from error + if len(encoded) > _MAX_DOCUMENT_BYTES: + raise CanonicalJsonError("maximum document size exceeded") + return encoded + + +__all__ = ["CanonicalJsonError", "canonical_json"] diff --git a/code/src/doc2harness/contracts/primitives.py b/code/src/doc2harness/contracts/primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..e1910519865381f3ba3a64201edc5cc59f157e49 --- /dev/null +++ b/code/src/doc2harness/contracts/primitives.py @@ -0,0 +1,38 @@ +"""Validation helpers shared by contract documents.""" + +from __future__ import annotations + +import re +import unicodedata +from typing import Any + +from doc2harness.contracts.canonical import ( + CanonicalJsonError, +) + +_DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z", re.ASCII) + + +class ContractDocumentError(ValueError): + """Raised when an immutable contract envelope fails closed validation.""" + + +def require_string(value: Any, *, name: str, nfc: bool = True) -> str: + if not isinstance(value, str): + raise ContractDocumentError(f"{name} must be a string") + if nfc and unicodedata.normalize("NFC", value) != value: + raise ContractDocumentError(f"{name} must already be Unicode NFC") + return value + + +def require_digest(value: Any, *, name: str) -> str: + parsed = require_string(value, name=name, nfc=False) + if _DIGEST.fullmatch(parsed) is None: + raise ContractDocumentError(f"{name} is not a v1 SHA-256 digest") + return parsed + + +__all__ = [ + "CanonicalJsonError", + "ContractDocumentError", +] diff --git a/code/src/doc2harness/runtime/__init__.py b/code/src/doc2harness/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb47dd63e0caa96d95de8292902c4ff4367cf30 --- /dev/null +++ b/code/src/doc2harness/runtime/__init__.py @@ -0,0 +1,11 @@ +"""Fail-closed local runtime framework.""" +from doc2harness.runtime.errors import RuntimeBoundaryError, RuntimeCapabilityUnavailable +from doc2harness.runtime.artifact_executor import ArtifactExecutionError, ArtifactExecutionRequest, artifact_tree_digest, load_typed_event_document, require_typed_event_hook_abi, run_artifact_driver +from doc2harness.runtime.artifact_store import canonical_artifact_digest +from doc2harness.runtime.catalog_executor import CatalogExecutionError, CatalogExecutionRequest, run_catalog + +__all__ = [ + "ArtifactExecutionError", "ArtifactExecutionRequest", "artifact_tree_digest", "canonical_artifact_digest", "load_typed_event_document", "require_typed_event_hook_abi", "run_artifact_driver", "CatalogExecutionError", "CatalogExecutionRequest", "run_catalog", + "RuntimeBoundaryError", + "RuntimeCapabilityUnavailable", +] diff --git a/code/src/doc2harness/runtime/artifact_executor.py b/code/src/doc2harness/runtime/artifact_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..85de140d13bd5474fbefe818a0b1c069f870b42b --- /dev/null +++ b/code/src/doc2harness/runtime/artifact_executor.py @@ -0,0 +1,234 @@ +"""Fail-closed execution boundary for reviewed production artifact drivers. + +The executor owns only the process boundary. A harness-specific driver owns +fixture materialisation and recorder hooks; it must publish typed facts through +the declared side channel. stdout, stderr, and trajectory text are +diagnostics and are never promoted to benchmark evidence. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import tempfile +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +from doc2harness.contracts.primitives import ContractDocumentError +from doc2harness.runtime.artifact_store import canonical_artifact_digest +from doc2harness.runtime.errors import RuntimeBoundaryError + +_DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z", re.ASCII) +_HOOK_RELATIVE = Path(".d2a_spec") / "typed_event_hooks.json" + + +class ArtifactExecutionError(RuntimeBoundaryError): + """A stable, path-free failure from the production artifact boundary.""" + + +@dataclass(frozen=True, slots=True) +class ArtifactExecutionRequest: + """Inputs for one driver invocation against an immutable source artifact.""" + + artifact: Path + driver_root: Path + driver_argv: tuple[str, ...] + output: Path + source_digest: str + task_digest: str + budget_digest: str + artifact_digest: str + timeout_seconds: float = 900.0 + + def __post_init__(self) -> None: + if not isinstance(self.artifact, Path) or not isinstance(self.driver_root, Path): + raise ContractDocumentError("artifact execution paths must use Path") + if not isinstance(self.output, Path): + raise ContractDocumentError("artifact execution output must use Path") + if type(self.driver_argv) is not tuple or not self.driver_argv: + raise ContractDocumentError("artifact driver argv must be non-empty") + if any(type(item) is not str or not item or "\0" in item for item in self.driver_argv): + raise ContractDocumentError("artifact driver argv contains an invalid item") + for value, name in ( + (self.source_digest, "source digest"), + (self.task_digest, "task digest"), + (self.budget_digest, "budget digest"), + (self.artifact_digest, "artifact digest"), + ): + if type(value) is not str or _DIGEST.fullmatch(value) is None: + raise ContractDocumentError(f"{name} is invalid") + if type(self.timeout_seconds) not in {int, float} or not 0 < self.timeout_seconds <= 3600: + raise ContractDocumentError("artifact execution timeout is invalid") + + +def artifact_tree_digest(root: Path, /) -> str: + """Hash a source tree with the verified artifact-store algorithm.""" + + if not isinstance(root, Path) or not root.is_dir() or not (root / "run_agent.sh").is_file(): + raise ArtifactExecutionError("SBH-ARTIFACT-UNAVAILABLE", "artifact is unavailable") + try: + return canonical_artifact_digest(root) + except (OSError, UnicodeError, ValueError, RuntimeBoundaryError): + raise ArtifactExecutionError("SBH-ARTIFACT-SCAN", "artifact tree cannot be scanned") from None + + +def require_typed_event_hook_abi(root: Path, /) -> dict[str, object]: + """Require the reviewed side-channel declaration on the driver package.""" + + marker = root / _HOOK_RELATIVE + try: + value = json.loads(marker.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError): + raise ArtifactExecutionError( + "SBH-TYPED-HOOK-ABI", "typed event hook ABI is missing or invalid" + ) from None + required = {"schema", "tool_lifecycle", "subprocess", "workspace", "cleanup"} + if ( + not isinstance(value, dict) + or set(value) != required + or value.get("schema") != "doc2harness.typed-event-hooks/1" + or any(value.get(name) is not True for name in required - {"schema"}) + ): + raise ArtifactExecutionError("SBH-TYPED-HOOK-ABI", "typed event hook ABI is incomplete") + return value + + +def _stderr_hint(stderr: bytes | str | None, scratch: str) -> str: + """The driver's final stderr line, with host paths removed. + + Closed errors must not leak filesystem layout, so the private scratch root + is replaced and any remaining absolute path is reduced to its basename. + What survives -- an exception type, a missing key, a docker refusal -- is + the part that says which failure this was. + """ + + if not stderr: + return "" + text = stderr.decode("utf-8", "replace") if isinstance(stderr, bytes) else stderr + lines = [line.strip() for line in text.strip().splitlines() if line.strip()] + if not lines: + return "" + last = lines[-1].replace(scratch, "") + last = re.sub(r"(? dict[str, object]: + """Load and bind one driver-produced typed-event envelope.""" + + expected = { + "source_digest": source_digest, + "task_digest": task_digest, + "budget_digest": budget_digest, + "artifact_digest": artifact_digest, + } + if any(_DIGEST.fullmatch(value) is None for value in expected.values()): + raise ContractDocumentError("typed event invocation binding is invalid") + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError): + raise ArtifactExecutionError("SBH-TYPED-EVENTS", "typed event output is unreadable") from None + if not isinstance(value, dict) or value.get("schema") != "doc2harness.typed-events/1": + raise ArtifactExecutionError("SBH-TYPED-EVENTS", "typed event schema is unsupported") + for name, digest in expected.items(): + if value.get(name) != digest: + raise ArtifactExecutionError("SBH-TYPED-EVENTS", "typed event binding differs from invocation") + events = value.get("events") + if not isinstance(events, list) or any(not isinstance(event, dict) for event in events): + raise ArtifactExecutionError("SBH-TYPED-EVENTS", "typed event list is invalid") + return value + + +def run_artifact_driver( + request: ArtifactExecutionRequest, + *, + environ: Mapping[str, str] | None = None, +) -> Path: + """Run a hook-capable driver against a private artifact copy. + + The source artifact is never edited. The driver receives only explicit + digest bindings and a path to the private copy; its typed side channel is + the sole accepted source of observations. + """ + + source_digest = artifact_tree_digest(request.artifact) + if source_digest != request.artifact_digest: + raise ArtifactExecutionError("SBH-ARTIFACT-IDENTITY", "artifact identity differs from request") + require_typed_event_hook_abi(request.driver_root) + request.output.parent.mkdir(parents=True, exist_ok=True) + child_env = dict(os.environ) + if environ is not None: + child_env.update(environ) + with tempfile.TemporaryDirectory(prefix="sbh-artifact-") as temporary: + private_artifact = Path(temporary) / "artifact" + typed_output = Path(temporary) / "typed_events.json" + shutil.copytree(request.artifact, private_artifact) + child_env.update( + { + "SBH_ARTIFACT_PATH": str(private_artifact), + "SBH_TYPED_EVENT_PATH": str(typed_output), + "SBH_SOURCE_DIGEST": request.source_digest, + "SBH_TASK_DIGEST": request.task_digest, + "SBH_BUDGET_DIGEST": request.budget_digest, + "SBH_ARTIFACT_DIGEST": request.artifact_digest, + } + ) + try: + completed = subprocess.run( + request.driver_argv, + cwd=private_artifact, + env=child_env, + stdin=subprocess.DEVNULL, + capture_output=True, + timeout=request.timeout_seconds, + check=False, + ) + except subprocess.TimeoutExpired: + raise ArtifactExecutionError("SBH-ARTIFACT-TIMEOUT", "artifact driver timed out") from None + except OSError: + raise ArtifactExecutionError("SBH-ARTIFACT-DRIVER", "artifact driver could not start") from None + if completed.returncode != 0: + # Carry the driver's own last words. Without them every driver + # crash -- a missing binary, a scenario bug, a transient docker + # refusal -- arrives as the same five words, and the only way to + # learn which one happened is to re-run the driver by hand outside + # the executor, rebuilding this environment from memory. The + # closed-error rule bars host paths and raw output, so the tail is + # scrubbed of both before it is attached. + raise ArtifactExecutionError( + "SBH-ARTIFACT-DRIVER", + f"artifact driver failed (rc={completed.returncode})" + f"{_stderr_hint(completed.stderr, temporary)}", + ) + if not typed_output.is_file(): + raise ArtifactExecutionError("SBH-TYPED-EVENTS", "artifact driver produced no typed event output") + load_typed_event_document( + typed_output, + source_digest=request.source_digest, + task_digest=request.task_digest, + budget_digest=request.budget_digest, + artifact_digest=request.artifact_digest, + ) + request.output.write_bytes(typed_output.read_bytes()) + return request.output + + +__all__ = [ + "ArtifactExecutionError", + "ArtifactExecutionRequest", + "artifact_tree_digest", + "load_typed_event_document", + "require_typed_event_hook_abi", + "run_artifact_driver", +] diff --git a/code/src/doc2harness/runtime/artifact_static_driver.py b/code/src/doc2harness/runtime/artifact_static_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..e0500579890a9d566ece63d840f1b8d727aa8f84 --- /dev/null +++ b/code/src/doc2harness/runtime/artifact_static_driver.py @@ -0,0 +1,84 @@ +"""Run one ``artifact`` probe against the private artifact copy.""" + +from __future__ import annotations + +import argparse +import json +import os +from dataclasses import asdict +from pathlib import Path + +from doc2harness.runtime.driver_evidence import evidence_digest as _digest + + +def _run_one() -> dict[str, object]: + from doc2harness.benchmark.definition import definition_digest + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.harnesses.artifact.contracts import ( + ArtifactProbeKind, + ArtifactProbeMetrics, + create_artifact_probe_observation, + ) + + scenario_id = os.environ["SBH_SCENARIO_ID"] + owner = load_scenario_owner(scenario_id) + if ".benchmark.harnesses.artifact." not in owner.module: + raise RuntimeError("artifact driver received a non-artifact scenario") + scenario = owner.scenario + root = Path(os.environ["SBH_ARTIFACT_PATH"]) + probe = scenario.probe + relative = "/".join(probe.paths[0].segments) + target = root / relative + file_exists = target.is_file() + directory_exists = target.is_dir() + size_bytes = target.stat().st_size if file_exists and probe.kind is ArtifactProbeKind.FILE_NONEMPTY else None + matching_members = None + project_marker = None + requirements_nonempty = None + if probe.kind is ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX: + matching_members = sum(1 for child in target.iterdir() if child.is_file() and child.name.endswith(probe.member_suffix or "")) if directory_exists else 0 + elif probe.kind is ArtifactProbeKind.DEPENDENCY_DECLARATION: + pyproject = root / "pyproject.toml" + requirements = root / "requirements.txt" + project_marker = pyproject.is_file() and "[project" in pyproject.read_text(encoding="utf-8", errors="replace") + requirements_nonempty = requirements.is_file() and requirements.stat().st_size > 0 + metrics = ArtifactProbeMetrics( + file_exists=file_exists if probe.kind in {ArtifactProbeKind.FILE_PRESENT, ArtifactProbeKind.FILE_NONEMPTY} else None, + directory_exists=directory_exists if probe.kind is ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX else None, + size_bytes=size_bytes, + matching_members=matching_members, + project_marker=project_marker, + requirements_nonempty=requirements_nonempty, + ) + evidence = (_digest({"path": relative, "exists": file_exists, "directory": directory_exists, "size": size_bytes, "members": matching_members, "project": project_marker, "requirements": requirements_nonempty}),) + observation = create_artifact_probe_observation( + scenario, + os.environ["SBH_ARTIFACT_ID"], + os.environ["SBH_ARTIFACT_DIGEST"], + metrics, + evidence, + ) + return {"observation": observation, "judgement": owner.judge(observation), "module": owner.module, + "definition_digest": definition_digest(owner.definition)} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + result = _run_one() + target = Path(os.environ["SBH_TYPED_EVENT_PATH"]) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps({ + "schema": "doc2harness.typed-events/1", + "source_digest": os.environ["SBH_SOURCE_DIGEST"], "task_digest": os.environ["SBH_TASK_DIGEST"], + "budget_digest": os.environ["SBH_BUDGET_DIGEST"], "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], + "artifact_id": os.environ["SBH_ARTIFACT_ID"], "scenario_id": os.environ["SBH_SCENARIO_ID"], + "scenario_module": result["module"], "definition_digest": result["definition_digest"], + "events": [{"type": "artifact-observation", "observation": asdict(result["observation"]), + "judgement": asdict(result["judgement"])}], + }, ensure_ascii=False, default=lambda value: value.value if hasattr(value, "value") else str(value), indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/artifact_store.py b/code/src/doc2harness/runtime/artifact_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8f30a9378ff851266524453b368e093804c782fc --- /dev/null +++ b/code/src/doc2harness/runtime/artifact_store.py @@ -0,0 +1,293 @@ +"""Trusted local artifact materialization for read-only Harness consumers. + +The runner-owned locator supplies only a host location. This store +independently recomputes the directory digest before transferring the same +pinned descriptor to the reader. Python object privacy is not treated as a security +boundary and no caller-created receipt can authorize bytes. +""" + +from __future__ import annotations + +import hashlib +import os +import stat +import unicodedata +from dataclasses import field as _field +from doc2harness.runtime.errors import ( + RuntimeBoundaryError, + RuntimeCapabilityUnavailable, +) + +_IGNORED_COMPONENTS = frozenset( + { + ".git", + "node_modules", + "__pycache__", + ".opencode", + ".pytest_cache", + ".mypy_cache", + ".d2a_spec", + ".build-submit", + ".build-result", + } +) +_MAX_DEPTH = 128 +_MAX_NAME_BYTES = 255 +_MAX_ROOT_BYTES = 4096 +_MAX_TREE_BYTES = 512 * 1024 * 1024 +_MAX_MEMBERS = 1_000_000 +_READ_CHUNK = 64 * 1024 + + +def _fail(code: str, message: str) -> RuntimeBoundaryError: + return RuntimeBoundaryError(code, message) + + +def _safe_component(value: str) -> bool: + if type(value) is not str or value in {"", ".", ".."}: + return False + try: + encoded = value.encode("utf-8", "strict") + except UnicodeError: + return False + return ( + len(encoded) <= _MAX_NAME_BYTES + and unicodedata.normalize("NFC", value) == value + and "/" not in value + and "\\" not in value + and "\x00" not in value + and all(ord(character) >= 32 and ord(character) != 127 for character in value) + ) + + +def _directory_flags() -> int: + names = ("O_DIRECTORY", "O_NOFOLLOW", "O_CLOEXEC") + if any(not hasattr(os, name) for name in names): + raise RuntimeCapabilityUnavailable( + "SBH-ARTIFACT-UNSUPPORTED", + "safe artifact directory access is unavailable", + ) + return os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + + +def _file_flags() -> int: + if not hasattr(os, "O_NOFOLLOW") or not hasattr(os, "O_CLOEXEC"): + raise RuntimeCapabilityUnavailable( + "SBH-ARTIFACT-UNSUPPORTED", + "safe artifact file access is unavailable", + ) + return os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK + + +def _binding(details: os.stat_result) -> tuple[int, int, int]: + return (details.st_dev, details.st_ino, stat.S_IFMT(details.st_mode)) + + +def _close_descriptors(*descriptors: int) -> None: + """Attempt every owned close and expose only a path-free typed failure.""" + + failed = False + for descriptor in descriptors: + if descriptor < 0: + continue + try: + os.close(descriptor) + except OSError: + failed = True + if failed: + raise _fail("SBH-ARTIFACT-INVARIANT", "artifact descriptors did not close safely") + + +def _open_root( + root: str | bytes, +) -> tuple[int, int, tuple[str, ...], tuple[tuple[int, int], ...]]: + if type(root) not in {str, bytes}: + raise _fail("SBH-ARTIFACT-ROOT", "artifact root is invalid") + size = len(root) if type(root) is bytes else len(root.encode("utf-8", "surrogatepass")) + decoded = os.fsdecode(root) + if ( + not root + or size > _MAX_ROOT_BYTES + or not decoded.startswith(os.sep) + or decoded.startswith("//") + or decoded.endswith(os.sep) + or os.path.normpath(decoded) != decoded + ): + raise _fail("SBH-ARTIFACT-ROOT", "artifact root is invalid") + parts = tuple(decoded.split(os.sep)[1:]) + if not parts or len(parts) > _MAX_DEPTH or any(not _safe_component(part) for part in parts): + raise _fail("SBH-ARTIFACT-ROOT", "artifact root is invalid") + anchor = current = -1 + identities: list[tuple[int, int]] = [] + try: + anchor = os.open(os.sep, _directory_flags()) + current = os.dup(anchor) + for component in parts: + replacement = os.open(component, _directory_flags(), dir_fd=current) + previous = current + current = replacement + _close_descriptors(previous) + details = os.fstat(current) + if not stat.S_ISDIR(details.st_mode): + raise OSError("artifact root component is not a directory") + identities.append((details.st_dev, details.st_ino)) + return current, anchor, parts, tuple(identities) + except (RuntimeBoundaryError, RuntimeCapabilityUnavailable): + _close_descriptors(current, anchor) + raise + except OSError: + _close_descriptors(current, anchor) + raise _fail("SBH-ARTIFACT-ROOT", "artifact root cannot be opened safely") from None + + +def _read_regular(parent_fd: int, name: str, before: os.stat_result, remaining: int) -> bytes: + descriptor = -1 + try: + descriptor = os.open(name, _file_flags(), dir_fd=parent_fd) + opened = os.fstat(descriptor) + if ( + _binding(before) != _binding(opened) + or before.st_nlink != 1 + or opened.st_nlink != 1 + or before.st_size != opened.st_size + or opened.st_size > remaining + ): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact file identity or size is unsafe") + chunks: list[bytes] = [] + left = opened.st_size + while left: + chunk = os.read(descriptor, min(_READ_CHUNK, left)) + if not chunk: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact file changed during verification") + chunks.append(chunk) + left -= len(chunk) + content = b"".join(chunks) + after = os.fstat(descriptor) + terminal = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if ( + _binding(opened) != _binding(after) + or _binding(after) != _binding(terminal) + or opened.st_size != after.st_size + or opened.st_mtime_ns != after.st_mtime_ns + or opened.st_ctime_ns != after.st_ctime_ns + ): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact file changed during verification") + return content + except RuntimeBoundaryError: + raise + except OSError: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact file cannot be verified safely") from None + finally: + _close_descriptors(descriptor) + + +def _tree_digest(root_fd: int, *, max_tree_bytes: int, max_members: int) -> tuple[str, int, int]: + files: list[tuple[str, str]] = [] + member_count = 0 + byte_count = 0 + + def visit(directory_fd: int, prefix: tuple[str, ...], depth: int) -> None: + nonlocal member_count, byte_count + if depth > _MAX_DEPTH: + raise _fail("SBH-ARTIFACT-OVERSIZE", "artifact tree exceeds the depth limit") + try: + names = sorted(os.listdir(directory_fd)) + except OSError: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact directory cannot be enumerated safely") from None + for name in names: + if not _safe_component(name): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact member name is unsafe") + member_count += 1 + if member_count > max_members: + raise _fail("SBH-ARTIFACT-OVERSIZE", "artifact tree exceeds the member limit") + if name in _IGNORED_COMPONENTS: + continue + try: + before = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + except OSError: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact member cannot be inspected") from None + relative = prefix + (name,) + if stat.S_ISLNK(before.st_mode): + # Links are never traversal input. A dangling link is inert, + # so it is excluded from the digest; becoming resolvable at any + # later verification is a tree mutation and fails closed. + try: + os.stat(name, dir_fd=directory_fd, follow_symlinks=True) + except FileNotFoundError: + continue + except OSError: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact link cannot be classified safely") from None + raise _fail("SBH-ARTIFACT-UNSAFE", "resolvable artifact links are forbidden") + if stat.S_ISDIR(before.st_mode): + child = -1 + try: + child = os.open(name, _directory_flags(), dir_fd=directory_fd) + opened = os.fstat(child) + if _binding(before) != _binding(opened): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact directory identity changed") + visit(child, relative, depth + 1) + after = os.fstat(child) + terminal = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if ( + _binding(opened) != _binding(after) + or _binding(after) != _binding(terminal) + or opened.st_mtime_ns != after.st_mtime_ns + or opened.st_ctime_ns != after.st_ctime_ns + ): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact directory changed during verification") + except RuntimeBoundaryError: + raise + except OSError: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact directory cannot be verified safely") from None + finally: + _close_descriptors(child) + continue + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1: + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact member type is unsafe") + content = _read_regular(directory_fd, name, before, max_tree_bytes - byte_count) + byte_count += len(content) + files.append(("/".join(relative), hashlib.sha256(content).hexdigest())) + + root_before = os.fstat(root_fd) + visit(root_fd, (), 0) + root_after = os.fstat(root_fd) + if ( + _binding(root_before) != _binding(root_after) + or root_before.st_mtime_ns != root_after.st_mtime_ns + or root_before.st_ctime_ns != root_after.st_ctime_ns + ): + raise _fail("SBH-ARTIFACT-UNSAFE", "artifact root changed during verification") + digest = hashlib.sha256() + for relative, file_digest in sorted(files): + digest.update(relative.encode("utf-8")) + digest.update(file_digest.encode("ascii")) + return "sha256:" + digest.hexdigest(), member_count, byte_count + + +def canonical_artifact_digest(root: str | os.PathLike[str], /) -> str: + """Compute the same digest used by the verified artifact store. + + Production execution must bind to the store's tree digest rather + than to a second, weaker path walk. The descriptor-relative walk also + applies the store's ignored-component, symlink, and mutation checks. + """ + + root_fd, anchor_fd, _, _ = _open_root(os.fspath(root)) + try: + digest, _, _ = _tree_digest( + root_fd, + max_tree_bytes=_MAX_TREE_BYTES, + max_members=_MAX_MEMBERS, + ) + return digest + finally: + _close_descriptors(root_fd, anchor_fd) + + +# Dataclass construction is complete; keep reflection evidence deterministic. +del _field + + +__all__ = [ + +] diff --git a/code/src/doc2harness/runtime/catalog_executor.py b/code/src/doc2harness/runtime/catalog_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5a00e6e072f2572570ccf26561eb1f78582715 --- /dev/null +++ b/code/src/doc2harness/runtime/catalog_executor.py @@ -0,0 +1,186 @@ +"""Fail-closed orchestration for a production artifact catalog run. + +This module owns the catalog-level boundary only. A reviewed driver still +owns fixture setup and harness-specific observation production. Each scenario +is invoked separately, bound to its catalog owner and definition digest, and +must emit one typed-event document; text streams are never evidence. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from pathlib import Path + +from doc2harness.benchmark.definition import definition_digest +from doc2harness.benchmark.dispatch import load_scenario_owner +from doc2harness.contracts.primitives import ContractDocumentError +from doc2harness.runtime.artifact_executor import ( + ArtifactExecutionRequest, + load_typed_event_document, + run_artifact_driver, +) +from doc2harness.runtime.errors import RuntimeBoundaryError + + +class CatalogExecutionError(RuntimeBoundaryError): + """A catalog run failed before it could produce a complete receipt.""" + + +@dataclass(frozen=True, slots=True) +class CatalogExecutionRequest: + """Inputs for one artifact and an explicit active scenario selection.""" + + artifact: Path + driver_root: Path + driver_argv: tuple[str, ...] + output_dir: Path + artifact_id: str + source_digest: str + task_digest: str + budget_digest: str + artifact_digest: str + scenario_ids: tuple[str, ...] + concurrency: int = 1 + timeout_seconds: float = 900.0 + + def __post_init__(self) -> None: + if not all(isinstance(value, Path) for value in (self.artifact, self.driver_root, self.output_dir)): + raise ContractDocumentError("catalog execution paths must use Path") + if type(self.driver_argv) is not tuple or not self.driver_argv: + raise ContractDocumentError("catalog driver argv must be non-empty") + if any(type(item) is not str or not item or "\0" in item for item in self.driver_argv): + raise ContractDocumentError("catalog driver argv contains an invalid item") + if type(self.artifact_id) is not str or not self.artifact_id or "\0" in self.artifact_id: + raise ContractDocumentError("catalog artifact id is invalid") + for value, name in ( + (self.source_digest, "source digest"), + (self.task_digest, "task digest"), + (self.budget_digest, "budget digest"), + (self.artifact_digest, "artifact digest"), + ): + if type(value) is not str or not value.startswith("sha256:") or len(value) != 71: + raise ContractDocumentError(f"catalog {name} is invalid") + if type(self.scenario_ids) is not tuple or not self.scenario_ids: + raise ContractDocumentError("catalog scenario selection must be non-empty") + if any(type(item) is not str or not item or "\0" in item for item in self.scenario_ids): + raise ContractDocumentError("catalog scenario selection contains an invalid id") + if len(set(self.scenario_ids)) != len(self.scenario_ids): + raise ContractDocumentError("catalog scenario selection contains duplicates") + if type(self.concurrency) is not int or self.concurrency < 1: + raise ContractDocumentError("catalog concurrency must be positive") + if type(self.timeout_seconds) not in {int, float} or not 0 < self.timeout_seconds <= 3600: + raise ContractDocumentError("catalog timeout is invalid") + + +def _scenario_output_path(root: Path, scenario_id: str) -> Path: + """Return a deterministic path after the ID has passed catalog validation.""" + + if "/" in scenario_id or "\\" in scenario_id or scenario_id in {".", ".."}: + raise CatalogExecutionError("SBH-CATALOG-SCENARIO-ID", "scenario id cannot become a path") + return root / f"{scenario_id}.json" + + +def _run_one(request: CatalogExecutionRequest, scenario_id: str, *, environ: Mapping[str, str] | None) -> dict[str, object]: + owner = load_scenario_owner(scenario_id) + expected_definition_digest = definition_digest(owner.definition) + output = _scenario_output_path(request.output_dir, scenario_id) + run_artifact_driver( + ArtifactExecutionRequest( + request.artifact, + request.driver_root, + request.driver_argv, + output, + request.source_digest, + request.task_digest, + request.budget_digest, + request.artifact_digest, + request.timeout_seconds, + ), + environ={ + **(dict(environ) if environ is not None else {}), + "SBH_ARTIFACT_ID": request.artifact_id, + "SBH_SCENARIO_ID": scenario_id, + "SBH_SCENARIO_MODULE": owner.module, + "SBH_DEFINITION_DIGEST": expected_definition_digest, + }, + ) + document = load_typed_event_document( + output, + source_digest=request.source_digest, + task_digest=request.task_digest, + budget_digest=request.budget_digest, + artifact_digest=request.artifact_digest, + ) + if ( + document.get("scenario_id") != scenario_id + or document.get("scenario_module") != owner.module + or document.get("definition_digest") != expected_definition_digest + or document.get("artifact_id") != request.artifact_id + ): + raise CatalogExecutionError( + "SBH-CATALOG-BINDING", + f"typed observation binding differs for {scenario_id}", + ) + return {"scenario_id": scenario_id, "scenario_module": owner.module, "document": document} + + +def run_catalog( + request: CatalogExecutionRequest, + *, + environ: Mapping[str, str] | None = None, +) -> Path: + """Execute every selected scenario and write one identity-bound receipt. + + Any failed, missing, duplicate, unknown, or mis-bound scenario aborts the + receipt. A partial directory is intentionally not presented as a result. + """ + + request.output_dir.mkdir(parents=True, exist_ok=True) + results: list[dict[str, object]] = [] + failures: list[str] = [] + workers = min(request.concurrency, len(request.scenario_ids)) + with ThreadPoolExecutor(max_workers=workers) as pool: + futures = { + pool.submit(_run_one, request, scenario_id, environ=environ): scenario_id + for scenario_id in request.scenario_ids + } + for future in as_completed(futures): + scenario_id = futures[future] + try: + results.append(future.result()) + except Exception as exc: # noqa: BLE001 # normalize at the catalog boundary + # Carry the message, not just the class. Every scenario failure + # arrives here as ArtifactExecutionError, so the class name alone + # separates nothing -- and the message is where the driver's own + # scrubbed stderr tail lives. + failures.append(f"{scenario_id}:{type(exc).__name__}: {exc}") + missing = set(request.scenario_ids) - {row["scenario_id"] for row in results} + if failures or missing: + # Name what failed: without the scenario ids a run that lost one + # scenario reads exactly like a product the executor refused outright, + # and diagnosis has to start by diffing the output directory. Scenario + # ids and exception type names are neither host paths nor raw output, so + # carrying them here keeps the closed-error contract. + detail = " | ".join(sorted(failures) + sorted(f"{s}:missing" for s in missing)) + raise CatalogExecutionError( + "SBH-CATALOG-INCOMPLETE", + "catalog run did not produce one valid bound result for every selected " + f"scenario ({len(failures) + len(missing)} of {len(request.scenario_ids)}: {detail})", + ) + results.sort(key=lambda row: str(row["scenario_id"])) + receipt = { + "schema": "doc2harness.production-catalog-receipt/1", + "artifact_id": request.artifact_id, + "artifact_digest": request.artifact_digest, + "scenario_count": len(results), + "rows": results, + } + target = request.output_dir / "catalog_receipt.json" + target.write_text(json.dumps(receipt, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return target + + +__all__ = ["CatalogExecutionError", "CatalogExecutionRequest", "run_catalog"] diff --git a/code/src/doc2harness/runtime/direct_mock_driver.py b/code/src/doc2harness/runtime/direct_mock_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..68f20c1a96e553f48ab6d3d66e46132fc44817ef --- /dev/null +++ b/code/src/doc2harness/runtime/direct_mock_driver.py @@ -0,0 +1,534 @@ +"""Run one active ``direct`` scenario through a real artifact. + +This is a production-driver boundary, not a scorer shortcut. The artifact is +invoked through its public ``run_agent.sh`` contract, the mock gateway is used +only as deterministic stimulus, and the active scenario-local judge receives a +typed ``DirectMockRawObservation``; no recorded result, runner, or verdict is +imported. +""" + +from __future__ import annotations +import argparse +import hashlib +import json +import os +import re +import socket +import subprocess +import sys +import tempfile +import threading +from dataclasses import asdict +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from doc2harness.runtime import mock_gateway +from doc2harness.runtime.driver_evidence import ( + CONTAINER_WORKSPACE, + evidence_digest as _digest, + read_status_document as _status, + read_trajectory_text as _trajectory, + request_facts as _request_facts, + run_artifact_entrypoint as _run_artifact, +) +from typing import Any + + +class _TrapProxy(ThreadingHTTPServer): + """Record any product request that incorrectly reaches the HTTP proxy.""" + + daemon_threads = True + + def __init__(self) -> None: + super().__init__(("0.0.0.0", 0), _TrapProxyHandler) + self.connections: list[dict[str, Any]] = [] + self.lock = threading.Lock() + + +class _TrapProxyHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _trap(self) -> None: + server: _TrapProxy = self.server + try: + length = int(self.headers.get("Content-Length", "0") or 0) + except ValueError: + length = 0 + body = self.rfile.read(length) if 0 < length <= 2 * 1024 * 1024 else b"" + kind = "self-check" if self.headers.get("X-Direct-Mock-Self") == "proxy-self-check" else "product" + with server.lock: + server.connections.append( + { + "api_key_seen": "sk-mock-test" in str(self.headers.get("Authorization") or ""), + "body_sha256": hashlib.sha256(body).hexdigest(), + "kind": kind, + "method": self.command, + "target": self.path, + } + ) + payload = b'{"proxy":"direct-mock-trap"}' + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(payload) + self.wfile.flush() + + do_CONNECT = _trap + do_GET = _trap + do_POST = _trap + + +def _raw_http(host: str, port: int, request: bytes) -> bytes: + with socket.create_connection((host, port), timeout=2) as connection: + connection.sendall(request) + connection.shutdown(socket.SHUT_WR) + chunks: list[bytes] = [] + while chunk := connection.recv(65536): + chunks.append(chunk) + return b"".join(chunks) + + +def _rounds(fixture: Any, observer: str | None = None) -> list[list[dict[str, Any]]]: + rounds: list[list[dict[str, Any]]] = [] + for group in fixture.rounds: + current: list[dict[str, Any]] = [] + for action in group: + if action.finish: + current.append({"name": "__finish__"}) + continue + args = dict(action.arguments) + if observer is not None: + args = { + key: value.replace("{OBSERVER}", observer) if isinstance(value, str) else value + for key, value in args.items() + } + name = action.tool_candidates[0] + if name in {"bash", "shell", "run_command", "execute", "exec", "terminal"}: + current.append({"name": name, "command": str(args.pop("command", "")), **args}) + else: + current.append({"name": name, "args": args}) + if current: + rounds.append(current) + return rounds + + +def _mode(recipe: Any) -> str: + return { + "SEQUENTIAL_PROBE": "seq_probe", + "FIXED_REPLY": "fixed_reply", + }.get(recipe.mode.value, recipe.mode.value.lower()) + + +def _facts( + scenario: Any, + workspace: Path, + requests: tuple[Any, ...], + trajectory: str, + raw_records: list[dict[str, Any]] | None = None, + proxy_observation: dict[str, Any] | None = None, + web_gets: list[dict[str, Any]] | None = None, +): + from doc2harness.benchmark.harnesses.direct.contracts import DirectMockFactKey, DirectMockObservedFact + + facts: dict[Any, bool | int | str] = {} + raw_records = raw_records or [] + proxy_observation = proxy_observation or {} + web_gets = web_gets or [] + + def _probe_seen(token: str) -> bool: + return any((bool((record.get("probes") or {}).get(token)) for record in raw_records)) + + def _tool_seen(*names: str) -> bool: + wanted = {item.lower().replace("-", "_") for item in names} + return any( + ( + wanted.intersection( + (str(name).lower().replace("-", "_") for name in record.get("tool_names") or ()) + ) + for record in raw_records + ) + ) + + tool_result_texts = [ + str(text) for record in raw_records for text in record.get("tool_result_texts") or () + ] + tool_result_blob = "\n".join(tool_result_texts) + token = scenario.recipe.expected_token + if not token: + found = re.search("[A-Z][A-Z0-9_]*_[0-9]{4}", str(getattr(scenario.recipe, "command", "") or "")) + if found: + token = found.group(0) + if token: + facts[DirectMockFactKey.EXPECTED_REPOSITORY_FILE] = any( + ( + token in p.read_text(encoding="utf-8", errors="replace") + for p in workspace.rglob("*") + if p.is_file() and p.stat().st_size <= 8 * 1024 * 1024 + ) + ) + names = {p.name for p in workspace.rglob("*") if p.is_file()} + facts[DirectMockFactKey.DENY_MARKER_PRESENT] = any((name.startswith("PERM_DENY_") for name in names)) + facts[DirectMockFactKey.SHARED_FILE_PRESENT] = (workspace / "shared.txt").is_file() + facts[DirectMockFactKey.SHARED_FILE_CONTENT] = ( + (workspace / "shared.txt").read_text(encoding="utf-8", errors="replace") + if (workspace / "shared.txt").is_file() + else "" + ) + facts[DirectMockFactKey.SHARED_FILE_MARKER] = "SHAREDW_4242" in str( + facts[DirectMockFactKey.SHARED_FILE_CONTENT] + ) + facts[DirectMockFactKey.PARALLEL_A] = (workspace / "pa.txt").is_file() + facts[DirectMockFactKey.PARALLEL_B] = (workspace / "pb.txt").is_file() + facts[DirectMockFactKey.RESPONSE_USAGE_HEALTHY] = scenario.recipe.mode.value in { + "NORMAL", + "SEQUENTIAL_PROBE", + } and bool(requests) + facts[DirectMockFactKey.REPOSITORY_CLEAN] = ( + not bool( + subprocess.run( + ("git", "status", "--porcelain"), cwd=workspace, capture_output=True, check=False + ).stdout + ) + if (workspace / ".git").is_dir() + else True + ) + facts[DirectMockFactKey.OFFLINE_LOOPBACK_ONLY] = all( + ( + item.path.startswith("/v1") or item.path.startswith("/local") or (not item.path) + for item in requests + ) + ) + facts[DirectMockFactKey.REASONING_REDACTED] = not any((item.has_reasoning for item in requests)) + if profile_name := getattr(getattr(scenario.recipe, "fixture_profile", None), "value", ""): + if profile_name == "WEB_FETCH": + gets = [item for item in web_gets if str(item.get("path", "")).startswith("/local-probe")] + facts[DirectMockFactKey.WEB_FETCH_HEALTHY] = ( + len(gets) == 1 + and gets[0].get("status") == 200 + and (gets[0].get("send_complete") is True) + and ("SBH_WEBFETCH_HEALTHY_BODY_7528" in tool_result_blob) + ) + facts[DirectMockFactKey.WEB_FAILURES_PRESERVED] = bool( + gets + and re.search( + "(?i)(?:http|status|status_code|code|->)[^0-9]{0,18}(?:404|429|500)", tool_result_blob + ) + and ( + re.search( + "(?i)(?:error|failed|failure|not found|too many requests|rate limit|server error)", + tool_result_blob, + ) + or re.search("(?i)[\"\\']?(?:ok|success)[\"\\']?\\s*[:=]\\s*false", tool_result_blob) + or re.search("(?i)[\"\\']?is[_-]?error[\"\\']?\\s*[:=]\\s*true", tool_result_blob) + ) + ) + if profile_name in {"QUALITY_GATE_PASS", "QUALITY_GATE_FAIL"}: + marker = workspace / "qgate.marker" + facts[DirectMockFactKey.QGATE_RAN] = marker.is_file() and "QGATE_RAN_7755" in marker.read_text( + encoding="utf-8", errors="replace" + ) + if profile_name in {"SHELL_EDGE_CONTROL", "SHELL_EDGE_TARGET"}: + facts[DirectMockFactKey.SHELL_CONTROL_BYTES] = "SHELL_EDGE_CONTROL_7731" in tool_result_blob + expected = "\n EDGE_CONTENT_7731 \n\nUNTRUNCATED_7731\n" + facts[DirectMockFactKey.SHELL_EDGE_BYTES] = any((expected in text for text in tool_result_texts)) + profile = getattr(getattr(scenario, "recipe", None), "fixture_profile", None) + profile_name = getattr(profile, "value", "") + if profile_name == "HTTP_PROXY": + proxy_self_checked = bool(proxy_observation) and all( + ( + proxy_observation.get("gateway_self_check") is True, + proxy_observation.get("proxy_self_check") is True, + proxy_observation.get("environment_exact") is True, + proxy_observation.get("gateway_request_count") == 1, + proxy_observation.get("proxy_product_connections") == 0, + proxy_observation.get("proxy_api_key_seen") is False, + proxy_observation.get("cleanup_complete") is True, + ) + ) + facts[DirectMockFactKey.PROXY_SELF_CHECKED] = proxy_self_checked + facts[DirectMockFactKey.EXPLICIT_ENDPOINT_BYPASSED_PROXY] = ( + proxy_self_checked and proxy_observation.get("proxy_injected") is True + ) + return tuple((DirectMockObservedFact(key, value) for key, value in facts.items())) + + +def _run_one() -> dict[str, Any]: + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.harnesses.direct.adapter import build_direct_mock_execution_plan + from doc2harness.benchmark.harnesses.direct.contracts import ( + DirectMockRawObservation, + apply_direct_mock_local_judge, + ) + from doc2harness.benchmark.definition import definition_digest + + scenario_id = os.environ.get("SBH_SCENARIO_ID", "") + if not scenario_id: + raise RuntimeError("SBH_SCENARIO_ID is required") + owner = load_scenario_owner(scenario_id) + if not owner.module.startswith("doc2harness.benchmark.harnesses.direct"): + raise RuntimeError("direct mock driver received a non-direct scenario") + scenario = owner.scenario + plan = build_direct_mock_execution_plan(scenario) + fixture = plan.fixture + artifact = Path(os.environ["SBH_ARTIFACT_PATH"]) + gateway = mock_gateway + gateway_server = gateway.ThreadingHTTPServer + + class _BridgeVisibleServer(gateway_server): + + def __init__(self, address, handler): + super().__init__(("0.0.0.0", address[1]), handler) + + gateway.ThreadingHTTPServer = _BridgeVisibleServer + with tempfile.TemporaryDirectory(prefix="sbh-direct-production-") as temporary: + root = Path(temporary) + home, workspace, output = (root / "home", root / "workspace", root / "out") + stale_cwd = root / "stale-cwd" + home.mkdir() + workspace.mkdir() + output.mkdir() + stale_cwd.mkdir() + for fixture_file in fixture.repository_files: + target = workspace.joinpath(*fixture_file.path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(fixture_file.content) + task = workspace / "task.json" + budget = workspace / "budget.json" + task_bytes = fixture.task_document + try: + task_document = json.loads(task_bytes) + except json.JSONDecodeError: + task_document = None + if isinstance(task_document, dict) and task_document.get("repo_dir") == "__REPO_DIR__": + task_document["repo_dir"] = CONTAINER_WORKSPACE + task_bytes = json.dumps(task_document, separators=(",", ":"), sort_keys=True).encode() + task.write_bytes(task_bytes) + budget.write_bytes(fixture.budget_document) + proof_token = ( + scenario.recipe.expected_token + or fixture.probe_token + or ( + "MOCK_PROOF_7731" + if scenario.recipe.mode.value in {"NORMAL"} + else "" + ) + ) + cfg = gateway.new_cfg( + mode=_mode(scenario.recipe), + command=scenario.recipe.command or "echo MOCK_PROOF_7731 > mock_proof.txt", + probe_token=fixture.probe_token or "", + probe_tokens=[fixture.probe_token] if fixture.probe_token else [], + rounds=_rounds(fixture), + reject_substr=scenario.recipe.reject_substring, + ) + if getattr(getattr(scenario.recipe, "fixture_profile", None), "value", "") == "WEB_FETCH": + failing = bool(getattr(scenario.recipe, "control_dependencies", ())) + cfg["web_status"] = 404 if failing else 200 + cfg["web_body"] = ( + "SBH_WEBFETCH_FAILING_BODY_8639" if failing else "SBH_WEBFETCH_HEALTHY_BODY_7528" + ) + server = gateway.make_server(cfg, 0) + cfg["rounds"] = _rounds(fixture, f"host.docker.internal:{int(server.server_address[1])}") + server.daemon_threads = True + server.block_on_close = False + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + proxy: _TrapProxy | None = None + proxy_thread: threading.Thread | None = None + proxy_observation: dict[str, Any] = {} + profile_name = getattr(getattr(scenario.recipe, "fixture_profile", None), "value", "") + if profile_name == "HTTP_PROXY": + proxy = _TrapProxy() + proxy_thread = threading.Thread(target=proxy.serve_forever, daemon=True) + proxy_thread.start() + gateway_check = _raw_http( + "127.0.0.1", + int(server.server_address[1]), + b"GET /direct-mock-self-check/gateway HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n", + ) + proxy_check = _raw_http( + "127.0.0.1", + int(proxy.server_address[1]), + b"GET http://direct-mock.invalid/self-check HTTP/1.1\r\nHost: direct-mock.invalid\r\nX-Direct-Mock-Self: proxy-self-check\r\nConnection: close\r\n\r\n", + ) + proxy_observation.update( + { + "gateway_self_check": gateway_check.startswith(b"HTTP/1.0 200 ") + or gateway_check.startswith(b"HTTP/1.1 200 "), + "proxy_self_check": proxy_check.startswith(b"HTTP/1.0 502 ") + or proxy_check.startswith(b"HTTP/1.1 502 "), + } + ) + env = dict(os.environ) + env.update(dict(fixture.environment)) + env.update({"HOME": str(home), "YUYAO_HOME": str(home / ".yuyao"), "PYTHONDONTWRITEBYTECODE": "1"}) + if proxy is not None: + injected = scenario.definition.scenario_id == "http_proxy_hermetic" + proxy_url = f"http://127.0.0.1:{proxy.server_address[1]}" + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env[name] = proxy_url if injected else "" + if injected: + env["SBH_TRAP_PROXY_URL"] = proxy_url + env["NO_PROXY"] = "" + env["no_proxy"] = "" + proxy_observation.update({"environment_exact": True, "proxy_injected": injected}) + argv = [ + str(artifact / "run_agent.sh"), + "--task-file", + str(task), + "--repo-dir", + str(workspace), + "--model-base-url", + f"http://127.0.0.1:{server.server_address[1]}{scenario.recipe.base_url_suffix}", + "--model-name", + scenario.recipe.model_name, + "--model-api-key", + "sk-mock-test", + "--budget-file", + str(budget), + "--out-dir", + str(output), + ] + if scenario.recipe.omitted_flag is not None: + omitted = scenario.recipe.omitted_flag.value + argv = [ + item for i, item in enumerate(argv) if item != omitted and (i == 0 or argv[i - 1] != omitted) + ] + completed, timed_out = _run_artifact( + artifact, + workspace, + home, + output, + task, + budget, + argv, + env, + int(server.server_address[1]), + min(scenario.recipe.timeout_seconds or 180, 600), + stale_cwd if scenario.recipe.stale_pwd_probe else None, + ) + if os.environ.get("SBH_DEBUG_DRIVER") == "1" and completed.stderr: + print(str(completed.stderr), file=sys.stderr, end="") + if os.environ.get("SBH_DEBUG_DRIVER") == "1": + print( + f"driver-debug rc={completed.returncode} workspace={sorted((p.relative_to(workspace).as_posix() for p in workspace.rglob('*')))} output={sorted((p.relative_to(output).as_posix() for p in output.rglob('*')))}", + file=sys.stderr, + ) + trajectory = _trajectory(home) + "\n" + _trajectory(workspace) + "\n" + _trajectory(output) + status = _status(output) + requests = _request_facts(cfg.get("requests", []), fixture.probe_token) + if proxy is not None: + product_connections = [item for item in proxy.connections if item.get("kind") == "product"] + proxy_observation.update( + { + "gateway_request_count": len(requests), + "proxy_product_connections": len(product_connections), + "proxy_api_key_seen": any( + (item.get("api_key_seen") is True for item in product_connections) + ), + } + ) + proxy.shutdown() + proxy.server_close() + if proxy_thread is not None: + proxy_thread.join(timeout=2) + proxy_observation["cleanup_complete"] = proxy_thread is None or not proxy_thread.is_alive() + server.shutdown() + server.server_close() + thread.join(timeout=2) + token = proof_token + marker = any( + ( + token and token in p.read_text(encoding="utf-8", errors="replace") + for p in workspace.rglob("*") + if p.is_file() and p.stat().st_size <= 8 * 1024 * 1024 + ) + ) + observation = DirectMockRawObservation( + scenario_id=scenario_id, + plan_digest=plan.plan_digest, + artifact_id=os.environ["SBH_ARTIFACT_ID"], + artifact_digest=os.environ["SBH_ARTIFACT_DIGEST"], + exit_code=int(completed.returncode), + status_written=bool(status), + exit_status=status.get("exit_status") if isinstance(status.get("exit_status"), str) else None, + cost_usd=status.get("cost_usd") if isinstance(status.get("cost_usd"), (int, float)) else None, + requests=requests, + proof_present=marker, + proof_contains_marker=marker, + trajectory_observed=bool(trajectory.strip()), + trajectory_contains_probe=bool(token and token in trajectory), + artifact_unchanged=True, + decoy_entries=(), + stderr_has_traceback="traceback (most recent call last)" in str(completed.stderr).lower(), + process_tree_clean=not timed_out, + gateway_clean=True, + workspace_clean=True, + backend_evidence_digest=_digest( + {"scenario_id": scenario_id, "requests": len(requests), "rc": completed.returncode} + ), + timed_out=timed_out, + trajectory=trajectory, + assistant_text=str(completed.stdout or ""), + facts=_facts( + scenario, + workspace, + requests, + trajectory, + cfg.get("requests", []), + proxy_observation, + cfg.get("web_gets", []), + ), + ) + judgement = apply_direct_mock_local_judge(scenario, observation, owner.judge) + return { + "observation": observation, + "judgement": judgement, + "plan_digest": plan.plan_digest, + "definition_digest": definition_digest(owner.definition), + "module": owner.module, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + result = _run_one() + observation = result["observation"] + judgement = result["judgement"] + target = Path(os.environ["SBH_TYPED_EVENT_PATH"]) + target.parent.mkdir(parents=True, exist_ok=True) + document = { + "schema": "doc2harness.typed-events/1", + "source_digest": os.environ["SBH_SOURCE_DIGEST"], + "task_digest": os.environ["SBH_TASK_DIGEST"], + "budget_digest": os.environ["SBH_BUDGET_DIGEST"], + "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], + "artifact_id": os.environ["SBH_ARTIFACT_ID"], + "scenario_id": os.environ["SBH_SCENARIO_ID"], + "scenario_module": result["module"], + "definition_digest": result["definition_digest"], + "events": [ + { + "type": "direct-mock-observation", + "observation": asdict(observation), + "judgement": asdict(judgement), + } + ], + } + target.write_text( + json.dumps( + document, + ensure_ascii=False, + default=lambda value: value.value if hasattr(value, "value") else str(value), + indent=2, + ) + + "\n", + encoding="utf-8", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/driver_dispatch.py b/code/src/doc2harness/runtime/driver_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..46e1afcc1d727e3679a2cea2b9fc6e325cf87107 --- /dev/null +++ b/code/src/doc2harness/runtime/driver_dispatch.py @@ -0,0 +1,93 @@ +"""Dispatch one catalog scenario to its reviewed Harness production driver. + +This is deliberately a thin dispatcher: family drivers own fixture setup and +typed observations, while this module owns only scenario selection and the +identity-bound event envelope. +""" + +from __future__ import annotations + +import argparse +import importlib +import json +import os +from dataclasses import asdict, is_dataclass +from pathlib import Path + + +def _json_value(value: object) -> object: + """Serialize dataclass and scenario-local NamedTuple judgements uniformly.""" + + if is_dataclass(value): + return asdict(value) + if hasattr(value, "_asdict"): + return {str(key): _json_value(item) for key, item in value._asdict().items()} + if isinstance(value, dict): + return {str(key): _json_value(item) for key, item in value.items()} + if isinstance(value, (tuple, list)): + return [_json_value(item) for item in value] + if hasattr(value, "value"): + return value.value + return value + + +def _driver_module(scenario_module: str) -> str: + """Map a scenario module to the reviewed driver that can execute it. + + Every family resolves to an in-package dotted path, so an installed wheel + can execute any of them without a checkout on ``sys.path``. + """ + if ".benchmark.harnesses.direct." in scenario_module: + return "doc2harness.runtime.direct_mock_driver" + if ".benchmark.harnesses.permission." in scenario_module: + return "doc2harness.runtime.permission_driver" + if ".benchmark.harnesses.file." in scenario_module: + return "doc2harness.runtime.file_tool_driver" + if ".benchmark.harnesses.artifact." in scenario_module: + return "doc2harness.runtime.artifact_static_driver" + if ".benchmark.harnesses.state." in scenario_module: + return "doc2harness.runtime.state_driver" + if ".benchmark.harnesses.headless." in scenario_module: + return "doc2harness.runtime.headless_driver" + if ".benchmark.harnesses.startup." in scenario_module: + return "doc2harness.runtime.startup_driver" + if ".benchmark.harnesses.tui." in scenario_module: + return "doc2harness.runtime.tui_driver" + if ".benchmark.harnesses.extension." in scenario_module: + return "doc2harness.runtime.extension_driver" + raise RuntimeError(f"no reviewed production driver for {scenario_module}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.definition import definition_digest + + scenario_id = os.environ.get("SBH_SCENARIO_ID", "") + owner = load_scenario_owner(scenario_id) + module = importlib.import_module(_driver_module(owner.module)) + result = module._run_one() # family modules expose the reviewed typed boundary + target = Path(os.environ["SBH_TYPED_EVENT_PATH"]) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps({ + "schema": "doc2harness.typed-events/1", + "source_digest": os.environ["SBH_SOURCE_DIGEST"], + "task_digest": os.environ["SBH_TASK_DIGEST"], + "budget_digest": os.environ["SBH_BUDGET_DIGEST"], + "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], + "artifact_id": os.environ["SBH_ARTIFACT_ID"], + "scenario_id": scenario_id, + "scenario_module": owner.module, + "definition_digest": definition_digest(owner.definition), + "events": [{ + "type": f"{owner.definition.classification.primary}-observation", + "observation": _json_value(result["observation"]), + "judgement": _json_value(result["judgement"]), + }], + }, ensure_ascii=False, default=lambda value: value.value if hasattr(value, "value") else str(value), indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/driver_evidence.py b/code/src/doc2harness/runtime/driver_evidence.py new file mode 100644 index 0000000000000000000000000000000000000000..4680d24d5fa9de0829ff912ea384f848874824d1 --- /dev/null +++ b/code/src/doc2harness/runtime/driver_evidence.py @@ -0,0 +1,244 @@ +"""Shared evidence helpers for the production drivers. + +They stay deliberately narrow: digest evidence, read the artifact's own status +document, collect trajectory text, summarise recorded gateway requests, and +invoke the artifact's public entrypoint. None of them decides an outcome. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import subprocess +from pathlib import Path +from typing import Any +from doc2harness.runtime.resource_limits import container_memory_flags + + +# Where _run_artifact mounts the workspace inside the evaluation container. +# Exported because the task document must name this path, not the host one. +CONTAINER_WORKSPACE = "/sbh-workspace" + +def evidence_digest(value: object) -> str: + return "sha256:" + hashlib.sha256( + b"doc2harness.direct-mock-production-driver/1\0" + + json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + ).hexdigest() + + +def read_status_document(out_dir: Path) -> dict[str, Any]: + try: + value = json.loads((out_dir / "status.json").read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError): + return {} + if not isinstance(value, dict): + return {} + # Artifacts report either ``status`` or ``exit_status``; normalize the + # explicit status document, never infer + # a verdict from free-form stdout. + if "exit_status" not in value and isinstance(value.get("status"), str): + value["exit_status"] = value["status"] + return value + + +def read_trajectory_text(root: Path) -> str: + chunks: list[str] = [] + if not root.exists(): + return "" + for path in sorted(root.rglob("*")): + if not path.is_file() or path.stat().st_size > 64 * 1024 * 1024: + continue + names = {part.lower() for part in path.parts} + if ".trajectory" not in names and "trajectory" not in path.name.lower() and path.name not in { + "events.jsonl", "steps.jsonl", "trace.md" + }: + continue + chunks.append(path.read_text(encoding="utf-8", errors="replace")) + return "\n".join(chunks) + + +def request_facts(records: list[dict[str, Any]], token: str | None): + from doc2harness.benchmark.harnesses.direct.contracts import DirectMockRequestFact + + facts = [] + for record in records: + probes = record.get("probes") or {} + result_texts = tuple(str(item) for item in (record.get("tool_result_texts") or ())) + # The gateway retains the full role sequence, while the public typed + # contract intentionally caps this diagnostic at 32 entries. Keep + # the bounded tail rather than letting a long session invalidate the + # entire catalog receipt. + message_roles = tuple(str(item) for item in (record.get("msg_roles") or ())) + facts.append( + DirectMockRequestFact( + body_bytes=int(record.get("body_bytes", 0)), + has_tools=bool(record.get("has_tools")), + tool_names=tuple(str(item) for item in (record.get("tool_names") or ())), + probe_seen=bool(probes.get(token)) if token else False, + message_count=int(record.get("n_messages", 0)), + message_roles=message_roles[-32:], + path=str(record.get("path") or ""), + model=str(record.get("model") or ""), + nonleading_system=bool(record.get("nonleading_system")), + orphan_tool_result=bool(record.get("orphan_tool_result")), + lone_surrogate=bool(record.get("lone_surrogate")), + has_any_null=bool(record.get("has_any_null")), + empty_content_block=bool(record.get("empty_content_block")), + dangling_tool_use=bool(record.get("dangling_tool_use")), + trailing_empty_assistant=bool(record.get("trailing_empty_assistant")), + tool_result_max_bytes=int(record.get("tool_result_max_bytes", 0)), + target_tool_result=next((item for item in reversed(result_texts) if item), ""), + has_reasoning=bool(record.get("has_reasoning")), + ) + ) + return tuple(facts) + + +def run_artifact_entrypoint( + artifact: Path, + workspace: Path, + home: Path, + output: Path, + task: Path, + budget: Path, + argv: list[str], + env: dict[str, str], + port: int, + timeout: int, + stale_cwd: Path | None = None, +) -> tuple[subprocess.CompletedProcess[str], bool]: + """Run the unchanged artifact inside the reviewed evaluation image. + + The artifact source is mounted read-only; only the declared repository, + home and output directories are writable. This keeps the production path + from accidentally succeeding because the host happens to have the + artifact's Python dependencies installed. + """ + + image = os.environ.get("SBH_EVALUATION_IMAGE", "doc2harness/evaluation:candidate") + container_env = { + "HOME": "/sbh-home", + "YUYAO_HOME": "/sbh-home/.yuyao", + "PYTHONDONTWRITEBYTECODE": "1", + "D2A_MODEL_BASE_URL": f"http://host.docker.internal:{port}/v1", + # The other two halves of the model configuration. A product is + # entitled to treat "configured" as all three being present, and one + # does exactly that (``model.is_configured`` requires name and key as + # well) - so with only the URL set, its sub-agent declines to start and + # answers "[sub-agent could not run: model not configured]". Points + # about what a sub-agent does then pass vacuously: nothing escaped the + # step budget because nothing ran. So all three are set. + "D2A_MODEL_NAME": "litellm_proxy/mock", + "D2A_MODEL_API_KEY": "sk-mock-test", + } + command = [ + "docker", "run", *container_memory_flags(), "--rm", "--init", + "--network", "bridge", + "--add-host=host.docker.internal:host-gateway", + "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m", + "--user", f"{os.getuid()}:{os.getgid()}", + "-v", f"{artifact}:/sbh-artifact:ro", + "-v", f"{workspace}:/sbh-workspace:rw", + "-v", f"{home}:/sbh-home:rw", + "-v", f"{output}:/sbh-output:rw", + ] + if stale_cwd is not None: + command.extend(("-v", f"{stale_cwd}:/sbh-stale:rw", "-w", "/sbh-stale")) + forwarded = { + k: v for k, v in env.items() + if k.startswith("D2A_") and k not in {"D2A_MODEL_BASE_URL", "D2A_MODEL_NAME", "D2A_MODEL_API_KEY"} + } + # A point that observes how an external tool was launched puts a recording + # wrapper ahead of the real binary on PATH. The wrapper execs the real one, + # so nothing about the search changes - but without the PATH the launch is + # unobservable and the point cannot tell a mishandled invocation from an + # absent observation. + if env.get("SBH_CONTAINER_PATH"): + forwarded["PATH"] = str(env["SBH_CONTAINER_PATH"]) + # A hermeticity point needs the ambient configuration it is about to + # actually be present: with nothing to be sealed from, a product that reads + # whatever config it finds is indistinguishable from one that seals. + if env.get("SBH_CONTAINER_RG_CONFIG"): + forwarded["RIPGREP_CONFIG_PATH"] = str(env["SBH_CONTAINER_RG_CONFIG"]) + forwarded["RG_CONFIG_PATH"] = str(env["SBH_CONTAINER_RG_CONFIG"]) + if env.get("SBH_CONTAINER_RG_HOME"): + forwarded["HOME"] = str(env["SBH_CONTAINER_RG_HOME"]) + forwarded["XDG_CONFIG_HOME"] = str(env["SBH_CONTAINER_RG_HOME"]) + "/.config" + # The proxy point works by putting a trap proxy in the ambient environment + # and requiring the explicit model endpoint to reach the gateway anyway, + # so the proxy variables have to reach the container: forwarding only + # ``D2A_*`` names would leave the product no proxy to honour or bypass. + # Rewrite the loopback address the host chose into the one the container + # can reach. + # + # Only the trap proxy this driver started is rewritten. A scenario may + # instead declare a proxy of its own - the offline point names a dead port + # and exempts loopback through ``NO_PROXY`` - and there the loopback + # address is the literal subject of the test. Rewriting it moves the + # gateway out from behind that exemption, so every request is sent to a + # closed port and a healthy product fails to start at all. Those values + # are forwarded exactly as declared. + trap = str(env.get("SBH_TRAP_PROXY_URL") or "") + for name in ( + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", + "http_proxy", "https_proxy", "all_proxy", + "NO_PROXY", "no_proxy", + ): + if name in env: + value = str(env[name]) + # Rewrite only the trap this driver started; a scenario's own + # declared proxy travels verbatim. + if trap and value == trap: + value = value.replace( + "http://127.0.0.1:", "http://host.docker.internal:", 1 + ) + forwarded[name] = value + # A scenario that exempts loopback from its own proxy is naming the + # gateway: when the harness and the product share a host, the gateway + # *is* 127.0.0.1 and the exemption covers it. In a container the gateway + # answers on ``host.docker.internal``, which that exemption does not name, + # so every model request is handed to the scenario's deliberately dead + # proxy and a healthy product cannot start. Extend the exemption to the + # address the gateway actually has here, preserving what it meant. + for name in ("NO_PROXY", "no_proxy"): + value = forwarded.get(name) + if value and "127.0.0.1" in value and "host.docker.internal" not in value: + forwarded[name] = value + ",host.docker.internal" + for key, value in {**container_env, **forwarded}.items(): + command.extend(("-e", f"{key}={value}")) + command.extend((image, "/sbh-artifact/run_agent.sh")) + translated = { + str(task): f"{CONTAINER_WORKSPACE}/task.json", + str(workspace): CONTAINER_WORKSPACE, + str(budget): "/sbh-workspace/budget.json", + str(output): "/sbh-output", + } + for item in argv[1:]: + if item.startswith("http://127.0.0.1:"): + command.append(item.replace("http://127.0.0.1:", "http://host.docker.internal:", 1)) + else: + command.append(translated.get(item, item)) + try: + completed = subprocess.run( + command, + cwd=workspace, + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + return completed, False + except subprocess.TimeoutExpired as exc: + return subprocess.CompletedProcess(command, -1, exc.stdout or "", exc.stderr or ""), True + + +__all__ = [ + "evidence_digest", + "read_status_document", + "read_trajectory_text", + "request_facts", + "run_artifact_entrypoint", +] diff --git a/code/src/doc2harness/runtime/errors.py b/code/src/doc2harness/runtime/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b683d7c5ff85a563c74fd851c054ba96fbbcea --- /dev/null +++ b/code/src/doc2harness/runtime/errors.py @@ -0,0 +1,23 @@ +"""Stable, path-free failures for the local runtime boundary.""" + +from __future__ import annotations + + +class RuntimeBoundaryError(RuntimeError): + """A closed runtime failure which never embeds host paths or raw output.""" + + def __init__(self, code: str, message: str | None = None) -> None: + if message is None: + message = code + code = "SBH-RUNTIME-ERROR" + if type(code) is not str or type(message) is not str: + raise TypeError("runtime errors require exact strings") + super().__init__(message) + self.code = code + + +class RuntimeCapabilityUnavailable(RuntimeBoundaryError): + """A required platform primitive cannot be proved by the injected backend.""" + + +__all__ = ["RuntimeBoundaryError", "RuntimeCapabilityUnavailable"] diff --git a/code/src/doc2harness/runtime/extension_driver.py b/code/src/doc2harness/runtime/extension_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..a132f641a0b942924f2e022d91744d72d84a7d66 --- /dev/null +++ b/code/src/doc2harness/runtime/extension_driver.py @@ -0,0 +1,290 @@ +"""Run one extension counterfactual with a real CLI and a closed fixture. + +The fixture is created outside the artifact and mounted as a temporary root; +the typed observation records only discovery markers, request counts, and +cleanup facts. Verdict logic remains in the scenario oracle. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import pty +import select +import signal +import subprocess +import tempfile +import threading +import time +from dataclasses import asdict +from pathlib import Path +from typing import Any + +from doc2harness.runtime import mock_gateway +from doc2harness.runtime.direct_mock_driver import _digest +from doc2harness.runtime.resource_limits import container_memory_flags + + +def _read_pty(master: int, buffer: bytearray, seconds: float) -> None: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + ready, _, _ = select.select([master], [], [], 0.1) + if not ready: + continue + try: + buffer.extend(os.read(master, 65536)) + except OSError: + return + + +_WIRE_MARKERS = { + "commands": "EXTSYM_COMMAND_BODY_9417", + "skills": "EXTSYM_SKILL_BODY_9418", + "plugins": "EXTSYM_PLUGIN_BODY_9419", +} +_EXEC_MARKERS = { + "commands": "EXTSYM_COMMAND_EXEC_9420", + "hooks": "EXTSYM_HOOK_EXEC_9421", + "plugins": "EXTSYM_PLUGIN_EXEC_9422", +} + + +def _extension_fixture(root: Path, mode: str) -> tuple[Path, dict[str, Path], bool]: + repo = root / "repo" + inside = repo / "extension-definition-sources" + outside = root / "external-definition-sources" + markers = root / "extension-markers" + for directory in (repo, inside, outside, markers, root / "home"): + directory.mkdir(parents=True, exist_ok=True) + source = inside if mode == "inside" else outside + marker_paths = {face: markers / f"{face}.marker" for face in _EXEC_MARKERS} + + def shell_marker(face: str) -> str: + # Definitions are interpreted inside the evaluation container; use + # the mounted root path rather than the host's temporary pathname. + return f"printf '{_EXEC_MARKERS[face]}\\n' >> '/sbh-root/extension-markers/{face}.marker'" + + definitions = { + "command.md": ( + "---\ndescription: symlink definition probe\n---\n" + f"!{{{shell_marker('commands')}}}\n" + f"Carry the exact marker {_WIRE_MARKERS['commands']} into this turn.\n" + ), + "SKILL.md": ( + "---\nname: extsymskill\ndescription: symlink definition probe\n" + "triggers: [extsymskill]\n---\n" + f"Carry the exact marker {_WIRE_MARKERS['skills']} into this turn.\n" + ), + "hooks.json": json.dumps({ + "hooks": { + "beforeShellExecution": [{"matcher": "*", "command": shell_marker("hooks")}], + "beforeToolUse": [{"matcher": "*", "command": shell_marker("hooks")}], + }, + }), + "plugin.json": json.dumps({ + "name": "extsympackage", + "description": "symlink definition probe", + "commands": [{ + "name": "extsymplugin", + "description": "symlink definition probe", + "prompt": f"!{{{shell_marker('plugins')}}}\nCarry the exact marker {_WIRE_MARKERS['plugins']} into this turn.", + "body": f"!{{{shell_marker('plugins')}}}\nCarry the exact marker {_WIRE_MARKERS['plugins']} into this turn.", + }], + "hooks": {"beforeShellExecution": [{"matcher": "*", "command": shell_marker("plugins")}]}, + }), + } + targets: dict[str, Path] = {} + for name, text in definitions.items(): + target = source / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + targets[name] = target + links = { + repo / "commands" / "extsymcommand.md": targets["command.md"], + repo / "skills" / "extsymskill" / "SKILL.md": targets["SKILL.md"], + repo / "hooks.json": targets["hooks.json"], + repo / "plugins" / "extsympackage" / "plugin.json": targets["plugin.json"], + } + for link, target in links.items(): + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(os.path.relpath(target, link.parent) if mode == "inside" else target) + repo_real = repo.resolve() + shape: dict[str, bool] = {} + for link, target in links.items(): + resolved = link.resolve(strict=True) + contained = os.path.commonpath((str(repo_real), str(resolved))) == str(repo_real) + shape[str(link.relative_to(repo))] = ( + link.is_symlink() and resolved == target.resolve(strict=True) + and contained == (mode == "inside") + ) + return repo, marker_paths, bool(shape) and all(shape.values()) + + +def _run_mode(scenario: Any, artifact: Path, mode: str) -> tuple[Any, dict[str, Any]]: + from doc2harness.benchmark.harnesses.extension.contracts import ( + ExtensionFace, + ExtensionRunObservation, + ) + + gateway_module = mock_gateway + marker_tokens = list(_WIRE_MARKERS.values()) + rounds = [ + [{"name": "bash", "command": scenario.recipe.round_command}], + [{"name": "__finish__"}], + ] + cfg = gateway_module.new_cfg( + mode="seq_probe", rounds=rounds, probe_tokens=marker_tokens, + ) + server = gateway_module.ThreadingHTTPServer(("0.0.0.0", 0), gateway_module.Handler) + server.cfg = cfg + server.daemon_threads = True + server.block_on_close = False + threading.Thread(target=server.serve_forever, daemon=True).start() + driver_error = "" + timed_out = False + returncode: int | None = None + with tempfile.TemporaryDirectory(prefix="sbh-extension-production-") as temporary: + root = Path(temporary) + repo, marker_paths, fixture_ok = _extension_fixture(root, mode) + home = root / "home" + screen = bytearray() + env = dict(os.environ) + env.update({ + "HOME": str(home), "YUYAO_HOME": str(home / ".yuyao"), + "PYTHONDONTWRITEBYTECODE": "1", "TERM": "xterm-256color", + "D2A_MODEL_BASE_URL": f"http://host.docker.internal:{server.server_address[1]}/v1", + "D2A_MODEL_NAME": "mock/release-extension", "D2A_MODEL_API_KEY": "sk-mock-test", + }) + image = os.environ.get("SBH_EVALUATION_IMAGE", "doc2harness/evaluation:candidate") + command = [ + "docker", "run", *container_memory_flags(), "--rm", "--init", "-it", "--network", "bridge", + "--add-host=host.docker.internal:host-gateway", "--read-only", + "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m", "--user", f"{os.getuid()}:{os.getgid()}", + "-v", f"{artifact}:/sbh-artifact:ro", "-v", f"{root}:/sbh-root:rw", + "-w", "/sbh-root/repo", + "-e", "HOME=/sbh-root/home", "-e", "YUYAO_HOME=/sbh-root/home/.yuyao", + "-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "TERM=xterm-256color", + "-e", f"D2A_MODEL_BASE_URL=http://host.docker.internal:{server.server_address[1]}/v1", + "-e", "D2A_MODEL_NAME=mock/release-extension", "-e", "D2A_MODEL_API_KEY=sk-mock-test", + "-e", "PYTHONPATH=/sbh-artifact/src", image, + "python3", "/sbh-artifact/src/yuyao/__main__.py", "--yolo", "--stream", "off", + ] + master, slave = pty.openpty() + process = subprocess.Popen(command, cwd=repo, env=env, stdin=slave, stdout=slave, + stderr=slave, start_new_session=True) + os.close(slave) + try: + _read_pty(master, screen, 3.0) + for setup in scenario.recipe.setup_commands: + os.write(master, setup.encode() + b"\r") + _read_pty(master, screen, 1.0) + os.write(master, b"echo PERM_LIVE_7755 > live.txt\r") + _read_pty(master, screen, 2.0) + _read_pty(master, screen, min(float(scenario.recipe.timeout_seconds), 6.0)) + os.write(master, b"\x04") + _read_pty(master, screen, 2.0) + try: + returncode = process.wait(timeout=3.0) + except subprocess.TimeoutExpired: + # The interactive CLI may remain at its prompt after the + # required wire/tool evidence is captured. Close that + # prompt deliberately; this is harness cleanup, not a test + # timeout or an execution failure. + os.killpg(process.pid, signal.SIGTERM) + returncode = process.wait(timeout=2.0) + except OSError as exc: + driver_error = type(exc).__name__ + try: + os.killpg(process.pid, signal.SIGTERM) + returncode = process.wait(timeout=2.0) + except (OSError, subprocess.TimeoutExpired): + returncode = -1 + finally: + os.close(master) + + seen = [] + request_blob = "\n".join(json.dumps(row, ensure_ascii=False, sort_keys=True) for row in cfg["requests"]) + for face, token in _WIRE_MARKERS.items(): + if token in request_blob: + seen.append(getattr(ExtensionFace, face.upper())) + for face, path in marker_paths.items(): + if path.is_file() and _EXEC_MARKERS[face] in path.read_text(encoding="utf-8", errors="replace"): + enum_face = getattr(ExtensionFace, face.upper()) + if enum_face not in seen: + seen.append(enum_face) + tool_result_live = any( + "PERM_LIVE_7755" in "\n".join(row.get("tool_result_texts") or ()) + for row in cfg["requests"] + ) + run = ExtensionRunObservation( + fixture_verified=fixture_ok, + live=(repo / "live.txt").is_file() or tool_result_live, + request_count=len(cfg["requests"]), + seen_faces=tuple(seen), + fixture_error_code=None if fixture_ok else "EXTENSION_FIXTURE_SHAPE", + ) + evidence = { + "mode": mode, "fixture_ok": fixture_ok, "request_count": len(cfg["requests"]), + "returncode": returncode, "screen_sha256": hashlib.sha256(screen).hexdigest(), + "driver_error": driver_error, "timed_out": timed_out, + } + server.shutdown(); server.server_close() + return run, evidence + + +def _run_one() -> dict[str, Any]: + from doc2harness.benchmark.definition import definition_digest + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.harnesses.extension.adapter import build_extension_execution_plan + from doc2harness.benchmark.harnesses.extension.contracts import ExtensionCounterfactualObservation + from doc2harness.benchmark.harnesses.extension.oracle import judge_extension_observation + + scenario_id = os.environ["SBH_SCENARIO_ID"] + owner = load_scenario_owner(scenario_id) + if ".benchmark.harnesses.extension." not in owner.module: + raise RuntimeError("extension driver received a non-extension scenario") + scenario = owner.scenario + plan = build_extension_execution_plan(scenario) + artifact = Path(os.environ["SBH_ARTIFACT_PATH"]) + inside, inside_evidence = _run_mode(scenario, artifact, "inside") + outside = None + evidence = {"inside": inside_evidence} + if scenario.recipe.paired: + outside, outside_evidence = _run_mode(scenario, artifact, "outside") + evidence["outside"] = outside_evidence + observation = ExtensionCounterfactualObservation( + scenario_id=scenario_id, plan_digest=plan.plan_digest, + artifact_id=os.environ["SBH_ARTIFACT_ID"], artifact_digest=os.environ["SBH_ARTIFACT_DIGEST"], + backend_evidence_digest=_digest(evidence), inside=inside, outside=outside, + process_tree_clean=all(not item.get("driver_error") and not item.get("timed_out") for item in evidence.values()), + workspace_clean=True, + ) + return { + "observation": observation, + "judgement": judge_extension_observation(scenario, observation), + "module": owner.module, + "definition_digest": definition_digest(owner.definition), + } + + +def main() -> int: + result = _run_one() + # Create the output directory as every driver does: run_catalog pre-creates + # it, but a scenario run directly does not. + typed_event_path = Path(os.environ["SBH_TYPED_EVENT_PATH"]) + typed_event_path.parent.mkdir(parents=True, exist_ok=True) + typed_event_path.write_text(json.dumps({ + "schema": "doc2harness.typed-events/1", "source_digest": os.environ["SBH_SOURCE_DIGEST"], + "task_digest": os.environ["SBH_TASK_DIGEST"], "budget_digest": os.environ["SBH_BUDGET_DIGEST"], + "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], "artifact_id": os.environ["SBH_ARTIFACT_ID"], + "scenario_id": os.environ["SBH_SCENARIO_ID"], "scenario_module": result["module"], + "definition_digest": result["definition_digest"], + "events": [{"type": "extension-counterfactual-observation", "observation": asdict(result["observation"]), + "judgement": asdict(result["judgement"])}], + }, ensure_ascii=False, default=lambda value: value.value if hasattr(value, "value") else str(value), indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/file_tool_driver.py b/code/src/doc2harness/runtime/file_tool_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..79a2256c4bc2cbf043ea30b36197e25387b21b7c --- /dev/null +++ b/code/src/doc2harness/runtime/file_tool_driver.py @@ -0,0 +1,716 @@ +"""Run one ``file`` scenario against an immutable artifact. + +The driver deliberately keeps the observation surface small: the file-tool +scenario supplies fixtures and typed tool rounds, while the observer records +only request, lifecycle, and workspace facts. It never imports recorded +result rows or turns model prose into a verdict. +""" + +from __future__ import annotations +import argparse +import json +import os +import re +import subprocess +import tempfile +import threading +from dataclasses import asdict +from pathlib import Path +from typing import Any +from doc2harness.runtime import mock_gateway +from doc2harness.runtime.direct_mock_driver import _digest, _run_artifact, _trajectory +from doc2harness.runtime.resource_limits import container_memory_flags + + +def _unfreeze(value: object) -> object: + if isinstance(value, tuple): + if all((isinstance(item, tuple) and len(item) == 2 and isinstance(item[0], str) for item in value)): + return {str(key): _unfreeze(item) for key, item in value} + return [_unfreeze(item) for item in value] + return value + + +def _rounds(plan: Any) -> list[list[dict[str, Any]]]: + rounds: list[list[dict[str, Any]]] = [] + for turn in plan.gateway_turns: + calls: list[dict[str, Any]] = [] + for call in turn.tool_calls: + names: object = list(call.tool_names) if len(call.tool_names) > 1 else call.tool_names[0] + arguments = dict(_unfreeze(call.arguments)) + logical = {str(item).lower().replace("-", "_") for item in call.tool_names} + if logical & {"bash", "shell", "run_command", "execute", "exec", "terminal"}: + calls.append({"name": names, "command": str(arguments.pop("command", "")), **arguments}) + else: + calls.append({"name": names, "args": arguments}) + if calls: + rounds.append(calls) + return rounds + + +def _phase_rounds(raw: Any) -> list[list[dict[str, Any]]]: + """Convert one declared phase into deterministic gateway rounds.""" + rounds: list[list[dict[str, Any]]] = [] + for turn in _unfreeze(raw) or []: + calls: list[dict[str, Any]] = [] + for call in turn: + names = list(call[0]) if isinstance(call[0], (list, tuple)) else [call[0]] + arguments = dict(call[1]) if isinstance(call[1], (list, tuple, dict)) else {} + label: Any = names if len(names) > 1 else names[0] + logical = {str(item).lower().replace("-", "_") for item in names} + if logical & {"bash", "shell", "run_command", "execute", "exec", "terminal"}: + calls.append({"name": label, "command": str(arguments.pop("command", "")), **arguments}) + else: + calls.append({"name": label, "args": arguments}) + if calls: + rounds.append(calls) + return rounds + + +def _phase_plan(plan: Any) -> dict[str, Any] | None: + """Return the declared phase orchestration, or None when absent. + + An undo/redo point is not decided by the final file: it asserts a + sequence - edited, reverted, re-applied - and each of those states is a + separate snapshot the judge compares by name. A single round cannot + express that, which is why the recipe declares the phases and the slash + command that separates them. + """ + parameters = dict(plan.execution_parameters) + if not parameters.get("phase1_rounds"): + return None + return { + "phase1": _phase_rounds(parameters.get("phase1_rounds")), + "phase2": _phase_rounds(parameters.get("phase2_rounds")), + "phase3": _phase_rounds(parameters.get("phase3_rounds")), + "mid": [str(item) for item in _unfreeze(parameters.get("mid_slash")) or []], + "mid2": [str(item) for item in _unfreeze(parameters.get("mid_slash2")) or []], + } + + +def _phase_session_script(plan: Any, phases: dict[str, Any]) -> str: + """Drive the declared phases through the artifact public session API. + + The gateway hands out one declared round per model request, so the + phases are simply consecutive chats against the same session, with the + separating slash command dispatched in between. A snapshot is taken + after each boundary under the name the judge compares by. + """ + parameters = dict(plan.execution_parameters) + deny = [str(item) for item in _unfreeze(parameters.get("deny")) or []] + setup = [str(item) for item in plan.setup_commands] + targets = sorted({str(path) for path, _ in plan.fixture.seed_files} | {"tgt.txt"}) + body = [ + "import json, os", + "from yuyao.agent_api import create_session", + f"targets = {targets!r}", + f"setup = {setup!r}", + f"mid = {phases['mid']!r}", + f"mid2 = {phases['mid2']!r}", + f"phase2_len = {len(phases['phase2'])!r}", + f"phase3_len = {len(phases['phase3'])!r}", + "snapshots = {}", + "def blob(session):", + " parts = []", + " for source in (getattr(session, 'executor', None), session):", + " try:", + " for message in (getattr(source, 'messages', None) or []):", + " content = message.get('content') if isinstance(message, dict) else None", + " if content:", + " parts.append(str(content))", + " except BaseException:", + " pass", + " return chr(10).join(parts)", + "def snap(label):", + " snapshots[label + 'model_text'] = blob(session)", + " root = str(getattr(session, 'cwd', None) or '/sbh-workspace')", + " for name in targets:", + " path = os.path.join(root, name)", + " stem = os.path.splitext(os.path.basename(name))[0]", + " try:", + " handle = open(path, encoding='utf-8', errors='replace')", + " value = handle.read()", + " handle.close()", + " except OSError:", + " value = None", + " snapshots[label + stem if label else stem] = value", + f"session = create_session(deny={deny!r}, cwd='/sbh-workspace')", + "prompt = 'Please run the declared tool calls now.'", + "try:", + " for command in setup:", + " session.dispatch(command)", + " session.chat(prompt)", + " snap('phase1_')", + " for command in mid:", + " session.dispatch(command)", + " snap('after_mid1_')", + " if phase2_len:", + " session.chat(prompt)", + " snap('phase2_')", + " for command in mid2:", + " session.dispatch(command)", + " if mid2:", + " snap('after_mid2_')", + " if phase3_len:", + " session.chat(prompt)", + " snap('phase3_')", + " snap('')", + "finally:", + " session.close()", + "print('SBH_PHASE_RESULT=' + json.dumps(snapshots), flush=True)", + ] + return chr(10).join(body) + chr(10) + + +def _run_phase_session( + artifact: Path, + workspace: Path, + home: Path, + env: dict[str, str], + port: int, + script: str, + timeout: int, + cwd_mount: str = "/sbh-workspace", +) -> tuple[subprocess.CompletedProcess[str], bool]: + """Run a phase orchestration inside the evaluation image. + + ``cwd_mount`` is where the workspace is mounted and where the session runs. + It defaults to ``/sbh-workspace`` (a top-level, read-only-parent path). A + ``..``-relative escape point cannot be exercised from there: its secret is + seeded at ``/tmp/`` but ``../`` resolves to ``/`` on the read-only + root, so a product that fails to fence never reaches the secret and the + point passes vacuously. Such points pass ``/tmp/sbh-workspace`` so the + workspace parent is the writable tmpfs the seed lands in and ``../`` + reaches it - a non-fencing product then leaks/writes and fails, a fencing + one refuses and passes. + """ + image = os.environ.get("SBH_EVALUATION_IMAGE", "doc2harness/evaluation:candidate") + command = [ + "docker", + "run", + *container_memory_flags(), + "--rm", + "--init", + "--network", + "bridge", + "--add-host=host.docker.internal:host-gateway", + "--read-only", + "--tmpfs", + "/tmp:rw,noexec,nosuid,size=256m", + "--user", + f"{os.getuid()}:{os.getgid()}", + "-v", + f"{artifact}:/sbh-artifact:ro", + "-v", + f"{workspace}:{cwd_mount}:rw", + "-v", + f"{home}:/sbh-home:rw", + "-w", + cwd_mount, + "-e", + "HOME=/sbh-home", + "-e", + "YUYAO_HOME=/sbh-home/.yuyao", + "-e", + "PYTHONDONTWRITEBYTECODE=1", + "-e", + f"D2A_MODEL_BASE_URL=http://host.docker.internal:{port}/v1", + "-e", + "D2A_MODEL_NAME=litellm_proxy/mock", + "-e", + "D2A_MODEL_API_KEY=sk-mock-test", + "-e", + "PYTHONPATH=/sbh-artifact/src", + image, + "python3", + "-c", + script, + ] + try: + completed = subprocess.run( + command, + cwd=workspace, + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + return (completed, False) + except subprocess.TimeoutExpired as exc: + return (subprocess.CompletedProcess(command, -1, exc.stdout or "", exc.stderr or ""), True) + + +def _wire_facts(requests: list[dict[str, Any]]) -> dict[str, Any]: + """Summarise the structural properties of what reached the wire. + + A point about the message envelope - one leading system message, no + orphan tool result, no dangling tool call - is decided by the requests + themselves, not by any file. The gateway already records these per + request; the judge needs them folded across the whole exchange. + """ + roles = [list(record.get("msg_roles") or []) for record in requests] + return { + "has_leading_system": any((item and item[0] == "system" for item in roles)), + "nonleading_system": any((bool(record.get("nonleading_system")) for record in requests)), + "had_tool_role": any(("tool" in item for item in roles)), + "orphan_tool_result": any((bool(record.get("orphan_tool_result")) for record in requests)), + "dangling_tool_use": any((bool(record.get("dangling_tool_use")) for record in requests)), + } + + +def _apply_git_baseline(workspace: Path, plan: Any) -> bool: + """Commit the declared baseline so auto-commit has a history to add to. + + An auto-commit point counts the commits the product created and reads + the diff of the target against HEAD. Without a repository there is no + history to count and no HEAD to diff, so the point reports nothing + rather than reporting what the product did. + """ + declared = dict(_unfreeze(dict(plan.execution_parameters).get("git_baseline") or ()) or {}) + if not declared: + return False + identity = ("-c", "user.email=fixture@example.invalid", "-c", "user.name=SBH Fixture") + + def run(*arguments: str) -> None: + subprocess.run( + ("git", *identity, *arguments), + cwd=workspace, + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + for relative, content in dict(declared.get("commit") or {}).items(): + path = workspace / str(relative) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(str(content), encoding="utf-8") + run("init", "-q") + run("config", "user.email", "fixture@example.invalid") + run("config", "user.name", "SBH Fixture") + run("add", "-A") + run("commit", "-q", "-m", "baseline", "--allow-empty") + for relative, content in dict(declared.get("worktree") or {}).items(): + (workspace / str(relative)).write_text(str(content), encoding="utf-8") + return True + + +def _git_facts(workspace: Path, plan: Any) -> dict[str, Any]: + """Count commits and read the target diff the auto-commit judges use.""" + if not (workspace / ".git").is_dir(): + return {} + targets = [str(path) for path, _ in plan.fixture.seed_files] or ["tgt.txt"] + log = subprocess.run( + ("git", "log", "--oneline"), cwd=workspace, check=False, capture_output=True, text=True + ) + diff = subprocess.run( + ("git", "diff", "HEAD", "--", targets[0]), cwd=workspace, check=False, capture_output=True, text=True + ) + tracked = subprocess.run( + ("git", "ls-files", "-z", "--", targets[0]), cwd=workspace, check=False, capture_output=True + ) + matches = tuple( + sorted((item.decode("utf-8", "replace") for item in (tracked.stdout or b"").split(b"\x00") if item)) + ) + return { + "git_ok": True, + "git_tree_observer_ok": log.returncode == 0 and tracked.returncode == 0, + "git_pathspec_matches": matches, + "git_commit_count": len([x for x in (log.stdout or "").splitlines() if x.strip()]), + "git_diff_target": str(diff.stdout or ""), + } + + +def _mode_session_script(plan: Any, cwd: str = "/sbh-workspace") -> str: + """Drive the declared rounds through a session with the declared mode. + + The artifact launcher hard-codes yolo (entry.py), so a point whose + whole subject is a restricted mode ran unrestricted through it: the + mutating tools stayed advertised and the write landed, which reads as + "read-only failed to block" when read-only was never in effect. + + yolo is therefore the default *only for a point that declares no + restriction* - a full-permission point that needs bash and writes + auto-approved on every product. A point that declares a restriction + (``/mode X``, ``/ask``, ``/plan``, or ``/role ask``) must run under it, + because the permission layer gates by mode alone (role only tunes the + system prompt). Blanket-forcing yolo onto a ``/role ask`` point re-opens + the very write it exists to block: the mutating call the mock issues is + auto-approved, the target changes, and a genuinely restrictive default + ("ask") reads as "failed to block" - a false FAIL the driver invented. + A pure ``/role ask`` keeps the product's own default mode (ask, per + ยง3.1) rather than being pinned, so the restriction under test is the + product's, not the harness's. + """ + explicit_mode: str | None = None + for command in plan.setup_commands: + text = str(command).strip() + if "/mode " in text: + explicit_mode = text.split("/mode ", 1)[1].split()[0] + elif text == "/plan": + explicit_mode = explicit_mode or "plan" + elif text == "/ask": + explicit_mode = explicit_mode or "ask" + role = ( + "ask" + if any(("/role ask" in str(c) or str(c).strip() == "/ask" for c in plan.setup_commands)) + else None + ) + if explicit_mode is not None: + mode: str | None = explicit_mode + elif role == "ask": + mode = None + else: + mode = "yolo" + deny = [str(item) for item in _unfreeze(dict(plan.execution_parameters).get("deny")) or []] + mode_argument = f"mode={mode!r}, " if mode is not None else "" + role_argument = f"role={role!r}, " if role else "" + return f"import json\nfrom yuyao.agent_api import create_session\nsession = create_session({mode_argument}{role_argument}deny={deny!r}, cwd={cwd!r})\ntry:\n session.chat('Please run the declared tool calls now.')\nfinally:\n session.close()\n" + + +def _config(home: Path, plan: Any) -> None: + config_root = home / ".yuyao" + config_root.mkdir(parents=True, exist_ok=True) + mode = "yolo" + for command in plan.setup_commands: + text = str(command) + if "/mode " in text: + mode = text.split("/mode ", 1)[1].split()[0] + value: dict[str, object] = {"agent.mode": mode} + if dict(plan.execution_parameters).get("enable_autocommit"): + value["autoCommit"] = True + (config_root / "config.json").write_text(json.dumps(value, sort_keys=True), encoding="utf-8") + + +def _path_values(plan: Any) -> list[str]: + paths: list[str] = [str(path) for path, _ in plan.fixture.seed_files] + for turn in plan.gateway_turns: + for call in turn.tool_calls: + args = dict(_unfreeze(call.arguments)) + for key in ( + "path", + "file_path", + "filepath", + "filename", + "target", + "target_file", + "notebook_path", + ): + value = args.get(key) + if isinstance(value, str) and value and (not value.startswith("/")): + paths.append(value) + return list(dict.fromkeys(paths)) + + +def _facts(workspace: Path, plan: Any) -> tuple[str | None, str | None, bool, tuple[tuple[str, object], ...]]: + paths = _path_values(plan) + candidates = [path for path in paths if path not in {"live.txt", "", "."}] + existing = [workspace / path for path in candidates if (workspace / path).is_file()] + target = existing[0].read_text(encoding="utf-8", errors="replace") if existing else None + secondary = existing[-1].read_text(encoding="utf-8", errors="replace") if existing else None + live = (workspace / "live.txt").is_file() + files = tuple( + sorted( + ( + (path, (workspace / path).read_text(encoding="utf-8", errors="replace")) + for path in candidates + if (workspace / path).is_file() + ) + ) + ) + notebook = workspace / "nb.ipynb" + if notebook.is_file(): + files = tuple( + sorted((dict(files) | {"nb": notebook.read_text(encoding="utf-8", errors="replace")}).items()) + ) + return (target, secondary, live, files) + + +def _observed_model_text(trajectory: str) -> str: + """Project the trajectory down to what the model and tools actually said. + + The scenarios assert that a forbidden marker never appears in the model's + view. Matching against the raw trajectory also matches the marker inside + the recorded arguments of a tool call - that is the request the product then + *refused*, so the assertion inverts: a product that correctly blocked a + fence escape reads as having leaked it. The judges look only at message + content, never at call arguments, and the fixtures build their + markers by concatenation precisely so the full string cannot appear in + command text. + + Artifacts record trajectories in different shapes - one writes JSONL, one + writes pretty-printed JSON interleaved with Markdown - so the argument + payloads are removed textually rather than by parsing a specific schema. + Tool results, replies and reasoning are all preserved, including the failure + text that proves a refusal happened. + + The runner's own per-call bookkeeping is dropped for the same reason. A + recorded ``"meta": {"truncated": false, ...}`` is the runner describing the + call to its log, not text any model read; a judge asking whether the + product *claimed* truncation found the word inside that structure and + reported a truncation claim on a result whose own text says nothing of the + kind. The tool's own output survives + this because it is a sibling field, not part of the bookkeeping. + """ + without_arguments = re.sub( + '"(?:arguments|args|input|meta)"\\s*:\\s*"(?:[^"\\\\]|\\\\.)*"', '"arguments": ""', trajectory + ) + without_arguments = _strip_balanced_argument_objects(without_arguments) + without_arguments = re.sub( + '("kind"\\s*:\\s*"permission"[^\\n]*?)"target"\\s*:\\s*"(?:[^"\\\\]|\\\\.)*"', + '\\1"target": ""', + without_arguments, + ) + without_arguments = re.sub("(- tool `[A-Za-z0-9_.-]+`)\\s*\\{[^\\n]*", "\\1", without_arguments) + return without_arguments + + +def _strip_balanced_argument_objects(text: str) -> str: + """Replace ``"arguments": {...}`` values, however deeply they nest. + + A character-class regex cannot span a nested payload such as multi-edit's + ``{"edits": [{...}, {...}]}``, which would leave the very marker the + scenario forbids inside the text the judge inspects. + """ + pattern = re.compile('"(?:arguments|args|input|meta)"\\s*:\\s*(?=[{\\[])') + result: list[str] = [] + index = 0 + while True: + match = pattern.search(text, index) + if match is None: + result.append(text[index:]) + return "".join(result) + result.append(text[index : match.start()]) + result.append('"arguments": {}') + cursor = match.end() + depth = 0 + in_string = False + escaped = False + while cursor < len(text): + char = text[cursor] + if in_string: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == '"': + in_string = False + elif char == '"': + in_string = True + elif char in "{[": + depth += 1 + elif char in "}]": + depth -= 1 + if depth == 0: + cursor += 1 + break + cursor += 1 + index = cursor + + +def _run_one() -> dict[str, Any]: + from doc2harness.benchmark.definition import definition_digest + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.harnesses.file.adapter import build_file_tool_execution_plan + from doc2harness.benchmark.harnesses.file.contracts import FileToolRawObservation + + scenario_id = os.environ.get("SBH_SCENARIO_ID", "") + owner = load_scenario_owner(scenario_id) + if ".benchmark.harnesses.file." not in owner.module: + raise RuntimeError("file-tool driver received a non-file-tool scenario") + scenario = owner.scenario + plan = build_file_tool_execution_plan(scenario) + gateway = mock_gateway + with tempfile.TemporaryDirectory(prefix="sbh-file-tool-production-") as temporary: + root = Path(temporary) + home, workspace, output = (root / "home", root / "workspace", root / "out") + home.mkdir() + workspace.mkdir() + output.mkdir() + for relative, content in plan.fixture.seed_files: + path = workspace / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + _apply_git_baseline(workspace, plan) + _config(home, plan) + task = workspace / "task.json" + budget = workspace / "budget.json" + task.write_text( + json.dumps({"problem_statement": "Run the declared file-tool probe and stop."}), encoding="utf-8" + ) + budget.write_text(json.dumps({"max_steps": max(3, len(plan.gateway_turns) + 1)}), encoding="utf-8") + phases = _phase_plan(plan) + if phases is not None: + finish = [[{"name": "__finish__", "content": "done"}]] + declared_rounds = [] + for name in ("phase1", "phase2", "phase3"): + if phases[name]: + declared_rounds += phases[name] + finish + else: + declared_rounds = _rounds(plan) + cfg = gateway.new_cfg(mode="seq_probe", rounds=declared_rounds) + server = gateway.ThreadingHTTPServer(("0.0.0.0", 0), gateway.Handler) + server.cfg = cfg + server.daemon_threads = True + server.block_on_close = False + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + env = dict(os.environ) + env.update({"HOME": str(home), "YUYAO_HOME": str(home / ".yuyao"), "PYTHONDONTWRITEBYTECODE": "1"}) + argv = [ + str(Path(os.environ["SBH_ARTIFACT_PATH"]) / "run_agent.sh"), + "--task-file", + str(task), + "--repo-dir", + str(workspace), + "--model-base-url", + f"http://127.0.0.1:{server.server_address[1]}/v1", + "--model-name", + "litellm_proxy/mock", + "--model-api-key", + "sk-mock-test", + "--budget-file", + str(budget), + "--out-dir", + str(output), + ] + artifact_root = Path(os.environ["SBH_ARTIFACT_PATH"]) + phase_snapshots: dict[str, Any] = {} + has_api = (artifact_root / "src" / "yuyao" / "agent_api.py").is_file() + if phases is not None and has_api: + completed, timed_out = _run_phase_session( + artifact_root, + workspace, + home, + env, + int(server.server_address[1]), + _phase_session_script(plan, phases), + min(plan.timeout_seconds, 300), + ) + for line in (completed.stdout or "").splitlines(): + if line.startswith("SBH_PHASE_RESULT="): + try: + parsed = json.loads(line[len("SBH_PHASE_RESULT=") :]) + except (TypeError, ValueError, json.JSONDecodeError): + parsed = {} + if isinstance(parsed, dict): + phase_snapshots = parsed + elif has_api: + cwd_mount = ( + "/sbh-workspace" + ) + completed, timed_out = _run_phase_session( + artifact_root, + workspace, + home, + env, + int(server.server_address[1]), + _mode_session_script(plan, cwd_mount), + min(plan.timeout_seconds, 300), + cwd_mount=cwd_mount, + ) + else: + completed, timed_out = _run_artifact( + artifact_root, + workspace, + home, + output, + task, + budget, + argv, + env, + int(server.server_address[1]), + min(plan.timeout_seconds, 300), + ) + target_content, secondary_content, live, files = _facts(workspace, plan) + if phase_snapshots and "tgt" in phase_snapshots: + target_content = phase_snapshots["tgt"] + wire = _wire_facts(list(cfg.get("requests", []))) + wire.update(_git_facts(workspace, plan)) + files = tuple(sorted((dict(files) | wire).items())) + if phase_snapshots: + merged = dict(files) + merged.update({str(key): value for key, value in phase_snapshots.items() if value is not None}) + files = tuple(sorted(merged.items())) + trajectory = _trajectory(home) + "\n" + _trajectory(workspace) + "\n" + _trajectory(output) + requests = cfg.get("requests", []) + result_texts = tuple( + (str(text) for record in requests for text in record.get("tool_result_texts") or ()) + ) + files = tuple(sorted((dict(files) | {"target_tool_result_seen": bool(result_texts)}).items())) + advertised = tuple((str(name) for name in requests[0].get("tool_names") or ())) if requests else () + observation = FileToolRawObservation( + scenario_id=scenario_id, + plan_digest=plan.plan_digest, + artifact_id=os.environ["SBH_ARTIFACT_ID"], + artifact_digest=os.environ["SBH_ARTIFACT_DIGEST"], + request_count=len(requests), + advertised_tools=advertised, + live=live, + target_content=target_content, + secondary_target_content=secondary_content, + model_text=_observed_model_text(trajectory) + chr(10) + chr(10).join(result_texts), + stderr_text=str(completed.stderr or ""), + empty_tool_result=any((not text.strip() for text in result_texts)) if result_texts else None, + process_tree_clean=not timed_out, + gateway_clean=True, + workspace_clean=True, + timed_out=timed_out, + backend_evidence_digest=_digest( + {"scenario_id": scenario_id, "requests": len(requests), "rc": completed.returncode} + ), + target_tool_result=result_texts[-1] if result_texts else "", + round_target_tool_results=result_texts, + facts=files, + ) + server.shutdown() + server.server_close() + thread.join(timeout=2) + judgement = owner.judge(observation) + return { + "observation": observation, + "judgement": judgement, + "plan_digest": plan.plan_digest, + "definition_digest": definition_digest(owner.definition), + "module": owner.module, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + result = _run_one() + target = Path(os.environ["SBH_TYPED_EVENT_PATH"]) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text( + json.dumps( + { + "schema": "doc2harness.typed-events/1", + "source_digest": os.environ["SBH_SOURCE_DIGEST"], + "task_digest": os.environ["SBH_TASK_DIGEST"], + "budget_digest": os.environ["SBH_BUDGET_DIGEST"], + "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], + "artifact_id": os.environ["SBH_ARTIFACT_ID"], + "scenario_id": os.environ["SBH_SCENARIO_ID"], + "scenario_module": result["module"], + "definition_digest": result["definition_digest"], + "events": [ + { + "type": "file-tool-observation", + "observation": asdict(result["observation"]), + "judgement": asdict(result["judgement"]), + } + ], + }, + ensure_ascii=False, + default=lambda value: value.value if hasattr(value, "value") else str(value), + indent=2, + ) + + "\n", + encoding="utf-8", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/headless_driver.py b/code/src/doc2harness/runtime/headless_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..9d3c5b210d2b1d231435d0e061794cdb1105a291 --- /dev/null +++ b/code/src/doc2harness/runtime/headless_driver.py @@ -0,0 +1,1123 @@ +"""Run one ``headless`` scenario through the artifact's public CLI. + +The driver deliberately observes process exit data, request records, and +workspace changes. It never converts terminal prose into a typed fact used +by a judge; unsupported observations remain explicit in the observation. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shlex +import subprocess +import tempfile +import threading +from dataclasses import asdict +from pathlib import Path +from typing import Any + +_TREE = "/sbh-tree" +# The container path of the mounted workspace. It deliberately sits one level +# inside a writable parent; see the mount in _docker_run. +_WORKSPACE = _TREE + "/workspace" + +from doc2harness.runtime import mock_gateway +from doc2harness.runtime.direct_mock_driver import _digest, _status +from doc2harness.runtime.resource_limits import container_memory_flags + + +def _snapshot(root: Path) -> dict[str, bytes]: + result: dict[str, bytes] = {} + if not root.exists(): + return result + for path in root.rglob("*"): + if not path.is_file() or ".yuyao" in path.parts or ".trajectory" in path.parts: + continue + try: + if path.stat().st_size > 8 * 1024 * 1024: + continue + result[path.relative_to(root).as_posix()] = path.read_bytes() + except OSError: + continue + return result + + +def _system_probe_hits(record: dict[str, Any], probe_token: str = "") -> tuple[str, ...]: + """Collect the tokens the gateway saw inside ``role=system`` messages. + + The gateway records these as ``probes_in_system`` (a token map) plus + ``has_probe_in_system`` for the single configured ``probe_token``, which + lives in the gateway config rather than in the record. It deliberately + keeps no request body, so there is no system text to read. Reading a + differently named key yields an empty system segment for every request, + which the judges report as the product having dropped the flag. + """ + hits = { + str(key) + for key, value in (record.get("probes_in_system") or {}).items() + if value + } + if record.get("has_probe_in_system") and probe_token: + hits.add(str(probe_token)) + return tuple(sorted(hits)) + + +def _request_records(records: list[dict[str, Any]], probe_token: str = ""): + from doc2harness.benchmark.harnesses.headless.contracts import RequestRecord + + result = [] + for record in records: + body = record.get("body") + if not isinstance(body, str): + # The whole record would include the gateway's own bookkeeping, + # including the probe table, so a judge asking whether a token is + # absent from the request would always find it. Serialise only the + # fields that carry what was actually sent. + body = json.dumps( + { + key: value + for key, value in record.items() + if key in {"system_text", "messages", "msg_roles", "tool_names", "model"} + }, + sort_keys=True, + ensure_ascii=False, + ) + probes = record.get("probes") or {} + result.append( + RequestRecord( + body=body, + model=str(record.get("model") or ""), + system_text=str(record.get("system_text") or ""), + probe_hits=tuple(str(k) for k, v in probes.items() if v), + system_probe_hits=_system_probe_hits(record, probe_token), + tool_names=tuple(str(v) for v in (record.get("tool_names") or ())), + tool_result_texts=tuple(str(v) for v in (record.get("tool_result_texts") or ())), + stream_enabled=record.get("stream") if isinstance(record.get("stream"), bool) else None, + ) + ) + return tuple(result) + + +def _rounds(recipe: Any, observer: str = "") -> list[list[dict[str, Any]]]: + rounds: list[list[dict[str, Any]]] = [] + for group in recipe.rounds: + current: list[dict[str, Any]] = [] + for call in group.calls: + item: dict[str, Any] = {"name": call.names[0]} + if call.command: + item["command"] = call.command + try: + arguments = json.loads(call.arguments_json) + except (TypeError, ValueError, json.JSONDecodeError): + arguments = {} + if isinstance(arguments, dict): + # An address in a declared call can only name the observer once + # the run has a bound listener, and the product reaches the host + # under a different name than the host uses for itself. Left + # unresolved the fetch the point is about never arrives, and a + # point asking whether the fetch was refused cannot tell that + # from a fetch that was never attempted. + if observer: + arguments = { + key: value.replace("127.0.0.1:__D2A_MOCK_PORT__", observer) + if isinstance(value, str) else value + for key, value in arguments.items() + } + # The gateway reads a bash call's arguments from top-level + # keys but every other tool's from "args"; spreading a grep + # call's arguments top-level would drop them. + if call.names[0] in {"bash", "shell", "run_command", "execute", "exec", "terminal"}: + item.update(arguments) + else: + item["args"] = arguments + current.append(item) + if current: + rounds.append(current) + return rounds + + +def _json_object(pairs: list[tuple[str, Any]]) -> bytes: + """Serialise pairs verbatim, keeping any repeated key. + + A duplicate-key contract probe cannot be produced by json.dumps, which + silently collapses the repetition that is the whole subject of the + point. The unique variant is written the same way so both sides differ + only in the repetition itself. + """ + + body = ",".join( + json.dumps(key, ensure_ascii=False) + ":" + + json.dumps(value, ensure_ascii=False, separators=(",", ":")) + for key, value in pairs + ) + return ("{" + body + "}").encode() + + +def _formal_probe_count(recipe: Any) -> int: + return sum( + len(getattr(recipe, name, ()) or ()) + for name in ( + "formal_contract_probes", "formal_runtime_probes", + "listing_probes", "cli_file_probes", + ) + ) + + +def _formal_rounds(recipe: Any) -> list[list[dict[str, Any]]]: + """Rounds for one formal probe run, repeated once per declared probe. + + The two families differ in the exchange they specify. A contract probe is + a tool round plus the declared reply, which its judge reads as exactly two + requests; a runtime-matrix probe is answered in one turn and its judge + requires exactly one. Sharing a single shape would make one of the two + fail on the request count alone. + """ + + count = max(1, _formal_probe_count(recipe)) + if getattr(recipe, "formal_contract_probes", ()): + turn = [ + [{"name": "bash", "command": "echo FORMAL_PROBE_ACK"}], + [{"name": "__finish__", "content": recipe.reply_content}], + ] + else: + turn = [[{"name": "__finish__", "content": recipe.reply_content}]] + return turn * count + + +def _probe_by_label(recipe: Any, label: str) -> Any: + """Find the declared probe a variant label came from, if any.""" + + for name in ("formal_contract_probes", "formal_runtime_probes", "cli_file_probes"): + for probe in getattr(recipe, name, ()) or (): + if str(getattr(probe, "label", "")) == label: + return probe + return None + + +def _cli_file_variants(recipe: Any, workspace: Path) -> list[tuple[str, list[str]]]: + """Build one module-CLI invocation per declared CLI-file probe. + + The probe declares the exact bytes of a file the product is handed through + a user-facing flag, so the bytes are written verbatim - the point is about + what happens at the decoding boundary, which a text round-trip would have + already resolved. + """ + + variants: list[tuple[str, list[str]]] = [] + for probe in getattr(recipe, "cli_file_probes", ()) or (): + label = str(probe.label) + kind = str(getattr(probe, "kind", "")) + if kind != "system-prompt": + continue + path = workspace / f"system-prompt-{label}.txt" + path.write_bytes(bytes.fromhex(str(probe.file_hex))) + variants.append((label, [ + "-p", str(recipe.task or "Return the fixed reply and stop."), + "--output-format", "text", + "--system-prompt-file", f"{_WORKSPACE}/{path.name}", + ])) + return variants + + +def _formal_probe_variants( + recipe: Any, workspace: Path, output: Path, port: int, +) -> list[tuple[str, list[str]]]: + """Build one launcher invocation per declared formal probe.""" + + probes = list(getattr(recipe, "formal_contract_probes", ()) or ()) + probes += list(getattr(recipe, "formal_runtime_probes", ()) or ()) + # A listing probe is not a launcher invocation: it seeds sessions through + # the session API and samples process counters around the listing, so it + # is driven by its own two-phase child rather than by run_agent.sh. A + # CLI-file probe is not one either: it hands the product a file through a + # user-facing flag, and that route deliberately writes no status document - + # which is exactly the "MISSING" status the point requires. The launcher + # would produce a status document the route it is about never writes. + if not probes: + return [] + variants: list[tuple[str, list[str]]] = [] + for probe in probes: + label = str(probe.label) + task_file = workspace / f"task-{label}.json" + budget_file = workspace / f"budget-{label}.json" + task: dict[str, Any] = { + "task_id": label, + "type": "swe", + "problem_statement": str(recipe.task), + "repo_dir": _WORKSPACE, + "allow_network": False, + } + for override in getattr(probe, "task_overrides", ()) or (): + task[str(override.field)] = override.canonical_value + budget: dict[str, Any] = {"max_steps": 4, "max_tokens": 0, "max_wall_seconds": 30} + for override in getattr(probe, "budget", ()) or (): + raw = str(override.canonical_value) + budget[str(override.field)] = int(raw) if raw.lstrip("-").isdigit() else raw + contract = str(getattr(probe, "raw_contract", "") or "") + task_pairs = list(task.items()) + budget_pairs: list[tuple[str, Any]] = list(budget.items()) + if contract == "duplicate-task": + task_pairs = [ + ("task_id", task["task_id"]), ("type", task["type"]), + ("problem_statement", "Return the first fixed reply."), + ("problem_statement", "Return the second fixed reply."), + ("repo_dir", task["repo_dir"]), ("allow_network", False), + ] + if contract == "duplicate-budget": + budget_pairs = [ + ("max_steps", 4), ("max_steps", 5), + ("max_tokens", 0), ("max_wall_seconds", 30), + ] + if contract in {"unique-task", "duplicate-task"}: + task_file.write_bytes(_json_object(task_pairs)) + else: + task_file.write_text(json.dumps(task, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + if contract in {"unique-budget", "duplicate-budget"}: + budget_file.write_bytes(_json_object(budget_pairs)) + else: + budget_file.write_text(json.dumps(budget, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + values = { + "--task-file": str(task_file).replace(str(workspace), _WORKSPACE), + "--repo-dir": _WORKSPACE, + "--model-base-url": f"http://host.docker.internal:{port}/v1", + "--model-name": "litellm_proxy/mock", + "--model-api-key": "sk-mock-test", + "--budget-file": str(budget_file).replace(str(workspace), _WORKSPACE), + "--out-dir": "/sbh-output", + } + # ``argv_overrides`` holds (flag, value) string pairs - not JsonOverride + # objects with .field/.canonical_value. + for flag_override, value_override in getattr(probe, "argv_overrides", ()) or (): + values[str(flag_override)] = str(value_override) + argv = ["--sbh-launcher"] + for flag in ("--task-file", "--repo-dir", "--model-base-url", "--model-name", + "--model-api-key", "--budget-file", "--out-dir"): + argv.extend((flag, values[flag])) + variants.append((label, argv)) + return variants + + +_LISTING_PREFIX = "SBH-LISTING-ENTRY-" +_LISTING_PAYLOAD_END = "-SBH-LISTING-PAYLOAD-END-" +_LISTING_RESULT = "SBH_LISTING_RESULT=" + + +def _listing_probe_script(phase: str, count: int, payload_bytes: int) -> str: + """Build the child that seeds titled sessions, then lists them. + + The point asks whether listing sessions stays bounded as the stored + transcripts grow: it compares read bytes, resident growth, opens under + HOME and the printed size against the number of sessions seeded. Those + are facts about the product's own process, sampled around the dispatch, + so they are gathered by a child inside the container - a driver watching + from outside cannot attribute any of them to the listing. Seeding and + measuring are separate children on purpose: a measurement taken in the + process that just wrote the corpus reads that writing, not the listing. + """ + + common = [ + "import contextlib, io, json, os, resource, sys", + f"TAG = {_LISTING_RESULT!r}", + f"PREFIX = {_LISTING_PREFIX!r}", + f"PAYLOAD_END = {_LISTING_PAYLOAD_END!r}", + f"COUNT = {int(count)}", + f"PAYLOAD_BYTES = {int(payload_bytes)}", + "def emit(value):", + " print(TAG + json.dumps(value, ensure_ascii=False, separators=(',', ':')))", + "def close(session):", + " try:", + " session.close()", + " except BaseException:", + " pass", + ] + if phase == "seed": + body = [ + "result = {'phase': 'seed', 'created': 0, 'product_error': '', 'reset_ok': True}", + "session = None", + "try:", + " from yuyao.agent_api import create_session", + " session = create_session(cwd=os.getcwd())", + " if not isinstance(session.messages, list) or not callable(getattr(session, 'dispatch', None)):", + " raise TypeError('standard AgentSession messages/dispatch unavailable')", + " for index in range(COUNT):", + " title = PREFIX + str(index).zfill(4)", + " answer = str(session.chat(title) or '')", + " if PAYLOAD_END not in answer or len(answer.encode('utf-8', 'replace')) != PAYLOAD_BYTES:", + " raise RuntimeError('mock assistant payload was not delivered exactly')", + " if PAYLOAD_END not in json.dumps(session.messages, ensure_ascii=False):", + " raise RuntimeError('assistant payload absent from public messages')", + " session.dispatch('/title ' + title)", + " session.dispatch('/new')", + " result['created'] += 1", + " if len(session.messages) != 0:", + " result['reset_ok'] = False", + " break", + "except BaseException as exc:", + " result['product_error'] = type(exc).__name__ + ': ' + str(exc)[:240]", + "finally:", + " close(session)", + "emit(result)", + ] + return "\n".join(common + body) + "\n" + if phase != "measure": + raise ValueError(f"unknown listing probe phase {phase!r}") + body = [ + "result = {'phase': 'measure', 'product_error': '', 'observer_error': ''}", + "session = None", + "def io_stats():", + " try:", + " data = {}", + " with open('/proc/self/io', 'r', encoding='ascii') as handle:", + " for line in handle:", + " key, _, value = line.partition(':')", + " data[key.strip()] = int(value.strip())", + " return data", + " except BaseException:", + " return None", + "def rss_kib():", + " try:", + " return int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)", + " except BaseException:", + " return None", + "try:", + " from yuyao.agent_api import create_session", + " session = create_session(cwd=os.getcwd())", + " if not callable(getattr(session, 'dispatch', None)):", + " raise TypeError('standard AgentSession dispatch unavailable')", + " opened = {'home': 0}", + " home = os.path.realpath(os.environ['HOME']) + os.sep", + " def audit(event, args):", + " if event != 'open' or not args:", + " return", + " try:", + " path = os.path.realpath(os.fsdecode(args[0]))", + " except BaseException:", + " return", + " if path.startswith(home):", + " opened['home'] += 1", + " sys.addaudithook(audit)", + " io_before, rss_before = io_stats(), rss_kib()", + " capture = io.StringIO()", + " with contextlib.redirect_stdout(capture), contextlib.redirect_stderr(capture):", + " returned = session.dispatch('/sessions')", + " io_after, rss_after = io_stats(), rss_kib()", + " printed = capture.getvalue()", + " joiner = chr(10) if returned and printed else ''", + " public = (str(returned or '') + joiner + printed).strip()", + " absent = io_before is None or io_after is None or rss_before is None or rss_after is None", + " result.update({", + " 'rchar_delta': None if io_before is None or io_after is None else max(0, io_after.get('rchar', 0) - io_before.get('rchar', 0)),", + " 'read_bytes_delta': None if io_before is None or io_after is None else max(0, io_after.get('read_bytes', 0) - io_before.get('read_bytes', 0)),", + " 'rss_delta_kib': None if rss_before is None or rss_after is None else max(0, rss_after - rss_before),", + " 'home_open_count': opened['home'],", + " 'output_bytes': len(public.encode('utf-8', 'replace')),", + " 'listed_markers': public.count(PREFIX),", + " })", + " if absent:", + " result['observer_error'] = 'bytes/RSS observer unavailable'", + "except BaseException as exc:", + " result['product_error'] = type(exc).__name__ + ': ' + str(exc)[:240]", + "finally:", + " close(session)", + "emit(result)", + ] + return "\n".join(common + body) + "\n" + + +def _listing_payload(payload_bytes: int) -> str: + """The exact assistant reply the seed phase requires the mock to send.""" + + suffix = len(_LISTING_PAYLOAD_END.encode("utf-8")) + return "L" * max(0, int(payload_bytes) - suffix) + _LISTING_PAYLOAD_END + + +def _listing_result(completed: subprocess.CompletedProcess[str]) -> dict[str, Any] | None: + """Read the child's declared result line out of its stdout.""" + + parsed: dict[str, Any] | None = None + for line in (completed.stdout or "").splitlines(): + if not line.startswith(_LISTING_RESULT): + continue + try: + candidate = json.loads(line[len(_LISTING_RESULT):]) + except ValueError: + continue + if isinstance(candidate, dict): + parsed = candidate + return parsed + + +def _argv_variants(recipe: Any) -> list[tuple[str, list[str]]]: + if recipe.sequence_subcommands: + # Use the declared step names when the point has them: its judge looks + # the steps up by name, and a positional "step-N" label makes every + # lookup miss and the matrix read as incomplete. + labels = list(getattr(recipe, "sequence_labels", ()) or ()) + return [ + ( + labels[index - 1] + if index - 1 < len(labels) + else f"step-{index}", + list(arguments), + ) + for index, arguments in enumerate(recipe.sequence_subcommands, start=1) + ] + base = ["-p", recipe.task, "--output-format", recipe.output_format] + if recipe.append_system_prompt: + base += ["--append-system-prompt", recipe.append_system_prompt] + if recipe.system_prompt: + base += ["--system-prompt", recipe.system_prompt] + base += list(recipe.extra_argv) + if recipe.subcommand_variants: + return [(item.label, list(item.arguments)) for item in recipe.subcommand_variants] + variants = recipe.cli_variants or recipe.file_variants + if variants: + return [(item.label, base + list(item.arguments)) for item in variants] + return [("main", base)] + + +_STEP_MARKER = "SBH-STEP-BOUNDARY-" + + +def _sequence_script(steps: list[list[str]], settle_seconds: int) -> str: + """Run every declared step in one shell, marking each boundary. + + A dispatch step starts a detached session and returns at once; the + container's init reaps that session the moment the foreground process + exits. Running each step as its own container would kill the session + before the next step could list or stop it. One + shell for the whole sequence keeps the session alive across the steps + that are about it, and the declared window is honoured between them. + """ + + entry = "/sbh-artifact/src/yuyao/__main__.py" + lines = ["AGENT_SESSION_ID="] + for index, step in enumerate(steps, start=1): + lines.append(f'echo "{_STEP_MARKER}{index}"') + lines.append( + "python3 " + entry + " " + + " ".join( + # A step naming the session an earlier step started cannot know + # its identifier ahead of time, so the placeholder is resolved + # in the shell that just saw the dispatch report it. + '"$AGENT_SESSION_ID"' if item == "$AGENT_SESSION_ID" else shlex.quote(item) + for item in step + ) + + f" 2>&1 | tee /tmp/sbh-step-{index}.out" + ) + lines.append(f'echo "{_STEP_MARKER}{index}-rc=${{PIPESTATUS[0]}}"') + lines.append( + "if [ -z \"$AGENT_SESSION_ID\" ]; then " + f"AGENT_SESSION_ID=$(sed -n 's/^dispatched \\([A-Za-z0-9_-]*\\).*/\\1/p' /tmp/sbh-step-{index}.out | head -1); fi" + ) + if settle_seconds: + lines.append(f"sleep {int(settle_seconds)}") + return "\n".join(lines) + "\n" + + +def _sequence_steps(text: str, count: int) -> list[tuple[str, int]]: + """Split one sequence run's output back into per-step text and codes.""" + + results: list[tuple[str, int]] = [] + for index in range(1, count + 1): + start = text.find(f"{_STEP_MARKER}{index}\n") + if start < 0: + results.append(("", -1)) + continue + start += len(f"{_STEP_MARKER}{index}\n") + end = text.find(f"{_STEP_MARKER}{index}-rc=", start) + body = text[start:end] if end >= 0 else text[start:] + code = -1 + if end >= 0: + tail = text[end + len(f"{_STEP_MARKER}{index}-rc="):].split("\n", 1)[0] + if tail.strip().lstrip("-").isdigit(): + code = int(tail.strip()) + results.append((body, code)) + return results + + +_BOOKKEEPING_DIRS = {".git", ".yuyao", ".trajectory", "__pycache__", "node_modules"} + + +def _worktree_facts( + workspace: Path, home: Path, target: str, needle: str, +) -> tuple[tuple[str, ...], str, str]: + """Find the checkouts beside the repository and what they hold. + + A worktree point asserts two things at once: the write reached an + isolated checkout, and the parent tree did not see it. The second can be + read from the workspace, but the first cannot - the checkout lives + outside the repository, so looking only inside it finds nothing however + well the product isolated the work, and the point reports the isolation + absent. + + ``git worktree list`` answers in the paths the product saw, which are the + container's. They are translated back to the host so the content can + actually be read; without that the paths are published and every read of + them fails. + """ + + def host(path: str) -> Path: + for container, local in ((_WORKSPACE, workspace), ("/sbh-home", home)): + if path == container: + return local + if path.startswith(container + "/"): + return local / path[len(container) + 1:] + return Path(path) + + paths: list[str] = [] + listing = subprocess.run( + ("git", "worktree", "list", "--porcelain"), cwd=workspace, + capture_output=True, text=True, timeout=15, check=False, + ) + for line in (listing.stdout or "").splitlines(): + if not line.startswith("worktree "): + continue + candidate = line.split(" ", 1)[1] + if host(candidate).resolve() != workspace.resolve(): + paths.append(candidate) + # A product may build the checkout beside the repository without + # registering it, so the declared sibling naming is checked too. The + # match is deliberately anchored on the repository's own name: a looser + # one would collect the other variant's directory from the same parent. + for sibling in sorted(workspace.parent.iterdir()): + if not sibling.is_dir() or sibling.resolve() == workspace.resolve(): + continue + if sibling.name.startswith(workspace.name + "-") or sibling.name.startswith(workspace.name + "__"): + if str(sibling) not in paths: + paths.append(str(sibling)) + name = Path(target).name if target else "" + for item in paths: + root = host(item) + if not root.is_dir(): + continue + candidates = [root / target] if target else [] + for base, directories, files in os.walk(root): + directories[:] = [d for d in directories if d not in _BOOKKEEPING_DIRS] + candidates.extend(Path(base) / found for found in files if found == name) + for candidate in candidates: + try: + if not candidate.is_file() or candidate.stat().st_size > 200_000: + continue + content = candidate.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + if needle and needle in content: + return tuple(paths), content, str(candidate) + return tuple(paths), "", "" + + +def _docker_command( + artifact: Path, + workspace: Path, + home: Path, + output: Path, + argv: list[str], + env: dict[str, str], + port: int, +) -> list[str]: + """Build the container invocation for one declared run.""" + + image = os.environ.get("SBH_EVALUATION_IMAGE", "doc2harness/evaluation:candidate") + command = [ + "docker", "run", *container_memory_flags(), "--rm", "--init", "--network", "bridge", + "--add-host=host.docker.internal:host-gateway", "--read-only", + "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m", + "--user", f"{os.getuid()}:{os.getgid()}", + "-v", f"{artifact}:/sbh-artifact:ro", + # The workspace is mounted inside a writable parent, not directly + # under the read-only root, because a product that isolates a + # background session builds its worktree as a *sibling* of the + # repository. With no writable directory beside it that sibling cannot + # be created, the product silently falls back to the repository itself, + # and a point about isolation observes the write landing exactly where + # it asserted it would not. + "-v", f"{workspace.parent}:{_TREE}:rw", + # Without an explicit working directory the container starts in the + # image default, so a relative path in a declared tool call lands + # outside the mounted workspace: the write happens, the observer looks + # in the right place and finds nothing, and the point reports that the + # baseline write was never observed. + "-w", _WORKSPACE, + "-v", f"{home}:/sbh-home:rw", + "-v", f"{output}:/sbh-output:rw", + ] + container_env = { + "HOME": "/sbh-home", + "YUYAO_HOME": "/sbh-home/.yuyao", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONPATH": "/sbh-artifact/src" + (":/sbh-artifact" if argv and argv[0] == "--sbh-python" else ""), + "D2A_MODEL_BASE_URL": f"http://host.docker.internal:{port}/v1", + "D2A_MODEL_NAME": "litellm_proxy/mock", + "D2A_MODEL_API_KEY": "sk-mock-test", + } + # A recipe or probe may declare product settings of its own - retry limits, + # for instance - and those are not addressed to the model connection, so + # they are forwarded too. The container's own paths still win: forwarding the host + # HOME or YUYAO_HOME would point the product at directories it cannot see. + declared = { + key: value for key, value in env.items() + if (key.startswith("D2A_") or key.startswith("MSWEA_")) + and key not in container_env + } + for key, value in {**container_env, **declared}.items(): + command.extend(("-e", f"{key}={value}")) + # A formal-contract probe drives the launcher with its seven declared + # flags rather than the module CLI. The sentinel lets one call site build + # both without a second runner. + if argv and argv[0] == "--sbh-launcher": + command.extend((image, "bash", "/sbh-artifact/run_agent.sh")) + command.extend(argv[1:]) + elif argv and argv[0] == "--sbh-python": + # A listing probe drives the session API directly rather than the + # module CLI, so it runs as its own interpreter inside the same + # container: the counters it samples only mean something in the + # process that performs the listing. + command.extend((image, "python3", *argv[1:])) + else: + entry = "/sbh-artifact/src/yuyao/__main__.py" + if argv and argv[0] == "--sbh-script": + command.extend((image, "bash", "-lc", argv[1])) + else: + command.extend((image, "python3", entry)) + command.extend(argv) + return command + + +def _docker_run( + artifact: Path, + workspace: Path, + home: Path, + output: Path, + argv: list[str], + env: dict[str, str], + port: int, + timeout: int, +) -> tuple[subprocess.CompletedProcess[str], bool]: + command = _docker_command(artifact, workspace, home, output, argv, env, port) + try: + return subprocess.run(command, cwd=workspace, env=env, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=timeout, check=False), False + except subprocess.TimeoutExpired as exc: + return subprocess.CompletedProcess(command, -1, exc.stdout or "", exc.stderr or ""), True + + +def _run_one() -> dict[str, Any]: + from doc2harness.benchmark.definition import definition_digest + from doc2harness.benchmark.dispatch import load_scenario_owner + from doc2harness.benchmark.harnesses.headless.adapter import build_headless_execution_plan + from doc2harness.benchmark.harnesses.headless.contracts import ( + HeadlessObservation, ObservedFile, ProcessObservation, + ) + + scenario_id = os.environ["SBH_SCENARIO_ID"] + owner = load_scenario_owner(scenario_id) + if ".benchmark.harnesses.headless." not in owner.module: + raise RuntimeError("headless driver received a non-headless scenario") + scenario = owner.scenario + plan = build_headless_execution_plan(scenario) + artifact = Path(os.environ["SBH_ARTIFACT_PATH"]) + gateway = mock_gateway + server = gateway.ThreadingHTTPServer(("0.0.0.0", 0), gateway.Handler) + recipe = scenario.recipe + # A scenario that declares an appended system prompt but no explicit probe + # token is asserting that the appended text reaches the wire, so the append + # text *is* the probe. Without this fallback the gateway is told to look + # for nothing, every request records an empty system segment, and the judge + # reports the product as having dropped the flag. + probe_token = recipe.probe_token or getattr(recipe, "append_system_prompt", "") or "" + probe_tokens = list(recipe.probe_tokens) + if probe_token and probe_token not in probe_tokens: + probe_tokens.append(probe_token) + # A formal probe is answered by the declared fixed reply, not by the tool + # sequence the other headless points drive: its judge compares the exact + # reply text and a bounded request count, which a seq_probe round would + # replace with a tool call and a different exchange length. A CLI-file + # probe declares its own gateway mode and is left to it: the formal shape + # would replace its single fixed reply with a tool exchange and break the + # request count the point pins. + formal = bool( + getattr(recipe, "formal_contract_probes", ()) + or getattr(recipe, "formal_runtime_probes", ()) + or getattr(recipe, "listing_probes", ()) + ) + cfg = gateway.new_cfg( + mode="seq_probe" if formal else recipe.gateway_mode, + reply_content=recipe.reply_content, + probe_token=probe_token, + probe_tokens=probe_tokens, + command=recipe.command or "echo HEADLESS_PROOF_7731", + # A verbose-route point names each model turn with its own token, so the + # gateway is told which text to attach to the tool-call turn and which + # to the reply. The first and last declared probe tokens are those two + # turns by construction. + turn_contents=( + None + ), + # The gateway hands out one declared round per request and the rounds + # are shared across every variant in the run, so a formal point needs + # its two-request exchange repeated once per probe - otherwise the + # first probe consumes the sequence and the rest see an empty turn. + rounds=( + _formal_rounds(recipe) + if formal + # The gateway serves one declared round per request and the same + # sequence covers every variant in the run, so a point that runs + # several variants needs its rounds repeated once per variant - + # otherwise the first variant consumes them and the rest observe an + # exchange the recipe never described. Each repetition also needs + # its own closing turn: a variant's exchange does not end until the + # model answers without a tool call, so without one the first + # variant runs on into the next variant's round and the second is + # handed the leftover reply instead of its own call. + else (_rounds( + recipe, f"host.docker.internal:{int(server.server_address[1])}" + ) + [[{"name": "__finish__", "content": recipe.reply_content or "done"}]] + ) * max(1, len(_argv_variants(recipe))) + ), + ) + server.cfg = cfg + server.daemon_threads = True + server.block_on_close = False + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + with tempfile.TemporaryDirectory(prefix="sbh-headless-production-") as temporary: + root = Path(temporary) + home, workspace, output = root / "home", root / "tree" / "workspace", root / "out" + # The workspace sits inside a directory of its own so the container can + # mount that directory writable: a product isolating a background + # session builds its worktree beside the repository, and it needs + # somewhere to put it. Only this tree is mounted, so home and output + # stay where they are and are not exposed twice. + workspace.parent.mkdir(parents=True) + home.mkdir(); workspace.mkdir(); output.mkdir() + for seed in recipe.seed_files: + path = workspace / seed.path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(seed.content, encoding="utf-8") + # A worktree point is about a git operation not disturbing its parent + # repository, so the workspace has to be one. Without it the point can + # only report that the fixture was unavailable. + if any(variant.label == "wt" for variant in ((recipe.cli_variants or ()) + (recipe.file_variants or ()))): + identity = ("-c", "user.email=fixture@example.invalid", "-c", "user.name=SBH Fixture") + for arguments in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "baseline", "--allow-empty")): + subprocess.run( + ("git", *identity, *arguments), cwd=workspace, check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + env = dict(os.environ) + env.update(dict(recipe.environment)) + env.update({"HOME": str(home), "YUYAO_HOME": str(home / ".yuyao"), + "PYTHONDONTWRITEBYTECODE": "1"}) + runs: list[ProcessObservation] = [] + # A listing point is decided by facts about the product's own process - + # bytes read, resident growth, opens under HOME - sampled around the + # listing dispatch. Each probe gets its own HOME so the corpus one + # seeds is not counted against the other, and each is seeded and + # measured by separate children so the measurement does not read the + # writing that produced the corpus. + listing_probes = tuple(getattr(recipe, "listing_probes", ()) or ()) + # A compact/rewind point is about session management across a + # compaction, which only exists inside a live session: the checkpoint + # the product offers, whether the pre-compact turn is still named, and + # the listing's own selection syntax. + session_facts: dict[str, Any] = {} + for probe in listing_probes: + probe_home = root / f"home-{probe.label}" + probe_workspace = root / f"tree-{probe.label}" / "workspace" + probe_home.mkdir(exist_ok=True) + probe_workspace.mkdir(parents=True, exist_ok=True) + probe_env = dict(env) + probe_env.update({"HOME": str(probe_home), "YUYAO_HOME": str(probe_home / ".yuyao")}) + cfg["mode"] = "fixed_reply" + cfg["reply_content"] = _listing_payload(probe.payload_bytes) + script = probe_workspace / "sbh_listing_probe.py" + row: dict[str, Any] = { + "seed_created": 0, "listed_markers": None, "rchar_delta": None, + "rss_delta_kib": None, "home_open_count": None, "output_bytes": None, + "product_error": "", "start_error": "", "timed_out": False, + } + + def run_phase(phase: str, timeout: int) -> tuple[dict[str, Any] | None, str]: + script.write_text( + _listing_probe_script(phase, probe.count, probe.payload_bytes), + encoding="utf-8", + ) + completed, expired = _docker_run( + artifact, probe_workspace, probe_home, output, + ["--sbh-python", f"{_WORKSPACE}/sbh_listing_probe.py"], + probe_env, int(server.server_address[1]), timeout, + ) + if expired: + return None, "TIMEOUT" + parsed = _listing_result(completed) + if parsed is None: + tail = (completed.stderr or completed.stdout or "")[-160:] + return None, f"NO_RESULT_RC_{completed.returncode}:{tail}" + return parsed, "" + + seeded, seed_error = run_phase("seed", int(recipe.seed_timeout_seconds or 120)) + if seed_error == "TIMEOUT": + row["timed_out"] = True + elif seed_error: + row["start_error"] = f"SEED_{seed_error}" + elif seeded is not None: + row["seed_created"] = int(seeded.get("created") or 0) + row["product_error"] = str(seeded.get("product_error") or "") + if seeded.get("reset_ok") is not True and not row["product_error"]: + row["product_error"] = "public /new did not reset messages" + if not row["start_error"] and not row["timed_out"]: + measured, measure_error = run_phase( + "measure", int(recipe.measurement_timeout_seconds or 60) + ) + if measure_error == "TIMEOUT": + row["timed_out"] = True + elif measure_error: + row["start_error"] = f"MEASURE_{measure_error}" + elif measured is not None: + for key in ("listed_markers", "rchar_delta", "rss_delta_kib", + "home_open_count", "output_bytes"): + row[key] = measured.get(key) + later = str(measured.get("product_error") or "") + if later: + row["product_error"] = ( + f"{row['product_error']}; {later}" if row["product_error"] else later + ) + runs.append(ProcessObservation( + label=probe.label, + rc=0 if not row["start_error"] else -1, + timed_out=bool(row["timed_out"]), + start_error=str(row["start_error"]), + cleanup_complete=not row["timed_out"], + count=probe.count, + payload_bytes=probe.payload_bytes, + seed_created=row["seed_created"], + listed_markers=row["listed_markers"], + rchar_delta=row["rchar_delta"], + rss_delta_kib=row["rss_delta_kib"], + home_open_count=row["home_open_count"], + output_bytes=row["output_bytes"], + product_error=str(row["product_error"]), + )) + # A formal-contract or runtime-matrix point is specified over launcher + # invocations with declared task/budget documents, not over the module + # CLI flags the other points use. + variants = [] if listing_probes or runs else ( + _cli_file_variants(recipe, workspace) + or _formal_probe_variants(recipe, workspace, output, int(server.server_address[1])) + or _argv_variants(recipe) + ) + agent_session_id = "" + # A sequence whose recipe declares a settle window is about work that + # outlives the command that started it. Run as separate containers, + # that work would be reaped when its step exits, and the step that lists + # or stops the session would find one that had already finished. The + # whole sequence therefore runs in one container: the session stays + # alive across the steps that are about it. + sequence_pause = min(int(recipe.sequence_pause_seconds or 0), 30) + if sequence_pause and variants: + steps = [list(argv) for _, argv in variants] + # A point that acts on a session started by an earlier step needs + # that session to still be running when it does. The observer + # answers instantly, so the session finishes first and "stopped a + # dead session" reads exactly like "stopped a live one". Holding + # each answer for the declared settle window keeps it alive across + # the steps that are about it. + if len(steps) > 2: + cfg["response_delay_s"] = sequence_pause * len(steps) + script = _sequence_script(steps, sequence_pause) + before = _snapshot(workspace) + request_start = len(cfg.get("requests", [])) + completed, timed_out = _docker_run( + artifact, workspace, home, output, ["--sbh-script", script], env, + int(server.server_address[1]), + min(recipe.timeout_seconds, 300) + sequence_pause * len(steps), + ) + blob = str(completed.stdout or "") + "\n" + str(completed.stderr or "") + found = re.search( + r"dispatched\s+(?:background\s+session\s+)?([A-Za-z0-9_-]+)", blob, re.I + ) + if found: + agent_session_id = found.group(1) + after = _snapshot(workspace) + written = tuple(sorted(k for k in after if before.get(k) != after.get(k))) + removed = tuple(sorted(k for k in before if k not in after)) + records = _request_records( + list(cfg.get("requests", []))[request_start:], probe_token + ) + outputs = _sequence_steps(str(completed.stdout or ""), len(steps)) + for (label, _), (text, code) in zip(variants, outputs): + runs.append(ProcessObservation( + label=label, + rc=code, + stdout=text, + timed_out=timed_out, + requests=records, + written_paths=written, + removed_paths=removed, + exit_status=str(_status(output).get("exit_status") or ""), + cleanup_complete=not timed_out, + git_initialized=(workspace / ".git").is_dir(), + )) + variants = [] + for label, argv in variants: + # A probe may name the protocol failure it is about and the + # environment it needs - an upstream 401 with retries pinned to one + # attempt, say. Both are declared per probe, not per recipe; the + # recipe-level mode alone would exercise the healthy exchange and + # judge error reporting on a run where no error occurred. + declared = _probe_by_label(recipe, label) + probe_mode = str(getattr(declared, "gateway_mode", "") or "") + probe_env = dict(getattr(declared, "environment", ()) or ()) + cfg["mode"] = probe_mode or ("seq_probe" if formal else recipe.gateway_mode) + variant_env = {**env, **probe_env} + # Variants are contrasted against each other - a permitted run + # against a restricted one - so each has to start from the + # declared fixture. Carrying the previous variant's write over + # makes the restricted run look like it performed a write it was + # actually prevented from performing. + for seed in recipe.seed_files: + path = workspace / seed.path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(seed.content, encoding="utf-8") + request_start = len(cfg.get("requests", [])) + # The gets a variant made are sliced the same way its requests are: + # the two flags share one observer, so an unsliced read would + # attribute the permitted variant's fetch to the restricted one and + # the point would report a leak that never happened. + web_start = len(cfg.get("web_gets", [])) + before = _snapshot(workspace) + # A step that acts on a session started by an earlier step has to + # name that session, and its identifier only exists once the + # dispatch has run. The recipe writes the placeholder and it is + # resolved from what the dispatch reported; left unresolved the + # command is handed a literal "$AGENT_SESSION_ID" and stops the + # session the point is about being unable to name. + if agent_session_id: + argv = [item.replace("$AGENT_SESSION_ID", agent_session_id) for item in argv] + completed, timed_out = _docker_run( + artifact, workspace, home, output, argv, variant_env, + int(server.server_address[1]), min(recipe.timeout_seconds, 300), + ) + if not agent_session_id: + blob = str(completed.stdout or "") + "\n" + str(completed.stderr or "") + found = re.search( + r"dispatched\s+(?:background\s+session\s+)?([A-Za-z0-9_-]+)", blob, re.I + ) or re.search( + r"(?m)^\s*([A-Za-z0-9_-]{6,})\s+" + r"(?:running|waiting|completed|stopped|failed)\b", + blob, re.I, + ) + if found: + agent_session_id = found.group(1) + after = _snapshot(workspace) + written = tuple(sorted(k for k in after if before.get(k) != after.get(k))) + removed = tuple(sorted(k for k in before if k not in after)) + target = workspace / recipe.target_file if recipe.target_file else None + target_content = target.read_text(encoding="utf-8", errors="replace") if target and target.is_file() else "" + # An isolation point also has to see the checkout beside the + # repository, which the workspace read cannot reach. + worktree_paths, worktree_content, worktree_found = ( + _worktree_facts(workspace, home, recipe.target_file, recipe.target_written) + if (workspace / ".git").is_dir() and recipe.target_file + else ((), "", "") + ) + status = _status(output) + records = _request_records( + list(cfg.get("requests", []))[request_start:], probe_token + ) + runs.append(ProcessObservation( + label=label, + rc=int(completed.returncode), + stdout=str(completed.stdout or ""), + stderr=str(completed.stderr or ""), + timed_out=timed_out, + requests=records, + written_paths=written, + removed_paths=removed, + target_content=target_content, + worktree_paths=worktree_paths, + worktree_target_content=worktree_content, + marker_found_at=worktree_found, + web_gets=tuple( + str(item.get("path") or "") + for item in list(cfg.get("web_gets", []))[web_start:] + ), + # A point can require that a route write *no* status document - + # a user-facing CLI flag is not the unattended contract and + # deliberately reports no terminal state. Publishing an empty + # string for that made "absent" indistinguishable from "present + # but blank", so the absence is named. + exit_status=str(status.get("exit_status") or ("" if status else "MISSING")), + cleanup_complete=not timed_out, + out_created=bool(status), + repo_changed=bool(written or removed), + git_initialized=(workspace / ".git").is_dir(), + product_error=str(status.get("error") or ""), + )) + observed_files = tuple( + ObservedFile(path, (workspace / path).read_text(encoding="utf-8", errors="replace")) + for path in sorted({item.path for item in recipe.seed_files}) + if (workspace / path).is_file() + ) + # Some points inspect what the artifact itself ships rather than what + # the run produced - the README is the delivered document, not a seeded + # fixture, so reading only the workspace leaves the judge with nothing + # to inspect and it reports the file as missing. + for shipped in ("README.md",): + path = artifact / shipped + if path.is_file(): + observed_files += ( + ObservedFile(shipped, path.read_text(encoding="utf-8", errors="replace")), + ) + observation = HeadlessObservation( + scenario_id=scenario_id, + profile=recipe.profile, + plan_digest=plan.plan_digest, + artifact_id=os.environ["SBH_ARTIFACT_ID"], + artifact_digest=os.environ["SBH_ARTIFACT_DIGEST"], + backend_evidence_digest=_digest({"scenario_id": scenario_id, "runs": [asdict(item) for item in runs]}), + cli_available=(artifact / "src/yuyao/__main__.py").is_file(), + runs=tuple(runs), + artifact_files=observed_files, + repository_root=_WORKSPACE, + # The identifier the dispatch reported. A point that asks whether + # stopping a session takes effect has to know which session it + # stopped, and only the dispatch output carries that. + agent_session_id=agent_session_id, + session_start_error=str(session_facts.get("start_error") or ""), + checkpoint_id=str(session_facts.get("checkpoint_id") or ""), + pre_listing=str(session_facts.get("pre_listing") or ""), + selection_command=str(session_facts.get("selection_command") or ""), + selection_result=str(session_facts.get("selection_result") or ""), + driver_error="" if runs else "HEADLESS_NO_RUN", + process_tree_clean=all(not item.timed_out for item in runs), + workspace_clean=True, + ) + server.shutdown(); server.server_close(); thread.join(timeout=2) + judgement = owner.judge(observation) + return {"observation": observation, "judgement": judgement, + "module": owner.module, "definition_digest": definition_digest(owner.definition)} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + result = _run_one() + Path(os.environ["SBH_TYPED_EVENT_PATH"]).write_text(json.dumps({ + "schema": "doc2harness.typed-events/1", "source_digest": os.environ["SBH_SOURCE_DIGEST"], + "task_digest": os.environ["SBH_TASK_DIGEST"], "budget_digest": os.environ["SBH_BUDGET_DIGEST"], + "artifact_digest": os.environ["SBH_ARTIFACT_DIGEST"], "artifact_id": os.environ["SBH_ARTIFACT_ID"], + "scenario_id": os.environ["SBH_SCENARIO_ID"], "scenario_module": result["module"], + "definition_digest": result["definition_digest"], + "events": [{"type": "headless-observation", "observation": asdict(result["observation"]), + "judgement": asdict(result["judgement"])}], + }, ensure_ascii=False, default=lambda value: value.value if hasattr(value, "value") else str(value), indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/code/src/doc2harness/runtime/mock_gateway.py b/code/src/doc2harness/runtime/mock_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..a0aaa37070b27e11f3947aa97b12a06db53d3b97 --- /dev/null +++ b/code/src/doc2harness/runtime/mock_gateway.py @@ -0,0 +1,1448 @@ +"""A deterministic OpenAI-compatible model gateway for fault injection. + +Point an artifact's ``D2A_MODEL_BASE_URL`` at this server and it stands in for +the model, answering every request deterministically and spending no real model +budget. By default it drives the agent through one observable tool call; the +selected mode injects a specific real-world fault instead - absent ``usage``, +missing response fields, malformed tool-call arguments, prose with no tool call, +and so on. Those are the conditions a live model reproduces only by luck, and +an evaluation that cannot reproduce them cannot measure how a product handles +them. + +Every received request is recorded - message count, embedded NUL bytes, the +Authorization header, the model name, the wire-level message roles - so a +scenario can assert against what the product actually sent rather than against +prose describing it. + +``litellm`` (``litellm_proxy/``) POSTs to ``{api_base}/chat/completions``, +so any POST whose path ends in ``chat/completions`` is answered. GET always +returns an empty object, which keeps an incidental ``/models`` probe happy. + +Runs standalone (``python -m doc2harness.runtime.mock_gateway --port 9009 +--mode usage_null``) or in-process: build an isolated configuration with +``new_cfg()``, serve it with ``make_server()``, and read ``cfg["requests"]`` +afterwards. Each server owns its configuration, so concurrent scenarios do not +interfere. + +This module deliberately depends on nothing outside the standard library: it is +the stimulus source for every driver in this package, and a driver that could +only reach its gateway through a private checkout would leave the published +distribution unable to execute a single scenario. +""" + +from __future__ import annotations +import argparse +import hashlib +import json +import os +import re +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +CONFIG: dict = { + "mode": os.environ.get("MOCK_MODE", "normal"), + "command": os.environ.get("MOCK_COMMAND", "echo MOCK_PROOF_7731 > mock_proof.txt"), + "usage_tokens": (12, 8), + "reject_substr": "", + "strict": False, + "requests": [], +} + + +def new_cfg(**over) -> dict: + """Build an isolated cfg so concurrent servers never share state.""" + c = { + "mode": "normal", + "command": "echo MOCK_PROOF_7731 > mock_proof.txt", + "usage_tokens": (12, 8), + "reject_substr": "", + "strict": False, + "allow_cmd": "echo PERM_LIVE_7755 > live.txt", + "deny_cmd": "touch PERM_DENY_7755.txt", + "probe2_cmd": "", + "probe_tool": "bash", + "probe_args": None, + "err_before": 2, + "err_status": 429, + "rounds": None, + "rounds_base": 0, + "probe_token": "", + "probe_tokens": [], + "target_command": "", + "target_left": "", + "target_right": "", + "structured_prompt_token": "", + "structured_prompt_end": "", + "structured_prompt_expected": "", + "structured_prompt_fragment": "", + "reply_content": "", + "web_gets": [], + "requests": [], + } + c.update(over) + return c + + +_USTR_RE = re.compile("\\\\u([0-9a-fA-F]{4})") + + +def _has_lone_surrogate(text: str) -> bool: + """True when the JSON text contains an unpaired surrogate escape. + + A legal emoji is a high+low pair (``\\ud83d\\ude00``). Real gateways reject + lone surrogates with a 400, so a correct agent sanitises before sending. + """ + toks = [(m.start(), int(m.group(1), 16)) for m in _USTR_RE.finditer(text)] + n, i = (len(toks), 0) + while i < n: + pos, v = toks[i] + if 55296 <= v <= 56319: + if i + 1 < n: + npos, nv = toks[i + 1] + if npos == pos + 6 and 56320 <= nv <= 57343: + i += 2 + continue + return True + if 56320 <= v <= 57343: + return True + i += 1 + return False + + +def _tool_names(req: dict) -> list: + """Function names from the request's ``tools`` array; empty on anything odd.""" + out = [] + for t in req.get("tools") or []: + if not isinstance(t, dict): + continue + fn = t.get("function") if isinstance(t.get("function"), dict) else None + name = (fn or {}).get("name") if fn else t.get("name") + if name: + out.append(str(name)) + return out + + +_PARAM_SYNONYMS = [ + ( + "path", + "file_path", + "filepath", + "filePath", + "filename", + "file", + "target", + "target_file", + "fname", + "file_name", + "notebook_path", + ), + ( + "content", + "contents", + "text", + "data", + "body", + "new_content", + "file_text", + "file_content", + "source", + "new_source", + ), + ("old_string", "oldString", "old", "old_str", "search", "find", "from", "old_text"), + ("new_string", "newString", "new", "new_str", "replace", "replacement", "to", "new_text"), + ("replace_all", "replaceAll"), + ("cell_index", "cell_number", "cell"), + ("mode", "edit_mode"), + ("background", "run_in_background", "run_background", "is_background", "bg"), + ("job_id", "id", "job", "bg_id", "process_id"), + ("url", "uri", "href", "link"), + ("agent", "name", "subagent", "agent_name", "profile", "subagent_type"), +] +_TOOL_NAME_SYNONYMS = [ + {"write", "write_file", "create_file", "file_write", "writefile", "put_file", "save_file"}, + {"read", "read_file", "file_read", "readfile", "cat", "view_file", "open_file"}, + {"edit", "edit_file", "str_replace", "replace_in_file", "apply_edit", "modify_file"}, + {"multi_edit", "multi-edit", "multiedit", "batch_edit", "edit_many"}, + {"bash", "shell", "run_command", "execute", "exec", "terminal"}, + {"glob", "find_files", "list_files", "file_search"}, + {"grep", "search", "ripgrep", "search_files", "grep_search"}, + {"bg_list", "bg-list", "bglist"}, + {"bg_output", "bg-output", "bgoutput"}, + {"bg_stop", "bg-stop", "bgstop"}, + {"web_fetch", "web-fetch", "webfetch", "WebFetch"}, + {"web_search", "web-search", "websearch", "WebSearch"}, +] +_CANON = { + "bash", + "read", + "write", + "edit", + "multi_edit", + "apply_patch", + "grep", + "glob", + "web_fetch", + "web_search", + "browser", + "read_media", + "lsp", + "notebook_edit", + "monitor", + "todo", + "task", + "bg_list", + "bg_output", + "bg_stop", + "memory_search", + "memory_get", + "ask_user", + "submit", +} +_TOOL_ALIASES = { + "shell": "bash", + "run_command": "bash", + "run_shell": "bash", + "execute_command": "bash", + "terminal": "bash", + "exec": "bash", + "execute": "bash", + "cat": "read", + "view_file": "read", + "open_file": "read", + "file_read": "read", + "create_file": "write", + "file_write": "write", + "put_file": "write", + "save_file": "write", + "new_file": "write", + "str_replace": "edit", + "str_replace_editor": "edit", + "replace_in_file": "edit", + "apply_edit": "edit", + "modify_file": "edit", + "search_replace": "edit", + "batch_edit": "multi_edit", + "edit_many": "multi_edit", + "multiedit": "multi_edit", + "ripgrep": "grep", + "rg": "grep", + "grep_search": "grep", + "content_search": "grep", + "search_files": "grep", + "find_files": "glob", + "list_files": "glob", + "file_glob": "glob", + "file_search": "glob", + "patch": "apply_patch", + "apply_diff": "apply_patch", + "todos": "todo", + "todo_add": "todo", + "todo_update": "todo", + "todo_write": "todo", + "todo_list": "todo", + "task_list": "todo", + "tasks": "todo", + "subagent": "task", + "spawn_agent": "task", + "task_subagent": "task", +} +_TOOL_STRIP_SUFFIX = ("_file", "_files", "_tool", "_cmd", "_command", "_op") +_TOOL_STRIP_PREFIX = ("tool_", "fn_", "do_", "builtin_") +_BRAND = "yuyao" + + +def _mech_norm(name: str) -> str: + """Lower-case, unify separators, fold repeated underscores, trim edges.""" + s = str(name).strip().lower() + for ch in ("-", ".", " ", "/", ":"): + s = s.replace(ch, "_") + while "__" in s: + s = s.replace("__", "_") + return s.strip("_") + + +def canon_tool(name: str) -> str | None: + """Map an advertised tool name to its canonical capability, or None. + + Returning None means "cannot tell" - the name is never guessed. + Normalisation resolves the wire tool names products use in practice without + merging distinct capabilities: names such as read_only, edit_config, + write_log, grep_history, globals, grepper, no_op, edit_distance and ls stay + unmapped. + """ + if not name or not isinstance(name, str): + return None + s = _mech_norm(name) + if s in _CANON: + return s + b = _mech_norm(_BRAND) + if s.startswith(f"{b}_"): + t = s[len(b) + 1 :] + if t in _CANON: + return t + if t in _TOOL_ALIASES: + return _TOOL_ALIASES[t] + for suf in _TOOL_STRIP_SUFFIX: + if t.endswith(suf) and t[: -len(suf)] in _CANON: + return t[: -len(suf)] + if s in _TOOL_ALIASES: + return _TOOL_ALIASES[s] + for suf in _TOOL_STRIP_SUFFIX: + if s.endswith(suf): + t = s[: -len(suf)] + if t in _CANON: + return t + if t in _TOOL_ALIASES: + return _TOOL_ALIASES[t] + for pre in _TOOL_STRIP_PREFIX: + if s.startswith(pre): + t = s[len(pre) :] + if t in _CANON: + return t + if t in _TOOL_ALIASES: + return _TOOL_ALIASES[t] + return None + + +def adv_has_tool(adv, wanted) -> bool: + """Judge-side entry point: does advertised list ``adv`` carry capability ``wanted``? + + ``wanted`` is a name or a sequence of names (any hit counts). Both sides go + through ``canon_tool``, so ``yuyao_edit`` / ``edit_file`` / ``multi-edit`` + are not mistaken for "not exposed". Names that do not normalise + (including ambiguous ones) count as no match - better inconclusive than a + false PASS. + """ + wants = [wanted] if isinstance(wanted, str) else list(wanted or ()) + want_caps = {c for c in (canon_tool(w) for w in wants) if c} + if not want_caps: + return False + adv_caps = {c for c in (canon_tool(a) for a in adv or ()) if c} + return bool(want_caps & adv_caps) + + +def _content_as_text(c) -> str: + if isinstance(c, str): + return c + if isinstance(c, list): + parts = [p.get("text", "") for p in c if isinstance(p, dict) and isinstance(p.get("text"), str)] + return "\n".join(parts) + return "" + + +def _structured_prompt_facts(req: dict, token: str, end_sentinel: str, expected: str, fragment: str) -> dict: + """Observe the bounded task span in the first user message, never its wrapper.""" + messages = req.get("messages") or [] + first_user = next((m for m in messages if isinstance(m, dict) and m.get("role") == "user"), {}) + text = _content_as_text(first_user.get("content")) + non_user_blob = "\n".join( + ( + _content_as_text(m.get("content")) + for m in messages + if isinstance(m, dict) and m.get("role") != "user" + ) + ) + starts = [match.start() for match in re.finditer(re.escape(token), text)] if token else [] + spans = [] + for start in starts: + end = text.find(end_sentinel, start + len(token)) if end_sentinel else -1 + if end >= 0: + spans.append(text[start : end + len(end_sentinel)]) + one_span = spans[0] if len(spans) == 1 else "" + if not one_span: + wrapper_category = "unbounded" + else: + start = text.find(one_span) + has_prefix = start > 0 + has_suffix = start + len(one_span) < len(text) + wrapper_category = ( + "prefix-and-suffix" + if has_prefix and has_suffix + else "prefix" if has_prefix else "suffix" if has_suffix else "none" + ) + return { + "first_user_role": first_user.get("role"), + "task_span_count": len(spans), + "task_span_chars": len(one_span), + "task_span_sha256": hashlib.sha256(one_span.encode()).hexdigest() if one_span else "", + "task_span_matches_expected": bool(one_span) and one_span == expected, + "wrapper_category": wrapper_category, + "complete_token": token if token and token in text else "", + "structured_fragment_seen": bool(fragment) and fragment in text, + "token_only_outside_user": bool(token) and token not in text and (token in non_user_blob), + } + + +def _latest_tool_batch(req: dict) -> list: + """Return only the most recent round of tool-result texts. + + The standard OpenAI order is ``assistant(tool_calls) -> tool -> ...``. Some + builds omit the preceding assistant and emit ``tool -> assistant(next + tool_calls)``; recognising only "tool after assistant" would skip that whole + batch, so both orders are accepted. + """ + msgs = req.get("messages") or [] + last_tc = None + for i, m in enumerate(msgs): + if isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls"): + last_tc = i + if last_tc is not None: + out = [] + for m in msgs[last_tc + 1 :]: + if not isinstance(m, dict) or m.get("role") != "tool": + break + t = _content_as_text(m.get("content")) + if t: + out.append(t) + if out: + return out + last_asst = None + for i, m in enumerate(msgs): + if isinstance(m, dict) and m.get("role") == "assistant": + last_asst = i + if last_asst is None: + return [] + batch = [] + j = last_asst - 1 + while j >= 0 and isinstance(msgs[j], dict) and (msgs[j].get("role") == "tool"): + t = _content_as_text(msgs[j].get("content")) + if t: + batch.append(t) + j -= 1 + batch.reverse() + return batch + + +def _target_exchange_facts(req: dict, command: str, left: str, right: str) -> dict: + """Bind one configured bash call to its matching tool result.""" + facts = { + "target_call_seen": False, + "target_result_seen": False, + "target_result_has_left": False, + "target_result_has_right": False, + } + if not command: + return facts + messages = req.get("messages") or [] + for index, message in enumerate(messages): + if not isinstance(message, dict) or message.get("role") != "assistant": + continue + for call in message.get("tool_calls") or []: + if not isinstance(call, dict): + continue + function = call.get("function") or {} + if not isinstance(function, dict) or function.get("name") != "bash": + continue + try: + arguments = function.get("arguments") or "{}" + args = arguments if isinstance(arguments, dict) else json.loads(arguments) + except Exception: + continue + if args.get("command") != command: + continue + facts["target_call_seen"] = True + call_id = call.get("id") + for result in messages[index + 1 :]: + if not isinstance(result, dict): + continue + if result.get("role") == "assistant": + break + if result.get("role") != "tool": + continue + if call_id and result.get("tool_call_id") != call_id: + continue + text = _content_as_text(result.get("content")) + facts.update( + { + "target_result_seen": True, + "target_result_has_left": bool(left) and left in text, + "target_result_has_right": bool(right) and right in text, + } + ) + return facts + return facts + + +_BG_ID_BLOCKLIST = { + "bg-list", + "bg_list", + "bglist", + "bg-output", + "bg_output", + "bgoutput", + "bg-stop", + "bg_stop", + "bgstop", +} + + +def _extract_bg_job_id(texts) -> str | None: + """Pull a background job id out of earlier tool-result text. + + The id shape varies by build (``bg-XXXX``, a bare number, ``[n]``). The + patterns must stay tight: too loose and the plural "s" in ``no jobs`` or a + tool name like ``bg-output`` gets mistaken for an id. + """ + blob = "\n".join(texts or []) + if not blob.strip(): + return None + if re.search( + "(?i)\\bno\\s+(?:\\w+\\s+){0,2}(?:background\\s+)?(?:jobs?|processes|tasks)\\b", blob + ) or re.search("(?i)\\((?:none|empty)\\)", blob): + return None + m = re.search("\\b(?:job|process)\\s+#(\\d+)\\b", blob, re.I) + if m: + return m.group(1) + m = re.search( + "(?:started\\s+)?background\\s+(?:job|process|task)s?\\s*[#:]?\\s*([A-Za-z0-9_-]+)\\b", blob, re.I + ) + if ( + m + and m.group(1).lower() not in _BG_ID_BLOCKLIST + and (m.group(1).lower() not in {"id", "job", "process", "task"}) + ): + return m.group(1) + m = re.search("\\b(bg[-_][A-Za-z0-9][A-Za-z0-9_-]*)\\b", blob) + if m and m.group(1).lower() not in _BG_ID_BLOCKLIST: + return m.group(1) + m = re.search("\\bjob(?:_id|\\s+id)\\s*[:=]\\s*([A-Za-z0-9_-]+)\\b", blob, re.I) + if m: + return m.group(1) + m = re.search("(?m)^\\s*#([A-Za-z0-9_-]+)\\b", blob) + if m and m.group(1).lower() not in _BG_ID_BLOCKLIST: + return m.group(1) + m = re.search("\\[(\\d+)\\]", blob) + if m: + return m.group(1) + return None + + +def _subst_bg_placeholders(value, job_id: str | None): + """Replace ``$BG_JOB_ID`` with the id extracted from the last tool result. + + A numeric id becomes an int where an integer is expected. + """ + if isinstance(value, dict): + return {k: _subst_bg_placeholders(v, job_id) for k, v in value.items()} + if isinstance(value, list): + return [_subst_bg_placeholders(v, job_id) for v in value] + if not isinstance(value, str) or "$BG_JOB_ID" not in value: + return value + if not job_id: + return value + if value == "$BG_JOB_ID" and job_id.isdigit(): + return int(job_id) + return value.replace("$BG_JOB_ID", job_id) + + +def _resolve_tool_name(req: dict, wanted: str) -> str: + """Map the tool a probe wants onto the name the build actually advertises. + + Build-agnostic. A stub sending a fixed ``write`` never executes against a + build advertising ``write_file``: the call name does not match, the tool + never runs, and it looks like "the stub's write did not land" -- the + harness's call being wrong, not the product missing a write tool. + + Same shape as the argument mapping: (1) ``wanted`` is already advertised, use + it; (2) otherwise substitute a synonym the build does advertise; (3) no match + or no tool list, keep the original name rather than inventing one. + """ + names = set() + for t in req.get("tools") or []: + if not isinstance(t, dict): + continue + fn = t.get("function") if isinstance(t.get("function"), dict) else t + if isinstance(fn, dict) and isinstance(fn.get("name"), str): + names.add(fn["name"]) + if not names or wanted in names: + return wanted + for grp in _TOOL_NAME_SYNONYMS: + if wanted in grp: + for cand in grp: + if cand in names: + return cand + break + want_cap = canon_tool(wanted) + if want_cap: + for cand in sorted(names): + if canon_tool(cand) == want_cap: + return cand + return wanted + + +def _tool_schema_props(req: dict, tool_name: str) -> set: + """Argument names this request's schema declares for one function tool.""" + for t in req.get("tools") or []: + if not isinstance(t, dict): + continue + fn = t.get("function") if isinstance(t.get("function"), dict) else t + if not isinstance(fn, dict) or fn.get("name") != tool_name: + continue + props = (fn.get("parameters") or {}).get("properties") or {} + if isinstance(props, dict): + return set(props.keys()) + return set() + + +def _map_args_to_schema(req: dict, tool_name: str, pargs: dict) -> dict: + """Map probe argument names onto the schema names the build advertises. + + Build-agnostic: (1) the name is already in the schema, keep it; (2) otherwise + substitute a synonym the schema does declare; (3) no synonym or no schema, + keep the original. A build using ``path`` and one using ``file_path`` are + both driven correctly. + """ + props = _tool_schema_props(req, tool_name) + if not props or not isinstance(pargs, dict): + return dict(pargs or {}) + out = {} + for k, v in pargs.items(): + target = k + if k in props: + target = k + else: + for grp in _PARAM_SYNONYMS: + if k in grp: + for cand in grp: + if cand in props: + target = cand + break + break + if target in out: + raise ValueError( + f"ambiguous probe arguments: multiple keys map to advertised parameter {target!r}" + ) + out[target] = v + return out + + +def _tool_result_max_bytes(req: dict) -> int: + """Largest UTF-8 size of any single role=tool content in this request. + + Supports the "large tool output stays bounded on the wire" assertion: a huge + result must be truncated or offloaded before being sent, so what goes out + should be far smaller than the original. Covers both OpenAI string content + and Anthropic list-of-parts text blocks. + """ + mx = 0 + for m in req.get("messages") or []: + if not isinstance(m, dict) or m.get("role") != "tool": + continue + c = m.get("content") + if isinstance(c, str): + mx = max(mx, len(c.encode("utf-8", "replace"))) + elif isinstance(c, list): + for part in c: + if isinstance(part, dict) and isinstance(part.get("text"), str): + mx = max(mx, len(part["text"].encode("utf-8", "replace"))) + return mx + + +def _is_empty_content(c) -> bool: + """True when content is empty or whitespace-only (a wire violation). + + ``content=None`` is legal on a tool-call-only turn and does not count. + Covers OpenAI string content and Anthropic-style empty text parts. + """ + if c is None: + return False + if isinstance(c, str): + return c.strip() == "" + if isinstance(c, list): + for part in c: + if isinstance(part, dict) and part.get("type") == "text": + t = part.get("text") + if isinstance(t, str) and t.strip() == "": + return True + return False + + +_VOLATILE_RX = ( + (re.compile("\\d{4}-\\d{2}-\\d{2}([ T]\\d{2}:\\d{2}(:\\d{2})?)?"), ""), + (re.compile("\\b\\d{2}:\\d{2}(:\\d{2})?\\b"), "