techtree 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. techtree/__init__.py +35 -0
  2. techtree/__main__.py +14 -0
  3. techtree/canonical.py +239 -0
  4. techtree/catalog/__init__.py +25 -0
  5. techtree/catalog/repository.py +400 -0
  6. techtree/catalog/service.py +419 -0
  7. techtree/cli/__init__.py +1 -0
  8. techtree/cli/app.py +416 -0
  9. techtree/cli/commands/__init__.py +1 -0
  10. techtree/cli/commands/climb.py +1223 -0
  11. techtree/cli/commands/doctor.py +147 -0
  12. techtree/cli/commands/engine.py +207 -0
  13. techtree/cli/commands/proof.py +556 -0
  14. techtree/cli/commands/publish.py +447 -0
  15. techtree/cli/commands/release.py +303 -0
  16. techtree/cli/commands/run.py +1067 -0
  17. techtree/cli/commands/setup.py +181 -0
  18. techtree/cli/commands/skill.py +221 -0
  19. techtree/cli/commands/uplift.py +698 -0
  20. techtree/cli/commands/withdraw.py +212 -0
  21. techtree/cli/confirm.py +47 -0
  22. techtree/cli/context.py +96 -0
  23. techtree/cli/invoke.py +220 -0
  24. techtree/cli/output.py +280 -0
  25. techtree/constants.py +138 -0
  26. techtree/crypto.py +128 -0
  27. techtree/doctor/__init__.py +1 -0
  28. techtree/doctor/checks.py +675 -0
  29. techtree/doctor/execution_checks.py +435 -0
  30. techtree/doctor/service.py +326 -0
  31. techtree/drafts/__init__.py +32 -0
  32. techtree/drafts/source.py +146 -0
  33. techtree/drafts/store.py +992 -0
  34. techtree/engines/__init__.py +1 -0
  35. techtree/engines/bundle.py +251 -0
  36. techtree/engines/installer.py +679 -0
  37. techtree/engines/registry.py +235 -0
  38. techtree/engines/runner.py +170 -0
  39. techtree/errors.py +262 -0
  40. techtree/fs.py +234 -0
  41. techtree/harness.py +108 -0
  42. techtree/identity/__init__.py +41 -0
  43. techtree/identity/models.py +113 -0
  44. techtree/identity/service.py +199 -0
  45. techtree/identity/store.py +263 -0
  46. techtree/ids.py +85 -0
  47. techtree/manifests/__init__.py +39 -0
  48. techtree/manifests/builder.py +433 -0
  49. techtree/manifests/compare.py +376 -0
  50. techtree/models/__init__.py +282 -0
  51. techtree/models/base.py +201 -0
  52. techtree/models/campaign.py +484 -0
  53. techtree/models/catalog.py +227 -0
  54. techtree/models/cli.py +151 -0
  55. techtree/models/climb.py +254 -0
  56. techtree/models/data_policy.py +130 -0
  57. techtree/models/engine.py +156 -0
  58. techtree/models/episode_receipt.py +130 -0
  59. techtree/models/evaluation_backend.py +113 -0
  60. techtree/models/experiment.py +154 -0
  61. techtree/models/run.py +214 -0
  62. techtree/models/skill.py +156 -0
  63. techtree/models/uplift_report.py +158 -0
  64. techtree/models/validation.py +299 -0
  65. techtree/paths.py +116 -0
  66. techtree/presentation/__init__.py +31 -0
  67. techtree/presentation/build.py +1242 -0
  68. techtree/presentation/compact.py +246 -0
  69. techtree/presentation/evidence.py +169 -0
  70. techtree/presentation/models.py +358 -0
  71. techtree/presentation/rich.py +312 -0
  72. techtree/presentation/sanitize.py +156 -0
  73. techtree/publication/__init__.py +44 -0
  74. techtree/publication/address.py +180 -0
  75. techtree/publication/coordinates.py +26 -0
  76. techtree/publication/journal.py +212 -0
  77. techtree/publication/keccak.py +183 -0
  78. techtree/publication/models.py +209 -0
  79. techtree/publication/offer.py +35 -0
  80. techtree/publication/service.py +618 -0
  81. techtree/publication/transport.py +296 -0
  82. techtree/publication/verify.py +242 -0
  83. techtree/publication/withdraw.py +156 -0
  84. techtree/py.typed +0 -0
  85. techtree/receipts/__init__.py +52 -0
  86. techtree/receipts/bundle.py +578 -0
  87. techtree/receipts/compare.py +1065 -0
  88. techtree/receipts/episode.py +672 -0
  89. techtree/receipts/execution.py +630 -0
  90. techtree/receipts/observed.py +474 -0
  91. techtree/receipts/set.py +336 -0
  92. techtree/receipts/uplift.py +655 -0
  93. techtree/receipts/verify.py +1055 -0
  94. techtree/release/__init__.py +9 -0
  95. techtree/release/bootstrap.py +509 -0
  96. techtree/release/checks.py +376 -0
  97. techtree/release/document.py +125 -0
  98. techtree/release/generate.py +221 -0
  99. techtree/release/models.py +293 -0
  100. techtree/release/provenance.py +109 -0
  101. techtree/resources/catalog/campaigns/hello-world-climb.json +1 -0
  102. techtree/resources/catalog/catalog.json +32 -0
  103. techtree/resources/catalog/climbs/hello-world-climb.json +1 -0
  104. techtree/resources/catalog/data-policies/hello-world-climb.json +1 -0
  105. techtree/resources/catalog/taskset-validations/hello-world-climb.json +1 -0
  106. techtree/resources/catalog/validation-evidence/hello-world-climb.json +1 -0
  107. techtree/resources/engines/default/engine.json +20 -0
  108. techtree/resources/engines/default/packages/procedure-transfer-v1/procedure_transfer_v1/__init__.py +7 -0
  109. techtree/resources/engines/default/packages/procedure-transfer-v1/procedure_transfer_v1/algorithm.py +136 -0
  110. techtree/resources/engines/default/packages/procedure-transfer-v1/procedure_transfer_v1/dataset.py +156 -0
  111. techtree/resources/engines/default/packages/procedure-transfer-v1/procedure_transfer_v1/env.py +48 -0
  112. techtree/resources/engines/default/packages/procedure-transfer-v1/procedure_transfer_v1/taskset.py +163 -0
  113. techtree/resources/engines/default/packages/procedure-transfer-v1/pyproject.toml +13 -0
  114. techtree/resources/engines/default/pyproject.toml +23 -0
  115. techtree/resources/engines/default/tools/inspect_taskset.py +124 -0
  116. techtree/resources/engines/default/tools/normalize_eval_output.py +470 -0
  117. techtree/resources/engines/default/tools/normalize_validation.py +222 -0
  118. techtree/resources/engines/default/uv.lock +1758 -0
  119. techtree/resources/harness/hermes-agent-0.19.0.json +69 -0
  120. techtree/resources/release/build-provenance.json +4 -0
  121. techtree/resources/release/release-core.json +24 -0
  122. techtree/runs/__init__.py +31 -0
  123. techtree/runs/artifacts.py +750 -0
  124. techtree/runs/child_registry.py +228 -0
  125. techtree/runs/events.py +478 -0
  126. techtree/runs/executor.py +140 -0
  127. techtree/runs/fake.py +741 -0
  128. techtree/runs/launcher.py +253 -0
  129. techtree/runs/machine.py +489 -0
  130. techtree/runs/real.py +789 -0
  131. techtree/runs/service.py +616 -0
  132. techtree/runs/store.py +555 -0
  133. techtree/runs/validation.py +259 -0
  134. techtree/runs/variants.py +684 -0
  135. techtree/settings.py +143 -0
  136. techtree/skills/__init__.py +14 -0
  137. techtree/skills/archive.py +282 -0
  138. techtree/skills/policy.py +62 -0
  139. techtree/skills/scanner.py +394 -0
  140. techtree/skills/service.py +752 -0
  141. techtree/skills/starter.py +434 -0
  142. techtree/tasksets/__init__.py +1 -0
  143. techtree/tasksets/membership.py +269 -0
  144. techtree/tasksets/provider.py +207 -0
  145. techtree/tasksets/resolver.py +311 -0
  146. techtree/tasksets/service.py +484 -0
  147. techtree/tasksets/verifiers_cli.py +538 -0
  148. techtree/uplift/__init__.py +20 -0
  149. techtree/uplift/context.py +544 -0
  150. techtree/uplift/derive.py +203 -0
  151. techtree/uplift/public_tasks.py +151 -0
  152. techtree/uplift/service.py +719 -0
  153. techtree/uplift/source.py +160 -0
  154. techtree/verifiers/__init__.py +31 -0
  155. techtree/verifiers/budget.py +219 -0
  156. techtree/verifiers/child.py +633 -0
  157. techtree/verifiers/compiler.py +432 -0
  158. techtree/verifiers/config.py +365 -0
  159. techtree/verifiers/credentials.py +321 -0
  160. techtree/verifiers/image.py +126 -0
  161. techtree/verifiers/models.py +527 -0
  162. techtree/verifiers/outputs.py +368 -0
  163. techtree/verifiers/progress.py +192 -0
  164. techtree/verifiers/supervisor.py +341 -0
  165. techtree/verifiers/verify.py +782 -0
  166. techtree/version.py +39 -0
  167. techtree/worker/__init__.py +18 -0
  168. techtree/worker/execute.py +487 -0
  169. techtree/worker/main.py +57 -0
  170. techtree-0.1.0.dist-info/METADATA +344 -0
  171. techtree-0.1.0.dist-info/RECORD +174 -0
  172. techtree-0.1.0.dist-info/WHEEL +4 -0
  173. techtree-0.1.0.dist-info/entry_points.txt +3 -0
  174. techtree-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,124 @@
