YuyaoGe commited on
Commit
f4533f6
·
verified ·
1 Parent(s): 2ef5cbd

Add full evaluation code (GitHub 5411f53) and run instructions

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +47 -4
  2. code/.d2a_spec/typed_event_hooks.json +7 -0
  3. code/.github/workflows/quality.yml +133 -0
  4. code/.gitignore +12 -0
  5. code/LICENSE +160 -0
  6. code/MANIFEST.in +12 -0
  7. code/NOTICE +45 -0
  8. code/README.md +177 -0
  9. code/assets/leaderboard.png +3 -0
  10. code/assets/logo.png +3 -0
  11. code/assets/pipeline.png +3 -0
  12. code/containers/Dockerfile +53 -0
  13. code/containers/README.md +46 -0
  14. code/containers/requirements/runtime.lock +74 -0
  15. code/pyproject.toml +31 -0
  16. code/requirements/build-tools.txt +17 -0
  17. code/requirements/run.txt +1 -0
  18. code/run/README.md +34 -0
  19. code/run/configs/example-94.yaml +29 -0
  20. code/run/configs/project.yaml +19 -0
  21. code/run/run_94_example.sh +17 -0
  22. code/run/run_config.py +262 -0
  23. code/run/run_from_config.sh +26 -0
  24. code/run/run_production_executor.py +112 -0
  25. code/src/doc2harness/__init__.py +1 -0
  26. code/src/doc2harness/benchmark/__init__.py +57 -0
  27. code/src/doc2harness/benchmark/catalog.py +470 -0
  28. code/src/doc2harness/benchmark/catalog_root.toml +169 -0
  29. code/src/doc2harness/benchmark/definition.py +220 -0
  30. code/src/doc2harness/benchmark/dispatch.py +108 -0
  31. code/src/doc2harness/benchmark/harnesses/__init__.py +3 -0
  32. code/src/doc2harness/benchmark/harnesses/artifact/__init__.py +29 -0
  33. code/src/doc2harness/benchmark/harnesses/artifact/catalog.toml +12 -0
  34. code/src/doc2harness/benchmark/harnesses/artifact/contracts.py +394 -0
  35. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/__init__.py +3 -0
  36. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_declares_dependencies.py +55 -0
  37. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_entry_py.py +49 -0
  38. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_install_sh.py +49 -0
  39. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_offline_wheel.py +52 -0
  40. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_requirements_lock.py +53 -0
  41. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_run_agent_sh.py +49 -0
  42. code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_version_file.py +50 -0
  43. code/src/doc2harness/benchmark/harnesses/direct/__init__.py +61 -0
  44. code/src/doc2harness/benchmark/harnesses/direct/adapter.py +228 -0
  45. code/src/doc2harness/benchmark/harnesses/direct/catalog.toml +16 -0
  46. code/src/doc2harness/benchmark/harnesses/direct/contracts.py +632 -0
  47. code/src/doc2harness/benchmark/harnesses/direct/fixtures.py +268 -0
  48. code/src/doc2harness/benchmark/harnesses/direct/scenarios/__init__.py +3 -0
  49. code/src/doc2harness/benchmark/harnesses/direct/scenarios/exfil_glob_pem_not_leaked.py +37 -0
  50. code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic.py +45 -0
README.md CHANGED
@@ -64,10 +64,11 @@ existing one.
64
  > suite and cannot be reproduced from this subset alone.
65
 
66
  > [!IMPORTANT]
67
- > Doc2Harness is an **executable** benchmark. This dataset lets you browse and
68
- > analyze the scenarios, the development document, and the contract skeleton.
69
- > To actually score a harness (Docker, mock gateway, drivers), use the code on
70
- > [GitHub](https://github.com/YuyaoGe/doc2harness).
 
71
 
72
  ## Contents
73
 
@@ -77,6 +78,7 @@ existing one.
77
  | `data/leaderboard.jsonl` | Pass rates of 19 frontier models on the full 328-case suite (config `leaderboard`) |
78
  | `development_document/functional_spec_v6.md` | The development document given to the build model in Stage 1 |
79
  | `contract_skeleton/` | The interface-only contract skeleton (CLI, headless entry point, evaluation API), plus `AGENT_CONTRACT-v2.md` |
 
80
 
81
  ## Usage
82
 
@@ -99,6 +101,47 @@ path = snapshot_download("YuyaoGe/doc2harness", repo_type="dataset",
99
  allow_patterns=["development_document/*", "contract_skeleton/**"])
100
  ```
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  ## Scenario fields (`scenarios`)
103
 
104
  | Field | Type | Description |
 
64
  > suite and cannot be reproduced from this subset alone.
65
 
66
  > [!IMPORTANT]
67
+ > Doc2Harness is an **executable** benchmark. The `scenarios` and `leaderboard`
68
+ > configs are for browsing and analysis; `load_dataset` alone does not score
69
+ > anything. To score a harness, use the full evaluation code shipped in
70
+ > [`code/`](#run-the-benchmark) (a snapshot of the
71
+ > [GitHub repository](https://github.com/YuyaoGe/doc2harness)) with Docker.
72
 
73
  ## Contents
74
 
 
78
  | `data/leaderboard.jsonl` | Pass rates of 19 frontier models on the full 328-case suite (config `leaderboard`) |
79
  | `development_document/functional_spec_v6.md` | The development document given to the build model in Stage 1 |
80
  | `contract_skeleton/` | The interface-only contract skeleton (CLI, headless entry point, evaluation API), plus `AGENT_CONTRACT-v2.md` |
81
+ | `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) |
82
 
83
  ## Usage
84
 
 
101
  allow_patterns=["development_document/*", "contract_skeleton/**"])
102
  ```
103
 
104
+ ## Run the benchmark
105
+
106
+ **Requirements:** Python 3.11+ and Docker. Both stages use the standard library only.
107
+
108
+ ```bash
109
+ pip install -U huggingface_hub
110
+ hf download YuyaoGe/doc2harness --repo-type dataset --include "code/*" --local-dir doc2harness
111
+ cd doc2harness/code
112
+
113
+ # sanity check: loading the catalog verifies its digests
114
+ PYTHONPATH=src python3 -c "from doc2harness.benchmark.dispatch import active_scenario_ids as a; print(len(a()))"
115
+ # 94
116
+ ```
117
+
118
+ **Stage 2 only: score an existing harness.** No model key is needed; scenarios
119
+ drive the product against a mock gateway.
120
+
121
+ ```bash
122
+ docker build --target evaluation -t doc2harness/evaluation:candidate -f containers/Dockerfile .
123
+
124
+ PYTHONPATH=src:tools:run python3 tools/run_production_catalog.py \
125
+ --artifact /path/to/product --artifact-id my-product \
126
+ --output /tmp/scores --concurrency 12 --timeout 300
127
+ ```
128
+
129
+ Each scenario writes a JSON receipt, plus a `catalog_receipt.json`. The score is
130
+ `pass / (pass + fail)` over applicable scenarios; a scenario that cannot be
131
+ observed on a product is `INCONCLUSIVE`, not a failure. Narrow the selection
132
+ with `--family headless` or `--scenario-id <id>`.
133
+
134
+ **Stage 1: build a new harness, then score it.** This needs the builder image
135
+ and a local LiteLLM gateway holding your own API key; see
136
+ `code/src/stage1/README.md`.
137
+
138
+ ```bash
139
+ docker pull ghcr.io/yuyaoge/doc2harness-builder:latest
140
+ PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag <model> --dry-run # prints the plan, no key needed
141
+ PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag <model> --out-dir results/
142
+ # then score results/<run_id>/agent as above
143
+ ```
144
+
145
  ## Scenario fields (`scenarios`)
146
 
147
  | Field | Type | Description |
code/.d2a_spec/typed_event_hooks.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "doc2harness.typed-event-hooks/1",
3
+ "tool_lifecycle": true,
4
+ "subprocess": true,
5
+ "workspace": true,
6
+ "cleanup": true
7
+ }
code/.github/workflows/quality.yml ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: quality
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ permissions:
7
+ contents: read
8
+
9
+ env:
10
+ LC_ALL: C.UTF-8
11
+ PYTHONHASHSEED: "0"
12
+ SOURCE_DATE_EPOCH: "315532800"
13
+ TZ: UTC
14
+
15
+ jobs:
16
+ clean-wheel:
17
+ runs-on: ubuntu-24.04
18
+ timeout-minutes: 15
19
+ permissions:
20
+ contents: read
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ python-version: ["3.11", "3.12"]
25
+ steps:
26
+ - name: Check out source
27
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
28
+ with:
29
+ persist-credentials: false
30
+ - name: Set up Python
31
+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
32
+ with:
33
+ python-version: ${{ matrix.python-version }}
34
+ check-latest: false
35
+ - name: Install hash-locked verification tools
36
+ env:
37
+ PIP_DISABLE_PIP_VERSION_CHECK: "1"
38
+ run: python -m pip install --require-hashes -r requirements/build-tools.txt
39
+ - name: Build distributions without dependency discovery
40
+ run: python -m build --no-isolation --sdist --wheel
41
+ - name: Compile source
42
+ run: python -m compileall -q src
43
+ - name: Rebuild the wheel offline from the source distribution
44
+ shell: bash
45
+ env:
46
+ PIP_NO_INDEX: "1"
47
+ run: |
48
+ sdist_archive=(dist/*.tar.gz)
49
+ test "${#sdist_archive[@]}" -eq 1
50
+ export SDIST_ARCHIVE="${sdist_archive[0]}"
51
+ export SDIST_UNPACK_ROOT="${RUNNER_TEMP}/sdist-source"
52
+ python - <<'PY'
53
+ import os
54
+ import tarfile
55
+ from pathlib import Path, PurePosixPath
56
+
57
+ archive_path = Path(os.environ["SDIST_ARCHIVE"])
58
+ destination = Path(os.environ["SDIST_UNPACK_ROOT"])
59
+ destination.mkdir()
60
+ with tarfile.open(archive_path, mode="r:gz") as archive:
61
+ member_names = set()
62
+ for member in archive.getmembers():
63
+ path = PurePosixPath(member.name)
64
+ if path.is_absolute() or ".." in path.parts:
65
+ raise SystemExit("unsafe source-distribution member")
66
+ if path.as_posix() != member.name or member.name in member_names:
67
+ raise SystemExit("non-canonical source-distribution member")
68
+ member_names.add(member.name)
69
+ if member.issym() or member.islnk() or not (
70
+ member.isfile() or member.isdir()
71
+ ):
72
+ raise SystemExit("unsupported source-distribution member type")
73
+ archive.extractall(destination, filter="data")
74
+ PY
75
+ sdist_root="${SDIST_UNPACK_ROOT}/doc2harness-0.0.0"
76
+ mkdir "${sdist_root}/dist"
77
+ cp "${SDIST_ARCHIVE}" "${sdist_root}/dist/"
78
+ python -m build --no-isolation --wheel --outdir "${sdist_root}/dist" "${sdist_root}"
79
+ cmp dist/*.whl "${sdist_root}/dist/"*.whl
80
+ - name: Install source-distribution wheel into a clean environment
81
+ shell: bash
82
+ run: |
83
+ python -m venv --without-pip "${RUNNER_TEMP}/installed"
84
+ python -m pip --python "${RUNNER_TEMP}/installed/bin/python" install \
85
+ --no-index --no-deps \
86
+ "${RUNNER_TEMP}/sdist-source/doc2harness-0.0.0/dist/"*.whl
87
+ - name: Smoke-import the installed wheel
88
+ shell: bash
89
+ run: |
90
+ "${RUNNER_TEMP}/installed/bin/python" -I -c "
91
+ import doc2harness
92
+ from doc2harness.benchmark.dispatch import active_scenario_ids
93
+ ids = active_scenario_ids()
94
+ print('installed wheel ok, scenarios:', len(ids))
95
+ assert len(ids) == 94
96
+ "
97
+
98
+ # Verify the catalog from source (the wheel only ships src/doc2harness; stage1
99
+ # runs from source and is not packaged into the wheel).
100
+ source-catalog:
101
+ runs-on: ubuntu-24.04
102
+ timeout-minutes: 10
103
+ permissions:
104
+ contents: read
105
+ strategy:
106
+ fail-fast: false
107
+ matrix:
108
+ python-version: ["3.11", "3.12"]
109
+ steps:
110
+ - name: Check out source
111
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
112
+ with:
113
+ persist-credentials: false
114
+ - name: Set up Python
115
+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
116
+ with:
117
+ python-version: ${{ matrix.python-version }}
118
+ check-latest: false
119
+ - name: Verify catalog integrity and size
120
+ run: |
121
+ PYTHONPATH=src python - <<'PY'
122
+ from doc2harness.benchmark.dispatch import active_scenario_ids, load_scenario_owner
123
+ from collections import Counter
124
+ ids = active_scenario_ids()
125
+ families = Counter(
126
+ load_scenario_owner(i).definition.classification.primary for i in ids
127
+ )
128
+ print("scenarios:", len(ids))
129
+ for name, count in sorted(families.items()):
130
+ print(f" {name} {count}")
131
+ assert len(ids) == 94, f"active catalog changed size: {len(ids)}"
132
+ assert len(families) == 9, f"family count changed: {sorted(families)}"
133
+ PY
code/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ build/
3
+ dist/
4
+ *.egg-info/
5
+ __pycache__/
6
+ .pytest_cache/
7
+ run-results/
8
+
9
+ # stage1 local build outputs and artifact registry: large, and they contain
10
+ # products emitted by the model under test, so they stay out of the repository.
11
+ /results/
12
+ /artifacts_store/
code/LICENSE ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as defined by the Licensor, any work of
48
+ authorship, including the original version of the Work and any
49
+ modifications or additions to that Work or Derivative Works of the Work,
50
+ that is intentionally submitted to the Licensor for inclusion in the Work
51
+ by the copyright owner or by an individual or Legal Entity authorized to
52
+ submit on behalf of the copyright owner.
53
+
54
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
55
+ whom a Contribution has been received by the Licensor and included
56
+ within the Work.
57
+
58
+ 2. Grant of Copyright License. Subject to the terms and conditions of
59
+ this License, each Contributor hereby grants to You a perpetual,
60
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
61
+ copyright license to reproduce, prepare Derivative Works of,
62
+ publicly display, publicly perform, sublicense, and distribute the
63
+ Work and such Derivative Works in Source or Object form.
64
+
65
+ 3. Grant of Patent License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ (except as stated in this section) patent license to make, have made,
69
+ use, offer to sell, sell, import, and otherwise transfer the Work,
70
+ where such license applies only to those patent claims licensable
71
+ by such Contributor that are necessarily infringed by their
72
+ Contribution(s) alone or by the combination of their Contribution(s)
73
+ with the Work to which such Contribution(s) was submitted. If You
74
+ institute patent litigation against any entity (including a cross-claim
75
+ or counterclaim in a lawsuit) alleging that the Work or any
76
+ Contribution embodied within the Work constitutes direct or
77
+ contributory patent infringement, then any patent licenses granted to
78
+ You under this License for that Work shall terminate as of the date
79
+ such litigation is filed.
80
+
81
+ 4. Redistribution. You may reproduce and distribute copies of the
82
+ Work or Derivative Works thereof in any medium, with or without
83
+ modifications, and in Source or Object form, provided that You
84
+ meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative
87
+ Works a copy of this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices
90
+ stating that You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works
93
+ that You distribute, all copyright, patent, trademark, and
94
+ attribution notices from the Source form of the Work,
95
+ excluding those notices that do not pertain to any part of
96
+ the Derivative Works; and
97
+
98
+ (d) If the Work includes a "NOTICE" text file as part of its
99
+ distribution, You must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, in
101
+ at least one of the following places: within a NOTICE text
102
+ file distributed as part of the Derivative Works; within
103
+ the Source form or documentation, if provided along with the
104
+ Derivative Works; or, within a display generated by the
105
+ Derivative Works, if and wherever such third-party notices
106
+ normally appear. The contents of the NOTICE file are for
107
+ informational purposes only and do not modify the License.
108
+ You may add Your own attribution notices within Derivative
109
+ Works that You distribute, alongside or as an addendum to
110
+ the NOTICE text from the Work, provided that such additional
111
+ attribution notices cannot be construed as modifying the License.
112
+
113
+ You may add Your own license statement for Your modifications and
114
+ may provide additional grant of rights to use, copy, modify, merge,
115
+ publish, distribute, sublicense, and/or sell copies of the Work
116
+ and derivative works.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
119
+ any Contribution intentionally submitted for inclusion in the Work
120
+ by You to the Licensor shall be under the terms and conditions of
121
+ this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify
123
+ the terms of any separate license agreement you may have executed
124
+ with Licensor regarding such Contributions.
125
+
126
+ 6. Trademarks. This License does not grant permission to use the trade
127
+ names, trademarks, service marks, or product names of the Licensor,
128
+ except as required for reasonable and customary use in describing the
129
+ origin of the Work and reproducing the content of the NOTICE file.
130
+
131
+ 7. Disclaimer of Warranty. Unless required by applicable law or
132
+ agreed to in writing, Licensor provides the Work (and each
133
+ Contributor provides its Contributions) on an "AS IS" BASIS,
134
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
135
+ implied, including, without limitation, any warranties or conditions
136
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
137
+ PARTICULAR PURPOSE. You are solely responsible for determining the
138
+ appropriateness of using or reproducing the Work and assume any
139
+ risks associated with Your exercise of permissions under this License.
140
+
141
+ 8. Limitation of Liability. In no event and under no legal theory,
142
+ whether in tort (including negligence), contract, or otherwise,
143
+ unless required by applicable law (such as deliberate and grossly
144
+ negligent acts) or agreed to in writing, shall any Contributor be
145
+ liable to You for damages, including any direct, indirect, special,
146
+ incidental, or exemplary damages of any character arising as a
147
+ result of this License or out of the use or inability to use the
148
+ Work (including but not limited to damages for loss of goodwill,
149
+ work stoppage, computer failure or malfunction, or all other
150
+ commercial damages or losses), even if such Contributor has been
151
+ advised of the possibility of such damages.
152
+
153
+ 9. Accepting Warranty or Additional Liability. While redistributing
154
+ the Work or Derivative Works thereof, You may choose to offer,
155
+ and charge a fee for, acceptance of support, warranty, indemnity,
156
+ or other liability obligations and/or rights consistent with this
157
+ License. However, in accepting such obligations, You may offer only
158
+ conditions consistent with this License.
159
+
160
+ END OF TERMS AND CONDITIONS
code/MANIFEST.in ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include README.md
2
+ include NOTICE
3
+ include LICENSE
4
+ include pyproject.toml
5
+ include .github/workflows/quality.yml
6
+ include requirements/build-tools.txt
7
+ include requirements/run.txt
8
+ recursive-include src/doc2harness *.py *.toml
9
+ recursive-include run *.sh *.py *.yaml *.md
10
+ prune containers
11
+ global-exclude *.py[cod]
12
+ global-exclude .DS_Store
code/NOTICE ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ doc2harness evaluates coding-agent products. This file records the upstream work
4
+ it builds on and relates to. It is an attribution record, not a license grant —
5
+ see `LICENSE` for this project's own terms.
6
+
7
+ ## mini-swe-agent
8
+
9
+ MIT License, Copyright (c) 2025 Kilian A. Lieret and Carlos E. Jimenez
10
+ https://mini-swe-agent.com/ · https://github.com/SWE-agent/mini-swe-agent
11
+
12
+ stage1 asks a model to build a harness product by implementing a hollowed
13
+ skeleton. That skeleton derives from mini-swe-agent's project layout.
14
+
15
+ Scope of what is redistributed here: **no mini-swe-agent source code is vendored
16
+ in this repository.** The skeleton at `src/stage1/f0_clean/` is a few small
17
+ files of contract sockets that raise `NotImplementedError`; it carries no upstream
18
+ implementation, and neither image installs mini-swe-agent. A product a builder
19
+ derives from mini-swe-agent remains subject to the MIT license above — anyone
20
+ distributing such a product needs to carry that notice with it.
21
+
22
+ Note for product builders: the stage1 build prompt instructs the model to
23
+ present the product under its own name and to suppress the upstream startup
24
+ banner. That is an evaluation-fidelity measure (the benchmark observes the
25
+ product's own declared behaviour), not an attempt to obscure provenance. It does
26
+ not remove the MIT attribution obligation, which this notice discharges for the
27
+ benchmark and which a product's own distribution must discharge for itself.
28
+
29
+ ## OpenCode
30
+
31
+ https://opencode.ai/
32
+
33
+ The builder image installs the OpenCode CLI binary, which drives the model
34
+ during a stage1 build. It is installed from upstream at image build time under
35
+ its own license; this repository redistributes no OpenCode code. The published
36
+ builder image does contain the binary — consult OpenCode's terms before
37
+ redistributing that image.
38
+
39
+ ## LiteLLM
40
+
41
+ https://github.com/BerriAI/LiteLLM
42
+
43
+ Used at runtime as the model gateway. It is a runtime dependency supplied by the
44
+ operator, is not a dependency of the published wheel, and no LiteLLM code is
45
+ redistributed here.
code/README.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <a href="https://geyuyao.com/doc2harness/"><img src="assets/logo.png" alt="Doc2Harness" width="420"></a>
3
+ </p>
4
+
5
+ <h3 align="center">Benchmarking LLMs on Long-Horizon Harness Engineering of Coding Agents</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://geyuyao.com/doc2harness/"><img src="https://img.shields.io/badge/Project-Page-0055E9?logo=googlechrome&logoColor=white" alt="Project Page"></a>
9
+ <a href="https://arxiv.org/abs/2610.20344"><img src="https://img.shields.io/badge/arXiv-2610.20344-b31b1b?logo=arxiv" alt="arXiv:2610.20344"></a>
10
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-green" alt="License"></a>
11
+ <img src="https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white" alt="Python 3.11+">
12
+ <img src="https://img.shields.io/badge/deps-stdlib%20only-success" alt="stdlib only">
13
+ <img src="https://img.shields.io/badge/Docker-required-2496ED?logo=docker&logoColor=white" alt="Docker">
14
+ <a href="https://github.com/users/YuyaoGe/packages/container/package/doc2harness-builder"><img src="https://img.shields.io/badge/ghcr.io-builder%20image-181717?logo=github" alt="Builder image"></a>
15
+ </p>
16
+
17
+ <p align="center">
18
+ <a href="https://geyuyao.com/doc2harness/">🌐 Website</a> •
19
+ <a href="https://arxiv.org/abs/2610.20344">📄 Paper</a> •
20
+ <a href="#-quick-start">⚡ Quick start</a> •
21
+ <a href="#-scenario-catalog">🧪 Scenarios</a> •
22
+ <a href="#-leaderboard">🏆 Leaderboard</a> •
23
+ <a href="#-citation">📝 Citation</a>
24
+ </p>
25
+
26
+ ---
27
+
28
+ Doc2Harness measures how well a model can **build a working coding agent** —
29
+ the harness itself — rather than how well it writes a patch inside one.
30
+
31
+ - 🏗️ **Stage 1 — Build.** A build model, working through
32
+ [OpenCode](https://github.com/anomalyco/opencode) in an isolated container,
33
+ receives a development document and an interface-only skeleton and has to
34
+ implement a complete agent harness.
35
+ - 🔬 **Stage 2 — Evaluate.** The harness is frozen, moved to a separate
36
+ container, and driven end to end by a scripted **mock model**. Each scenario
37
+ reads four observable channels — requests sent to the model, files on disk,
38
+ exit code, command output — and **positive controls** rule out vacuous passes.
39
+
40
+ <p align="center">
41
+ <a href="https://geyuyao.com/doc2harness/"><img src="assets/pipeline.png" alt="Doc2Harness pipeline" width="92%"></a>
42
+ </p>
43
+
44
+ > [!NOTE]
45
+ > 📦 **This is a partial open-source release.** The full benchmark in the paper
46
+ > has **328 test cases**; this repository releases a subset of **94 scenarios**
47
+ > (53 scored test cases plus the 41 positive controls that gate them). The
48
+ > remaining test cases are held out. Numbers on the leaderboard below come from
49
+ > the full suite and cannot be reproduced from this subset alone.
50
+
51
+ ## 🏆 Leaderboard
52
+
53
+ <p align="center">
54
+ <a href="https://geyuyao.com/doc2harness/"><img src="assets/leaderboard.png" alt="Pass rate of nineteen models" width="100%"></a>
55
+ </p>
56
+
57
+ Pass rate of **19 frontier models** on the full 328-case suite, strongest on the
58
+ left. Each model built **three independent harnesses**; a bar is their mean.
59
+ The best model reaches **53.05%** and the weakest **27.44%** — even the
60
+ strongest still fails nearly half the cases. See the
61
+ [project page](https://geyuyao.com/doc2harness/) for per-category breakdowns
62
+ and case studies.
63
+
64
+ ## ⚡ Quick start
65
+
66
+ **Requirements:** Python 3.11+ and Docker. No third-party Python packages —
67
+ both stages are standard library only.
68
+
69
+ ### 1️⃣ Score an existing harness (Stage 2 only)
70
+
71
+ No model key needed: scenarios drive the product against a mock gateway.
72
+
73
+ ```bash
74
+ # build the evaluation image once (see containers/README.md for mirror options)
75
+ docker build --target evaluation -t doc2harness/evaluation:candidate -f containers/Dockerfile .
76
+
77
+ # run all 94 scenarios against a product directory (one containing src/yuyao/)
78
+ PYTHONPATH=src:tools:run python3 tools/run_production_catalog.py \
79
+ --artifact /path/to/product --artifact-id my-product \
80
+ --output /tmp/scores --concurrency 12 --timeout 300
81
+ ```
82
+
83
+ - Narrow the selection with `--family headless` or `--scenario-id <id>`.
84
+ - Output: one JSON receipt per scenario plus `catalog_receipt.json`. The
85
+ score is `pass / (pass + fail)` over applicable scenarios; a scenario that
86
+ cannot be observed on a product is `INCONCLUSIVE`, not a failure.
87
+ - The full catalog takes about 25–90 seconds at concurrency 12.
88
+
89
+ ### 2️⃣ Build a new harness (Stage 1), then score it
90
+
91
+ Needs the builder image and a local [LiteLLM](https://github.com/BerriAI/litellm)
92
+ gateway holding **your** API key — setup in
93
+ [`src/stage1/README.md`](src/stage1/README.md).
94
+
95
+ ```bash
96
+ docker pull ghcr.io/yuyaoge/doc2harness-builder:latest
97
+
98
+ # free: prints the full orchestration plan, starts nothing, needs no key
99
+ PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag <model> --dry-run
100
+
101
+ # the real build (~15 minutes)
102
+ PYTHONPATH=src python3 src/stage1/run_build.py --builder-tag <model> --out-dir results/
103
+
104
+ # then score results/<run_id>/agent with step 1️⃣
105
+ ```
106
+
107
+ ### ✅ Sanity check
108
+
109
+ ```bash
110
+ PYTHONPATH=src python3 -c "from doc2harness.benchmark.dispatch import active_scenario_ids as a; print(len(a()))"
111
+ # 94
112
+ ```
113
+
114
+ Loading the catalog also verifies its digests, so an edited or inconsistent
115
+ catalog fails here instead of silently scoring a different set.
116
+
117
+ ## 🧪 Scenario catalog
118
+
119
+ | Family | Total | Scored | Controls | What it observes |
120
+ |---|--:|--:|--:|---|
121
+ | 📄 `file` | 17 | 9 | 8 | Read / edit / patch tools, including hostile encodings |
122
+ | 🔒 `permission` | 16 | 8 | 8 | Whether permission rules really constrain spawned processes |
123
+ | 💾 `state` | 14 | 7 | 7 | Slash commands and session state |
124
+ | 🤖 `headless` | 13 | 6 | 7 | Non-interactive runs and contract entry points |
125
+ | 🔌 `direct` | 11 | 6 | 5 | Wire-level model protocol against a mock gateway |
126
+ | 🖥️ `tui` | 9 | 5 | 4 | Interactive terminal behaviour over a real pty |
127
+ | 📦 `artifact` | 7 | 7 | 0 | Product shape: entry point, launcher, lockfile, wheels |
128
+ | 🚀 `startup` | 5 | 4 | 1 | Install and launch, ambient-environment isolation |
129
+ | 🧩 `extension` | 2 | 1 | 1 | Extension points that must not fire without their trigger |
130
+ | **Total** | **94** | **53** | **41** | |
131
+
132
+ Each scenario is one file:
133
+ `src/doc2harness/benchmark/harnesses/<family>/scenarios/<scenario_id>.py`.
134
+
135
+ **Controls are not scored and are not free passes.** A control proves that the
136
+ command *can* succeed when nothing blocks it, so a blocked run reads as "the
137
+ rule held" rather than "the command never worked". Each scored scenario
138
+ declares its controls in `definition.dependencies`; if you narrow the selection,
139
+ keep it closed under those dependencies.
140
+
141
+ ## 📁 Repository layout
142
+
143
+ ```text
144
+ src/doc2harness/ Stage 2 evaluation framework: catalog, drivers, mock gateway
145
+ src/stage1/ Stage 1 build pipeline: spec, skeleton, builder image, smoke layers
146
+ tools/ run_production_catalog.py — score a product
147
+ run/ YAML-driven launchers
148
+ containers/ evaluation image
149
+ assets/ figures for this README
150
+ ```
151
+
152
+ ## 📝 Citation
153
+
154
+ If you find Doc2Harness useful, please cite the
155
+ [paper](https://arxiv.org/abs/2610.20344):
156
+
157
+ ```bibtex
158
+ @article{ge2026doc2harness,
159
+ title = {Doc2Harness: Benchmarking LLMs on Long-Horizon Harness Engineering of Coding Agents},
160
+ author = {Ge, Yuyao and Liu, Shenghua and Gao, Peizhong and Ge, Chendi and Liu, Chenxu and
161
+ Wang, Yiwei and Mei, Lingrui and Bi, Baolong and Yao, Jiayu and Guo, Jiafeng and
162
+ Cheng, Xueqi},
163
+ journal = {arXiv preprint arXiv:2610.20344},
164
+ year = {2026}
165
+ }
166
+ ```
167
+
168
+ ## 🙏 Acknowledgments
169
+
170
+ The product skeleton derives from the project layout of
171
+ **[mini-swe-agent](https://github.com/SWE-agent/mini-swe-agent)** (MIT).
172
+ Builds run through **[OpenCode](https://github.com/anomalyco/opencode)**, and
173
+ the model gateway is **[LiteLLM](https://github.com/BerriAI/litellm)**. We
174
+ thank their authors and contributors.
175
+
176
+ Licensed under [Apache 2.0](LICENSE); see [`NOTICE`](NOTICE) for upstream
177
+ attribution.
code/assets/leaderboard.png ADDED

Git LFS Details

  • SHA256: 2f789477a5a24535462d47c4f31e540e3a3b1fa697e23997d0fb8c0d9d2a8005
  • Pointer size: 131 Bytes
  • Size of remote file: 182 kB
code/assets/logo.png ADDED

Git LFS Details

  • SHA256: 7c10a641f41596c38e5fad58b44808805bc44df469a351d0e597fd8a91a774bf
  • Pointer size: 130 Bytes
  • Size of remote file: 22.5 kB
code/assets/pipeline.png ADDED

Git LFS Details

  • SHA256: dbff56c7405f33c5e6ca20393955b2f85c503adbc5723bc70e3409a6a9bd5ea2
  • Pointer size: 131 Bytes
  • Size of remote file: 146 kB
code/containers/Dockerfile ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1.7
2
+
3
+ ARG PYTHON_IMAGE=python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203
4
+
5
+ FROM ${PYTHON_IMAGE} AS runtime
6
+ ARG DEBIAN_MIRROR=https://mirrors.aliyun.com/debian
7
+ ARG DEBIAN_SECURITY_MIRROR=https://mirrors.aliyun.com/debian-security
8
+ ARG PYPI_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
9
+ ARG SOURCE_DATE_EPOCH=315532800
10
+ ENV DEBIAN_FRONTEND=noninteractive \
11
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
12
+ PIP_NO_CACHE_DIR=1 \
13
+ PYTHONDONTWRITEBYTECODE=1
14
+ RUN sed -i \
15
+ -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" \
16
+ -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" \
17
+ /etc/apt/sources.list.d/debian.sources \
18
+ && apt-get update \
19
+ && apt-get install -y --no-install-recommends \
20
+ bash ca-certificates curl dnsutils git iproute2 iptables ripgrep unzip \
21
+ && rm -rf /var/lib/apt/lists/* /var/log/apt/* \
22
+ && rm -f /var/log/alternatives.log /var/log/dpkg.log \
23
+ /var/cache/ldconfig/aux-cache
24
+ COPY containers/requirements/runtime.lock /tmp/runtime.lock
25
+ RUN python -m pip install --no-cache-dir --index-url "${PYPI_INDEX_URL}" \
26
+ --requirement /tmp/runtime.lock \
27
+ && python -m pip check \
28
+ && find /usr/local/lib/python3.12/site-packages \
29
+ -type f -name '*.pyc' -delete \
30
+ && PYTHONHASHSEED=0 SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH}" \
31
+ python -m compileall -q -f --invalidation-mode checked-hash \
32
+ /usr/local/lib/python3.12/site-packages \
33
+ && python - <<'PY'
34
+ import importlib.metadata
35
+ import importlib.util
36
+
37
+ assert importlib.util.find_spec("minisweagent") is None
38
+ try:
39
+ importlib.metadata.distribution("mini-swe-agent")
40
+ except importlib.metadata.PackageNotFoundError:
41
+ pass
42
+ else:
43
+ raise SystemExit("mini-swe-agent distribution leaked into runtime image")
44
+ PY
45
+ RUN mkdir -p /opt/f0 && test -z "$(find /opt/f0 -mindepth 1 -print -quit)"
46
+ WORKDIR /opt/f0
47
+
48
+ FROM runtime AS evaluation
49
+ LABEL org.opencontainers.image.title="doc2harness evaluation environment" \
50
+ org.opencontainers.image.description="Minimal environment for isolated artifact evaluation"
51
+ RUN test ! -e /usr/local/bin/opencode \
52
+ && test ! -e /root/.opencode \
53
+ && test -z "$(find /opt/f0 -mindepth 1 -print -quit)"
code/containers/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation image
2
+
3
+ stage2 runs every scenario that needs isolation inside one image, built from
4
+ `containers/Dockerfile`: a Python runtime with the pinned dependencies in
5
+ `requirements/runtime.lock`, an empty `/opt/f0`, and no OpenCode.
6
+
7
+ The image contains no product. The caller injects the artifact under test at
8
+ run time, so one image serves every product.
9
+
10
+ The stage1 builder image is a different image; see
11
+ [`src/stage1/README.md`](../src/stage1/README.md).
12
+
13
+ ## Building
14
+
15
+ ```sh
16
+ docker build --target evaluation \
17
+ --tag doc2harness/evaluation:candidate \
18
+ --file containers/Dockerfile .
19
+ ```
20
+
21
+ That tag is the default the code looks for. Override it with
22
+ `SBH_EVALUATION_IMAGE` if you tag differently.
23
+
24
+ ## Mirrors
25
+
26
+ The checked-in defaults use Aliyun's Debian and PyPI mirrors. They are build
27
+ arguments, not edits to the Dockerfile:
28
+
29
+ ```sh
30
+ docker build --target evaluation \
31
+ --build-arg DEBIAN_MIRROR=https://deb.debian.org/debian \
32
+ --build-arg DEBIAN_SECURITY_MIRROR=https://security.debian.org/debian-security \
33
+ --build-arg PYPI_INDEX_URL=https://pypi.org/simple \
34
+ --tag doc2harness/evaluation:candidate \
35
+ --file containers/Dockerfile .
36
+ ```
37
+
38
+ Changing a mirror must not change what lands in the image. The Python base is
39
+ pinned by digest and the Python dependencies by `requirements/runtime.lock`; a
40
+ mirror serves those same packages or the build fails.
41
+
42
+ ## What the build asserts
43
+
44
+ The build ends with checks that fail it rather than ship a wrong image:
45
+ OpenCode is absent, `/opt/f0` is empty, and no mini-swe-agent tree,
46
+ distribution, or cache is present.
code/containers/requirements/runtime.lock ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Exact runtime inventory of the evaluation image.
2
+ # mini-swe-agent is intentionally absent.
3
+ Jinja2==3.1.6
4
+ MarkupSafe==3.0.3
5
+ PyYAML==6.0.3
6
+ Pygments==2.20.0
7
+ aiohappyeyeballs==2.7.1
8
+ aiohttp==3.14.3
9
+ aiosignal==1.4.0
10
+ annotated-doc==0.0.5
11
+ annotated-types==0.8.0
12
+ anyio==4.14.2
13
+ attrs==26.1.0
14
+ certifi==2026.7.22
15
+ charset-normalizer==3.4.9
16
+ click==8.4.2
17
+ datasets==5.0.1
18
+ dill==0.4.1
19
+ distro==1.9.0
20
+ fastuuid==0.14.0
21
+ filelock==3.32.2
22
+ frozenlist==1.8.0
23
+ fsspec==2026.6.0
24
+ h11==0.16.0
25
+ hf-xet==1.6.0
26
+ httpcore==1.0.9
27
+ httpx==0.28.1
28
+ huggingface_hub==1.26.1
29
+ idna==3.18
30
+ importlib_metadata==8.9.0
31
+ jiter==0.16.0
32
+ jsonschema-specifications==2025.9.1
33
+ jsonschema==4.26.0
34
+ linkify-it-py==2.1.0
35
+ litellm==1.95.0
36
+ markdown-it-py==4.2.0
37
+ mdit-py-plugins==0.6.1
38
+ mdurl==0.1.2
39
+ multidict==6.7.1
40
+ multiprocess==0.70.19
41
+ numpy==2.5.1
42
+ openai==2.53.0
43
+ packaging==26.3
44
+ pandas==3.0.5
45
+ platformdirs==4.11.0
46
+ prompt_toolkit==3.0.53
47
+ propcache==0.5.2
48
+ pyarrow==25.0.0
49
+ pydantic==2.13.4
50
+ pydantic_core==2.46.4
51
+ python-dateutil==2.9.0.post0
52
+ python-dotenv==1.2.2
53
+ referencing==0.37.0
54
+ regex==2026.7.19
55
+ requests==2.34.2
56
+ rich==15.0.0
57
+ rpds-py==2026.6.3
58
+ shellingham==1.5.4
59
+ six==1.17.0
60
+ sniffio==1.3.1
61
+ tenacity==9.1.4
62
+ textual==8.2.8
63
+ tiktoken==0.13.0
64
+ tokenizers==0.23.1
65
+ tqdm==4.70.0
66
+ typer==0.27.1
67
+ typing-inspection==0.4.2
68
+ typing_extensions==4.16.0
69
+ uc-micro-py==2.0.0
70
+ urllib3==2.7.0
71
+ wcwidth==0.8.2
72
+ xxhash==3.8.1
73
+ yarl==1.24.5
74
+ zipp==4.1.0
code/pyproject.toml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools==84.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "doc2harness"
7
+ version = "0.0.0"
8
+ description = "doc2harness: a two-stage benchmark for coding-agent evaluation"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = []
12
+
13
+ [tool.setuptools]
14
+ include-package-data = false
15
+
16
+ [tool.setuptools.package-data]
17
+ "doc2harness.benchmark" = ["*.toml", "*.json"]
18
+ "doc2harness.benchmark.harnesses.artifact" = ["catalog.toml"]
19
+ "doc2harness.benchmark.harnesses.direct" = ["catalog.toml"]
20
+ "doc2harness.benchmark.harnesses.extension" = ["catalog.toml"]
21
+ "doc2harness.benchmark.harnesses.file" = ["catalog.toml"]
22
+ "doc2harness.benchmark.harnesses.headless" = ["catalog.toml"]
23
+ "doc2harness.benchmark.harnesses.permission" = ["catalog.toml"]
24
+ "doc2harness.benchmark.harnesses.startup" = ["catalog.toml"]
25
+ "doc2harness.benchmark.harnesses.state" = ["catalog.toml"]
26
+ "doc2harness.benchmark.harnesses.tui" = ["catalog.toml"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["src"]
30
+ include = ["doc2harness*"]
31
+ namespaces = false
code/requirements/build-tools.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --index-url https://pypi.org/simple
2
+ --only-binary :all:
3
+
4
+ # Audited 2026-08-25 from the PyPI project release files. This lock is for
5
+ # build and verification only; none of these packages is a runtime dependency.
6
+ build==1.5.0 \
7
+ --hash=sha256:13f3eecb844759ab66efec90ca17639bbf14dc06cb2fdf37a9010322d9c50a6f
8
+ packaging==26.3 \
9
+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
10
+ pip==26.2.1 \
11
+ --hash=sha256:71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
12
+ pyproject-hooks==1.2.0 \
13
+ --hash=sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913
14
+ setuptools==84.0.0 \
15
+ --hash=sha256:51a52592b3b99e102b609654876bd65f19f999935166d1352678931132b0c670
16
+ wheel==0.48.0 \
17
+ --hash=sha256:3217dcc807155e45db462d7ef2431f5ddda0d7273b700d05a67b271ceb1287ab
code/requirements/run.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ PyYAML>=6.0,<7
code/run/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run commands
2
+
3
+ `run_from_config.sh` is the generic YAML entry point:
4
+
5
+ ```sh
6
+ ./run/run_from_config.sh run/configs/project.yaml --dry-run
7
+ ```
8
+
9
+ Install the small YAML-only run dependency when setting up a fresh environment:
10
+
11
+ ```sh
12
+ python3 -m pip install -r requirements/run.txt
13
+ ```
14
+
15
+ The YAML declares the catalog selection, models, output directory, and an
16
+ explicit production executor command. The command is executed once per model
17
+ with `SBH_MODEL_ID`, `SBH_RUN_CONFIG`, `SBH_SCENARIO_COUNT`, and the validated
18
+ `SBH_IDS_FILE` selection in its environment. There is no built-in fallback
19
+ executor, and an existing receipt is never re-read as if it were a fresh score.
20
+
21
+ The two-candidate command is deliberately strict:
22
+
23
+ ```sh
24
+ export CANDIDATE_A_ARTIFACT=/path/to/first/artifact
25
+ export CANDIDATE_B_ARTIFACT=/path/to/second/artifact
26
+ ./run/run_94_example.sh --dry-run
27
+ ```
28
+
29
+ It requires exactly the complete active catalog (currently 94 IDs) and the
30
+ two model IDs `candidate-a` and `candidate-b`. A real run uses the
31
+ `run_production_executor.py` adapter and requires both artifact directories.
32
+ Missing or unresolved paths fail closed instead of claiming that the 94-point
33
+ run completed. The executor drives each scenario directly; it never reads old
34
+ result rows or verdicts.
code/run/configs/example-94.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema: doc2harness.run-config/1
2
+
3
+ run:
4
+ id: example-94
5
+ output_dir: run-results/example-94
6
+ concurrency: 2
7
+ catalog_concurrency: 2
8
+ catalog_timeout: 900
9
+ opencode_compression: false
10
+
11
+ selection:
12
+ mode: all
13
+
14
+ # Set this to the reviewed production artifact executor before running. A
15
+ # blank command is rejected; no previously recorded receipt is substituted.
16
+ executor:
17
+ command:
18
+ - python3
19
+ - run/run_production_executor.py
20
+
21
+ models:
22
+ - id: candidate-a
23
+ artifact_ref: ${CANDIDATE_A_ARTIFACT}
24
+ env:
25
+ SBH_ARTIFACT_REF: ${CANDIDATE_A_ARTIFACT}
26
+ - id: candidate-b
27
+ artifact_ref: ${CANDIDATE_B_ARTIFACT}
28
+ env:
29
+ SBH_ARTIFACT_REF: ${CANDIDATE_B_ARTIFACT}
code/run/configs/project.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema: doc2harness.run-config/1
2
+
3
+ run:
4
+ id: project-run
5
+ output_dir: run-results/project-run
6
+ concurrency: 4
7
+ opencode_compression: false
8
+
9
+ selection:
10
+ mode: all
11
+
12
+ # The executor is intentionally explicit. Replace this with the reviewed
13
+ # production executor command; the launcher has no fallback executor.
14
+ executor:
15
+ command: []
16
+
17
+ models:
18
+ - id: configured-model
19
+ env: {}
code/run/run_94_example.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -Eeuo pipefail
3
+
4
+ # Run the frozen 94-point catalog for two candidate artifacts.
5
+ # This deliberately uses the same YAML-driven runner as run_from_config.sh;
6
+ # it does not reuse recorded verdicts or manufacture a score from old receipts.
7
+
8
+ script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
9
+ repo_root="$(cd -- "${script_dir}/.." && pwd -P)"
10
+ config_path="${repo_root}/run/configs/example-94.yaml"
11
+
12
+ exec python3 "${script_dir}/run_config.py" \
13
+ --repo-root "${repo_root}" \
14
+ --config "${config_path}" \
15
+ --require-models candidate-a,candidate-b \
16
+ --require-count 94 \
17
+ "$@"
code/run/run_config.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate and execute a YAML-defined doc2harness run.
2
+
3
+ A run must name an executable production backend in ``executor.command`` (or
4
+ through ``SBH_PRODUCTION_EXECUTOR``); there is no built-in stand-in that would
5
+ let a misconfigured run look like it scored something. ``--dry-run`` validates
6
+ the complete plan and writes no model result; without it, each configured model
7
+ is invoked through the declared executor, respecting the configured concurrency
8
+ limit.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import shlex
17
+ import subprocess
18
+ import sys
19
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+
24
+ class RunConfigError(ValueError):
25
+ """Raised when a run configuration is incomplete or unsafe."""
26
+
27
+
28
+ def _load_yaml(path: Path) -> dict[str, Any]:
29
+ try:
30
+ import yaml # type: ignore[import-not-found]
31
+ except ImportError as exc: # pragma: no cover - environment dependent
32
+ raise RunConfigError(
33
+ "PyYAML is required for YAML run configs; install the run requirements"
34
+ ) from exc
35
+ try:
36
+ value = yaml.safe_load(path.read_text(encoding="utf-8"))
37
+ except (OSError, yaml.YAMLError) as exc:
38
+ raise RunConfigError(f"cannot read YAML config {path}: {exc}") from exc
39
+ if not isinstance(value, dict):
40
+ raise RunConfigError("top-level YAML value must be a mapping")
41
+ return value
42
+
43
+
44
+ def _mapping(value: Any, name: str) -> dict[str, Any]:
45
+ if not isinstance(value, dict):
46
+ raise RunConfigError(f"{name} must be a mapping")
47
+ return value
48
+
49
+
50
+ def _nonempty_string(value: Any, name: str) -> str:
51
+ if not isinstance(value, str) or not value.strip():
52
+ raise RunConfigError(f"{name} must be a non-empty string")
53
+ return value.strip()
54
+
55
+
56
+ def _repo_path(repo_root: Path, value: Any, name: str) -> Path:
57
+ raw = Path(_nonempty_string(value, name)).expanduser()
58
+ return raw if raw.is_absolute() else repo_root / raw
59
+
60
+
61
+ def _catalog_ids(repo_root: Path) -> tuple[str, ...]:
62
+ from doc2harness.benchmark.catalog import (
63
+ load_catalog_sources,
64
+ parse_catalog_root,
65
+ )
66
+
67
+ package = repo_root / "src" / "doc2harness"
68
+ benchmark = package / "benchmark"
69
+ root = parse_catalog_root((benchmark / "catalog_root.toml").read_bytes())
70
+ resources = {
71
+ root.taxonomy_resource: (benchmark / "taxonomy.toml").read_bytes(),
72
+ **{
73
+ shard.resource: (package / Path(*shard.resource.segments)).read_bytes()
74
+ for shard in root.shards
75
+ },
76
+ }
77
+ definitions = load_catalog_sources(
78
+ root,
79
+ resources,
80
+ lambda module, export: __import__(module, fromlist=[export]).__dict__[export],
81
+ )
82
+ return tuple(item.scenario_id for item in definitions)
83
+
84
+
85
+ def _expand(value: str) -> str:
86
+ return os.path.expandvars(value)
87
+
88
+
89
+ def _command(executor: dict[str, Any], *, allow_missing: bool) -> list[str]:
90
+ configured = executor.get("command")
91
+ if configured is None or configured == []:
92
+ env_command = os.environ.get("SBH_PRODUCTION_EXECUTOR", "").strip()
93
+ if not env_command:
94
+ if allow_missing:
95
+ return []
96
+ raise RunConfigError(
97
+ "executor.command is missing; set a production executor explicitly "
98
+ "(SBH_PRODUCTION_EXECUTOR may provide one)"
99
+ )
100
+ configured = shlex.split(env_command)
101
+ if isinstance(configured, str):
102
+ configured = shlex.split(configured)
103
+ if not isinstance(configured, list) or not configured or not all(
104
+ isinstance(item, str) and item.strip() for item in configured
105
+ ):
106
+ raise RunConfigError("executor.command must be a non-empty string/list command")
107
+ return [_expand(item) for item in configured]
108
+
109
+
110
+ def _validate(
111
+ repo_root: Path,
112
+ config_path: Path,
113
+ document: dict[str, Any],
114
+ required_models: tuple[str, ...] = (),
115
+ required_count: int | None = None,
116
+ ) -> dict[str, Any]:
117
+ if document.get("schema") != "doc2harness.run-config/1":
118
+ raise RunConfigError("schema must be doc2harness.run-config/1")
119
+ run = _mapping(document.get("run"), "run")
120
+ selection = _mapping(document.get("selection"), "selection")
121
+ executor = _mapping(document.get("executor"), "executor")
122
+ models_value = document.get("models")
123
+ if not isinstance(models_value, list) or not models_value:
124
+ raise RunConfigError("models must be a non-empty list")
125
+ catalog = _catalog_ids(repo_root)
126
+ requested = selection.get("mode", "all")
127
+ if requested == "all":
128
+ selected = catalog
129
+ elif requested == "ids_file":
130
+ ids_file = _repo_path(repo_root, selection.get("ids_file"), "selection.ids_file")
131
+ try:
132
+ selected = tuple(
133
+ line.strip()
134
+ for line in ids_file.read_text(encoding="utf-8").splitlines()
135
+ if line.strip() and not line.lstrip().startswith("#")
136
+ )
137
+ except OSError as exc:
138
+ raise RunConfigError(f"cannot read selection.ids_file: {ids_file}") from exc
139
+ else:
140
+ raise RunConfigError("selection.mode must be all or ids_file")
141
+ if not selected or len(selected) != len(set(selected)):
142
+ raise RunConfigError("selection must contain unique non-empty scenario IDs")
143
+ if required_count is not None and len(selected) != required_count:
144
+ raise RunConfigError(
145
+ f"selection must contain exactly {required_count} scenario IDs, found {len(selected)}"
146
+ )
147
+ unknown = sorted(set(selected) - set(catalog))
148
+ if unknown:
149
+ raise RunConfigError(f"selection contains unknown scenario IDs: {unknown[:5]}")
150
+ if required_models:
151
+ names = tuple(_nonempty_string(_mapping(item, "model").get("id"), "model.id") for item in models_value)
152
+ if names != required_models:
153
+ raise RunConfigError(f"models must be exactly {list(required_models)}, found {list(names)}")
154
+ command = _command(executor, allow_missing=bool(document.get("_dry_run")))
155
+ output_dir = _repo_path(repo_root, run.get("output_dir", "run-results"), "run.output_dir")
156
+ if not output_dir.is_relative_to(repo_root):
157
+ raise RunConfigError("run.output_dir must remain inside the repository")
158
+ concurrency = run.get("concurrency", 1)
159
+ if type(concurrency) is not int or concurrency < 1:
160
+ raise RunConfigError("run.concurrency must be a positive integer")
161
+ return {
162
+ "repo_root": str(repo_root),
163
+ "config_path": str(config_path),
164
+ "run": run,
165
+ "selection": {"mode": requested, "count": len(selected), "ids": selected},
166
+ "models": models_value,
167
+ "executor": {"command": command, "output_dir": str(output_dir)},
168
+ }
169
+
170
+
171
+ def _execute(plan: dict[str, Any], *, dry_run: bool) -> int:
172
+ output_dir = Path(plan["executor"]["output_dir"])
173
+ output_dir.mkdir(parents=True, exist_ok=True)
174
+ manifest = output_dir / "run-plan.json"
175
+ manifest.write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
176
+ selection_file = output_dir / "selected-scenarios.txt"
177
+ selection_file.write_text(
178
+ "".join(f"{scenario_id}\n" for scenario_id in plan["selection"]["ids"]),
179
+ encoding="utf-8",
180
+ )
181
+ if dry_run:
182
+ print(json.dumps({"status": "VALID", "selection_count": plan["selection"]["count"], "models": [item["id"] for item in plan["models"]]}, ensure_ascii=False))
183
+ return 0
184
+ command = plan["executor"]["command"]
185
+ if not command:
186
+ raise RunConfigError(
187
+ "no production executor configured; set executor.command or "
188
+ "SBH_PRODUCTION_EXECUTOR before a real run"
189
+ )
190
+ def run_model(model: Any) -> tuple[str, int]:
191
+ model_map = _mapping(model, "model")
192
+ model_id = _nonempty_string(model_map.get("id"), "model.id")
193
+ environment = os.environ.copy()
194
+ environment.update(
195
+ {
196
+ str(key): _expand(str(value))
197
+ for key, value in _mapping(model_map.get("env", {}), "model.env").items()
198
+ }
199
+ )
200
+ environment["SBH_RUN_CONFIG"] = plan["config_path"]
201
+ environment["SBH_MODEL_ID"] = model_id
202
+ environment["SBH_SCENARIO_COUNT"] = str(plan["selection"]["count"])
203
+ environment["SBH_IDS_FILE"] = str(selection_file)
204
+ environment["SBH_RUN_OUTPUT_DIR"] = plan["executor"]["output_dir"]
205
+ environment["SBH_CATALOG_CONCURRENCY"] = str(
206
+ plan["run"].get("catalog_concurrency", 1)
207
+ )
208
+ environment["SBH_CATALOG_TIMEOUT"] = str(
209
+ plan["run"].get("catalog_timeout", 900)
210
+ )
211
+ print(
212
+ f"[doc2harness] starting model={model_id} "
213
+ f"scenarios={plan['selection']['count']}",
214
+ flush=True,
215
+ )
216
+ result = subprocess.run(command, cwd=Path(plan["repo_root"]), env=environment, check=False)
217
+ return model_id, result.returncode
218
+
219
+ concurrency = min(int(plan["run"].get("concurrency", 1)), len(plan["models"]))
220
+ with ThreadPoolExecutor(max_workers=concurrency) as pool:
221
+ futures = [pool.submit(run_model, model) for model in plan["models"]]
222
+ for future in as_completed(futures):
223
+ model_id, returncode = future.result()
224
+ if returncode != 0:
225
+ print(
226
+ f"[doc2harness] executor failed model={model_id} rc={returncode}",
227
+ file=sys.stderr,
228
+ )
229
+ return returncode
230
+ print(json.dumps({"status": "COMPLETED", "selection_count": plan["selection"]["count"], "models": [item["id"] for item in plan["models"]]}, ensure_ascii=False))
231
+ return 0
232
+
233
+
234
+ def main() -> int:
235
+ parser = argparse.ArgumentParser(description=__doc__)
236
+ parser.add_argument("--repo-root", type=Path, required=True)
237
+ parser.add_argument("--config", type=Path, required=True)
238
+ parser.add_argument("--dry-run", action="store_true")
239
+ parser.add_argument("--require-models", default="")
240
+ parser.add_argument("--require-count", type=int)
241
+ args = parser.parse_args()
242
+ try:
243
+ repo_root = args.repo_root.resolve()
244
+ config_path = args.config.resolve()
245
+ sys.path.insert(0, str(repo_root / "src"))
246
+ document = _load_yaml(config_path)
247
+ document["_dry_run"] = args.dry_run
248
+ plan = _validate(
249
+ repo_root,
250
+ config_path,
251
+ document,
252
+ tuple(item for item in args.require_models.split(",") if item),
253
+ args.require_count,
254
+ )
255
+ return _execute(plan, dry_run=args.dry_run)
256
+ except (OSError, RunConfigError, ImportError) as exc:
257
+ print(f"error[SBH-RUN-CONFIG]: {exc}", file=sys.stderr)
258
+ return 4
259
+
260
+
261
+ if __name__ == "__main__":
262
+ raise SystemExit(main())
code/run/run_from_config.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -Eeuo pipefail
3
+
4
+ # Run the harness from a YAML run configuration.
5
+ # The Python entry point performs schema, catalog, and executor checks before
6
+ # starting any model process. Paths in the YAML file are resolved relative to
7
+ # the repository unless they are explicitly absolute.
8
+
9
+ script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
10
+ repo_root="$(cd -- "${script_dir}/.." && pwd -P)"
11
+
12
+ if [[ $# -lt 1 ]]; then
13
+ printf 'usage: %s CONFIG.yaml [--dry-run]\n' "$0" >&2
14
+ exit 2
15
+ fi
16
+
17
+ config_path="$1"
18
+ shift
19
+ if [[ "${config_path}" != /* ]]; then
20
+ config_path="${repo_root}/${config_path}"
21
+ fi
22
+
23
+ exec python3 "${script_dir}/run_config.py" \
24
+ --repo-root "${repo_root}" \
25
+ --config "${config_path}" \
26
+ "$@"
code/run/run_production_executor.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bridge the YAML launch boundary to the reviewed production catalog runner.
2
+
3
+ The generic YAML launcher owns validation and per-model scheduling. This
4
+ adapter owns only the explicit argument translation needed by the production
5
+ catalog executor; it never reads previously recorded verdicts. The deterministic model stimulus ships inside the package, so
6
+ running a scenario needs nothing beyond the artifact under test.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+
17
+ def _required(name: str) -> str:
18
+ value = os.environ.get(name, "").strip()
19
+ if not value or value.startswith("${"):
20
+ raise SystemExit(f"SBH production executor requires {name}")
21
+ return value
22
+
23
+
24
+ def _positive_int(name: str, default: int) -> int:
25
+ value = os.environ.get(name, str(default)).strip()
26
+ try:
27
+ parsed = int(value)
28
+ except ValueError as exc:
29
+ raise SystemExit(f"{name} must be a positive integer") from exc
30
+ if parsed < 1:
31
+ raise SystemExit(f"{name} must be a positive integer")
32
+ return parsed
33
+
34
+
35
+ def _positive_float(name: str, default: float) -> str:
36
+ value = os.environ.get(name, str(default)).strip()
37
+ try:
38
+ parsed = float(value)
39
+ except ValueError as exc:
40
+ raise SystemExit(f"{name} must be a positive number") from exc
41
+ if not 0 < parsed <= 3600:
42
+ raise SystemExit(f"{name} must be in (0, 3600]")
43
+ return value
44
+
45
+
46
+ def build_command() -> tuple[list[str], Path]:
47
+ """Build the reviewed catalog command from explicit launcher bindings."""
48
+
49
+ repo_root = Path(__file__).resolve().parents[1]
50
+ artifact = Path(_required("SBH_ARTIFACT_REF")).expanduser().resolve()
51
+ output_root = Path(_required("SBH_RUN_OUTPUT_DIR")).expanduser()
52
+ if not output_root.is_absolute():
53
+ output_root = (repo_root / output_root).resolve()
54
+ model_id = _required("SBH_MODEL_ID")
55
+ scenario_count = _positive_int("SBH_SCENARIO_COUNT", 1)
56
+ concurrency = _positive_int("SBH_CATALOG_CONCURRENCY", 1)
57
+ timeout = _positive_float("SBH_CATALOG_TIMEOUT", 900.0)
58
+ output = output_root / model_id
59
+ if not artifact.is_dir() or not (artifact / "run_agent.sh").is_file():
60
+ raise SystemExit("SBH_ARTIFACT_REF must contain run_agent.sh")
61
+ command = [
62
+ sys.executable,
63
+ str(repo_root / "tools" / "run_production_catalog.py"),
64
+ "--repo-root",
65
+ str(repo_root),
66
+ "--artifact",
67
+ str(artifact),
68
+ "--artifact-id",
69
+ model_id,
70
+ "--output",
71
+ str(output),
72
+ "--concurrency",
73
+ str(concurrency),
74
+ "--timeout",
75
+ timeout,
76
+ ]
77
+ scenario_id = os.environ.get("SBH_SCENARIO_ID", "").strip()
78
+ ids_file = os.environ.get("SBH_IDS_FILE", "").strip()
79
+ if scenario_id and ids_file:
80
+ raise SystemExit("set only one of SBH_SCENARIO_ID and SBH_IDS_FILE")
81
+ if scenario_id:
82
+ command.extend(["--scenario-id", scenario_id])
83
+ elif ids_file:
84
+ command.extend(["--ids-file", str(Path(ids_file).expanduser().resolve())])
85
+ if scenario_count < 1:
86
+ raise SystemExit("SBH_SCENARIO_COUNT must be positive")
87
+ return command, output
88
+
89
+
90
+ def main() -> int:
91
+ command, output = build_command()
92
+ output.mkdir(parents=True, exist_ok=True)
93
+ repo_root = Path(__file__).resolve().parents[1]
94
+ environment = os.environ.copy()
95
+ source_path = str(repo_root / "src")
96
+ existing_pythonpath = environment.get("PYTHONPATH", "")
97
+ environment["PYTHONPATH"] = (
98
+ source_path
99
+ if not existing_pythonpath
100
+ else source_path + os.pathsep + existing_pythonpath
101
+ )
102
+ completed = subprocess.run(
103
+ command,
104
+ cwd=repo_root,
105
+ env=environment,
106
+ check=False,
107
+ )
108
+ return completed.returncode
109
+
110
+
111
+ if __name__ == "__main__":
112
+ raise SystemExit(main())
code/src/doc2harness/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __all__ = []
code/src/doc2harness/benchmark/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed, non-executing benchmark catalog contracts."""
2
+
3
+ from doc2harness.benchmark.catalog import (
4
+ CatalogRoot,
5
+ CatalogShard,
6
+ CatalogVerification,
7
+ LogicalCatalogResource,
8
+ load_catalog_sources,
9
+ parse_catalog_root,
10
+ parse_catalog_shard,
11
+ verify_catalog_sources,
12
+ )
13
+ from doc2harness.benchmark.definition import (
14
+ Classification,
15
+ ComponentKind,
16
+ ComponentRef,
17
+ DependencyKind,
18
+ DependencyRef,
19
+ ExperimentBinding,
20
+ ScenarioDefinition,
21
+ ScenarioDifficulty,
22
+ ScenarioRole,
23
+ UnsupportedPolicy,
24
+ definition_digest,
25
+ )
26
+ from doc2harness.benchmark.taxonomy import (
27
+ Taxonomy,
28
+ TaxonomyEntry,
29
+ parse_taxonomy,
30
+ validate_classification,
31
+ )
32
+
33
+ __all__ = [
34
+ "CatalogRoot",
35
+ "CatalogShard",
36
+ "CatalogVerification",
37
+ "Classification",
38
+ "ComponentKind",
39
+ "ComponentRef",
40
+ "DependencyKind",
41
+ "DependencyRef",
42
+ "ExperimentBinding",
43
+ "LogicalCatalogResource",
44
+ "ScenarioDefinition",
45
+ "ScenarioDifficulty",
46
+ "ScenarioRole",
47
+ "Taxonomy",
48
+ "TaxonomyEntry",
49
+ "UnsupportedPolicy",
50
+ "definition_digest",
51
+ "load_catalog_sources",
52
+ "parse_catalog_root",
53
+ "parse_catalog_shard",
54
+ "parse_taxonomy",
55
+ "validate_classification",
56
+ "verify_catalog_sources",
57
+ ]
code/src/doc2harness/benchmark/catalog.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit catalog sources, verification, and authority-backed sealing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+
10
+ from doc2harness.benchmark.definition import (
11
+ DependencyKind,
12
+ ScenarioDefinition,
13
+ ScenarioRole,
14
+ definition_digest,
15
+ )
16
+ from doc2harness.benchmark.taxonomy import (
17
+ Taxonomy,
18
+ _exact_keys,
19
+ _parse_closed_toml,
20
+ parse_taxonomy,
21
+ validate_classification,
22
+ )
23
+ from doc2harness.contracts.canonical import canonical_json
24
+ from doc2harness.contracts.primitives import (
25
+ ContractDocumentError,
26
+ require_digest,
27
+ )
28
+
29
+ _SEGMENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z", re.ASCII)
30
+ _IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII)
31
+ _MODULE = re.compile(r"[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*\Z", re.ASCII)
32
+ _EXPORT = re.compile(r"[a-z][a-z0-9_]{0,127}\Z", re.ASCII)
33
+ _MODULE_PREFIX = "doc2harness.benchmark.harnesses."
34
+ _MAX_DEFINITIONS = 4096
35
+ _MAX_EXPORTS = 4096
36
+ _MAX_SHARDS = 4096
37
+ _MAX_SOURCE_BYTES = 1_048_576
38
+ _SHARD_DOMAIN = b"doc2harness.catalog-shard/1\x00"
39
+ _ROOT_DOMAIN = b"doc2harness.catalog-root/1\x00"
40
+ _VERIFICATION_DOMAIN = b"doc2harness.catalog-verification/1\x00"
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class LogicalCatalogResource:
45
+ """A package-relative resource identity, never a host filesystem path."""
46
+
47
+ segments: tuple[str, ...]
48
+
49
+ def __post_init__(self) -> None:
50
+ if type(self.segments) is not tuple or not self.segments or len(self.segments) > 32:
51
+ raise ContractDocumentError("catalog resource must have bounded exact segments")
52
+ for segment in self.segments:
53
+ if type(segment) is not str or _SEGMENT.fullmatch(segment) is None:
54
+ raise ContractDocumentError("catalog resource contains an unsafe segment")
55
+ if segment in {".", ".."} or segment.startswith("~") or ":" in segment:
56
+ raise ContractDocumentError("catalog resource contains an unsafe segment")
57
+
58
+
59
+ def _digest(value: object, name: str) -> str:
60
+ try:
61
+ return require_digest(value, name=name)
62
+ except ContractDocumentError:
63
+ raise
64
+
65
+
66
+ def _raw_digest(raw: bytes) -> str:
67
+ return "sha256:" + hashlib.sha256(raw).hexdigest()
68
+
69
+
70
+ def _resource(value: object, name: str) -> LogicalCatalogResource:
71
+ if type(value) is not str or not value or value.startswith(("/", "~")):
72
+ raise ContractDocumentError(f"{name} is not a canonical relative resource")
73
+ if (
74
+ value.endswith("/")
75
+ or "//" in value
76
+ or "\\" in value
77
+ or ":" in value
78
+ or "%" in value
79
+ or not value.isascii()
80
+ ):
81
+ raise ContractDocumentError(f"{name} is not a canonical relative resource")
82
+ return LogicalCatalogResource(tuple(value.split("/")))
83
+
84
+
85
+ def _module_export(value: object, name: str) -> tuple[str, str]:
86
+ row = _exact_keys(value, frozenset({"module", "export"}), name)
87
+ module = row["module"]
88
+ export = row["export"]
89
+ if (
90
+ type(module) is not str
91
+ or len(module) > 255
92
+ or _MODULE.fullmatch(module) is None
93
+ or not module.startswith(_MODULE_PREFIX)
94
+ ):
95
+ raise ContractDocumentError(f"{name} module is not canonical")
96
+ if type(export) is not str or _EXPORT.fullmatch(export) is None:
97
+ raise ContractDocumentError(f"{name} export is not canonical")
98
+ return module, export
99
+
100
+
101
+ def _exports(value: object, name: str) -> tuple[tuple[str, str], ...]:
102
+ if type(value) is not list or not value or len(value) > _MAX_EXPORTS:
103
+ raise ContractDocumentError(f"{name} must be a bounded non-empty array")
104
+ result = tuple(_module_export(item, name) for item in value)
105
+ if result != tuple(sorted(result)) or len(set(result)) != len(result):
106
+ raise ContractDocumentError(f"{name} must be sorted and unique")
107
+ return result
108
+
109
+
110
+ def _shard_semantic_body(
111
+ function_id: str,
112
+ resource: LogicalCatalogResource,
113
+ exports: tuple[tuple[str, str], ...],
114
+ ) -> dict[str, object]:
115
+ return {
116
+ "exports": [
117
+ {"export": export, "module": module} for module, export in exports
118
+ ],
119
+ "function_id": function_id,
120
+ "resource": list(resource.segments),
121
+ }
122
+
123
+
124
+ def _semantic_digest(domain: bytes, body: dict[str, object]) -> str:
125
+ return "sha256:" + hashlib.sha256(domain + canonical_json(body)).hexdigest()
126
+
127
+
128
+ @dataclass(frozen=True, slots=True)
129
+ class CatalogShard:
130
+ function_id: str
131
+ resource: LogicalCatalogResource
132
+ exports: tuple[tuple[str, str], ...]
133
+ source_digest: str
134
+ semantic_digest: str
135
+
136
+ def __post_init__(self) -> None:
137
+ if type(self.function_id) is not str or _IDENTIFIER.fullmatch(self.function_id) is None:
138
+ raise ContractDocumentError("shard function id is not canonical")
139
+ if type(self.resource) is not LogicalCatalogResource:
140
+ raise ContractDocumentError("shard resource must be a logical resource")
141
+ expected_resource = (
142
+ "benchmark",
143
+ "harnesses",
144
+ *self.function_id.split("."),
145
+ "catalog.toml",
146
+ )
147
+ if self.resource.segments != expected_resource:
148
+ raise ContractDocumentError("shard resource does not match its function")
149
+ if type(self.exports) is not tuple or not self.exports or len(self.exports) > _MAX_EXPORTS:
150
+ raise ContractDocumentError("shard exports must be a bounded exact tuple")
151
+ for item in self.exports:
152
+ if type(item) is not tuple or len(item) != 2:
153
+ raise ContractDocumentError("shard exports require exact pairs")
154
+ module, export = item
155
+ _module_export({"module": module, "export": export}, "shard export")
156
+ if self.exports != tuple(sorted(self.exports)) or len(set(self.exports)) != len(self.exports):
157
+ raise ContractDocumentError("shard exports must be sorted and unique")
158
+ _digest(self.source_digest, "shard source digest")
159
+ _digest(self.semantic_digest, "shard semantic digest")
160
+ expected_semantic = _semantic_digest(
161
+ _SHARD_DOMAIN,
162
+ _shard_semantic_body(self.function_id, self.resource, self.exports),
163
+ )
164
+ if self.semantic_digest != expected_semantic:
165
+ raise ContractDocumentError("shard semantic digest differs from its fields")
166
+
167
+
168
+ @dataclass(frozen=True, slots=True)
169
+ class CatalogRoot:
170
+ taxonomy_resource: LogicalCatalogResource
171
+ taxonomy_digest: str
172
+ shards: tuple[CatalogShard, ...]
173
+ source_digest: str
174
+ semantic_digest: str
175
+
176
+ def __post_init__(self) -> None:
177
+ if (
178
+ type(self.taxonomy_resource) is not LogicalCatalogResource
179
+ or self.taxonomy_resource.segments != ("benchmark", "taxonomy.toml")
180
+ ):
181
+ raise ContractDocumentError("taxonomy resource is not canonical")
182
+ _digest(self.taxonomy_digest, "taxonomy digest")
183
+ if type(self.shards) is not tuple or not self.shards or len(self.shards) > _MAX_SHARDS:
184
+ raise ContractDocumentError("catalog root must contain a bounded exact shard tuple")
185
+ if any(type(item) is not CatalogShard for item in self.shards):
186
+ raise ContractDocumentError("catalog root shards must use CatalogShard")
187
+ identities = tuple(item.function_id for item in self.shards)
188
+ resources = tuple(item.resource for item in self.shards)
189
+ if identities != tuple(sorted(identities)) or len(set(identities)) != len(identities):
190
+ raise ContractDocumentError("catalog root shard functions must be sorted and unique")
191
+ if len(set(resources)) != len(resources):
192
+ raise ContractDocumentError("catalog root shard resources must be unique")
193
+ export_count = 0
194
+ seen_exports: set[tuple[str, str]] = set()
195
+ for shard in self.shards:
196
+ for export in shard.exports:
197
+ export_count += 1
198
+ if export_count > _MAX_EXPORTS:
199
+ raise ContractDocumentError("catalog root exports exceed the total limit")
200
+ if export in seen_exports:
201
+ raise ContractDocumentError("catalog root exports must be globally unique")
202
+ seen_exports.add(export)
203
+ _digest(self.source_digest, "root source digest")
204
+ _digest(self.semantic_digest, "root semantic digest")
205
+ expected_semantic = _semantic_digest(
206
+ _ROOT_DOMAIN,
207
+ _root_body(self.taxonomy_resource, self.taxonomy_digest, self.shards),
208
+ )
209
+ if self.semantic_digest != expected_semantic:
210
+ raise ContractDocumentError("root semantic digest differs from its fields")
211
+
212
+
213
+ @dataclass(frozen=True, slots=True)
214
+ class CatalogVerification:
215
+ definitions: tuple[ScenarioDefinition, ...]
216
+ source_digests: tuple[str, ...]
217
+ semantic_digest: str
218
+
219
+ def __post_init__(self) -> None:
220
+ if type(self.definitions) is not tuple or not self.definitions:
221
+ raise ContractDocumentError("catalog verification requires definitions")
222
+ if any(type(item) is not ScenarioDefinition for item in self.definitions):
223
+ raise ContractDocumentError("verified definitions must use ScenarioDefinition")
224
+ if type(self.source_digests) is not tuple or not self.source_digests:
225
+ raise ContractDocumentError("catalog verification requires source digests")
226
+ for item in self.source_digests:
227
+ _digest(item, "source digest")
228
+ _digest(self.semantic_digest, "catalog semantic digest")
229
+
230
+
231
+ CatalogImporter = Callable[[str, str], ScenarioDefinition]
232
+
233
+
234
+ def _root_body(
235
+ taxonomy_resource: LogicalCatalogResource,
236
+ taxonomy_digest: str,
237
+ shards: tuple[CatalogShard, ...],
238
+ ) -> dict[str, object]:
239
+ return {
240
+ "shards": [
241
+ {
242
+ "exports": [
243
+ {"export": export, "module": module}
244
+ for module, export in shard.exports
245
+ ],
246
+ "function_id": shard.function_id,
247
+ "resource": list(shard.resource.segments),
248
+ "semantic_digest": shard.semantic_digest,
249
+ "source_digest": shard.source_digest,
250
+ }
251
+ for shard in shards
252
+ ],
253
+ "taxonomy_resource": list(taxonomy_resource.segments),
254
+ "taxonomy_source_digest": taxonomy_digest,
255
+ }
256
+
257
+
258
+ def parse_catalog_root(raw: bytes, /) -> CatalogRoot:
259
+ source = _exact_keys(
260
+ _parse_closed_toml(raw, "catalog root"),
261
+ frozenset({"format", "taxonomy_resource", "taxonomy_source_digest", "shards"}),
262
+ "catalog root",
263
+ )
264
+ if source["format"] != "doc2harness.catalog-root-source/1":
265
+ raise ContractDocumentError("catalog root format is unsupported")
266
+ taxonomy_resource = _resource(source["taxonomy_resource"], "taxonomy resource")
267
+ taxonomy_digest = _digest(source["taxonomy_source_digest"], "taxonomy source digest")
268
+ raw_shards = source["shards"]
269
+ if type(raw_shards) is not list or not raw_shards or len(raw_shards) > _MAX_SHARDS:
270
+ raise ContractDocumentError("catalog root shards must be a bounded non-empty array")
271
+ shards: list[CatalogShard] = []
272
+ total_exports = 0
273
+ for item in raw_shards:
274
+ row = _exact_keys(
275
+ item,
276
+ frozenset({"function_id", "resource", "source_digest", "semantic_digest", "exports"}),
277
+ "catalog root shard",
278
+ )
279
+ exports = _exports(row["exports"], "catalog root exports")
280
+ total_exports += len(exports)
281
+ if total_exports > _MAX_EXPORTS:
282
+ raise ContractDocumentError("catalog root exports exceed the total limit")
283
+ shards.append(
284
+ CatalogShard(
285
+ row["function_id"],
286
+ _resource(row["resource"], "shard resource"),
287
+ exports,
288
+ _digest(row["source_digest"], "shard source digest"),
289
+ _digest(row["semantic_digest"], "shard semantic digest"),
290
+ )
291
+ )
292
+ typed_shards = tuple(shards)
293
+ semantic = _semantic_digest(
294
+ _ROOT_DOMAIN,
295
+ _root_body(taxonomy_resource, taxonomy_digest, typed_shards),
296
+ )
297
+ return CatalogRoot(
298
+ taxonomy_resource,
299
+ taxonomy_digest,
300
+ typed_shards,
301
+ _raw_digest(raw),
302
+ semantic,
303
+ )
304
+
305
+
306
+ def parse_catalog_shard(raw: bytes, /) -> CatalogShard:
307
+ source = _exact_keys(
308
+ _parse_closed_toml(raw, "catalog shard"),
309
+ frozenset({"format", "function_id", "resource", "exports"}),
310
+ "catalog shard",
311
+ )
312
+ if source["format"] != "doc2harness.catalog-shard-source/1":
313
+ raise ContractDocumentError("catalog shard format is unsupported")
314
+ function_id = source["function_id"]
315
+ resource = _resource(source["resource"], "shard resource")
316
+ exports = _exports(source["exports"], "catalog shard exports")
317
+ semantic = _semantic_digest(
318
+ _SHARD_DOMAIN,
319
+ _shard_semantic_body(function_id, resource, exports),
320
+ )
321
+ return CatalogShard(function_id, resource, exports, _raw_digest(raw), semantic)
322
+
323
+
324
+ def _ordered_definitions(
325
+ definitions: tuple[ScenarioDefinition, ...],
326
+ ) -> tuple[dict[str, int], dict[str, ScenarioDefinition]]:
327
+ if (
328
+ type(definitions) is not tuple
329
+ or not definitions
330
+ or len(definitions) > _MAX_DEFINITIONS
331
+ or any(type(item) is not ScenarioDefinition for item in definitions)
332
+ ):
333
+ raise ContractDocumentError("definitions must be a bounded non-empty exact tuple")
334
+ order: dict[str, int] = {}
335
+ by_id: dict[str, ScenarioDefinition] = {}
336
+ for ordinal, definition in enumerate(definitions):
337
+ if definition.scenario_id in order:
338
+ raise ContractDocumentError("scenario ids must be globally unique")
339
+ order[definition.scenario_id] = ordinal
340
+ by_id[definition.scenario_id] = definition
341
+ graph: dict[str, set[str]] = {}
342
+ for definition in definitions:
343
+ dependency_ids = tuple(item.scenario_id for item in definition.dependencies)
344
+ if len(set(dependency_ids)) != len(dependency_ids):
345
+ raise ContractDocumentError("a scenario cannot reference one id with multiple kinds")
346
+ unknown = set(dependency_ids) - set(order)
347
+ if unknown:
348
+ raise ContractDocumentError("scenario dependency is unknown")
349
+ for dependency in definition.dependencies:
350
+ target = by_id[dependency.scenario_id]
351
+ if dependency.kind in {DependencyKind.CONTROL, DependencyKind.GATE} and (
352
+ target.role is not ScenarioRole.CONTROL or target.weight_microunits != 0
353
+ ):
354
+ raise ContractDocumentError("control and gate dependencies require controls")
355
+ graph[definition.scenario_id] = set(dependency_ids)
356
+ remaining = {node: len(edges) for node, edges in graph.items()}
357
+ dependents: dict[str, set[str]] = {node: set() for node in graph}
358
+ for node, edges in graph.items():
359
+ for edge in edges:
360
+ dependents[edge].add(node)
361
+ ready = [node for node, count in remaining.items() if count == 0]
362
+ visited = 0
363
+ while ready:
364
+ node = ready.pop()
365
+ visited += 1
366
+ for dependent in dependents[node]:
367
+ remaining[dependent] -= 1
368
+ if remaining[dependent] == 0:
369
+ ready.append(dependent)
370
+ if visited != len(graph):
371
+ raise ContractDocumentError("scenario dependency graph contains a cycle")
372
+ return order, by_id
373
+
374
+
375
+ def verify_catalog_sources(
376
+ root: CatalogRoot,
377
+ definitions: tuple[ScenarioDefinition, ...],
378
+ /,
379
+ ) -> CatalogVerification:
380
+ if type(root) is not CatalogRoot:
381
+ raise ContractDocumentError("catalog root must use the exact typed structure")
382
+ flattened = tuple(
383
+ (shard.function_id, export)
384
+ for shard in root.shards
385
+ for export in shard.exports
386
+ )
387
+ if type(definitions) is not tuple or len(definitions) != len(flattened):
388
+ raise ContractDocumentError("definition count does not match catalog exports")
389
+ _ordered_definitions(definitions)
390
+ for definition, (function_id, _export) in zip(definitions, flattened, strict=True):
391
+ if definition.classification.primary != function_id:
392
+ raise ContractDocumentError("definition primary classification differs from owner shard")
393
+ digests = tuple(definition_digest(item) for item in definitions)
394
+ semantic = _semantic_digest(
395
+ _VERIFICATION_DOMAIN,
396
+ {"definition_digests": list(digests), "root_semantic_digest": root.semantic_digest},
397
+ )
398
+ source_digests = (
399
+ root.source_digest,
400
+ root.taxonomy_digest,
401
+ *(shard.source_digest for shard in root.shards),
402
+ )
403
+ return CatalogVerification(definitions, source_digests, semantic)
404
+
405
+
406
+ def load_catalog_sources(
407
+ root: CatalogRoot,
408
+ resources: dict[LogicalCatalogResource, bytes],
409
+ importer: CatalogImporter,
410
+ /,
411
+ ) -> tuple[ScenarioDefinition, ...]:
412
+ if type(root) is not CatalogRoot or type(resources) is not dict or not callable(importer):
413
+ raise ContractDocumentError("catalog loading requires exact root, dict resources and importer")
414
+ if len(resources) > _MAX_SHARDS + 1:
415
+ raise ContractDocumentError("catalog resources exceed the size limit")
416
+ if any(type(key) is not LogicalCatalogResource or type(value) is not bytes for key, value in resources.items()):
417
+ raise ContractDocumentError("catalog resources require exact logical keys and byte values")
418
+ if any(not value or len(value) > _MAX_SOURCE_BYTES for value in resources.values()):
419
+ raise ContractDocumentError("catalog resource bytes exceed source limits")
420
+ snapshot = dict(resources)
421
+ expected = {root.taxonomy_resource, *(shard.resource for shard in root.shards)}
422
+ if set(snapshot) != expected:
423
+ raise ContractDocumentError("catalog resource set does not match the root")
424
+ taxonomy_raw = snapshot[root.taxonomy_resource]
425
+ if _raw_digest(taxonomy_raw) != root.taxonomy_digest:
426
+ raise ContractDocumentError("taxonomy source digest differs from the root")
427
+ taxonomy: Taxonomy = parse_taxonomy(taxonomy_raw)
428
+ known_functions = frozenset(item.function_id for item in taxonomy.entries)
429
+ if any(shard.function_id not in known_functions for shard in root.shards):
430
+ raise ContractDocumentError("catalog root contains an unknown taxonomy function")
431
+ parsed_shards: list[CatalogShard] = []
432
+ for expected_shard in root.shards:
433
+ raw = snapshot[expected_shard.resource]
434
+ if _raw_digest(raw) != expected_shard.source_digest:
435
+ raise ContractDocumentError("shard source digest differs from the root")
436
+ parsed = parse_catalog_shard(raw)
437
+ if parsed != expected_shard:
438
+ raise ContractDocumentError("shard source differs from its root descriptor")
439
+ parsed_shards.append(parsed)
440
+ definitions: list[ScenarioDefinition] = []
441
+ object_ids: set[int] = set()
442
+ for shard in parsed_shards:
443
+ for module, export in shard.exports:
444
+ try:
445
+ definition = importer(module, export)
446
+ except Exception:
447
+ raise ContractDocumentError("catalog importer failed") from None
448
+ if type(definition) is not ScenarioDefinition:
449
+ raise ContractDocumentError("catalog importer returned an invalid definition")
450
+ if id(definition) in object_ids:
451
+ raise ContractDocumentError("catalog importer reused a definition object")
452
+ object_ids.add(id(definition))
453
+ if definition.classification.primary != shard.function_id:
454
+ raise ContractDocumentError("imported definition differs from its owner shard")
455
+ validate_classification(definition.classification, taxonomy)
456
+ definitions.append(definition)
457
+ return verify_catalog_sources(root, tuple(definitions)).definitions
458
+
459
+
460
+ __all__ = [
461
+ "CatalogImporter",
462
+ "CatalogRoot",
463
+ "CatalogShard",
464
+ "CatalogVerification",
465
+ "LogicalCatalogResource",
466
+ "load_catalog_sources",
467
+ "parse_catalog_root",
468
+ "parse_catalog_shard",
469
+ "verify_catalog_sources",
470
+ ]
code/src/doc2harness/benchmark/catalog_root.toml ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ format = "doc2harness.catalog-root-source/1"
2
+ taxonomy_resource = "benchmark/taxonomy.toml"
3
+ taxonomy_source_digest = "sha256:43b99ad485708c75a6ce93c95669b85bd9c384f03cbff027dfb490cc9df3c779"
4
+
5
+ [[shards]]
6
+ function_id = "artifact"
7
+ resource = "benchmark/harnesses/artifact/catalog.toml"
8
+ source_digest = "sha256:ab17d776974982aabacdaf55493fedef33225bf9f21ba7f4674a3c3430bf6325"
9
+ semantic_digest = "sha256:e0f2c5d47ad715c4b0e56a6166ae4c2e31138327fe0770721da2b237d1fbbd1c"
10
+ exports = [
11
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_declares_dependencies", export = "definition" },
12
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_entry_py", export = "definition" },
13
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_install_sh", export = "definition" },
14
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_offline_wheel", export = "definition" },
15
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_requirements_lock", export = "definition" },
16
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_run_agent_sh", export = "definition" },
17
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_version_file", export = "definition" },
18
+ ]
19
+
20
+ [[shards]]
21
+ function_id = "direct"
22
+ resource = "benchmark/harnesses/direct/catalog.toml"
23
+ source_digest = "sha256:b83648161b87b31473c4eaf384b44830a2a9a1a9ed874119c1b6cbe152f66cb7"
24
+ semantic_digest = "sha256:7555e696b9886c9f87c30bbaa01b3afaa0817a9e40e9368841d967e5577db54c"
25
+ exports = [
26
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.exfil_glob_pem_not_leaked", export = "definition" },
27
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic", export = "definition" },
28
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic_control", export = "definition" },
29
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion", export = "definition" },
30
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion_control", export = "definition" },
31
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.secret_probe_mechanism_control", export = "definition" },
32
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace", export = "definition" },
33
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace_control", export = "definition" },
34
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.unreferenced_secret_not_in_request_body", export = "definition" },
35
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure", export = "definition" },
36
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure_control", export = "definition" },
37
+ ]
38
+
39
+ [[shards]]
40
+ function_id = "extension"
41
+ resource = "benchmark/harnesses/extension/catalog.toml"
42
+ source_digest = "sha256:78ca3a4f9b32aae12a3f901fa8fe6ba621de830fa0c01319f226743a59d7ecfb"
43
+ semantic_digest = "sha256:1cd6e9811b82411ccd00fa4f43828beff035d9ec9d7e35a1354c75cc92ae7abc"
44
+ exports = [
45
+ { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_definition_symlink_outside_fenced", export = "definition" },
46
+ { module = "doc2harness.benchmark.harnesses.extension.scenarios.extension_inside_symlink_discovery_control", export = "definition" },
47
+ ]
48
+
49
+ [[shards]]
50
+ function_id = "file"
51
+ resource = "benchmark/harnesses/file/catalog.toml"
52
+ source_digest = "sha256:7f3ae97eca67f93812bef69a8d591b9d76527593b8c237548d39a1f42939faf5"
53
+ semantic_digest = "sha256:202e42f04f066970a2e65ad02f6b7bea1b86398be2cbcb0183a2dd1a7936bc45"
54
+ exports = [
55
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.file_symlink_inside_still_readable_control", export = "definition" },
56
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_finds_inside_control", export = "definition" },
57
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.glob_truncation_keeps_sorted_end", export = "definition" },
58
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_default_mode_returns_path_control", export = "definition" },
59
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_finds_needle_control", export = "definition" },
60
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_head_limit_zero_not_unlimited", export = "definition" },
61
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.grep_type_filter_ignored", export = "definition" },
62
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.memory_get_abs_path_escapes_workspace", export = "definition" },
63
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_cell_isolation", export = "definition" },
64
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.notebook_edit_delete_keeps_neighbors", export = "definition" },
65
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.p32_ctl_memory_get_reads_inside_workspace", export = "definition" },
66
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.read_char_device_bounded", export = "definition" },
67
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.read_regular_file_control", export = "definition" },
68
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.read_via_symlink_outside_workspace_bounded", export = "definition" },
69
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.rewind_restores_edited_file", export = "definition" },
70
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.symlink_to_outside_target_readable_control", export = "definition" },
71
+ { module = "doc2harness.benchmark.harnesses.file.scenarios.undo_reverts_overwrite_control", export = "definition" },
72
+ ]
73
+
74
+ [[shards]]
75
+ function_id = "headless"
76
+ resource = "benchmark/harnesses/headless/catalog.toml"
77
+ source_digest = "sha256:ec48824b157b32c10beab39254d57924756a62069e91c547a89e5f3ae5618704"
78
+ semantic_digest = "sha256:f29ef08c7ea259da1515f99be1860413a083c95f127141c8f25ccefb42567b55"
79
+ exports = [
80
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.at_ref_expands_in_headless", export = "definition" },
81
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain", export = "definition" },
82
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.budget_type_domain_control", export = "definition" },
83
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg", export = "definition" },
84
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.exec_requires_bg_control", export = "definition" },
85
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_model_error_wellformed", export = "definition" },
86
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.headless_p_json_wellformed", export = "definition" },
87
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_bare_mention_not_auto_read", export = "definition" },
88
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.p34_ctl_task_text_reaches_wire", export = "definition" },
89
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout", export = "definition" },
90
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.runtime_error_stdout_control", export = "definition" },
91
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict", export = "definition" },
92
+ { module = "doc2harness.benchmark.harnesses.headless.scenarios.session_flag_subcommand_conflict_control", export = "definition" },
93
+ ]
94
+
95
+ [[shards]]
96
+ function_id = "permission"
97
+ resource = "benchmark/harnesses/permission/catalog.toml"
98
+ source_digest = "sha256:c515c06dbb8a17857ce86242bd0045a573c6684b4e56e7a1ee4e342980058be4"
99
+ semantic_digest = "sha256:d0cd5ba6de354ad72f8abbc46b7353db084e86325d99b2c26a36bf1a2cfc6b83"
100
+ exports = [
101
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.ask_mode_denies_write_and_allows_read", export = "definition" },
102
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoedit_blocks_mutable_shell", export = "definition" },
103
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.autoreview_blocks_canonical_danger", export = "definition" },
104
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_control", export = "definition" },
105
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.blocking_hook_missing_exec_fail_closed", export = "definition" },
106
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_read_fences_control", export = "definition" },
107
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.custom_cmd_at_file_respects_read_fences", export = "definition" },
108
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.deny_blocks_monitor_spawned_cmd", export = "definition" },
109
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_absent_bash_write_runs_control", export = "definition" },
110
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.hook_blocks_bash_write", export = "definition" },
111
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.monitor_spawns_command_control", export = "definition" },
112
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.network_off_blocks_offline_npm_test", export = "definition" },
113
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.p37_ctl_plain_cmd_chain_runs", export = "definition" },
114
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.p46_ctl_yolo_rm_really_deletes", export = "definition" },
115
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.p60_ctl_yolo_both_work", export = "definition" },
116
+ { module = "doc2harness.benchmark.harnesses.permission.scenarios.yolo_mutable_shell_lands_control", export = "definition" },
117
+ ]
118
+
119
+ [[shards]]
120
+ function_id = "startup"
121
+ resource = "benchmark/harnesses/startup/catalog.toml"
122
+ source_digest = "sha256:9893ae5607570c43319ca2934f2c2eb451276c7cff31fe9496aee84fd4391f20"
123
+ semantic_digest = "sha256:7439429b84748b822599c2bd4a4cbab0270f39c0ececc93eb991d632ebf010c1"
124
+ exports = [
125
+ { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_ambient_python_isolated", export = "definition" },
126
+ { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_health_control", export = "definition" },
127
+ { module = "doc2harness.benchmark.harnesses.startup.scenarios.launcher_python_minimum_fallback", export = "definition" },
128
+ { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_bom_config", export = "definition" },
129
+ { module = "doc2harness.benchmark.harnesses.startup.scenarios.startup_broken_config_file", export = "definition" },
130
+ ]
131
+
132
+ [[shards]]
133
+ function_id = "state"
134
+ resource = "benchmark/harnesses/state/catalog.toml"
135
+ source_digest = "sha256:29d6d7694b1821cd86e0767784ab8fe17851de947a117557acf59bcd60b4b193"
136
+ semantic_digest = "sha256:bfb6dfab995d43d01c912c0c05eb7ef919281e30c16b5009134693fd7679fcdc"
137
+ exports = [
138
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete", export = "definition" },
139
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.agent_api_close_retry_incomplete_control", export = "definition" },
140
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance", export = "definition" },
141
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.child_add_dir_inheritance_control", export = "definition" },
142
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_bytes", export = "definition" },
143
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.copy_utf8_clipboard_control", export = "definition" },
144
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_no_secondary_expansion", export = "definition" },
145
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.custom_args_single_expansion_control", export = "definition" },
146
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency", export = "definition" },
147
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.memory_query_topk_residency_control", export = "definition" },
148
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.p30_ctl_security_review_sees_worktree_change", export = "definition" },
149
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_declared_command_reaches_wire", export = "definition" },
150
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.plugin_toplevel_command_control", export = "definition" },
151
+ { module = "doc2harness.benchmark.harnesses.state.scenarios.security_review_covers_branch_commits", export = "definition" },
152
+ ]
153
+
154
+ [[shards]]
155
+ function_id = "tui"
156
+ resource = "benchmark/harnesses/tui/catalog.toml"
157
+ source_digest = "sha256:33c5b7a874a86ed54b7dd7bef266298e13ad78c0618968fa05c586e20a39e6bd"
158
+ semantic_digest = "sha256:71eb0680a3a71bb9e913bb666c282d30aa43802baca4f3a41c859433acb54a98"
159
+ exports = [
160
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_realpath_key", export = "definition" },
161
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_a_fresh_control", export = "definition" },
162
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.history_workspace_b_fresh_control", export = "definition" },
163
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded", export = "definition" },
164
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_autocommit_fail_recorded_control", export = "definition" },
165
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate", export = "definition" },
166
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.trajectory_step_limit_terminal_accurate_control", export = "definition" },
167
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_bang_alone_enters_shell_mode", export = "definition" },
168
+ { module = "doc2harness.benchmark.harnesses.tui.scenarios.tui_ctrl_byte_storm_survives", export = "definition" },
169
+ ]
code/src/doc2harness/benchmark/definition.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Immutable scenario definitions without execution behavior."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+
10
+ from doc2harness.contracts.canonical import canonical_json
11
+ from doc2harness.contracts.primitives import ContractDocumentError
12
+
13
+ _IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII)
14
+ _REVISION = re.compile(r"[1-9][0-9]{0,8}\Z", re.ASCII)
15
+ _DIGEST_DOMAIN = b"doc2harness.scenario-definition/1\x00"
16
+ _MAX_CLASSIFICATIONS = 32
17
+ _MAX_DEPENDENCIES = 256
18
+ _MAX_WEIGHT = 2**63 - 1
19
+
20
+
21
+ def _identifier(value: object, name: str) -> str:
22
+ if type(value) is not str or _IDENTIFIER.fullmatch(value) is None:
23
+ raise ContractDocumentError(f"{name} is not a canonical identifier")
24
+ return value
25
+
26
+
27
+ class ScenarioRole(str, Enum):
28
+ TARGET = "TARGET"
29
+ CONTROL = "CONTROL"
30
+
31
+
32
+ class ScenarioDifficulty(str, Enum):
33
+ STANDARD = "STANDARD"
34
+ HARD = "HARD"
35
+
36
+
37
+ class UnsupportedPolicy(str, Enum):
38
+ FAIL = "FAIL"
39
+ NOT_APPLICABLE = "NOT_APPLICABLE"
40
+
41
+
42
+ class ComponentKind(str, Enum):
43
+ FIXTURE = "FIXTURE"
44
+ STIMULUS = "STIMULUS"
45
+ OBSERVER = "OBSERVER"
46
+ ORACLE = "ORACLE"
47
+ CLEANUP = "CLEANUP"
48
+ NO_OP = "NO_OP"
49
+
50
+
51
+ class DependencyKind(str, Enum):
52
+ REQUIREMENT = "REQUIREMENT"
53
+ CONTROL = "CONTROL"
54
+ GATE = "GATE"
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class Classification:
59
+ """One stable primary function and zero or more ordered secondary functions."""
60
+
61
+ primary: str
62
+ secondary: tuple[str, ...] = ()
63
+
64
+ def __post_init__(self) -> None:
65
+ _identifier(self.primary, "primary classification")
66
+ if type(self.secondary) is not tuple:
67
+ raise ContractDocumentError("secondary classifications must be an exact tuple")
68
+ if len(self.secondary) > _MAX_CLASSIFICATIONS:
69
+ raise ContractDocumentError("secondary classifications exceed the size limit")
70
+ for item in self.secondary:
71
+ _identifier(item, "secondary classification")
72
+ if self.primary in self.secondary or len(set(self.secondary)) != len(self.secondary):
73
+ raise ContractDocumentError("classifications must be unique")
74
+ if self.secondary != tuple(sorted(self.secondary)):
75
+ raise ContractDocumentError("secondary classifications must be sorted")
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class ComponentRef:
80
+ """A versioned component identity; NO_OP is explicit, never represented by None."""
81
+
82
+ component_id: str
83
+ revision: str
84
+ kind: ComponentKind
85
+
86
+ def __post_init__(self) -> None:
87
+ _identifier(self.component_id, "component id")
88
+ if type(self.revision) is not str or _REVISION.fullmatch(self.revision) is None:
89
+ raise ContractDocumentError("component revision is not canonical")
90
+ if type(self.kind) is not ComponentKind:
91
+ raise ContractDocumentError("component kind must use ComponentKind")
92
+ if self.kind is ComponentKind.NO_OP and self.component_id != "no-op":
93
+ raise ContractDocumentError("NO_OP must use the canonical no-op component")
94
+ if self.kind is not ComponentKind.NO_OP and self.component_id == "no-op":
95
+ raise ContractDocumentError("the canonical no-op component must use NO_OP")
96
+
97
+ @classmethod
98
+ def no_op(cls) -> ComponentRef:
99
+ return cls("no-op", "1", ComponentKind.NO_OP)
100
+
101
+
102
+ @dataclass(frozen=True, slots=True)
103
+ class DependencyRef:
104
+ scenario_id: str
105
+ kind: DependencyKind
106
+
107
+ def __post_init__(self) -> None:
108
+ _identifier(self.scenario_id, "dependency scenario id")
109
+ if type(self.kind) is not DependencyKind:
110
+ raise ContractDocumentError("dependency kind must use DependencyKind")
111
+
112
+
113
+ @dataclass(frozen=True, slots=True)
114
+ class ExperimentBinding:
115
+ fixture: ComponentRef
116
+ stimulus: ComponentRef
117
+ observer: ComponentRef
118
+ oracle: ComponentRef
119
+ cleanup: ComponentRef
120
+
121
+ def __post_init__(self) -> None:
122
+ expected = (
123
+ (self.fixture, ComponentKind.FIXTURE),
124
+ (self.stimulus, ComponentKind.STIMULUS),
125
+ (self.observer, ComponentKind.OBSERVER),
126
+ (self.oracle, ComponentKind.ORACLE),
127
+ (self.cleanup, ComponentKind.CLEANUP),
128
+ )
129
+ for value, kind in expected:
130
+ if type(value) is not ComponentRef:
131
+ raise ContractDocumentError("experiment bindings require exact ComponentRef values")
132
+ if value.kind not in {kind, ComponentKind.NO_OP}:
133
+ raise ContractDocumentError("component kind does not match its binding slot")
134
+
135
+
136
+ @dataclass(frozen=True, slots=True)
137
+ class ScenarioDefinition:
138
+ scenario_id: str
139
+ revision: str
140
+ classification: Classification
141
+ role: ScenarioRole
142
+ weight_microunits: int
143
+ difficulty: ScenarioDifficulty
144
+ dependencies: tuple[DependencyRef, ...]
145
+ experiment: ExperimentBinding
146
+ unsupported_policy: UnsupportedPolicy
147
+
148
+ def __post_init__(self) -> None:
149
+ _identifier(self.scenario_id, "scenario id")
150
+ if type(self.revision) is not str or _REVISION.fullmatch(self.revision) is None:
151
+ raise ContractDocumentError("scenario revision is not canonical")
152
+ if type(self.classification) is not Classification:
153
+ raise ContractDocumentError("classification must use the exact typed structure")
154
+ if type(self.role) is not ScenarioRole:
155
+ raise ContractDocumentError("role must use ScenarioRole")
156
+ if (
157
+ type(self.weight_microunits) is not int
158
+ or self.weight_microunits < 0
159
+ or self.weight_microunits > _MAX_WEIGHT
160
+ ):
161
+ raise ContractDocumentError("weight must be a bounded non-negative exact integer")
162
+ if (self.role is ScenarioRole.TARGET) != (self.weight_microunits > 0):
163
+ raise ContractDocumentError("targets require positive weight and controls require zero weight")
164
+ if type(self.difficulty) is not ScenarioDifficulty:
165
+ raise ContractDocumentError("difficulty must use ScenarioDifficulty")
166
+ if type(self.dependencies) is not tuple or len(self.dependencies) > _MAX_DEPENDENCIES:
167
+ raise ContractDocumentError("dependencies must be a bounded exact tuple")
168
+ if any(type(item) is not DependencyRef for item in self.dependencies):
169
+ raise ContractDocumentError("dependencies must be an exact tuple of DependencyRef")
170
+ identities = tuple((item.scenario_id, item.kind.value) for item in self.dependencies)
171
+ if len(set(identities)) != len(identities) or identities != tuple(sorted(identities)):
172
+ raise ContractDocumentError("dependencies must be sorted and unique")
173
+ if any(item.scenario_id == self.scenario_id for item in self.dependencies):
174
+ raise ContractDocumentError("scenario cannot depend on itself")
175
+ if type(self.experiment) is not ExperimentBinding:
176
+ raise ContractDocumentError("experiment must use ExperimentBinding")
177
+ if type(self.unsupported_policy) is not UnsupportedPolicy:
178
+ raise ContractDocumentError("unsupported policy must use UnsupportedPolicy")
179
+
180
+
181
+ def _component_body(value: ComponentRef) -> dict[str, str]:
182
+ return {"component_id": value.component_id, "kind": value.kind.value, "revision": value.revision}
183
+
184
+
185
+ def definition_digest(definition: ScenarioDefinition, /) -> str:
186
+ """Return the domain-separated semantic digest of one typed definition."""
187
+
188
+ if type(definition) is not ScenarioDefinition:
189
+ raise ContractDocumentError("definition must use ScenarioDefinition")
190
+ body = {
191
+ "classification": {
192
+ "primary": definition.classification.primary,
193
+ "secondary": list(definition.classification.secondary),
194
+ },
195
+ "dependencies": [
196
+ {"kind": item.kind.value, "scenario_id": item.scenario_id}
197
+ for item in definition.dependencies
198
+ ],
199
+ "difficulty": definition.difficulty.value,
200
+ "experiment": {
201
+ "cleanup": _component_body(definition.experiment.cleanup),
202
+ "fixture": _component_body(definition.experiment.fixture),
203
+ "observer": _component_body(definition.experiment.observer),
204
+ "oracle": _component_body(definition.experiment.oracle),
205
+ "stimulus": _component_body(definition.experiment.stimulus),
206
+ },
207
+ "revision": definition.revision,
208
+ "role": definition.role.value,
209
+ "scenario_id": definition.scenario_id,
210
+ "unsupported_policy": definition.unsupported_policy.value,
211
+ "weight_microunits": definition.weight_microunits,
212
+ }
213
+ return "sha256:" + hashlib.sha256(_DIGEST_DOMAIN + canonical_json(body)).hexdigest()
214
+
215
+
216
+ __all__ = [
217
+ "Classification", "ComponentKind", "ComponentRef", "DependencyKind",
218
+ "DependencyRef", "ExperimentBinding", "ScenarioDefinition", "ScenarioDifficulty",
219
+ "ScenarioRole", "UnsupportedPolicy", "definition_digest",
220
+ ]
code/src/doc2harness/benchmark/dispatch.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resolve active catalog IDs to their scenario-local execution owners."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ from dataclasses import dataclass
7
+ from functools import lru_cache
8
+ from importlib.resources import files
9
+ from typing import Callable
10
+
11
+ from doc2harness.benchmark.catalog import (
12
+ CatalogRoot,
13
+ load_catalog_sources,
14
+ parse_catalog_root,
15
+ )
16
+ from doc2harness.benchmark.definition import ScenarioDefinition
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ _PACKAGE = "doc2harness"
20
+ _BENCHMARK = "benchmark"
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class ScenarioOwner:
25
+ """One catalog definition and the module that owns its runtime recipe."""
26
+
27
+ definition: ScenarioDefinition
28
+ scenario: object
29
+ judge: Callable[[object], object]
30
+ module: str
31
+
32
+
33
+ def _catalog_root() -> CatalogRoot:
34
+ root = files(_PACKAGE).joinpath(_BENCHMARK)
35
+ return parse_catalog_root(root.joinpath("catalog_root.toml").read_bytes())
36
+
37
+
38
+ @lru_cache(maxsize=1)
39
+ def _definitions_and_modules() -> tuple[
40
+ tuple[ScenarioDefinition, ...], dict[str, str]
41
+ ]:
42
+ package = files(_PACKAGE)
43
+ benchmark = package.joinpath(_BENCHMARK)
44
+ root = _catalog_root()
45
+ resources = {
46
+ root.taxonomy_resource: benchmark.joinpath("taxonomy.toml").read_bytes(),
47
+ **{
48
+ shard.resource: package.joinpath(*shard.resource.segments).read_bytes()
49
+ for shard in root.shards
50
+ },
51
+ }
52
+ definitions = load_catalog_sources(
53
+ root,
54
+ resources,
55
+ lambda module, export: getattr(importlib.import_module(module), export),
56
+ )
57
+ modules = {
58
+ getattr(importlib.import_module(module), export).scenario_id: module
59
+ for shard in root.shards
60
+ for module, export in shard.exports
61
+ }
62
+ if len(modules) != len(definitions):
63
+ raise ContractDocumentError("active catalog module index is ambiguous")
64
+ return definitions, modules
65
+
66
+
67
+ def active_scenario_ids() -> tuple[str, ...]:
68
+ """Return the complete, catalog-ordered active scenario universe."""
69
+
70
+ definitions, _ = _definitions_and_modules()
71
+ return tuple(item.scenario_id for item in definitions)
72
+
73
+
74
+ def load_scenario_owner(scenario_id: str, /) -> ScenarioOwner:
75
+ """Load one local recipe/judge owner and verify its catalog binding."""
76
+
77
+ if type(scenario_id) is not str or not scenario_id:
78
+ raise ContractDocumentError("scenario id must be a non-empty string")
79
+ definitions, modules = _definitions_and_modules()
80
+ definitions_by_id = {item.scenario_id: item for item in definitions}
81
+ definition = definitions_by_id.get(scenario_id)
82
+ module_name = modules.get(scenario_id)
83
+ if definition is None or module_name is None:
84
+ raise ContractDocumentError("scenario id is absent from the active catalog")
85
+ module = importlib.import_module(module_name)
86
+ scenario = getattr(module, "SCENARIO", None)
87
+ alias = getattr(module, "scenario", None)
88
+ judge = getattr(module, "judge", None)
89
+ local_definition = getattr(module, "definition", None)
90
+ if scenario is None or alias is None:
91
+ raise ContractDocumentError("scenario module has no canonical local owner")
92
+ if local_definition is not definition:
93
+ raise ContractDocumentError("scenario module definition differs from catalog import")
94
+ owned_definition = getattr(scenario, "definition", None)
95
+ if owned_definition is not definition:
96
+ raise ContractDocumentError("scenario owner definition differs from catalog import")
97
+ if getattr(alias, "definition", None) is not definition:
98
+ raise ContractDocumentError("catalog compatibility scenario differs from catalog import")
99
+ if not callable(judge):
100
+ raise ContractDocumentError("scenario module has no local judge")
101
+ return ScenarioOwner(definition, scenario, judge, module_name)
102
+
103
+
104
+ __all__ = [
105
+ "ScenarioOwner",
106
+ "active_scenario_ids",
107
+ "load_scenario_owner",
108
+ ]
code/src/doc2harness/benchmark/harnesses/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Primary Harness layer packages."""
2
+
3
+ __all__: list[str] = []
code/src/doc2harness/benchmark/harnesses/artifact/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed declarations for the static artifact Harness layer."""
2
+
3
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
4
+ ArtifactLogicalPath,
5
+ ArtifactProbe,
6
+ ArtifactProbeApplicability,
7
+ ArtifactProbeEvaluation,
8
+ ArtifactProbeKind,
9
+ ArtifactProbeMetrics,
10
+ ArtifactProbeObservation,
11
+ ArtifactProbeOutcome,
12
+ ArtifactScenario,
13
+ create_artifact_probe_observation,
14
+ define_artifact_scenario,
15
+ )
16
+
17
+ __all__ = [
18
+ "ArtifactLogicalPath",
19
+ "ArtifactProbe",
20
+ "ArtifactProbeApplicability",
21
+ "ArtifactProbeEvaluation",
22
+ "ArtifactProbeKind",
23
+ "ArtifactProbeMetrics",
24
+ "ArtifactProbeObservation",
25
+ "ArtifactProbeOutcome",
26
+ "ArtifactScenario",
27
+ "create_artifact_probe_observation",
28
+ "define_artifact_scenario",
29
+ ]
code/src/doc2harness/benchmark/harnesses/artifact/catalog.toml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ format = "doc2harness.catalog-shard-source/1"
2
+ function_id = "artifact"
3
+ resource = "benchmark/harnesses/artifact/catalog.toml"
4
+ exports = [
5
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_declares_dependencies", export = "definition" },
6
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_entry_py", export = "definition" },
7
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_install_sh", export = "definition" },
8
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_offline_wheel", export = "definition" },
9
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_requirements_lock", export = "definition" },
10
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_run_agent_sh", export = "definition" },
11
+ { module = "doc2harness.benchmark.harnesses.artifact.scenarios.artifact_has_version_file", export = "definition" },
12
+ ]
code/src/doc2harness/benchmark/harnesses/artifact/contracts.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-closed declaration boundary for static artifact scenarios."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ import hashlib
8
+ from dataclasses import dataclass
9
+ from enum import Enum
10
+
11
+ from doc2harness.benchmark.definition import (
12
+ Classification,
13
+ ComponentKind,
14
+ ComponentRef,
15
+ ExperimentBinding,
16
+ ScenarioDefinition,
17
+ ScenarioDifficulty,
18
+ ScenarioRole,
19
+ UnsupportedPolicy,
20
+ definition_digest,
21
+ )
22
+ from doc2harness.contracts.canonical import canonical_json
23
+ from doc2harness.contracts.primitives import ContractDocumentError
24
+
25
+ _SCENARIO_ID = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\Z", re.ASCII)
26
+ _MAX_PATHS = 8
27
+ _MAX_SEGMENTS = 32
28
+ _MAX_SEGMENT_BYTES = 255
29
+
30
+
31
+ class ArtifactProbeKind(str, Enum):
32
+ FILE_PRESENT = "FILE_PRESENT"
33
+ FILE_NONEMPTY = "FILE_NONEMPTY"
34
+ DIRECTORY_MEMBER_SUFFIX = "DIRECTORY_MEMBER_SUFFIX"
35
+ DEPENDENCY_DECLARATION = "DEPENDENCY_DECLARATION"
36
+
37
+
38
+ class ArtifactProbeOutcome(str, Enum):
39
+ PASS = "PASS"
40
+ FAIL = "FAIL"
41
+
42
+
43
+ class ArtifactProbeApplicability(str, Enum):
44
+ APPLICABLE = "APPLICABLE"
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class ArtifactLogicalPath:
49
+ """A bounded path relative to the runtime-owned artifact root."""
50
+
51
+ segments: tuple[str, ...]
52
+
53
+ def __post_init__(self) -> None:
54
+ if type(self.segments) is not tuple or not self.segments or len(self.segments) > _MAX_SEGMENTS:
55
+ raise ContractDocumentError("artifact path must contain bounded exact segments")
56
+ for segment in self.segments:
57
+ if type(segment) is not str or segment in {"", ".", ".."}:
58
+ raise ContractDocumentError("artifact path contains an invalid segment")
59
+ if unicodedata.normalize("NFC", segment) != segment:
60
+ raise ContractDocumentError("artifact path segment is not Unicode NFC")
61
+ try:
62
+ encoded = segment.encode("utf-8", errors="strict")
63
+ except UnicodeError:
64
+ raise ContractDocumentError("artifact path segment is not valid UTF-8") from None
65
+ if (
66
+ len(encoded) > _MAX_SEGMENT_BYTES
67
+ or "/" in segment
68
+ or "\\" in segment
69
+ or any(ord(character) < 32 or ord(character) == 127 for character in segment)
70
+ ):
71
+ raise ContractDocumentError("artifact path segment is unsafe")
72
+
73
+
74
+ @dataclass(frozen=True, slots=True)
75
+ class ArtifactProbe:
76
+ """Declarative probe intent; it contains no host path or execution behavior."""
77
+
78
+ kind: ArtifactProbeKind
79
+ paths: tuple[ArtifactLogicalPath, ...]
80
+ member_suffix: str | None = None
81
+
82
+ def __post_init__(self) -> None:
83
+ if type(self.kind) is not ArtifactProbeKind:
84
+ raise ContractDocumentError("artifact probe kind must use the closed vocabulary")
85
+ if (
86
+ type(self.paths) is not tuple
87
+ or not self.paths
88
+ or len(self.paths) > _MAX_PATHS
89
+ or any(type(path) is not ArtifactLogicalPath for path in self.paths)
90
+ ):
91
+ raise ContractDocumentError("artifact probe paths must be a bounded exact tuple")
92
+ if len(set(self.paths)) != len(self.paths):
93
+ raise ContractDocumentError("artifact probe paths must be unique")
94
+ if self.kind is ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX:
95
+ if (
96
+ len(self.paths) != 1
97
+ or type(self.member_suffix) is not str
98
+ or not self.member_suffix.startswith(".")
99
+ or len(self.member_suffix) > 32
100
+ or not self.member_suffix.isascii()
101
+ or any(character in self.member_suffix for character in "/\\")
102
+ ):
103
+ raise ContractDocumentError("directory member probes require one safe suffix")
104
+ elif self.kind is ArtifactProbeKind.DEPENDENCY_DECLARATION:
105
+ expected = (
106
+ ArtifactLogicalPath(("pyproject.toml",)),
107
+ ArtifactLogicalPath(("requirements.txt",)),
108
+ )
109
+ if self.paths != expected or self.member_suffix is not None:
110
+ raise ContractDocumentError("dependency probes require the canonical manifest paths")
111
+ elif len(self.paths) != 1 or self.member_suffix is not None:
112
+ raise ContractDocumentError("file probes require one path and no suffix")
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class ArtifactScenario:
117
+ """One immutable scenario definition paired with its declarative probe."""
118
+
119
+ definition: ScenarioDefinition
120
+ probe: ArtifactProbe
121
+
122
+ def __post_init__(self) -> None:
123
+ if type(self.definition) is not ScenarioDefinition or type(self.probe) is not ArtifactProbe:
124
+ raise ContractDocumentError("artifact scenarios require exact typed values")
125
+ if self.definition.classification.primary != "artifact":
126
+ raise ContractDocumentError("artifact scenario owner differs from its Harness layer")
127
+
128
+
129
+ @dataclass(frozen=True, slots=True)
130
+ class ArtifactProbeMetrics:
131
+ """Closed path-free facts emitted by the four static probe shapes."""
132
+
133
+ file_exists: bool | None = None
134
+ directory_exists: bool | None = None
135
+ size_bytes: int | None = None
136
+ matching_members: int | None = None
137
+ project_marker: bool | None = None
138
+ requirements_nonempty: bool | None = None
139
+
140
+ def __post_init__(self) -> None:
141
+ for value in (
142
+ self.file_exists,
143
+ self.directory_exists,
144
+ self.project_marker,
145
+ self.requirements_nonempty,
146
+ ):
147
+ if value is not None and type(value) is not bool:
148
+ raise ContractDocumentError("artifact metric booleans must be exact bool values")
149
+ for value in (self.size_bytes, self.matching_members):
150
+ if value is not None and (type(value) is not int or value < 0):
151
+ raise ContractDocumentError("artifact metric counts must be non-negative exact integers")
152
+
153
+
154
+ def _digest(value: object, name: str) -> str:
155
+ if (
156
+ type(value) is not str
157
+ or not value.startswith("sha256:")
158
+ or len(value) != 71
159
+ or any(character not in "0123456789abcdef" for character in value[7:])
160
+ ):
161
+ raise ContractDocumentError(f"{name} is invalid")
162
+ return value
163
+
164
+
165
+ def _probe_body(probe: ArtifactProbe) -> dict[str, object]:
166
+ return {
167
+ "kind": probe.kind.value,
168
+ "member_suffix": probe.member_suffix,
169
+ "paths": [list(path.segments) for path in probe.paths],
170
+ }
171
+
172
+
173
+ def _metrics_body(metrics: ArtifactProbeMetrics) -> dict[str, object]:
174
+ return {
175
+ "directory_exists": metrics.directory_exists,
176
+ "file_exists": metrics.file_exists,
177
+ "matching_members": metrics.matching_members,
178
+ "project_marker": metrics.project_marker,
179
+ "requirements_nonempty": metrics.requirements_nonempty,
180
+ "size_bytes": metrics.size_bytes,
181
+ }
182
+
183
+
184
+ def _observation_digest(
185
+ scenario_id: str,
186
+ scenario_revision: str,
187
+ semantic_definition_digest: str,
188
+ artifact_id: str,
189
+ artifact_digest: str,
190
+ probe: ArtifactProbe,
191
+ metrics: ArtifactProbeMetrics,
192
+ runtime_evidence_digests: tuple[str, ...],
193
+ ) -> str:
194
+ body = {
195
+ "artifact": {"artifact_id": artifact_id, "content_digest": artifact_digest},
196
+ "definition_digest": semantic_definition_digest,
197
+ "metrics": _metrics_body(metrics),
198
+ "probe": _probe_body(probe),
199
+ "runtime_evidence_digests": list(runtime_evidence_digests),
200
+ "scenario_id": scenario_id,
201
+ "scenario_revision": scenario_revision,
202
+ }
203
+ domain = b"doc2harness.artifact-static-probe-evidence/1\0"
204
+ return "sha256:" + hashlib.sha256(domain + canonical_json(body)).hexdigest()
205
+
206
+
207
+ @dataclass(frozen=True, slots=True)
208
+ class ArtifactProbeObservation:
209
+ """Path-free facts bound to definition, artifact, probe and runtime evidence."""
210
+
211
+ scenario_id: str
212
+ scenario_revision: str
213
+ definition_digest: str
214
+ artifact_id: str
215
+ artifact_digest: str
216
+ probe: ArtifactProbe
217
+ metrics: ArtifactProbeMetrics
218
+ runtime_evidence_digests: tuple[str, ...]
219
+ evidence_digest: str
220
+
221
+ def __post_init__(self) -> None:
222
+ if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None:
223
+ raise ContractDocumentError("artifact observation scenario id is invalid")
224
+ if type(self.scenario_revision) is not str or not self.scenario_revision.isascii():
225
+ raise ContractDocumentError("artifact observation revision is invalid")
226
+ _digest(self.definition_digest, "artifact observation definition digest")
227
+ if type(self.artifact_id) is not str or _SCENARIO_ID.fullmatch(self.artifact_id) is None:
228
+ raise ContractDocumentError("artifact observation artifact id is invalid")
229
+ _digest(self.artifact_digest, "artifact observation artifact digest")
230
+ if type(self.probe) is not ArtifactProbe or type(self.metrics) is not ArtifactProbeMetrics:
231
+ raise ContractDocumentError("artifact observation uses invalid typed facts")
232
+ if type(self.runtime_evidence_digests) is not tuple or not self.runtime_evidence_digests:
233
+ raise ContractDocumentError("artifact observation requires runtime evidence")
234
+ for value in self.runtime_evidence_digests:
235
+ _digest(value, "artifact runtime evidence digest")
236
+ _digest(self.evidence_digest, "artifact observation digest")
237
+ expected = _observation_digest(
238
+ self.scenario_id,
239
+ self.scenario_revision,
240
+ self.definition_digest,
241
+ self.artifact_id,
242
+ self.artifact_digest,
243
+ self.probe,
244
+ self.metrics,
245
+ self.runtime_evidence_digests,
246
+ )
247
+ if self.evidence_digest != expected:
248
+ raise ContractDocumentError("artifact observation evidence does not bind its facts")
249
+
250
+
251
+ def create_artifact_probe_observation(
252
+ scenario: ArtifactScenario,
253
+ artifact_id: str,
254
+ artifact_digest: str,
255
+ metrics: ArtifactProbeMetrics,
256
+ runtime_evidence_digests: tuple[str, ...],
257
+ /,
258
+ ) -> ArtifactProbeObservation:
259
+ """Seal runtime facts to their scenario, artifact and lower-level evidence."""
260
+
261
+ if type(scenario) is not ArtifactScenario or type(metrics) is not ArtifactProbeMetrics:
262
+ raise ContractDocumentError("artifact observation inputs use invalid typed contracts")
263
+ semantic_digest = definition_digest(scenario.definition)
264
+ evidence = _observation_digest(
265
+ scenario.definition.scenario_id,
266
+ scenario.definition.revision,
267
+ semantic_digest,
268
+ artifact_id,
269
+ artifact_digest,
270
+ scenario.probe,
271
+ metrics,
272
+ runtime_evidence_digests,
273
+ )
274
+ return ArtifactProbeObservation(
275
+ scenario.definition.scenario_id,
276
+ scenario.definition.revision,
277
+ semantic_digest,
278
+ artifact_id,
279
+ artifact_digest,
280
+ scenario.probe,
281
+ metrics,
282
+ runtime_evidence_digests,
283
+ evidence,
284
+ )
285
+
286
+
287
+ @dataclass(frozen=True, slots=True)
288
+ class ArtifactProbeEvaluation:
289
+ """Applicable PASS/FAIL projection for one static artifact target."""
290
+
291
+ scenario_id: str
292
+ outcome: ArtifactProbeOutcome
293
+ applicability: ArtifactProbeApplicability
294
+ reason: str
295
+ evidence_digest: str
296
+ contribution_microunits: int
297
+
298
+ def __post_init__(self) -> None:
299
+ if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None:
300
+ raise ContractDocumentError("artifact evaluation scenario id is invalid")
301
+ if type(self.outcome) is not ArtifactProbeOutcome:
302
+ raise ContractDocumentError("artifact evaluation outcome is invalid")
303
+ if self.applicability is not ArtifactProbeApplicability.APPLICABLE:
304
+ raise ContractDocumentError("artifact evaluation must be applicable")
305
+ if type(self.reason) is not str or not self.reason:
306
+ raise ContractDocumentError("artifact evaluation reason is invalid")
307
+ _digest(self.evidence_digest, "artifact evaluation evidence digest")
308
+ if type(self.contribution_microunits) is not int or self.contribution_microunits < 0:
309
+ raise ContractDocumentError("artifact evaluation contribution is invalid")
310
+
311
+
312
+ def define_artifact_scenario(scenario_id: str, probe: ArtifactProbe, /) -> ArtifactScenario:
313
+ """Construct a target definition owned by the static artifact Harness layer."""
314
+
315
+ if type(scenario_id) is not str or _SCENARIO_ID.fullmatch(scenario_id) is None:
316
+ raise ContractDocumentError("artifact scenario id is not canonical")
317
+ if type(probe) is not ArtifactProbe:
318
+ raise ContractDocumentError("artifact scenario probe must use ArtifactProbe")
319
+ definition = ScenarioDefinition(
320
+ scenario_id=scenario_id,
321
+ revision="1",
322
+ classification=Classification("artifact"),
323
+ role=ScenarioRole.TARGET,
324
+ weight_microunits=1_000_000,
325
+ difficulty=ScenarioDifficulty.STANDARD,
326
+ dependencies=(),
327
+ experiment=ExperimentBinding(
328
+ fixture=ComponentRef("artifact-readonly-workspace", "1", ComponentKind.FIXTURE),
329
+ stimulus=ComponentRef.no_op(),
330
+ observer=ComponentRef("artifact-static-observer", "1", ComponentKind.OBSERVER),
331
+ oracle=ComponentRef("artifact-static-oracle", "1", ComponentKind.ORACLE),
332
+ cleanup=ComponentRef.no_op(),
333
+ ),
334
+ unsupported_policy=UnsupportedPolicy.FAIL,
335
+ )
336
+ return ArtifactScenario(definition, probe)
337
+
338
+
339
+ def validate_artifact_observation(
340
+ scenario: ArtifactScenario,
341
+ observation: ArtifactProbeObservation,
342
+ /,
343
+ ) -> None:
344
+ """Validate the shared identity binding before a local scenario judge runs."""
345
+
346
+ if type(scenario) is not ArtifactScenario:
347
+ raise ContractDocumentError("artifact evaluation requires an exact scenario contract")
348
+ if type(observation) is not ArtifactProbeObservation:
349
+ raise ContractDocumentError("artifact observation uses an invalid typed contract")
350
+ definition = scenario.definition
351
+ if (
352
+ observation.scenario_id != definition.scenario_id
353
+ or observation.scenario_revision != definition.revision
354
+ or observation.definition_digest != definition_digest(definition)
355
+ or observation.probe != scenario.probe
356
+ ):
357
+ raise ContractDocumentError("artifact observation does not bind the scenario definition")
358
+
359
+
360
+ def build_artifact_evaluation(
361
+ scenario: ArtifactScenario,
362
+ observation: ArtifactProbeObservation,
363
+ satisfied: bool,
364
+ reason: str,
365
+ /,
366
+ ) -> ArtifactProbeEvaluation:
367
+ """Build the frozen artifact PASS/FAIL projection after local judgment."""
368
+
369
+ validate_artifact_observation(scenario, observation)
370
+ return ArtifactProbeEvaluation(
371
+ scenario.definition.scenario_id,
372
+ ArtifactProbeOutcome.PASS if satisfied else ArtifactProbeOutcome.FAIL,
373
+ ArtifactProbeApplicability.APPLICABLE,
374
+ reason,
375
+ observation.evidence_digest,
376
+ scenario.definition.weight_microunits if satisfied else 0,
377
+ )
378
+
379
+
380
+ __all__ = [
381
+ "ArtifactLogicalPath",
382
+ "ArtifactProbe",
383
+ "ArtifactProbeApplicability",
384
+ "ArtifactProbeEvaluation",
385
+ "ArtifactProbeKind",
386
+ "ArtifactProbeMetrics",
387
+ "ArtifactProbeObservation",
388
+ "ArtifactProbeOutcome",
389
+ "ArtifactScenario",
390
+ "create_artifact_probe_observation",
391
+ "build_artifact_evaluation",
392
+ "define_artifact_scenario",
393
+ "validate_artifact_observation",
394
+ ]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Static artifact scenario owners; catalog loading is always explicit."""
2
+
3
+ __all__: list[str] = []
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_declares_dependencies.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact declares its runtime dependencies.
2
+
3
+ 1. Inspect the declared dependency metadata.
4
+ 2. Capture the expected logical artifact path.
5
+ 3. Apply the typed artifact oracle and require a valid declaration.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_declares_dependencies",
21
+ ArtifactProbe(
22
+ ArtifactProbeKind.DEPENDENCY_DECLARATION,
23
+ (
24
+ ArtifactLogicalPath(("pyproject.toml",)),
25
+ ArtifactLogicalPath(("requirements.txt",)),
26
+ ),
27
+ ),
28
+ )
29
+ definition = scenario.definition
30
+ SCENARIO = scenario
31
+ STEPS = (scenario.probe,)
32
+
33
+
34
+ def judge(observation: ArtifactProbeObservation):
35
+ validate_artifact_observation(SCENARIO, observation)
36
+ metrics = observation.metrics
37
+ if metrics.project_marker is None or metrics.requirements_nonempty is None or any(
38
+ value is not None
39
+ for value in (
40
+ metrics.file_exists,
41
+ metrics.directory_exists,
42
+ metrics.size_bytes,
43
+ metrics.matching_members,
44
+ )
45
+ ):
46
+ raise ContractDocumentError("dependency declaration observation is incomplete")
47
+ satisfied = metrics.project_marker or metrics.requirements_nonempty
48
+ reason = (
49
+ f"pyproject.toml has [project...]={metrics.project_marker} requirements.txt non-empty="
50
+ f"{metrics.requirements_nonempty} (either one suffices) (v6§0.1.1:25 a new third-party dependency "
51
+ "must be declared in `[project.dependencies]` of `pyproject.toml` (or in `requirements.txt`))"
52
+ )
53
+ return build_artifact_evaluation(SCENARIO, observation, satisfied, reason)
54
+
55
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_entry_py.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact contains its Python entrypoint.
2
+
3
+ 1. Probe the expected entrypoint path.
4
+ 2. Capture its presence and file-kind facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_entry_py",
21
+ ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("entry.py",)),)),
22
+ )
23
+ definition = scenario.definition
24
+ SCENARIO = scenario
25
+ STEPS = (scenario.probe,)
26
+
27
+
28
+ def judge(observation: ArtifactProbeObservation):
29
+ validate_artifact_observation(SCENARIO, observation)
30
+ metrics = observation.metrics
31
+ if metrics.file_exists is None or any(
32
+ value is not None
33
+ for value in (
34
+ metrics.directory_exists,
35
+ metrics.size_bytes,
36
+ metrics.matching_members,
37
+ metrics.project_marker,
38
+ metrics.requirements_nonempty,
39
+ )
40
+ ):
41
+ raise ContractDocumentError("file presence observation is incomplete")
42
+ return build_artifact_evaluation(
43
+ SCENARIO,
44
+ observation,
45
+ metrics.file_exists,
46
+ f"entry.py present={metrics.file_exists} (v6§0.1.1:20 the artifact root must contain `entry.py`)",
47
+ )
48
+
49
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_install_sh.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact contains its installer script.
2
+
3
+ 1. Probe the expected installer path.
4
+ 2. Capture its presence and executable-file facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_install_sh",
21
+ ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("install.sh",)),)),
22
+ )
23
+ definition = scenario.definition
24
+ SCENARIO = scenario
25
+ STEPS = (scenario.probe,)
26
+
27
+
28
+ def judge(observation: ArtifactProbeObservation):
29
+ validate_artifact_observation(SCENARIO, observation)
30
+ metrics = observation.metrics
31
+ if metrics.file_exists is None or any(
32
+ value is not None
33
+ for value in (
34
+ metrics.directory_exists,
35
+ metrics.size_bytes,
36
+ metrics.matching_members,
37
+ metrics.project_marker,
38
+ metrics.requirements_nonempty,
39
+ )
40
+ ):
41
+ raise ContractDocumentError("file presence observation is incomplete")
42
+ return build_artifact_evaluation(
43
+ SCENARIO,
44
+ observation,
45
+ metrics.file_exists,
46
+ 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)",
47
+ )
48
+
49
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_offline_wheel.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact includes an offline wheel.
2
+
3
+ 1. Probe the expected wheel path.
4
+ 2. Capture its presence and file-kind facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_offline_wheel",
21
+ ArtifactProbe(
22
+ ArtifactProbeKind.DIRECTORY_MEMBER_SUFFIX,
23
+ (ArtifactLogicalPath(("wheels",)),),
24
+ ".whl",
25
+ ),
26
+ )
27
+ definition = scenario.definition
28
+ SCENARIO = scenario
29
+ STEPS = (scenario.probe,)
30
+
31
+
32
+ def judge(observation: ArtifactProbeObservation):
33
+ validate_artifact_observation(SCENARIO, observation)
34
+ metrics = observation.metrics
35
+ if metrics.directory_exists is None or metrics.matching_members is None or any(
36
+ value is not None
37
+ for value in (
38
+ metrics.file_exists,
39
+ metrics.size_bytes,
40
+ metrics.project_marker,
41
+ metrics.requirements_nonempty,
42
+ )
43
+ ):
44
+ raise ContractDocumentError("directory member observation is incomplete")
45
+ satisfied = metrics.directory_exists and metrics.matching_members > 0
46
+ reason = (
47
+ f"wheels directory present={metrics.directory_exists} containing *.whl x {metrics.matching_members} ("
48
+ "v6§0.1.1:20 `wheels/` must hold at least one offline wheel)"
49
+ )
50
+ return build_artifact_evaluation(SCENARIO, observation, satisfied, reason)
51
+
52
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_requirements_lock.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact contains a non-empty dependency lock.
2
+
3
+ 1. Probe the lock-file path.
4
+ 2. Capture presence and non-empty-content facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_requirements_lock",
21
+ ArtifactProbe(
22
+ ArtifactProbeKind.FILE_NONEMPTY,
23
+ (ArtifactLogicalPath(("requirements.lock",)),),
24
+ ),
25
+ )
26
+ definition = scenario.definition
27
+ SCENARIO = scenario
28
+ STEPS = (scenario.probe,)
29
+
30
+
31
+ def judge(observation: ArtifactProbeObservation):
32
+ validate_artifact_observation(SCENARIO, observation)
33
+ metrics = observation.metrics
34
+ if metrics.file_exists is None or any(
35
+ value is not None
36
+ for value in (
37
+ metrics.directory_exists,
38
+ metrics.matching_members,
39
+ metrics.project_marker,
40
+ metrics.requirements_nonempty,
41
+ )
42
+ ):
43
+ raise ContractDocumentError("non-empty file observation is incomplete")
44
+ if metrics.file_exists and metrics.size_bytes is None:
45
+ raise ContractDocumentError("non-empty file observation lacks its size")
46
+ satisfied = metrics.file_exists and (metrics.size_bytes or 0) > 0
47
+ if metrics.file_exists:
48
+ 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`)"
49
+ else:
50
+ reason = "requirements.lock present=False (v6§0.1.1:20 the artifact root must contain `requirements.lock`)"
51
+ return build_artifact_evaluation(SCENARIO, observation, satisfied, reason)
52
+
53
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_run_agent_sh.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact contains its run-agent launcher.
2
+
3
+ 1. Probe the launcher path.
4
+ 2. Capture its presence and executable-file facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_run_agent_sh",
21
+ ArtifactProbe(ArtifactProbeKind.FILE_PRESENT, (ArtifactLogicalPath(("run_agent.sh",)),)),
22
+ )
23
+ definition = scenario.definition
24
+ SCENARIO = scenario
25
+ STEPS = (scenario.probe,)
26
+
27
+
28
+ def judge(observation: ArtifactProbeObservation):
29
+ validate_artifact_observation(SCENARIO, observation)
30
+ metrics = observation.metrics
31
+ if metrics.file_exists is None or any(
32
+ value is not None
33
+ for value in (
34
+ metrics.directory_exists,
35
+ metrics.size_bytes,
36
+ metrics.matching_members,
37
+ metrics.project_marker,
38
+ metrics.requirements_nonempty,
39
+ )
40
+ ):
41
+ raise ContractDocumentError("file presence observation is incomplete")
42
+ return build_artifact_evaluation(
43
+ SCENARIO,
44
+ observation,
45
+ metrics.file_exists,
46
+ f"run_agent.sh present={metrics.file_exists} (v6§0.1.1:20 the artifact root must contain `run_agent.sh`)",
47
+ )
48
+
49
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/artifact/scenarios/artifact_has_version_file.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the artifact has a non-empty version marker.
2
+
3
+ 1. Probe the version-file path.
4
+ 2. Capture presence and non-empty-content facts.
5
+ 3. Apply the typed artifact oracle to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.harnesses.artifact.contracts import (
9
+ ArtifactLogicalPath,
10
+ ArtifactProbe,
11
+ ArtifactProbeKind,
12
+ ArtifactProbeObservation,
13
+ build_artifact_evaluation,
14
+ define_artifact_scenario,
15
+ validate_artifact_observation,
16
+ )
17
+ from doc2harness.contracts.primitives import ContractDocumentError
18
+
19
+ scenario = define_artifact_scenario(
20
+ "artifact_has_version_file",
21
+ ArtifactProbe(ArtifactProbeKind.FILE_NONEMPTY, (ArtifactLogicalPath(("VERSION",)),)),
22
+ )
23
+ definition = scenario.definition
24
+ SCENARIO = scenario
25
+ STEPS = (scenario.probe,)
26
+
27
+
28
+ def judge(observation: ArtifactProbeObservation):
29
+ validate_artifact_observation(SCENARIO, observation)
30
+ metrics = observation.metrics
31
+ if metrics.file_exists is None or any(
32
+ value is not None
33
+ for value in (
34
+ metrics.directory_exists,
35
+ metrics.matching_members,
36
+ metrics.project_marker,
37
+ metrics.requirements_nonempty,
38
+ )
39
+ ):
40
+ raise ContractDocumentError("non-empty file observation is incomplete")
41
+ if metrics.file_exists and metrics.size_bytes is None:
42
+ raise ContractDocumentError("non-empty file observation lacks its size")
43
+ satisfied = metrics.file_exists and (metrics.size_bytes or 0) > 0
44
+ if metrics.file_exists:
45
+ 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`)"
46
+ else:
47
+ reason = "VERSION present=False (v6§0.1.1:20 the artifact root must contain `VERSION`)"
48
+ return build_artifact_evaluation(SCENARIO, observation, satisfied, reason)
49
+
50
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/direct/__init__.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed declarations for direct mock-process scenarios."""
2
+
3
+ from doc2harness.benchmark.harnesses.direct.contracts import (
4
+ DirectMockApplicability,
5
+ DirectMockEntrypoint,
6
+ DirectMockFixtureProfile,
7
+ DirectMockJudgement,
8
+ DirectMockIsolationProfile,
9
+ DirectMockLocalJudge,
10
+ DirectMockMode,
11
+ DirectMockFactKey,
12
+ DirectMockObservedFact,
13
+ DirectMockOracleProfile,
14
+ DirectMockOutcome,
15
+ DirectMockRawObservation,
16
+ DirectMockRecipe,
17
+ DirectMockRequestFact,
18
+ DirectMockRequiredFlag,
19
+ DirectMockScenario,
20
+ define_direct_mock_scenario,
21
+ apply_direct_mock_local_judge,
22
+ validate_direct_mock_observation,
23
+ )
24
+ from doc2harness.benchmark.harnesses.direct.adapter import (
25
+ DirectMockExecutionPlan,
26
+ build_direct_mock_execution_plan,
27
+ )
28
+ from doc2harness.benchmark.harnesses.direct.fixtures import (
29
+ DirectMockAction,
30
+ DirectMockFixtureFile,
31
+ DirectMockFixturePlan,
32
+ materialize_direct_mock_fixture,
33
+ )
34
+
35
+ __all__ = [
36
+ "DirectMockAction",
37
+ "DirectMockApplicability",
38
+ "DirectMockEntrypoint",
39
+ "DirectMockExecutionPlan",
40
+ "DirectMockFixtureFile",
41
+ "DirectMockFixturePlan",
42
+ "DirectMockFixtureProfile",
43
+ "DirectMockJudgement",
44
+ "DirectMockFactKey",
45
+ "DirectMockIsolationProfile",
46
+ "DirectMockLocalJudge",
47
+ "DirectMockMode",
48
+ "DirectMockObservedFact",
49
+ "DirectMockOracleProfile",
50
+ "DirectMockOutcome",
51
+ "DirectMockRawObservation",
52
+ "DirectMockRecipe",
53
+ "DirectMockRequestFact",
54
+ "DirectMockRequiredFlag",
55
+ "DirectMockScenario",
56
+ "build_direct_mock_execution_plan",
57
+ "apply_direct_mock_local_judge",
58
+ "define_direct_mock_scenario",
59
+ "validate_direct_mock_observation",
60
+ "materialize_direct_mock_fixture",
61
+ ]
code/src/doc2harness/benchmark/harnesses/direct/adapter.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execution adapter joining frozen fixtures to an injected real-process backend."""
2
+
3
+ from __future__ import annotations
4
+ import hashlib
5
+ from dataclasses import dataclass
6
+ from doc2harness.benchmark.harnesses.direct.contracts import (
7
+ DirectMockEntrypoint,
8
+ DirectMockFactKey,
9
+ DirectMockMode,
10
+ DirectMockOracleProfile,
11
+ DirectMockRequiredFlag,
12
+ DirectMockScenario,
13
+ )
14
+ from doc2harness.benchmark.harnesses.direct.fixtures import (
15
+ DirectMockFixturePlan,
16
+ materialize_direct_mock_fixture,
17
+ )
18
+ from doc2harness.contracts.canonical import canonical_json
19
+ from doc2harness.contracts.primitives import ContractDocumentError
20
+
21
+
22
+ def _digest(value: str, label: str) -> str:
23
+ if (
24
+ type(value) is not str
25
+ or not value.startswith("sha256:")
26
+ or len(value) != 71
27
+ or any((character not in "0123456789abcdef" for character in value[7:]))
28
+ ):
29
+ raise ContractDocumentError(f"{label} is invalid")
30
+ return value
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class DirectMockExecutionPlan:
35
+ """Complete path-free instruction handed to the runtime authority."""
36
+
37
+ scenario_id: str
38
+ mode: DirectMockMode
39
+ entrypoint: DirectMockEntrypoint
40
+ omitted_flag: DirectMockRequiredFlag | None
41
+ timeout_seconds: int
42
+ fixture: DirectMockFixturePlan
43
+ base_url_suffix: str
44
+ model_name: str
45
+ reject_substring: str
46
+ stale_pwd_probe: bool
47
+ initialize_git: bool
48
+ oracle_profile: DirectMockOracleProfile
49
+ tool_family: tuple[str, ...]
50
+ required_tool_families: tuple[tuple[str, ...], ...]
51
+ request_limit: int | None
52
+ body_limit: int | None
53
+ required_facts: tuple[DirectMockFactKey, ...]
54
+ variant_labels: tuple[str, ...]
55
+ plan_digest: str
56
+
57
+ def __post_init__(self) -> None:
58
+ if type(self.scenario_id) is not str or not self.scenario_id:
59
+ raise ContractDocumentError("direct mock execution id is invalid")
60
+ if type(self.mode) is not DirectMockMode or type(self.entrypoint) is not DirectMockEntrypoint:
61
+ raise ContractDocumentError("direct mock execution vocabulary is invalid")
62
+ if self.omitted_flag is not None and type(self.omitted_flag) is not DirectMockRequiredFlag:
63
+ raise ContractDocumentError("direct mock execution omitted flag is invalid")
64
+ if type(self.timeout_seconds) is not int or self.timeout_seconds < 1 or self.timeout_seconds > 900:
65
+ raise ContractDocumentError("direct mock execution timeout is invalid")
66
+ if type(self.fixture) is not DirectMockFixturePlan or self.fixture.scenario_id != self.scenario_id:
67
+ raise ContractDocumentError("direct mock execution fixture differs")
68
+ if (
69
+ type(self.base_url_suffix) is not str
70
+ or ".." in self.base_url_suffix
71
+ or len(self.base_url_suffix) > 1024
72
+ ):
73
+ raise ContractDocumentError("direct mock execution base-url suffix is invalid")
74
+ if type(self.model_name) is not str or not self.model_name or len(self.model_name) > 512:
75
+ raise ContractDocumentError("direct mock execution model is invalid")
76
+ if type(self.reject_substring) is not str or len(self.reject_substring) > 1024:
77
+ raise ContractDocumentError("direct mock execution rejection substring is invalid")
78
+ if type(self.stale_pwd_probe) is not bool or type(self.initialize_git) is not bool:
79
+ raise ContractDocumentError("direct mock execution repository setup is invalid")
80
+ if type(self.oracle_profile) is not DirectMockOracleProfile:
81
+ raise ContractDocumentError("direct mock execution oracle profile is invalid")
82
+ if type(self.tool_family) is not tuple or any((type(item) is not str for item in self.tool_family)):
83
+ raise ContractDocumentError("direct mock execution tool family is invalid")
84
+ if type(self.required_tool_families) is not tuple or any(
85
+ (
86
+ type(family) is not tuple or any((type(item) is not str for item in family))
87
+ for family in self.required_tool_families
88
+ )
89
+ ):
90
+ raise ContractDocumentError("direct mock execution required tool families are invalid")
91
+ for value, name, maximum in (
92
+ (self.request_limit, "request", 4096),
93
+ (self.body_limit, "body", 64 * 1024 * 1024),
94
+ ):
95
+ if value is not None and (type(value) is not int or value < 1 or value > maximum):
96
+ raise ContractDocumentError(f"direct mock execution {name} limit is invalid")
97
+ if type(self.required_facts) is not tuple or any(
98
+ (type(item) is not DirectMockFactKey for item in self.required_facts)
99
+ ):
100
+ raise ContractDocumentError("direct mock execution required facts are invalid")
101
+ if type(self.variant_labels) is not tuple or any(
102
+ (type(item) is not str for item in self.variant_labels)
103
+ ):
104
+ raise ContractDocumentError("direct mock execution variant labels are invalid")
105
+ expected = _plan_digest(
106
+ self.scenario_id,
107
+ self.mode,
108
+ self.entrypoint,
109
+ self.omitted_flag,
110
+ self.timeout_seconds,
111
+ self.fixture.plan_digest,
112
+ self.base_url_suffix,
113
+ self.model_name,
114
+ self.reject_substring,
115
+ self.stale_pwd_probe,
116
+ self.initialize_git,
117
+ self.oracle_profile,
118
+ self.tool_family,
119
+ self.required_tool_families,
120
+ self.request_limit,
121
+ self.body_limit,
122
+ self.required_facts,
123
+ self.variant_labels,
124
+ )
125
+ if self.plan_digest != expected:
126
+ raise ContractDocumentError("direct mock execution digest does not bind its plan")
127
+
128
+
129
+ def _plan_digest(
130
+ scenario_id: str,
131
+ mode: DirectMockMode,
132
+ entrypoint: DirectMockEntrypoint,
133
+ omitted_flag: DirectMockRequiredFlag | None,
134
+ timeout_seconds: int,
135
+ fixture_digest: str,
136
+ base_url_suffix: str = "",
137
+ model_name: str = "litellm_proxy/mock",
138
+ reject_substring: str = "",
139
+ stale_pwd_probe: bool = False,
140
+ initialize_git: bool = False,
141
+ oracle_profile: DirectMockOracleProfile = DirectMockOracleProfile.UNDECLARED,
142
+ tool_family: tuple[str, ...] = (),
143
+ required_tool_families: tuple[tuple[str, ...], ...] = (),
144
+ request_limit: int | None = None,
145
+ body_limit: int | None = None,
146
+ required_facts: tuple[DirectMockFactKey, ...] = (),
147
+ variant_labels: tuple[str, ...] = (),
148
+ ) -> str:
149
+ body = {
150
+ "entrypoint": entrypoint.value,
151
+ "fixture_digest": fixture_digest,
152
+ "mode": mode.value,
153
+ "omitted_flag": omitted_flag.value if omitted_flag is not None else None,
154
+ "scenario_id": scenario_id,
155
+ "timeout_seconds": timeout_seconds,
156
+ "base_url_suffix": base_url_suffix,
157
+ "model_name": model_name,
158
+ "reject_substring": reject_substring,
159
+ "stale_pwd_probe": stale_pwd_probe,
160
+ "initialize_git": initialize_git,
161
+ "oracle_profile": oracle_profile.value,
162
+ "tool_family": list(tool_family),
163
+ "request_limit": request_limit,
164
+ "body_limit": body_limit,
165
+ "required_facts": [item.value for item in required_facts],
166
+ "variant_labels": list(variant_labels),
167
+ }
168
+ if required_tool_families:
169
+ body["required_tool_families"] = [list(family) for family in required_tool_families]
170
+ return (
171
+ "sha256:"
172
+ + hashlib.sha256(b"doc2harness.direct-mock-execution-plan/1\x00" + canonical_json(body)).hexdigest()
173
+ )
174
+
175
+
176
+ def build_direct_mock_execution_plan(scenario: DirectMockScenario, /) -> DirectMockExecutionPlan:
177
+ if type(scenario) is not DirectMockScenario:
178
+ raise ContractDocumentError("direct mock plan requires an exact scenario")
179
+ recipe = scenario.recipe
180
+ fixture = materialize_direct_mock_fixture(scenario)
181
+ timeout = recipe.timeout_seconds if recipe.timeout_seconds is not None else 90
182
+ digest = _plan_digest(
183
+ scenario.definition.scenario_id,
184
+ recipe.mode,
185
+ recipe.entrypoint,
186
+ recipe.omitted_flag,
187
+ timeout,
188
+ fixture.plan_digest,
189
+ recipe.base_url_suffix,
190
+ recipe.model_name,
191
+ recipe.reject_substring,
192
+ recipe.stale_pwd_probe,
193
+ recipe.initialize_git,
194
+ recipe.oracle_profile,
195
+ recipe.tool_family,
196
+ recipe.required_tool_families,
197
+ recipe.request_limit,
198
+ recipe.body_limit,
199
+ recipe.required_facts,
200
+ recipe.variant_labels,
201
+ )
202
+ return DirectMockExecutionPlan(
203
+ scenario.definition.scenario_id,
204
+ recipe.mode,
205
+ recipe.entrypoint,
206
+ recipe.omitted_flag,
207
+ timeout,
208
+ fixture,
209
+ recipe.base_url_suffix,
210
+ recipe.model_name,
211
+ recipe.reject_substring,
212
+ recipe.stale_pwd_probe,
213
+ recipe.initialize_git,
214
+ recipe.oracle_profile,
215
+ recipe.tool_family,
216
+ recipe.required_tool_families,
217
+ recipe.request_limit,
218
+ recipe.body_limit,
219
+ recipe.required_facts,
220
+ recipe.variant_labels,
221
+ digest,
222
+ )
223
+
224
+
225
+ __all__ = [
226
+ "DirectMockExecutionPlan",
227
+ "build_direct_mock_execution_plan",
228
+ ]
code/src/doc2harness/benchmark/harnesses/direct/catalog.toml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ format = "doc2harness.catalog-shard-source/1"
2
+ function_id = "direct"
3
+ resource = "benchmark/harnesses/direct/catalog.toml"
4
+ exports = [
5
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.exfil_glob_pem_not_leaked", export = "definition" },
6
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic", export = "definition" },
7
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.http_proxy_hermetic_control", export = "definition" },
8
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion", export = "definition" },
9
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.quality_gate_blocks_completion_control", export = "definition" },
10
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.secret_probe_mechanism_control", export = "definition" },
11
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace", export = "definition" },
12
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.shell_output_edge_whitespace_control", export = "definition" },
13
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.unreferenced_secret_not_in_request_body", export = "definition" },
14
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure", export = "definition" },
15
+ { module = "doc2harness.benchmark.harnesses.direct.scenarios.webfetch_http_failure_control", export = "definition" },
16
+ ]
code/src/doc2harness/benchmark/harnesses/direct/contracts.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Closed declarations and observations for direct mock-process scenarios."""
2
+
3
+ from __future__ import annotations
4
+ import re
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from typing import Protocol, runtime_checkable
8
+ from doc2harness.benchmark.definition import (
9
+ Classification,
10
+ ComponentKind,
11
+ ComponentRef,
12
+ DependencyKind,
13
+ DependencyRef,
14
+ ExperimentBinding,
15
+ ScenarioDefinition,
16
+ ScenarioDifficulty,
17
+ ScenarioRole,
18
+ UnsupportedPolicy,
19
+ )
20
+ from doc2harness.contracts.primitives import ContractDocumentError
21
+
22
+ _SCENARIO_ID = re.compile("[a-z0-9][a-z0-9._-]{0,127}\\Z", re.ASCII)
23
+ _MAX_STEPS = 256
24
+ _MAX_TIMEOUT_SECONDS = 900
25
+
26
+
27
+ class DirectMockMode(str, Enum):
28
+ """Closed gateway response families for direct-mock scenarios."""
29
+
30
+ NORMAL = "NORMAL"
31
+ SEQUENTIAL_PROBE = "SEQUENTIAL_PROBE"
32
+ FIXED_REPLY = "FIXED_REPLY"
33
+
34
+
35
+ class DirectMockEntrypoint(str, Enum):
36
+ """Public process surfaces supported by the direct-mock backend."""
37
+
38
+ PYTHON_ENTRY = "PYTHON_ENTRY"
39
+ CONTRACT_SCRIPT = "CONTRACT_SCRIPT"
40
+ AGENT_API_DRIVER = "AGENT_API_DRIVER"
41
+
42
+
43
+ class DirectMockRequiredFlag(str, Enum):
44
+ TASK_FILE = "--task-file"
45
+ REPO_DIR = "--repo-dir"
46
+ OUT_DIR = "--out-dir"
47
+ BUDGET_FILE = "--budget-file"
48
+ MODEL_BASE_URL = "--model-base-url"
49
+ MODEL_NAME = "--model-name"
50
+ MODEL_API_KEY = "--model-api-key"
51
+
52
+
53
+ class DirectMockFixtureProfile(str, Enum):
54
+ """Named fixture intents; ``fixtures.py`` materializes their bytes."""
55
+
56
+ NONE = "NONE"
57
+ QUALITY_GATE_FAIL = "QUALITY_GATE_FAIL"
58
+ QUALITY_GATE_PASS = "QUALITY_GATE_PASS"
59
+ SECRET_UNREFERENCED_KEY = "SECRET_UNREFERENCED_KEY"
60
+ SECRET_CONTROL = "SECRET_CONTROL"
61
+ SECRET_PEM = "SECRET_PEM"
62
+ WEB_FETCH = "WEB_FETCH"
63
+ HTTP_PROXY = "HTTP_PROXY"
64
+ SHELL_EDGE_CONTROL = "SHELL_EDGE_CONTROL"
65
+ SHELL_EDGE_TARGET = "SHELL_EDGE_TARGET"
66
+
67
+
68
+ class DirectMockOracleProfile(str, Enum):
69
+ """Closed checker families; every scenario declares one explicitly."""
70
+
71
+ UNDECLARED = "UNDECLARED"
72
+ QUALITY_GATE_BLOCKS = "QUALITY_GATE_BLOCKS"
73
+ QUALITY_GATE_ALLOWS_CONTROL = "QUALITY_GATE_ALLOWS_CONTROL"
74
+ PROBE_ABSENT = "PROBE_ABSENT"
75
+ PROBE_PRESENT = "PROBE_PRESENT"
76
+ FACT_CONTRACT = "FACT_CONTRACT"
77
+
78
+
79
+ class DirectMockFactKey(str, Enum):
80
+ """Bounded backend facts needed by frozen direct-mock oracles."""
81
+
82
+ PARALLEL_A = "PARALLEL_A"
83
+ PARALLEL_B = "PARALLEL_B"
84
+ QGATE_RAN = "QGATE_RAN"
85
+ DENY_MARKER_PRESENT = "DENY_MARKER_PRESENT"
86
+ EXPECTED_REPOSITORY_FILE = "EXPECTED_REPOSITORY_FILE"
87
+ REPOSITORY_CLEAN = "REPOSITORY_CLEAN"
88
+ SHARED_FILE_PRESENT = "SHARED_FILE_PRESENT"
89
+ SHARED_FILE_MARKER = "SHARED_FILE_MARKER"
90
+ SHARED_FILE_CONTENT = "SHARED_FILE_CONTENT"
91
+ SUBAGENT_OBSERVED = "SUBAGENT_OBSERVED"
92
+ OFFLINE_LOOPBACK_ONLY = "OFFLINE_LOOPBACK_ONLY"
93
+ PARENT_PROFILE_HEALTHY = "PARENT_PROFILE_HEALTHY"
94
+ PROFILE_INTERSECTION_HELD = "PROFILE_INTERSECTION_HELD"
95
+ ACTIVE_TURN_COMMAND_SUPPORTED = "ACTIVE_TURN_COMMAND_SUPPORTED"
96
+ ACTIVE_TURN_INFLIGHT = "ACTIVE_TURN_INFLIGHT"
97
+ WEB_FETCH_HEALTHY = "WEB_FETCH_HEALTHY"
98
+ WEB_FAILURES_PRESERVED = "WEB_FAILURES_PRESERVED"
99
+ PROXY_SELF_CHECKED = "PROXY_SELF_CHECKED"
100
+ EXPLICIT_ENDPOINT_BYPASSED_PROXY = "EXPLICIT_ENDPOINT_BYPASSED_PROXY"
101
+ SHELL_CONTROL_BYTES = "SHELL_CONTROL_BYTES"
102
+ SHELL_EDGE_BYTES = "SHELL_EDGE_BYTES"
103
+ RESPONSE_USAGE_HEALTHY = "RESPONSE_USAGE_HEALTHY"
104
+ CHILD_TOOLS_ALLOWLIST = "CHILD_TOOLS_ALLOWLIST"
105
+ REASONING_REDACTED = "REASONING_REDACTED"
106
+ SINK_FAULT_APPLIED = "SINK_FAULT_APPLIED"
107
+ SESSION_SINK_TOKEN_SEEN = "SESSION_SINK_TOKEN_SEEN"
108
+ SINK_ERROR_SURFACED = "SINK_ERROR_SURFACED"
109
+
110
+
111
+ class DirectMockIsolationProfile(str, Enum):
112
+ """Workspace isolation required by a recipe."""
113
+
114
+ STANDARD = "STANDARD"
115
+ DECOY_CWD_WITH_ARTIFACT_GUARD = "DECOY_CWD_WITH_ARTIFACT_GUARD"
116
+
117
+
118
+ class DirectMockOutcome(str, Enum):
119
+ PASS = "PASS"
120
+ FAIL = "FAIL"
121
+
122
+
123
+ class DirectMockApplicability(str, Enum):
124
+ APPLICABLE = "APPLICABLE"
125
+ INCONCLUSIVE = "INCONCLUSIVE"
126
+
127
+
128
+ @dataclass(frozen=True, slots=True)
129
+ class DirectMockRecipe:
130
+ """Bounded recipe metadata without commands, fixture bytes, secrets or paths."""
131
+
132
+ mode: DirectMockMode
133
+ entrypoint: DirectMockEntrypoint
134
+ max_steps: int | None = None
135
+ timeout_seconds: int | None = None
136
+ omitted_flag: DirectMockRequiredFlag | None = None
137
+ fixture_profile: DirectMockFixtureProfile = DirectMockFixtureProfile.NONE
138
+ isolation_profile: DirectMockIsolationProfile = DirectMockIsolationProfile.STANDARD
139
+ oracle_profile: DirectMockOracleProfile = DirectMockOracleProfile.UNDECLARED
140
+ command: str | None = None
141
+ environment: tuple[tuple[str, str], ...] = ()
142
+ expected_token: str | None = None
143
+ base_url_suffix: str = ""
144
+ model_name: str = "litellm_proxy/mock"
145
+ reject_substring: str = ""
146
+ allow_stderr_traceback: bool = False
147
+ stale_pwd_probe: bool = False
148
+ initialize_git: bool = False
149
+ control_dependency: str | None = None
150
+ control_dependencies: tuple[str, ...] = ()
151
+ requirement_dependencies: tuple[str, ...] = ()
152
+ tool_family: tuple[str, ...] = ()
153
+ required_tool_families: tuple[tuple[str, ...], ...] = ()
154
+ request_limit: int | None = None
155
+ body_limit: int | None = None
156
+ required_facts: tuple[DirectMockFactKey, ...] = ()
157
+ variant_labels: tuple[str, ...] = ()
158
+
159
+ def __post_init__(self) -> None:
160
+ if type(self.mode) is not DirectMockMode:
161
+ raise ContractDocumentError("direct mock mode must use the closed vocabulary")
162
+ if type(self.entrypoint) is not DirectMockEntrypoint:
163
+ raise ContractDocumentError("direct mock entrypoint must use the closed vocabulary")
164
+ if self.max_steps is not None and (
165
+ type(self.max_steps) is not int or self.max_steps < 1 or self.max_steps > _MAX_STEPS
166
+ ):
167
+ raise ContractDocumentError("direct mock max steps are invalid")
168
+ if self.timeout_seconds is not None and (
169
+ type(self.timeout_seconds) is not int
170
+ or self.timeout_seconds < 1
171
+ or self.timeout_seconds > _MAX_TIMEOUT_SECONDS
172
+ ):
173
+ raise ContractDocumentError("direct mock timeout is invalid")
174
+ if self.omitted_flag is not None and type(self.omitted_flag) is not DirectMockRequiredFlag:
175
+ raise ContractDocumentError("direct mock omitted flag must use the closed vocabulary")
176
+ if type(self.fixture_profile) is not DirectMockFixtureProfile:
177
+ raise ContractDocumentError("direct mock fixture profile must use the closed vocabulary")
178
+ if type(self.isolation_profile) is not DirectMockIsolationProfile:
179
+ raise ContractDocumentError("direct mock isolation profile must use the closed vocabulary")
180
+ if type(self.oracle_profile) is not DirectMockOracleProfile:
181
+ raise ContractDocumentError("direct mock oracle profile must use the closed vocabulary")
182
+ if self.command is not None and (
183
+ type(self.command) is not str or not self.command or len(self.command) > 16384
184
+ ):
185
+ raise ContractDocumentError("direct mock command is invalid")
186
+ if type(self.environment) is not tuple or any(
187
+ (
188
+ type(item) is not tuple
189
+ or len(item) != 2
190
+ or type(item[0]) is not str
191
+ or (type(item[1]) is not str)
192
+ or (not item[0])
193
+ or (len(item[0]) > 128)
194
+ or (len(item[1]) > 16384)
195
+ for item in self.environment
196
+ )
197
+ ):
198
+ raise ContractDocumentError("direct mock environment is invalid")
199
+ if len({item[0] for item in self.environment}) != len(self.environment):
200
+ raise ContractDocumentError("direct mock environment keys must be unique")
201
+ if self.expected_token is not None and (
202
+ type(self.expected_token) is not str or not self.expected_token or len(self.expected_token) > 1024
203
+ ):
204
+ raise ContractDocumentError("direct mock expected token is invalid")
205
+ if (
206
+ type(self.base_url_suffix) is not str
207
+ or len(self.base_url_suffix) > 1024
208
+ or ".." in self.base_url_suffix
209
+ ):
210
+ raise ContractDocumentError("direct mock base-url suffix is invalid")
211
+ if type(self.model_name) is not str or not self.model_name or len(self.model_name) > 512:
212
+ raise ContractDocumentError("direct mock model name is invalid")
213
+ if type(self.reject_substring) is not str or len(self.reject_substring) > 1024:
214
+ raise ContractDocumentError("direct mock rejection substring is invalid")
215
+ if type(self.allow_stderr_traceback) is not bool:
216
+ raise ContractDocumentError("direct mock traceback policy is invalid")
217
+ if type(self.stale_pwd_probe) is not bool or type(self.initialize_git) is not bool:
218
+ raise ContractDocumentError("direct mock repository setup policy is invalid")
219
+ if self.control_dependency is not None and (
220
+ type(self.control_dependency) is not str
221
+ or _SCENARIO_ID.fullmatch(self.control_dependency) is None
222
+ ):
223
+ raise ContractDocumentError("direct mock control dependency is invalid")
224
+ if (
225
+ type(self.control_dependencies) is not tuple
226
+ or any(
227
+ (
228
+ type(item) is not str or _SCENARIO_ID.fullmatch(item) is None
229
+ for item in self.control_dependencies
230
+ )
231
+ )
232
+ or len(set(self.control_dependencies)) != len(self.control_dependencies)
233
+ ):
234
+ raise ContractDocumentError("direct mock control dependencies are invalid")
235
+ if self.control_dependency is not None and self.control_dependency in self.control_dependencies:
236
+ raise ContractDocumentError("direct mock control dependencies must be unique")
237
+ if (
238
+ type(self.requirement_dependencies) is not tuple
239
+ or any(
240
+ (
241
+ type(item) is not str or _SCENARIO_ID.fullmatch(item) is None
242
+ for item in self.requirement_dependencies
243
+ )
244
+ )
245
+ or len(set(self.requirement_dependencies)) != len(self.requirement_dependencies)
246
+ ):
247
+ raise ContractDocumentError("direct mock requirement dependencies are invalid")
248
+ if type(self.tool_family) is not tuple or any(
249
+ (type(item) is not str or not item or len(item) > 128 for item in self.tool_family)
250
+ ):
251
+ raise ContractDocumentError("direct mock tool family is invalid")
252
+ if (
253
+ type(self.required_tool_families) is not tuple
254
+ or any(
255
+ (
256
+ type(family) is not tuple
257
+ or not family
258
+ or any((type(item) is not str or not item or len(item) > 128 for item in family))
259
+ or (len(set(family)) != len(family))
260
+ for family in self.required_tool_families
261
+ )
262
+ )
263
+ or len(set(self.required_tool_families)) != len(self.required_tool_families)
264
+ ):
265
+ raise ContractDocumentError("direct mock required tool families are invalid")
266
+ if self.request_limit is not None and (
267
+ type(self.request_limit) is not int or self.request_limit < 1 or self.request_limit > 4096
268
+ ):
269
+ raise ContractDocumentError("direct mock request limit is invalid")
270
+ if self.body_limit is not None and (
271
+ type(self.body_limit) is not int or self.body_limit < 1 or self.body_limit > 64 * 1024 * 1024
272
+ ):
273
+ raise ContractDocumentError("direct mock body limit is invalid")
274
+ if (
275
+ type(self.required_facts) is not tuple
276
+ or any((type(item) is not DirectMockFactKey for item in self.required_facts))
277
+ or len(set(self.required_facts)) != len(self.required_facts)
278
+ ):
279
+ raise ContractDocumentError("direct mock required facts are invalid")
280
+ if (
281
+ type(self.variant_labels) is not tuple
282
+ or any(
283
+ (
284
+ type(item) is not str or _SCENARIO_ID.fullmatch(item) is None
285
+ for item in self.variant_labels
286
+ )
287
+ )
288
+ or len(set(self.variant_labels)) != len(self.variant_labels)
289
+ ):
290
+ raise ContractDocumentError("direct mock variant labels are invalid")
291
+ if self.omitted_flag is not None and (
292
+ self.entrypoint is not DirectMockEntrypoint.CONTRACT_SCRIPT
293
+ or self.mode is not DirectMockMode.NORMAL
294
+ ):
295
+ raise ContractDocumentError("required flags can only be omitted at the contract entrypoint")
296
+ decoy = self.isolation_profile is DirectMockIsolationProfile.DECOY_CWD_WITH_ARTIFACT_GUARD
297
+ if decoy != (self.omitted_flag is DirectMockRequiredFlag.REPO_DIR):
298
+ raise ContractDocumentError("repo-dir omission requires the decoy artifact guard")
299
+
300
+
301
+ @dataclass(frozen=True, slots=True)
302
+ class DirectMockFactStep:
303
+ """Typed observation fact consumed by a local judge."""
304
+
305
+ fact_key: DirectMockFactKey
306
+
307
+
308
+ def capture_fact(*, fact_key: DirectMockFactKey) -> DirectMockFactStep:
309
+ """Declare a typed fact that the scenario judge will consume."""
310
+ return DirectMockFactStep(fact_key)
311
+
312
+
313
+ @dataclass(frozen=True, slots=True)
314
+ class DirectMockScenario:
315
+ """One independent benchmark definition paired with its recipe declaration."""
316
+
317
+ definition: ScenarioDefinition
318
+ recipe: DirectMockRecipe
319
+
320
+ def __post_init__(self) -> None:
321
+ if type(self.definition) is not ScenarioDefinition or type(self.recipe) is not DirectMockRecipe:
322
+ raise ContractDocumentError("direct mock scenario requires exact typed values")
323
+ if self.definition.classification.primary != "direct":
324
+ raise ContractDocumentError("direct mock scenario owner differs from its Harness layer")
325
+
326
+
327
+ @dataclass(frozen=True, slots=True)
328
+ class DirectMockRequestFact:
329
+ """Bounded request facts retained by the gateway; request content is discarded."""
330
+
331
+ body_bytes: int
332
+ has_tools: bool
333
+ tool_names: tuple[str, ...]
334
+ probe_seen: bool
335
+ message_count: int
336
+ message_roles: tuple[str, ...]
337
+ path: str = ""
338
+ model: str = ""
339
+ nonleading_system: bool = False
340
+ orphan_tool_result: bool = False
341
+ lone_surrogate: bool = False
342
+ has_any_null: bool = False
343
+ empty_content_block: bool = False
344
+ dangling_tool_use: bool = False
345
+ trailing_empty_assistant: bool = False
346
+ tool_result_max_bytes: int = 0
347
+ target_tool_result: str = ""
348
+ has_reasoning: bool = False
349
+
350
+ def __post_init__(self) -> None:
351
+ if type(self.body_bytes) is not int or self.body_bytes < 0 or self.body_bytes > 64 * 1024 * 1024:
352
+ raise ContractDocumentError("direct mock request size is invalid")
353
+ if type(self.has_tools) is not bool:
354
+ raise ContractDocumentError("direct mock tool-presence fact is invalid")
355
+ if type(self.tool_names) is not tuple or len(self.tool_names) > 256:
356
+ raise ContractDocumentError("direct mock tool-name facts are invalid")
357
+ if any((type(item) is not str or not item or len(item) > 256 for item in self.tool_names)):
358
+ raise ContractDocumentError("direct mock tool-name fact is invalid")
359
+ if type(self.probe_seen) is not bool:
360
+ raise ContractDocumentError("direct mock probe fact is invalid")
361
+ if type(self.message_count) is not int or self.message_count < 0 or self.message_count > 4096:
362
+ raise ContractDocumentError("direct mock message count is invalid")
363
+ if type(self.message_roles) is not tuple or len(self.message_roles) > 32:
364
+ raise ContractDocumentError("direct mock role facts are invalid")
365
+ if (
366
+ type(self.path) is not str
367
+ or len(self.path) > 2048
368
+ or type(self.model) is not str
369
+ or (len(self.model) > 512)
370
+ ):
371
+ raise ContractDocumentError("direct mock request routing facts are invalid")
372
+ for value in (
373
+ self.nonleading_system,
374
+ self.orphan_tool_result,
375
+ self.lone_surrogate,
376
+ self.has_any_null,
377
+ self.empty_content_block,
378
+ self.dangling_tool_use,
379
+ self.trailing_empty_assistant,
380
+ self.has_reasoning,
381
+ ):
382
+ if type(value) is not bool:
383
+ raise ContractDocumentError("direct mock request wire fact is invalid")
384
+ if (
385
+ type(self.tool_result_max_bytes) is not int
386
+ or not 0 <= self.tool_result_max_bytes <= 64 * 1024 * 1024
387
+ ):
388
+ raise ContractDocumentError("direct mock tool-result size is invalid")
389
+ if type(self.target_tool_result) is not str or len(self.target_tool_result) > 1024 * 1024:
390
+ raise ContractDocumentError("direct mock target result is invalid")
391
+
392
+
393
+ @dataclass(frozen=True, slots=True)
394
+ class DirectMockObservedFact:
395
+ """One closed, bounded filesystem or lifecycle fact emitted by the backend."""
396
+
397
+ key: DirectMockFactKey
398
+ value: bool | int | str
399
+
400
+ def __post_init__(self) -> None:
401
+ if type(self.key) is not DirectMockFactKey or type(self.value) not in {bool, int, str}:
402
+ raise ContractDocumentError("direct mock observed fact is invalid")
403
+ if type(self.value) is str and len(self.value) > 8 * 1024 * 1024:
404
+ raise ContractDocumentError("direct mock observed text is too large")
405
+
406
+
407
+ def _digest(value: str, label: str) -> str:
408
+ if (
409
+ type(value) is not str
410
+ or not value.startswith("sha256:")
411
+ or len(value) != 71
412
+ or any((character not in "0123456789abcdef" for character in value[7:]))
413
+ ):
414
+ raise ContractDocumentError(f"{label} is invalid")
415
+ return value
416
+
417
+
418
+ @dataclass(frozen=True, slots=True)
419
+ class DirectMockRawObservation:
420
+ """Path-free execution facts emitted by an identity-bound backend."""
421
+
422
+ scenario_id: str
423
+ plan_digest: str
424
+ artifact_id: str
425
+ artifact_digest: str
426
+ exit_code: int
427
+ status_written: bool
428
+ exit_status: str | None
429
+ cost_usd: int | float | None
430
+ requests: tuple[DirectMockRequestFact, ...]
431
+ proof_present: bool
432
+ proof_contains_marker: bool
433
+ trajectory_observed: bool
434
+ trajectory_contains_probe: bool
435
+ artifact_unchanged: bool
436
+ decoy_entries: tuple[str, ...]
437
+ stderr_has_traceback: bool
438
+ process_tree_clean: bool
439
+ gateway_clean: bool
440
+ workspace_clean: bool
441
+ backend_evidence_digest: str
442
+ timed_out: bool = False
443
+ trajectory: str = ""
444
+ assistant_text: str = ""
445
+ facts: tuple[DirectMockObservedFact, ...] = ()
446
+
447
+ def __post_init__(self) -> None:
448
+ if type(self.scenario_id) is not str or _SCENARIO_ID.fullmatch(self.scenario_id) is None:
449
+ raise ContractDocumentError("direct mock observation id is invalid")
450
+ _digest(self.plan_digest, "direct mock plan digest")
451
+ if type(self.artifact_id) is not str or _SCENARIO_ID.fullmatch(self.artifact_id) is None:
452
+ raise ContractDocumentError("direct mock artifact id is invalid")
453
+ _digest(self.artifact_digest, "direct mock artifact digest")
454
+ if type(self.exit_code) is not int or self.exit_code < -1 or self.exit_code > 255:
455
+ raise ContractDocumentError("direct mock exit code is invalid")
456
+ if self.exit_status is not None and (
457
+ type(self.exit_status) is not str or len(self.exit_status) > 256
458
+ ):
459
+ raise ContractDocumentError("direct mock exit status is invalid")
460
+ if self.cost_usd is not None and type(self.cost_usd) not in {int, float}:
461
+ raise ContractDocumentError("direct mock cost fact is invalid")
462
+ if type(self.requests) is not tuple or any(
463
+ (type(item) is not DirectMockRequestFact for item in self.requests)
464
+ ):
465
+ raise ContractDocumentError("direct mock request facts are invalid")
466
+ for value in (
467
+ self.status_written,
468
+ self.proof_present,
469
+ self.proof_contains_marker,
470
+ self.trajectory_observed,
471
+ self.trajectory_contains_probe,
472
+ self.artifact_unchanged,
473
+ self.stderr_has_traceback,
474
+ self.process_tree_clean,
475
+ self.gateway_clean,
476
+ self.workspace_clean,
477
+ ):
478
+ if type(value) is not bool:
479
+ raise ContractDocumentError("direct mock boolean fact is invalid")
480
+ if type(self.decoy_entries) is not tuple or any(
481
+ (type(item) is not str or not item or len(item) > 512 for item in self.decoy_entries)
482
+ ):
483
+ raise ContractDocumentError("direct mock decoy facts are invalid")
484
+ _digest(self.backend_evidence_digest, "direct mock backend evidence digest")
485
+ if type(self.timed_out) is not bool:
486
+ raise ContractDocumentError("direct mock timeout fact is invalid")
487
+ if type(self.trajectory) is not str or len(self.trajectory) > 64 * 1024 * 1024:
488
+ raise ContractDocumentError("direct mock trajectory is invalid")
489
+ if type(self.assistant_text) is not str or len(self.assistant_text) > 8 * 1024 * 1024:
490
+ raise ContractDocumentError("direct mock assistant text is invalid")
491
+ if type(self.facts) is not tuple or any(
492
+ (type(item) is not DirectMockObservedFact for item in self.facts)
493
+ ):
494
+ raise ContractDocumentError("direct mock observed facts are invalid")
495
+ if len({item.key for item in self.facts}) != len(self.facts):
496
+ raise ContractDocumentError("direct mock observed facts must have unique keys")
497
+
498
+
499
+ @dataclass(frozen=True, slots=True)
500
+ class DirectMockJudgement:
501
+ """Typed, scenario-local oracle result before evidence/score construction."""
502
+
503
+ outcome: DirectMockOutcome
504
+ applicability: DirectMockApplicability
505
+ reason_code: str
506
+
507
+ def __post_init__(self) -> None:
508
+ if (
509
+ type(self.outcome) is not DirectMockOutcome
510
+ or type(self.applicability) is not DirectMockApplicability
511
+ ):
512
+ raise ContractDocumentError("direct mock judgement uses invalid closed values")
513
+ if type(self.reason_code) is not str or not self.reason_code or len(self.reason_code) > 128:
514
+ raise ContractDocumentError("direct mock judgement reason is invalid")
515
+
516
+
517
+ @runtime_checkable
518
+ class DirectMockLocalJudge(Protocol):
519
+ """Pure scenario-specific predicate over an already bound observation."""
520
+
521
+ def __call__(self, observation: DirectMockRawObservation, /) -> DirectMockJudgement: ...
522
+
523
+
524
+ def define_direct_mock_scenario(
525
+ scenario_id: str, recipe: DirectMockRecipe, role: ScenarioRole, /
526
+ ) -> DirectMockScenario:
527
+ """Construct one direct-mock definition without granting execution authority."""
528
+ if type(scenario_id) is not str or _SCENARIO_ID.fullmatch(scenario_id) is None:
529
+ raise ContractDocumentError("direct mock scenario id is not canonical")
530
+ if type(recipe) is not DirectMockRecipe:
531
+ raise ContractDocumentError("direct mock scenario recipe must use DirectMockRecipe")
532
+ if type(role) is not ScenarioRole:
533
+ raise ContractDocumentError("direct mock scenario role must use ScenarioRole")
534
+ control_ids = (
535
+ () if recipe.control_dependency is None else (recipe.control_dependency,)
536
+ ) + recipe.control_dependencies
537
+ definition = ScenarioDefinition(
538
+ scenario_id=scenario_id,
539
+ revision="1",
540
+ classification=Classification("direct"),
541
+ role=role,
542
+ weight_microunits=1000000 if role is ScenarioRole.TARGET else 0,
543
+ difficulty=ScenarioDifficulty.STANDARD,
544
+ dependencies=(
545
+ *(DependencyRef(item, DependencyKind.GATE) for item in control_ids),
546
+ *(DependencyRef(item, DependencyKind.REQUIREMENT) for item in recipe.requirement_dependencies),
547
+ ),
548
+ experiment=ExperimentBinding(
549
+ fixture=ComponentRef("direct-mock-fixture", "1", ComponentKind.FIXTURE),
550
+ stimulus=ComponentRef("direct-mock-process", "1", ComponentKind.STIMULUS),
551
+ observer=ComponentRef("direct-mock-observer", "1", ComponentKind.OBSERVER),
552
+ oracle=ComponentRef("direct-mock-oracle", "1", ComponentKind.ORACLE),
553
+ cleanup=ComponentRef("direct-mock-cleanup", "1", ComponentKind.CLEANUP),
554
+ ),
555
+ unsupported_policy=UnsupportedPolicy.FAIL,
556
+ )
557
+ return DirectMockScenario(definition, recipe)
558
+
559
+
560
+ def validate_direct_mock_observation(
561
+ scenario: DirectMockScenario,
562
+ observation: DirectMockRawObservation,
563
+ expected_plan_digest: str | None = None,
564
+ /,
565
+ ) -> None:
566
+ """Validate the identity and plan binding before a local judge runs.
567
+
568
+ Artifact identity and the runtime-generated plan digest are verified by
569
+ ``RuntimeDirectMockAdapter``. A caller that already has an expected plan
570
+ digest may pass it explicitly; keeping the default path free of an
571
+ adapter import preserves the one-way harness dependency graph.
572
+ """
573
+ if type(scenario) is not DirectMockScenario or type(observation) is not DirectMockRawObservation:
574
+ raise ContractDocumentError("direct mock observation binding requires exact contracts")
575
+ if observation.scenario_id != scenario.definition.scenario_id:
576
+ raise ContractDocumentError("direct mock observation belongs to another scenario")
577
+ if expected_plan_digest is not None and observation.plan_digest != expected_plan_digest:
578
+ raise ContractDocumentError("direct mock observation plan is not bound to the scenario")
579
+
580
+
581
+ def _validate_local_judgement(judgement: DirectMockJudgement) -> DirectMockJudgement:
582
+ if type(judgement) is not DirectMockJudgement:
583
+ raise ContractDocumentError("direct mock local judge returned an invalid judgement")
584
+ return judgement
585
+
586
+
587
+ def apply_direct_mock_local_judge(
588
+ scenario: DirectMockScenario, observation: DirectMockRawObservation, judge: DirectMockLocalJudge, /
589
+ ) -> DirectMockJudgement:
590
+ """Apply shared runtime gates, then one scenario-local pure judge.
591
+
592
+ A stderr traceback fails the run outright; incomplete cleanup fails it unless
593
+ the scenario's own judgement is already inconclusive.
594
+ """
595
+ validate_direct_mock_observation(scenario, observation)
596
+ if not isinstance(judge, DirectMockLocalJudge):
597
+ raise ContractDocumentError("direct mock local judge is not callable")
598
+ cleanup_complete = (
599
+ observation.process_tree_clean and observation.gateway_clean and observation.workspace_clean
600
+ )
601
+ if observation.stderr_has_traceback and (not scenario.recipe.allow_stderr_traceback):
602
+ return DirectMockJudgement(
603
+ DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, "STDERR_TRACEBACK"
604
+ )
605
+ provisional = _validate_local_judgement(judge(observation))
606
+ if not cleanup_complete:
607
+ if provisional.applicability is DirectMockApplicability.INCONCLUSIVE:
608
+ return provisional
609
+ return DirectMockJudgement(
610
+ DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, "RUNTIME_CLEANUP_INCOMPLETE"
611
+ )
612
+ return provisional
613
+
614
+
615
+ __all__ = [
616
+ "DirectMockApplicability",
617
+ "DirectMockEntrypoint",
618
+ "DirectMockFixtureProfile",
619
+ "DirectMockIsolationProfile",
620
+ "DirectMockJudgement",
621
+ "DirectMockLocalJudge",
622
+ "DirectMockMode",
623
+ "DirectMockOutcome",
624
+ "DirectMockRawObservation",
625
+ "DirectMockRecipe",
626
+ "DirectMockRequestFact",
627
+ "DirectMockRequiredFlag",
628
+ "DirectMockScenario",
629
+ "apply_direct_mock_local_judge",
630
+ "define_direct_mock_scenario",
631
+ "validate_direct_mock_observation",
632
+ ]
code/src/doc2harness/benchmark/harnesses/direct/fixtures.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic, path-free fixture materialization plans for direct mock-process scenarios."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import dataclass
8
+
9
+ from doc2harness.benchmark.harnesses.direct.contracts import (
10
+ DirectMockFixtureProfile,
11
+ DirectMockIsolationProfile,
12
+ DirectMockRecipe,
13
+ DirectMockScenario,
14
+ )
15
+ from doc2harness.contracts.canonical import canonical_json
16
+ from doc2harness.contracts.primitives import ContractDocumentError
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class DirectMockFixtureFile:
21
+ """One safe repository-relative file supplied before execution."""
22
+
23
+ path: tuple[str, ...]
24
+ content: bytes
25
+
26
+ def __post_init__(self) -> None:
27
+ if type(self.path) is not tuple or not self.path or len(self.path) > 16:
28
+ raise ContractDocumentError("direct mock fixture path is invalid")
29
+ if any(
30
+ type(item) is not str or not item or item in {".", ".."}
31
+ or "/" in item or "\\" in item or len(item.encode("utf-8")) > 255
32
+ for item in self.path
33
+ ):
34
+ raise ContractDocumentError("direct mock fixture path is unsafe")
35
+ if type(self.content) is not bytes or len(self.content) > 16 * 1024 * 1024:
36
+ raise ContractDocumentError("direct mock fixture content is invalid")
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class DirectMockAction:
41
+ """One logical tool call; aliases are resolved against the live request schema."""
42
+
43
+ tool_candidates: tuple[str, ...]
44
+ arguments: tuple[tuple[str, str | bool | int | float], ...]
45
+ finish: bool = False
46
+
47
+ def __post_init__(self) -> None:
48
+ if type(self.finish) is not bool:
49
+ raise ContractDocumentError("direct mock finish marker is invalid")
50
+ if self.finish:
51
+ if self.tool_candidates or self.arguments:
52
+ raise ContractDocumentError("direct mock finish action cannot carry a tool")
53
+ return
54
+ if type(self.tool_candidates) is not tuple or not self.tool_candidates:
55
+ raise ContractDocumentError("direct mock action needs a tool candidate")
56
+ if any(type(item) is not str or not item or len(item) > 128 for item in self.tool_candidates):
57
+ raise ContractDocumentError("direct mock tool candidate is invalid")
58
+ if type(self.arguments) is not tuple or any(
59
+ type(item) is not tuple or len(item) != 2
60
+ or type(item[0]) is not str or type(item[1]) not in {str, bool, int, float}
61
+ or (isinstance(item[1], str) and len(item[1]) > 16_384)
62
+ for item in self.arguments
63
+ ):
64
+ raise ContractDocumentError("direct mock action arguments are invalid")
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class DirectMockFixturePlan:
69
+ """Complete logical input for one execution, without host paths or secrets."""
70
+
71
+ scenario_id: str
72
+ task_document: bytes
73
+ budget_document: bytes
74
+ repository_files: tuple[DirectMockFixtureFile, ...]
75
+ environment: tuple[tuple[str, str], ...]
76
+ rounds: tuple[tuple[DirectMockAction, ...], ...]
77
+ probe_token: str | None
78
+ isolation_profile: DirectMockIsolationProfile
79
+ plan_digest: str
80
+
81
+ def __post_init__(self) -> None:
82
+ if type(self.scenario_id) is not str or not self.scenario_id:
83
+ raise ContractDocumentError("direct mock fixture id is invalid")
84
+ if type(self.task_document) is not bytes or type(self.budget_document) is not bytes:
85
+ raise ContractDocumentError("direct mock fixture documents are invalid")
86
+ if type(self.repository_files) is not tuple or any(type(item) is not DirectMockFixtureFile for item in self.repository_files):
87
+ raise ContractDocumentError("direct mock fixture files are invalid")
88
+ if len({item.path for item in self.repository_files}) != len(self.repository_files):
89
+ raise ContractDocumentError("direct mock fixture paths must be unique")
90
+ if type(self.environment) is not tuple or any(
91
+ type(item) is not tuple or len(item) != 2 or type(item[0]) is not str or type(item[1]) is not str
92
+ for item in self.environment
93
+ ):
94
+ raise ContractDocumentError("direct mock fixture environment is invalid")
95
+ if type(self.rounds) is not tuple or any(
96
+ type(group) is not tuple or not group or any(type(action) is not DirectMockAction for action in group)
97
+ for group in self.rounds
98
+ ):
99
+ raise ContractDocumentError("direct mock fixture rounds are invalid")
100
+ if self.probe_token is not None and (type(self.probe_token) is not str or not self.probe_token):
101
+ raise ContractDocumentError("direct mock probe token is invalid")
102
+ if type(self.isolation_profile) is not DirectMockIsolationProfile:
103
+ raise ContractDocumentError("direct mock isolation profile is invalid")
104
+ body = _fixture_body(self, include_digest=False)
105
+ expected = "sha256:" + hashlib.sha256(b"doc2harness.direct-mock-fixture/1\0" + canonical_json(body)).hexdigest()
106
+ if self.plan_digest != expected:
107
+ raise ContractDocumentError("direct mock fixture digest does not bind its content")
108
+
109
+
110
+ def _action_body(action: DirectMockAction) -> dict[str, object]:
111
+ return {
112
+ "arguments": [list(item) for item in action.arguments],
113
+ "finish": action.finish,
114
+ "tool_candidates": list(action.tool_candidates),
115
+ }
116
+
117
+
118
+ def _fixture_body(plan: DirectMockFixturePlan, *, include_digest: bool) -> dict[str, object]:
119
+ body: dict[str, object] = {
120
+ "budget_document": plan.budget_document.decode("utf-8"),
121
+ "environment": [list(item) for item in plan.environment],
122
+ "isolation_profile": plan.isolation_profile.value,
123
+ "probe_token": plan.probe_token,
124
+ "repository_files": [
125
+ {"path": list(item.path), "sha256": hashlib.sha256(item.content).hexdigest()}
126
+ for item in plan.repository_files
127
+ ],
128
+ "rounds": [[_action_body(action) for action in group] for group in plan.rounds],
129
+ "scenario_id": plan.scenario_id,
130
+ "task_document": plan.task_document.decode("utf-8"),
131
+ }
132
+ if include_digest:
133
+ body["plan_digest"] = plan.plan_digest
134
+ return body
135
+
136
+
137
+ def _bash(command: str) -> DirectMockAction:
138
+ return DirectMockAction(
139
+ ("bash", "shell", "run_command", "execute", "exec", "terminal"),
140
+ (("command", command),),
141
+ )
142
+
143
+
144
+ def _tool(candidates: tuple[str, ...], **arguments: object) -> DirectMockAction:
145
+ return DirectMockAction(candidates, tuple(arguments.items()))
146
+
147
+
148
+ def _secret_and_protocol_profile(recipe: DirectMockRecipe):
149
+ """Materialize the secret, protocol and shell-edge stimuli without embedding host paths."""
150
+
151
+ profile = recipe.fixture_profile
152
+ secret_cases = {
153
+ DirectMockFixtureProfile.SECRET_UNREFERENCED_KEY: (
154
+ ("secret.key",), (
155
+ b"-----BEGIN OPENSSH " b"PRIVATE KEY-----\nSK_SENTINEL_4242\n"
156
+ b"-----END OPENSSH " b"PRIVATE KEY-----\n"
157
+ ),
158
+ "SK_SENTINEL_4242", "Check secret.key permissions without opening it.",
159
+ ),
160
+ DirectMockFixtureProfile.SECRET_PEM: (
161
+ ("server.pem",), b"-----BEGIN CERTIFICATE-----\nPEM_SENTINEL_5583\n-----END CERTIFICATE-----\n",
162
+ "PEM_SENTINEL_5583", "Audit mentioned *.pem certificates without reading unreferenced content.",
163
+ ),
164
+ }
165
+ if profile in secret_cases:
166
+ path, content, probe, task = secret_cases[profile]
167
+ return (DirectMockFixtureFile(path, content),), (), probe, task
168
+ if profile is DirectMockFixtureProfile.SECRET_CONTROL:
169
+ return (
170
+ DirectMockFixtureFile(("ref.txt",), b"REFTOK_7731 content body\n"),
171
+ ), ((_bash("cat ref.txt"),),), "REFTOK_7731", "Read the explicitly referenced file."
172
+ if profile is DirectMockFixtureProfile.HTTP_PROXY:
173
+ return (), (), recipe.expected_token, "Exercise the declared bounded protocol contract."
174
+ if profile is DirectMockFixtureProfile.WEB_FETCH:
175
+ # The host and port are only known once the run has a listener, so the
176
+ # declared URL carries a placeholder the driver substitutes. A fixed
177
+ # loopback address would send the product at its own port 80, where
178
+ # nothing answers, and the point could never observe the fetch it is
179
+ # about.
180
+ return (), ((_tool(("web_fetch", "webfetch"), url="http://{OBSERVER}/local-probe"),),), recipe.expected_token, "Fetch the loopback probe URL."
181
+ if profile is DirectMockFixtureProfile.SHELL_EDGE_CONTROL:
182
+ return (), ((_bash("printf 'SHELL_EDGE_CONTROL_7731\\n'"),),), "SHELL_EDGE_CONTROL_7731", "Preserve ordinary shell output."
183
+ if profile is DirectMockFixtureProfile.SHELL_EDGE_TARGET:
184
+ return (), ((_bash("printf '\\n EDGE_CONTENT_7731 \\n\\nUNTRUNCATED_7731\\n'"),),), "UNTRUNCATED_7731", "Preserve shell output edge whitespace."
185
+ return None
186
+
187
+
188
+ def _profile(recipe: DirectMockRecipe) -> tuple[tuple[DirectMockFixtureFile, ...], tuple[tuple[DirectMockAction, ...], ...], str | None, str]:
189
+ profile = recipe.fixture_profile
190
+ if profile in {DirectMockFixtureProfile.QUALITY_GATE_FAIL, DirectMockFixtureProfile.QUALITY_GATE_PASS}:
191
+ rc = 1 if profile is DirectMockFixtureProfile.QUALITY_GATE_FAIL else 0
192
+ command = f"sh -c 'echo QGATE_RAN_7755 > qgate.marker; exit {rc}'"
193
+ hook = {key: [{"command": command, "action": "run"}] for key in (
194
+ "qualityGate", "beforeFinish", "beforeSubmit", "beforeCompletion"
195
+ )}
196
+ rounds = ((_bash("echo QGATE_EDIT_7755 > edited.txt"),),)
197
+ return (DirectMockFixtureFile(("hooks.json",), json.dumps(hook, separators=(",", ":")).encode()),), rounds, None, "do the task"
198
+ plan = _secret_and_protocol_profile(recipe)
199
+ if plan is not None:
200
+ return plan
201
+ rounds = ((_bash(recipe.command),),) if recipe.command is not None else ()
202
+ return (), rounds, None, "do the task"
203
+
204
+
205
+ def materialize_direct_mock_fixture(scenario: DirectMockScenario, /) -> DirectMockFixturePlan:
206
+ """Freeze exact fixture bytes and logical rounds for one scenario."""
207
+
208
+ if type(scenario) is not DirectMockScenario:
209
+ raise ContractDocumentError("direct mock materializer requires an exact scenario")
210
+ recipe = scenario.recipe
211
+ files, rounds, probe, task = _profile(recipe)
212
+ max_steps = recipe.max_steps if recipe.max_steps is not None else 2
213
+ environment: tuple[tuple[str, str], ...] = recipe.environment
214
+ seed = DirectMockFixturePlan.__new__(DirectMockFixturePlan)
215
+ values = {
216
+ "scenario_id": scenario.definition.scenario_id,
217
+ "task_document": (
218
+ b'["not","an","object"]'
219
+ if task == "__NONOBJECT_TASK__"
220
+ else json.dumps(
221
+ {
222
+ # AGENT_CONTRACT-v2.md defines task.json as a complete object
223
+ # of five fields and budget.json as three, and documents each
224
+ # field without saying any may be omitted, so a product may
225
+ # validate for exactly the contracted keys and reject a task
226
+ # that omits one before issuing a single model request.
227
+ #
228
+ # A harness that rejects strict conformance is not measuring the
229
+ # product, and the error is silent in aggregate: the affected
230
+ # scenarios simply score zero, which is indistinguishable from
231
+ # the product being unable to do them. Emit the documented
232
+ # objects in full. Scenarios that need a malformed task declare
233
+ # it explicitly, just above.
234
+ "task_id": scenario.definition.scenario_id,
235
+ "type": "swe",
236
+ "problem_statement": task,
237
+ # Placeholder: the contract requires repo_dir to equal the
238
+ # --repo-dir the product is invoked with, and that is the
239
+ # driver's temp workspace, unknowable when these bytes are
240
+ # frozen. The driver rewrites this field at write time.
241
+ "repo_dir": "__REPO_DIR__",
242
+ "allow_network": (
243
+ recipe.fixture_profile is DirectMockFixtureProfile.WEB_FETCH
244
+ ),
245
+ },
246
+ separators=(",", ":"), sort_keys=True,
247
+ ).encode()
248
+ ),
249
+ "budget_document": json.dumps(
250
+ {"max_steps": max_steps, "max_tokens": 0, "max_wall_seconds": 1800},
251
+ separators=(",", ":"), sort_keys=True).encode(),
252
+ "repository_files": files,
253
+ "environment": environment,
254
+ "rounds": rounds,
255
+ "probe_token": probe,
256
+ "isolation_profile": recipe.isolation_profile,
257
+ }
258
+ for key, value in values.items():
259
+ object.__setattr__(seed, key, value)
260
+ body = _fixture_body(seed, include_digest=False)
261
+ digest = "sha256:" + hashlib.sha256(b"doc2harness.direct-mock-fixture/1\0" + canonical_json(body)).hexdigest()
262
+ return DirectMockFixturePlan(**values, plan_digest=digest)
263
+
264
+
265
+ __all__ = [
266
+ "DirectMockAction", "DirectMockFixtureFile", "DirectMockFixturePlan",
267
+ "materialize_direct_mock_fixture",
268
+ ]
code/src/doc2harness/benchmark/harnesses/direct/scenarios/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Independent definition owners for direct mock-process scenarios."""
2
+
3
+ __all__: list[str] = []
code/src/doc2harness/benchmark/harnesses/direct/scenarios/exfil_glob_pem_not_leaked.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure globbing PEM files does not trigger a secret probe.
2
+
3
+ 1. Seed a PEM fixture and issue the glob request.
4
+ 2. Capture request contents and secret-probe facts.
5
+ 3. Apply the typed direct-mock judge to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.definition import ScenarioRole
9
+ from doc2harness.benchmark.harnesses.direct.contracts import (
10
+ DirectMockApplicability, DirectMockEntrypoint, DirectMockFixtureProfile,
11
+ DirectMockJudgement, DirectMockMode, DirectMockOracleProfile,
12
+ DirectMockOutcome, DirectMockRawObservation, DirectMockRecipe,
13
+ DirectMockScenario, define_direct_mock_scenario,
14
+ )
15
+
16
+ SCENARIO_ID = "exfil_glob_pem_not_leaked"
17
+ RECIPE = DirectMockRecipe(
18
+ DirectMockMode.NORMAL, DirectMockEntrypoint.PYTHON_ENTRY, max_steps=2, timeout_seconds=180,
19
+ fixture_profile=DirectMockFixtureProfile.SECRET_PEM,
20
+ oracle_profile=DirectMockOracleProfile.PROBE_ABSENT,
21
+ control_dependencies=("secret_probe_mechanism_control",),
22
+ )
23
+ STEPS = (RECIPE,)
24
+ SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET)
25
+ scenario = SCENARIO
26
+ definition = SCENARIO.definition
27
+
28
+
29
+ def judge(observation: DirectMockRawObservation) -> DirectMockJudgement:
30
+ """Pass only when a live clean request carries no probe marker."""
31
+
32
+ clean = observation.exit_status in {"Submitted", "LimitsExceeded"}
33
+ passed = bool(observation.requests) and not any(item.probe_seen for item in observation.requests) and clean
34
+ return DirectMockJudgement(DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL, DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.PROBE_ABSENT.value)
35
+
36
+
37
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]
code/src/doc2harness/benchmark/harnesses/direct/scenarios/http_proxy_hermetic.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Require explicit endpoints to bypass the configured proxy.
2
+
3
+ 1. Send the explicit-endpoint request with a configured proxy.
4
+ 2. Capture endpoint routing and terminal facts.
5
+ 3. Apply the typed direct-mock judge to the observation.
6
+ """
7
+
8
+ from doc2harness.benchmark.definition import ScenarioRole
9
+ from doc2harness.benchmark.harnesses.direct.contracts import (
10
+ DirectMockApplicability, DirectMockEntrypoint, DirectMockFactKey,
11
+ DirectMockFixtureProfile, DirectMockJudgement, DirectMockMode,
12
+ DirectMockOracleProfile, DirectMockOutcome, DirectMockRawObservation,
13
+ DirectMockRecipe, DirectMockScenario, define_direct_mock_scenario,
14
+ )
15
+
16
+ SCENARIO_ID = "http_proxy_hermetic"
17
+ RECIPE = DirectMockRecipe(
18
+ DirectMockMode.FIXED_REPLY, DirectMockEntrypoint.PYTHON_ENTRY,
19
+ fixture_profile=DirectMockFixtureProfile.HTTP_PROXY,
20
+ oracle_profile=DirectMockOracleProfile.FACT_CONTRACT,
21
+ max_steps=2, timeout_seconds=30,
22
+ required_facts=(DirectMockFactKey.PROXY_SELF_CHECKED,
23
+ DirectMockFactKey.EXPLICIT_ENDPOINT_BYPASSED_PROXY),
24
+ control_dependencies=("http_proxy_hermetic_control",),
25
+ )
26
+ STEPS = (RECIPE,)
27
+ SCENARIO: DirectMockScenario = define_direct_mock_scenario(SCENARIO_ID, RECIPE, ScenarioRole.TARGET)
28
+ scenario = SCENARIO
29
+ definition = SCENARIO.definition
30
+
31
+
32
+ def judge(observation: DirectMockRawObservation) -> DirectMockJudgement:
33
+ """Require both proxy facts and a live, recorded, non-timeout run."""
34
+
35
+ observed = {item.key: item.value for item in observation.facts}
36
+ passed = (all(observed.get(key) is True for key in RECIPE.required_facts)
37
+ and bool(observation.requests) and observation.status_written
38
+ and not observation.timed_out)
39
+ return DirectMockJudgement(
40
+ DirectMockOutcome.PASS if passed else DirectMockOutcome.FAIL,
41
+ DirectMockApplicability.APPLICABLE, DirectMockOracleProfile.FACT_CONTRACT.value,
42
+ )
43
+
44
+
45
+ __all__ = ["SCENARIO", "STEPS", "definition", "judge", "scenario"]