1
+ """Report the identity of a taskset's first N tasks. Spec section 21.1.
2
+
3
+ This helper runs inside the managed engine, under the engine's own interpreter,
4
+ with the pinned Verifiers commit on its path. It is part of the engine bundle
5
+ and therefore part of the engine digest (decisions document 0003 A3): the code
6
+ that reads a taskset is pinned exactly as tightly as the library it reads it
7
+ with.
8
+
9
+ It prints identity and nothing else. Position, the raw Verifiers task hash, the
10
+ task's name, and its type are what a membership commitment is built from. The
11
+ prompt, the expected answer, and every other field of the task's wire data stay
12
+ inside the engine, because a helper that printed them would turn "freeze which
13
+ tasks are in the Climb" into "publish the answer key".
14
+
15
+ Membership is the first ``--num-tasks`` tasks in the taskset's own iteration
16
+ order (decisions document 0001). There is no shuffle option here, and there
17
+ never will be: ``Taskset.shuffle()`` is not called, not exposed, and not
18
+ reachable from this file.
19
+
20
+ Usage, from the host side::
21
+
22
+ <engine-python> <engine-root>/tools/inspect_taskset.py \\
23
+ --taskset-id procedure-transfer-v1 \\
24
+ --num-tasks 20 \\
25
+ --output <path>
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import re
33
+ from pathlib import Path
34
+
35
+ import verifiers.v1 as vf
36
+
37
+ SCHEMA_VERSION = "techtree.taskset-inspection.v1"
38
+ """The shape host-side Techtree parses. Adding a field is safe; changing the
39
+ meaning of one is a new version."""
40
+
41
+ RAW_TASK_HASH = re.compile(r"^[0-9a-f]{64}$")
42
+ """Verifiers emits unprefixed lowercase hexadecimal. The host normalizes it to
43
+ a Techtree digest at its own boundary; this file never guesses."""
44
+
45
+
46
+ def parse_args() -> argparse.Namespace:
47
+ """Parse the fixed helper arguments."""
48
+ parser = argparse.ArgumentParser(
49
+ description="Report the identity of a taskset's first N tasks.",
50
+ )
51
+ parser.add_argument("--taskset-id", required=True)
52
+ parser.add_argument("--num-tasks", required=True, type=int)
53
+ parser.add_argument("--output", required=True, type=Path)
54
+ return parser.parse_args()
55
+
56
+
57
+ def load_tasks(taskset_id: str, *, num_tasks: int) -> tuple[vf.Taskset, list[vf.Task]]:
58
+ """Load the taskset and take the first ``num_tasks`` tasks in load order."""
59
+ if num_tasks < 1:
60
+ raise SystemExit("--num-tasks must be at least 1")
61
+
62
+ taskset = vf.load_taskset(vf.TasksetConfig(id=taskset_id))
63
+ tasks = list(taskset.head(num_tasks))
64
+
65
+ if len(tasks) != num_tasks:
66
+ raise SystemExit(
67
+ f"taskset {taskset_id} yielded {len(tasks)} tasks, "
68
+ f"but {num_tasks} were requested"
69
+ )
70
+ return taskset, tasks
71
+
72
+
73
+ def task_record(position: int, task: vf.Task) -> dict[str, object]:
74
+ """Return the identity of one task: position, raw hash, name, and type."""
75
+ task_hash = task.hash
76
+ if RAW_TASK_HASH.fullmatch(task_hash) is None:
77
+ raise SystemExit(
78
+ f"task at position {position} reported a hash that is not 64 "
79
+ "lowercase hexadecimal characters"
80
+ )
81
+
82
+ return {
83
+ "position": position,
84
+ "task_hash": task_hash,
85
+ "name": task.data.name,
86
+ "task_type": type(task).__name__,
87
+ }
88
+
89
+
90
+ def inspect_taskset(taskset_id: str, *, num_tasks: int) -> dict[str, object]:
91
+ """Return the taskset's metadata and its ordered task records."""
92
+ taskset, tasks = load_tasks(taskset_id, num_tasks=num_tasks)
93
+ records = [task_record(position, task) for position, task in enumerate(tasks)]
94
+
95
+ hashes = [str(record["task_hash"]) for record in records]
96
+ if len(set(hashes)) != len(hashes):
97
+ raise SystemExit(
98
+ f"taskset {taskset_id} yielded two tasks with the same hash; "
99
+ "membership would be ambiguous"
100
+ )
101
+
102
+ return {
103
+ "schema_version": SCHEMA_VERSION,
104
+ "taskset_id": taskset_id,
105
+ "taskset_class": type(taskset).__name__,
106
+ "requested_num_tasks": num_tasks,
107
+ "task_count": len(records),
108
+ "tasks": records,
109
+ }
110
+
111
+
112
+ def main() -> None:
113
+ """Write one JSON object to the output path."""
114
+ arguments = parse_args()
115
+ document = inspect_taskset(arguments.taskset_id, num_tasks=arguments.num_tasks)
116
+ rendered = json.dumps(document, indent=2, sort_keys=True, ensure_ascii=False)
117
+
118
+ output = Path(arguments.output)
119
+ output.parent.mkdir(parents=True, exist_ok=True)
120
+ output.write_text(f"{rendered}\n", encoding="utf-8")
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
@@ -0,0 +1,470 @@
1
+ """Turn raw eval output into the protocol projection. Spec 6.12, decisions 0003 A3.
2
+
3
+ The Verifiers evaluation writes ``traces.jsonl``: one complete Episode per
4
+ line, appended as episodes finish. Two things make it unusable as a scientific
5
+ record on its own. Its order is completion order, which varies run to run and
6
+ has nothing to do with the Campaign's committed task membership. And it is a
7
+ full upstream wire record — timings, host paths, message graphs, the whole
8
+ transcript — most of which is either non-deterministic or not something a
9
+ receipt should carry.
10
+
11
+ This helper extracts the part that is a claim: for each task, in membership
12
+ order, which subject ran it under which configuration, under which sampling
13
+ settings, at what recorded token cost, and what Verifiers scored it. Everything
14
+ else stays where it is. The normalizer does not replace
15
+ ``traces.jsonl``; Techtree keeps the raw evidence and this projection side by
16
+ side, because a projection nobody can check against its source is an assertion
17
+ rather than evidence.
18
+
19
+ It belongs inside the engine bundle because it imports the pinned Verifiers
20
+ wire models and its reader. Reading a Trace with the version of Verifiers that
21
+ wrote it is the difference between interpreting the record and guessing at it,
22
+ and pinning the interpretation exactly as tightly as the library is the whole
23
+ point of decisions document 0003 A3.
24
+
25
+ It refuses rather than guesses. A run missing a task, scoring one twice,
26
+ seating a role other than ``subject``, or executing somewhere other than Docker
27
+ is not the run the Campaign described, and normalizing it anyway would produce
28
+ a tidy document making a false claim.
29
+
30
+ Usage, from the host side::
31
+
32
+ <engine-python> <engine-root>/tools/normalize_eval_output.py \\
33
+ --output-dir <eval output dir> \\
34
+ --membership <TasksetLock JSON> \\
35
+ --experiment-manifest <ExperimentManifest JSON> \\
36
+ --output <normalized-episodes.jsonl>
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import hashlib
43
+ import json
44
+ import re
45
+ from pathlib import Path
46
+ from typing import Any
47
+
48
+ from verifiers.v1.cli.output import read_episodes
49
+ from verifiers.v1.trace import WireTrace
50
+
51
+ #: The one role v0.1 evaluates. A trace seated anywhere else is a different
52
+ #: experiment (spec 6.5).
53
+ SUBJECT_ROLE = "subject"
54
+
55
+ #: The only subject runtime WP6 executes.
56
+ DOCKER_RUNTIME = "docker"
57
+
58
+ TECHTREE_DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$")
59
+ RAW_TASK_HASH = re.compile(r"^[0-9a-f]{64}$")
60
+ #: An OCI reference that names content. The digest is what a receipt can cite.
61
+ #: For a multi-platform repository it is the image *index* digest, which is what
62
+ #: a Campaign pins and what the local daemon confirms it holds.
63
+ IMAGE_INDEX_DIGEST = re.compile(r"@(sha256:[0-9a-f]{64})$")
64
+
65
+
66
+ def parse_args() -> argparse.Namespace:
67
+ """Parse the fixed helper arguments."""
68
+ parser = argparse.ArgumentParser(
69
+ description="Normalize raw Verifiers evaluation output.",
70
+ )
71
+ parser.add_argument("--output-dir", required=True, type=Path)
72
+ parser.add_argument("--membership", required=True, type=Path)
73
+ parser.add_argument("--experiment-manifest", required=True, type=Path)
74
+ parser.add_argument("--output", required=True, type=Path)
75
+ return parser.parse_args()
76
+
77
+
78
+ def load_membership(path: Path) -> list[str]:
79
+ """Load the Campaign's committed task hashes, in order.
80
+
81
+ Techtree writes hashes with a ``sha256:`` prefix and Verifiers records them
82
+ bare, so this is also the one place the two spellings meet.
83
+ """
84
+ document = json.loads(path.read_text(encoding="utf-8"))
85
+ hashes = document.get("ordered_task_hashes")
86
+ if not isinstance(hashes, list) or not hashes:
87
+ raise SystemExit("the taskset lock commits no ordered task hashes")
88
+
89
+ ordered: list[str] = []
90
+ for value in hashes:
91
+ if not isinstance(value, str) or TECHTREE_DIGEST.fullmatch(value) is None:
92
+ raise SystemExit(f"committed task hash {value!r} is not a Techtree digest")
93
+ ordered.append(value)
94
+ if len(set(ordered)) != len(ordered):
95
+ raise SystemExit("the taskset lock commits the same task twice")
96
+ return ordered
97
+
98
+
99
+ def load_experiment(path: Path) -> dict[str, Any]:
100
+ """Load the resolved experiment this evaluation claims to be."""
101
+ document = json.loads(path.read_text(encoding="utf-8"))
102
+ configuration = document.get("configuration")
103
+ subject = (configuration or {}).get("agents", {}).get(SUBJECT_ROLE)
104
+ if not isinstance(subject, dict):
105
+ raise SystemExit(
106
+ f"the experiment manifest defines no {SUBJECT_ROLE!r} agent to "
107
+ "normalize against"
108
+ )
109
+ return document
110
+
111
+
112
+ def read_wire_episodes(output_dir: Path) -> list[Any]:
113
+ """Read every persisted Episode with the pinned wire Trace type.
114
+
115
+ ``WireTrace`` reads any taskset's saved trace without importing that
116
+ taskset, which keeps this helper independent of whichever reference package
117
+ produced the run.
118
+ """
119
+ return read_episodes(output_dir, WireTrace)
120
+
121
+
122
+ def digest_text(value: str) -> str:
123
+ """Return the Techtree digest of one string's UTF-8 bytes."""
124
+ return f"sha256:{hashlib.sha256(value.encode('utf-8')).hexdigest()}"
125
+
126
+
127
+ def digest_json(value: Any) -> str:
128
+ """Return the Techtree digest of one value's canonical JSON form."""
129
+ return digest_text(
130
+ json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
131
+ )
132
+
133
+
134
+ def normalize_task_hash(raw: str | None) -> str:
135
+ """Return the Techtree spelling of one Verifiers task hash."""
136
+ if not isinstance(raw, str) or RAW_TASK_HASH.fullmatch(raw) is None:
137
+ raise SystemExit(f"a trace records no usable task hash: {raw!r}")
138
+ return f"sha256:{raw}"
139
+
140
+
141
+ def normalize_error(error: Any) -> dict[str, Any]:
142
+ """Project one upstream error.
143
+
144
+ The traceback is kept: this projection only ever holds errors from records
145
+ that failed, and a failure with its traceback stripped is a failure nobody
146
+ can act on.
147
+ """
148
+ return {
149
+ "type": error.type,
150
+ "message": error.message,
151
+ "traceback": error.traceback,
152
+ }
153
+
154
+
155
+ def normalize_reward(name: str, reward: Any) -> dict[str, Any]:
156
+ """Project one named reward, with its weighted contribution."""
157
+ if reward is None:
158
+ raise SystemExit(
159
+ f"reward {name!r} was never scored; an episode whose scoring did "
160
+ "not run is not a result"
161
+ )
162
+ score = float(reward.score)
163
+ weight = float(reward.weight)
164
+ value = score * weight
165
+ for label, number in (("score", score), ("weight", weight), ("value", value)):
166
+ if number != number or number in (float("inf"), float("-inf")):
167
+ raise SystemExit(f"reward {name!r} has a non-finite {label}")
168
+ return {"name": name, "score": score, "weight": weight, "value": value}
169
+
170
+
171
+ def normalize_tool(tool: Any) -> dict[str, Any]:
172
+ """Project one advertised tool by name and by digest.
173
+
174
+ A tool's description and parameter schema are prompt material. Hashing them
175
+ proves two variants were offered identical tools without republishing what
176
+ the subject was told.
177
+ """
178
+ return {
179
+ "name": tool.name,
180
+ "description_digest": digest_text(tool.description or ""),
181
+ "parameters_digest": digest_json(tool.parameters or {}),
182
+ }
183
+
184
+
185
+ def normalize_runtime(trace: Any) -> dict[str, Any]:
186
+ """Project the box one trace ran in.
187
+
188
+ The pinned Verifiers build records the reference it was asked to run and
189
+ nothing about what the daemon resolved it to, so this projection reports
190
+ exactly that: the reference, and the content digest the reference names. A
191
+ Campaign pins its subject image by digest, so a reference that names no
192
+ content is a run of something nobody can identify and is refused here
193
+ rather than described as if it were pinned.
194
+
195
+ What the local daemon confirmed — that it holds that content, and which
196
+ platform it served — is captured by Techtree beside this projection, and the
197
+ two are required to agree before a comparison is called controlled.
198
+ """
199
+ info = trace.agent.runtime
200
+ if info is None:
201
+ raise SystemExit(f"trace {trace.id} records no runtime")
202
+
203
+ kind = getattr(info, "type", None)
204
+ if kind != DOCKER_RUNTIME:
205
+ raise SystemExit(
206
+ f"trace {trace.id} ran on the {kind!r} runtime; WP6 evaluates the "
207
+ f"{DOCKER_RUNTIME!r} runtime only"
208
+ )
209
+
210
+ image = getattr(info, "image", None)
211
+ if not isinstance(image, str) or not image:
212
+ raise SystemExit(f"trace {trace.id} records no runtime image")
213
+
214
+ match = IMAGE_INDEX_DIGEST.search(image)
215
+ if match is None:
216
+ raise SystemExit(
217
+ f"trace {trace.id} ran {image!r}, which names a tag rather than "
218
+ "content; a controlled comparison runs a digest-pinned image"
219
+ )
220
+
221
+ return {
222
+ "kind": DOCKER_RUNTIME,
223
+ "runtime_id": getattr(info, "id", None),
224
+ "image": image,
225
+ "image_index_digest": match.group(1),
226
+ "cpu": _optional_float(getattr(info, "cpu", None)),
227
+ "memory_gb": _optional_float(getattr(info, "memory", None)),
228
+ }
229
+
230
+
231
+ def normalize_sampling(trace: Any) -> dict[str, Any]:
232
+ """Project the settings the subject was actually sampled under.
233
+
234
+ Read from the trace rather than from the configuration file the engine
235
+ wrote back out. Both are the engine's own answers, but only this one
236
+ travels with the rollout it describes, so a consumer holding a normalized
237
+ episode can compare two variants' effective sampling without opening a
238
+ second document beside it.
239
+
240
+ ``SamplingConfig`` allows provider-specific keys through, so every key the
241
+ engine resolved is projected and none is filtered: a parameter Techtree
242
+ never declared is exactly the sort of uncontrolled difference a comparison
243
+ has to be able to see.
244
+ """
245
+ sampling = trace.agent.config.sampling
246
+ if sampling is None:
247
+ raise SystemExit(
248
+ f"trace {trace.id} records no sampling settings, so how its subject "
249
+ "was sampled is unknown"
250
+ )
251
+ values: dict[str, Any] = {}
252
+ for key, value in sorted(sampling.model_dump(mode="json").items()):
253
+ if value is None:
254
+ continue
255
+ if not isinstance(value, str | int | float | bool):
256
+ raise SystemExit(
257
+ f"trace {trace.id} was sampled under a non-scalar {key!r}, "
258
+ "which cannot be compared between two variants"
259
+ )
260
+ values[str(key)] = value
261
+ if not values:
262
+ raise SystemExit(
263
+ f"trace {trace.id} resolved an empty sampling table, so how its "
264
+ "subject was sampled is unknown"
265
+ )
266
+ return values
267
+
268
+
269
+ def normalize_usage(trace: Any) -> dict[str, Any] | None:
270
+ """Project provider-reported token accounting, or nothing.
271
+
272
+ ``cost_usd`` is the provider's own number and is frequently absent. It is
273
+ projected as-is, never computed here: an operational record downstream
274
+ states where a cost came from, and a number this helper invented could not
275
+ be told apart from one the provider reported.
276
+ """
277
+ usage = trace.usage
278
+ if usage is None:
279
+ return None
280
+ return {
281
+ "input_tokens": int(usage.input_tokens),
282
+ "output_tokens": int(usage.completion_tokens),
283
+ "total_tokens": int(usage.total_tokens),
284
+ "cached_input_tokens": (
285
+ None
286
+ if usage.cached_input_tokens is None
287
+ else int(usage.cached_input_tokens)
288
+ ),
289
+ "cost_usd": (None if usage.cost is None else float(usage.cost)),
290
+ }
291
+
292
+
293
+ def normalize_trace(trace: Any, experiment: dict[str, Any]) -> dict[str, Any]:
294
+ """Project one subject rollout."""
295
+ if trace.agent.name != SUBJECT_ROLE:
296
+ raise SystemExit(
297
+ f"trace {trace.id} was produced by the {trace.agent.name!r} role; "
298
+ f"v0.1 evaluates {SUBJECT_ROLE!r} and nothing else"
299
+ )
300
+
301
+ harness = trace.agent.config.harness
302
+ if harness is None:
303
+ raise SystemExit(f"trace {trace.id} records no harness")
304
+
305
+ revision = trace.verifiers.commit
306
+ if not isinstance(revision, str) or not revision:
307
+ raise SystemExit(
308
+ f"trace {trace.id} records no Verifiers commit; this run was not "
309
+ "produced by an engine installed from the pinned source"
310
+ )
311
+
312
+ return {
313
+ "trace_id": trace.id,
314
+ "agent_role": SUBJECT_ROLE,
315
+ "task_hash": normalize_task_hash(trace.task.hash),
316
+ "ok": bool(trace.ok),
317
+ "verifiers_version": trace.verifiers.version,
318
+ "verifiers_revision": revision,
319
+ "model_id": trace.agent.config.model or "",
320
+ "sampling": normalize_sampling(trace),
321
+ "harness_id": harness.id,
322
+ "harness_version": str(getattr(harness, "version", "")),
323
+ "use_bundled_skill": bool(getattr(harness, "use_bundled_skill", False)),
324
+ "skill_root_digests": skill_root_digests(experiment),
325
+ "runtime": normalize_runtime(trace),
326
+ "tools": sorted(
327
+ (normalize_tool(tool) for tool in trace.tools),
328
+ key=lambda entry: entry["name"],
329
+ ),
330
+ "rewards": sorted(
331
+ (normalize_reward(name, reward) for name, reward in trace.rewards.items()),
332
+ key=lambda entry: entry["name"],
333
+ ),
334
+ "metrics": {
335
+ name: (None if value is None else float(value))
336
+ for name, value in sorted(trace.metrics.items())
337
+ },
338
+ "usage": normalize_usage(trace),
339
+ # One entry per exchange the interception layer recorded. The token
340
+ # counts above are an aggregate over exactly these calls, so a record
341
+ # that reports a cost has the call count that cost was incurred over.
342
+ "model_calls": len(trace.calls),
343
+ "num_turns": int(trace.num_turns),
344
+ "last_reply": trace.last_reply or None,
345
+ "errors": [normalize_error(error) for error in trace.errors],
346
+ "raw_trace_digest": digest_json(trace.model_dump(mode="json")),
347
+ }
348
+
349
+
350
+ def normalize_episode(episode: Any, experiment: dict[str, Any]) -> dict[str, Any]:
351
+ """Project one episode and the single subject trace it must carry."""
352
+ if len(episode.traces) != 1:
353
+ raise SystemExit(
354
+ f"episode {episode.id} carries {len(episode.traces)} traces; a "
355
+ "single-agent Campaign produces exactly one per episode"
356
+ )
357
+ trace = normalize_trace(episode.traces[0], experiment)
358
+ return {
359
+ "episode_id": episode.id,
360
+ "env_id": episode.env.id,
361
+ "task_hash": trace["task_hash"],
362
+ "task_position": -1,
363
+ "ok": bool(episode.ok),
364
+ "traces": [trace],
365
+ "errors": [normalize_error(error) for error in episode.errors],
366
+ "raw_episode_digest": digest_json(episode.model_dump(mode="json")),
367
+ }
368
+
369
+
370
+ def order_by_membership(
371
+ episodes: list[dict[str, Any]], ordered_task_hashes: list[str]
372
+ ) -> list[dict[str, Any]]:
373
+ """Join episodes onto the Campaign's committed membership, in order.
374
+
375
+ Line position in ``traces.jsonl`` is completion order, so this join is the
376
+ only thing that makes the projection comparable between two variants. It
377
+ refuses on anything that would leave the join ambiguous: a task with no
378
+ episode, a task with two, or an episode scoring a task the Campaign never
379
+ committed to.
380
+ """
381
+ by_hash: dict[str, dict[str, Any]] = {}
382
+ for episode in episodes:
383
+ task_hash = episode["task_hash"]
384
+ if task_hash in by_hash:
385
+ raise SystemExit(f"two episodes scored task {task_hash}")
386
+ by_hash[task_hash] = episode
387
+
388
+ unexpected = sorted(set(by_hash) - set(ordered_task_hashes))
389
+ if unexpected:
390
+ raise SystemExit(
391
+ f"the evaluation scored {len(unexpected)} task(s) the Campaign never "
392
+ f"committed to: {unexpected[0]}"
393
+ )
394
+ missing = [value for value in ordered_task_hashes if value not in by_hash]
395
+ if missing:
396
+ raise SystemExit(
397
+ f"the evaluation is missing {len(missing)} committed task(s), "
398
+ f"starting with {missing[0]}"
399
+ )
400
+
401
+ ordered: list[dict[str, Any]] = []
402
+ for position, task_hash in enumerate(ordered_task_hashes):
403
+ episode = by_hash[task_hash]
404
+ episode["task_position"] = position
405
+ ordered.append(episode)
406
+ return ordered
407
+
408
+
409
+ def subject_of(experiment: dict[str, Any]) -> dict[str, Any]:
410
+ """Return the manifest's subject agent."""
411
+ subject = experiment["configuration"]["agents"][SUBJECT_ROLE]
412
+ assert isinstance(subject, dict)
413
+ return subject
414
+
415
+
416
+ def skill_root_digests(experiment: dict[str, Any]) -> list[str]:
417
+ """Return the content digests of the skills this variant declared.
418
+
419
+ Read from the manifest rather than from the trace. Verifiers records the
420
+ directory a skill was mounted from, which is a run-owned host path; what a
421
+ receipt can cite is the content the Campaign pinned.
422
+ """
423
+ digests: list[str] = []
424
+ for skill in subject_of(experiment)["harness"].get("skills", []):
425
+ digest = skill.get("digest")
426
+ if not isinstance(digest, str) or TECHTREE_DIGEST.fullmatch(digest) is None:
427
+ raise SystemExit(f"the experiment declares an unusable skill: {skill!r}")
428
+ digests.append(digest)
429
+ return digests
430
+
431
+
432
+ def main() -> int:
433
+ """Write canonical compact JSONL ordered by task membership."""
434
+ arguments = parse_args()
435
+ experiment = load_experiment(Path(arguments.experiment_manifest))
436
+ membership = load_membership(Path(arguments.membership))
437
+
438
+ episodes = [
439
+ normalize_episode(episode, experiment)
440
+ for episode in read_wire_episodes(Path(arguments.output_dir))
441
+ ]
442
+ ordered = order_by_membership(episodes, membership)
443
+
444
+ output = Path(arguments.output)
445
+ output.parent.mkdir(parents=True, exist_ok=True)
446
+ output.write_text(
447
+ "".join(
448
+ json.dumps(
449
+ episode, sort_keys=True, separators=(",", ":"), ensure_ascii=False
450
+ )
451
+ + "\n"
452
+ for episode in ordered
453
+ ),
454
+ encoding="utf-8",
455
+ )
456
+ return 0
457
+
458
+
459
+ def _optional_float(value: Any) -> float | None:
460
+ """Return a finite float, or nothing."""
461
+ if value is None:
462
+ return None
463
+ number = float(value)
464
+ if number != number or number in (float("inf"), float("-inf")):
465
+ raise SystemExit(f"a runtime resource limit is not finite: {value!r}")
466
+ return number
467
+
468
+
469
+ if __name__ == "__main__":
470
+ raise SystemExit(main())