agentenv-framework 0.9.1254__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 (312) hide show
  1. agent_env/__init__.py +0 -0
  2. agent_env/a2a_agent/__init__.py +23 -0
  3. agent_env/a2a_agent/a2a_agent.py +600 -0
  4. agent_env/a2a_agent/conversation_store.py +356 -0
  5. agent_env/a2a_agent/object_transfer.py +609 -0
  6. agent_env/a2a_agent/protocol.py +238 -0
  7. agent_env/a2a_agent/store.py +201 -0
  8. agent_env/a2a_agent/validator.py +901 -0
  9. agent_env/artifact/__init__.py +48 -0
  10. agent_env/artifact/artifact.py +74 -0
  11. agent_env/artifact/artifacts/__init__.py +0 -0
  12. agent_env/artifact/artifacts/cli.py +83 -0
  13. agent_env/artifact/artifacts/docker_image.py +457 -0
  14. agent_env/artifact/artifacts/environment.py +89 -0
  15. agent_env/artifact/artifacts/environment_universe.py +156 -0
  16. agent_env/artifact/artifacts/file.py +214 -0
  17. agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
  18. agent_env/artifact/artifacts/skill.py +206 -0
  19. agent_env/artifact/artifacts/vm_image.py +95 -0
  20. agent_env/artifact/ref.py +15 -0
  21. agent_env/artifact/registry.py +251 -0
  22. agent_env/artifact/store.py +295 -0
  23. agent_env/artifact/universe.py +38 -0
  24. agent_env/attribution.py +41 -0
  25. agent_env/bundle/__init__.py +4 -0
  26. agent_env/bundle/_fs.py +128 -0
  27. agent_env/bundle/authoring.py +239 -0
  28. agent_env/bundle/installed.py +175 -0
  29. agent_env/bundle/ledger.py +269 -0
  30. agent_env/bundle/materialize.py +204 -0
  31. agent_env/bundle/parse.py +594 -0
  32. agent_env/bundle/plan.py +414 -0
  33. agent_env/bundle/resolve.py +404 -0
  34. agent_env/bundle/run.py +361 -0
  35. agent_env/cli/__init__.py +69 -0
  36. agent_env/cli/__main__.py +10 -0
  37. agent_env/cli/_installers.py +576 -0
  38. agent_env/cli/_plugin_changes.py +947 -0
  39. agent_env/cli/a2a_agent/__init__.py +22 -0
  40. agent_env/cli/a2a_agent/add_skill.py +97 -0
  41. agent_env/cli/a2a_agent/deploy.py +60 -0
  42. agent_env/cli/a2a_agent/get.py +15 -0
  43. agent_env/cli/a2a_agent/get_instance.py +26 -0
  44. agent_env/cli/a2a_agent/put.py +78 -0
  45. agent_env/cli/a2a_agent/validate.py +56 -0
  46. agent_env/cli/artifact/__init__.py +20 -0
  47. agent_env/cli/artifact/cli.py +83 -0
  48. agent_env/cli/artifact/environment.py +44 -0
  49. agent_env/cli/artifact/environment_universe.py +163 -0
  50. agent_env/cli/artifact/file_artifact_universe.py +281 -0
  51. agent_env/cli/artifact/skill.py +128 -0
  52. agent_env/cli/banner.py +25 -0
  53. agent_env/cli/config.py +263 -0
  54. agent_env/cli/env/__init__.py +31 -0
  55. agent_env/cli/env/deploy.py +112 -0
  56. agent_env/cli/env/gateway.py +57 -0
  57. agent_env/cli/env/get_instance.py +40 -0
  58. agent_env/cli/env/mcp_server.py +410 -0
  59. agent_env/cli/env/multi.py +282 -0
  60. agent_env/cli/env/service_db.py +99 -0
  61. agent_env/cli/env/snapshot.py +35 -0
  62. agent_env/cli/env/state/__init__.py +6 -0
  63. agent_env/cli/env/state/init.py +108 -0
  64. agent_env/cli/env/state/teardown.py +44 -0
  65. agent_env/cli/env/website.py +216 -0
  66. agent_env/cli/env/website_browser.py +67 -0
  67. agent_env/cli/eval/__init__.py +16 -0
  68. agent_env/cli/eval/add_tasks.py +63 -0
  69. agent_env/cli/eval/create.py +49 -0
  70. agent_env/cli/eval/run.py +194 -0
  71. agent_env/cli/identity/__init__.py +5 -0
  72. agent_env/cli/identity/client_identity.py +37 -0
  73. agent_env/cli/plugin.py +438 -0
  74. agent_env/cli/run.py +285 -0
  75. agent_env/cli/task/__init__.py +21 -0
  76. agent_env/cli/task/create.py +109 -0
  77. agent_env/cli/task/get.py +17 -0
  78. agent_env/cli/task/get_instance.py +34 -0
  79. agent_env/cli/task/run.py +615 -0
  80. agent_env/cli/task/validate.py +31 -0
  81. agent_env/cli/up.py +123 -0
  82. agent_env/cli/utils.py +183 -0
  83. agent_env/config/__init__.py +50 -0
  84. agent_env/config/describe.py +1067 -0
  85. agent_env/config/errors.py +13 -0
  86. agent_env/config/loader.py +245 -0
  87. agent_env/config/model.py +154 -0
  88. agent_env/config/paths.py +25 -0
  89. agent_env/config/plugin_tables.py +101 -0
  90. agent_env/config/provenance.py +134 -0
  91. agent_env/config/runtime.py +1064 -0
  92. agent_env/config/snapshot.py +81 -0
  93. agent_env/entity_refs.py +186 -0
  94. agent_env/env/__init__.py +49 -0
  95. agent_env/env/env.py +433 -0
  96. agent_env/env/env_artifact_store.py +87 -0
  97. agent_env/env/envs/__init__.py +7 -0
  98. agent_env/env/envs/_deployment.py +281 -0
  99. agent_env/env/envs/gateway_server.py +32 -0
  100. agent_env/env/envs/mcp_server.py +387 -0
  101. agent_env/env/envs/multi_env.py +780 -0
  102. agent_env/env/envs/service_db/Dockerfile +20 -0
  103. agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
  104. agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
  105. agent_env/env/envs/service_db.py +92 -0
  106. agent_env/env/envs/website.py +294 -0
  107. agent_env/env/envs/website_browser/Dockerfile +40 -0
  108. agent_env/env/envs/website_browser/__init__.py +17 -0
  109. agent_env/env/envs/website_browser/entrypoint.sh +13 -0
  110. agent_env/env/gateway/Dockerfile +14 -0
  111. agent_env/env/gateway/__init__.py +37 -0
  112. agent_env/env/gateway/clock.py +184 -0
  113. agent_env/env/gateway/constants.py +190 -0
  114. agent_env/env/gateway/entrypoint.py +156 -0
  115. agent_env/env/gateway/gateway.py +1095 -0
  116. agent_env/env/gateway/get_time.py +60 -0
  117. agent_env/env/gateway/requirements.txt +4 -0
  118. agent_env/env/gateway/triggers.py +1193 -0
  119. agent_env/env/legacy_protocol.py +146 -0
  120. agent_env/env/registry.py +93 -0
  121. agent_env/env/snapshot_store.py +372 -0
  122. agent_env/env/store.py +411 -0
  123. agent_env/eval/__init__.py +14 -0
  124. agent_env/eval/eval.py +68 -0
  125. agent_env/eval/store.py +116 -0
  126. agent_env/examples/hello/README.md +9 -0
  127. agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
  128. agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
  129. agent_env/examples/hello/tasks/hello.json +10 -0
  130. agent_env/explorer/__init__.py +12 -0
  131. agent_env/explorer/app.py +277 -0
  132. agent_env/explorer/openapi_docs.py +242 -0
  133. agent_env/explorer/plugin.py +95 -0
  134. agent_env/explorer/routers/__init__.py +1 -0
  135. agent_env/explorer/routers/common.py +174 -0
  136. agent_env/explorer/routers/conversations.py +25 -0
  137. agent_env/explorer/routers/objects.py +112 -0
  138. agent_env/explorer/routers/runs.py +475 -0
  139. agent_env/plugins/__init__.py +59 -0
  140. agent_env/plugins/_cli.py +244 -0
  141. agent_env/plugins/_discovery.py +97 -0
  142. agent_env/plugins/_inventory.py +262 -0
  143. agent_env/plugins/_registration.py +268 -0
  144. agent_env/plugins/_report.py +47 -0
  145. agent_env/plugins/_requirements.py +55 -0
  146. agent_env/providers/__init__.py +37 -0
  147. agent_env/providers/env_providers/__init__.py +12 -0
  148. agent_env/providers/env_providers/constants.py +13 -0
  149. agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
  150. agent_env/providers/env_providers/env_provider.py +237 -0
  151. agent_env/providers/env_providers/env_server_provider.py +133 -0
  152. agent_env/providers/env_state/__init__.py +49 -0
  153. agent_env/providers/env_state/env_state_provider.py +554 -0
  154. agent_env/providers/env_state/local_postgres.py +390 -0
  155. agent_env/providers/env_state/store.py +112 -0
  156. agent_env/providers/sandbox_providers/__init__.py +29 -0
  157. agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
  158. agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
  159. agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
  160. agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
  161. agent_env/providers/sandbox_providers/e2b/template.py +158 -0
  162. agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
  163. agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
  164. agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
  165. agent_env/providers/sandbox_providers/sandbox.py +387 -0
  166. agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
  167. agent_env/py.typed +0 -0
  168. agent_env/runner/__init__.py +16 -0
  169. agent_env/runner/local_runner.py +190 -0
  170. agent_env/runner/runner.py +127 -0
  171. agent_env/runner/store.py +94 -0
  172. agent_env/store/__init__.py +126 -0
  173. agent_env/store/_google.py +68 -0
  174. agent_env/store/base.py +33 -0
  175. agent_env/store/document_store/__init__.py +60 -0
  176. agent_env/store/document_store/document_store.py +519 -0
  177. agent_env/store/document_store/dynamodb_document_store.py +306 -0
  178. agent_env/store/document_store/evaluation.py +199 -0
  179. agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
  180. agent_env/store/document_store/mongo_document_store.py +259 -0
  181. agent_env/store/document_store/sqlite_document_store.py +314 -0
  182. agent_env/store/ids.py +123 -0
  183. agent_env/store/image_store/__init__.py +34 -0
  184. agent_env/store/image_store/ecr_image_store.py +131 -0
  185. agent_env/store/image_store/google_credentials.py +113 -0
  186. agent_env/store/image_store/image_store.py +113 -0
  187. agent_env/store/image_store/local_registry_image_store.py +106 -0
  188. agent_env/store/image_store/oci_registry_credentials.py +196 -0
  189. agent_env/store/local_state.py +27 -0
  190. agent_env/store/object_store/__init__.py +24 -0
  191. agent_env/store/object_store/gcs_object_store.py +415 -0
  192. agent_env/store/object_store/local_object_store.py +143 -0
  193. agent_env/store/object_store/object_store.py +198 -0
  194. agent_env/store/object_store/s3_object_store.py +354 -0
  195. agent_env/store/query.py +112 -0
  196. agent_env/store/routing.py +609 -0
  197. agent_env/store/secret_store/__init__.py +19 -0
  198. agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
  199. agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
  200. agent_env/store/secret_store/local_secret_store.py +47 -0
  201. agent_env/store/secret_store/secret_store.py +19 -0
  202. agent_env/task/__init__.py +27 -0
  203. agent_env/task/interrupts.py +109 -0
  204. agent_env/task/registry.py +27 -0
  205. agent_env/task/step_journal.py +99 -0
  206. agent_env/task/store.py +940 -0
  207. agent_env/task/task.py +815 -0
  208. agent_env/task/teardown.py +142 -0
  209. agent_env/task_step/__init__.py +47 -0
  210. agent_env/task_step/context.py +195 -0
  211. agent_env/task_step/context_ops.py +224 -0
  212. agent_env/task_step/registry.py +182 -0
  213. agent_env/task_step/review_store.py +118 -0
  214. agent_env/task_step/snapshot_utils/__init__.py +2 -0
  215. agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
  216. agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
  217. agent_env/task_step/store.py +129 -0
  218. agent_env/task_step/task_step.py +173 -0
  219. agent_env/task_step/task_steps/__init__.py +27 -0
  220. agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
  221. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
  222. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
  223. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
  224. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
  225. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
  226. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
  227. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
  228. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
  229. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
  230. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
  231. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
  232. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
  233. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
  234. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
  235. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
  236. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
  237. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
  238. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
  239. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
  240. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
  241. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
  242. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
  243. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
  244. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
  245. agent_env/task_step/task_steps/add_skills.py +240 -0
  246. agent_env/task_step/task_steps/apply_server_config.py +288 -0
  247. agent_env/task_step/task_steps/collect_artifacts.py +940 -0
  248. agent_env/task_step/task_steps/deploy_agent.py +626 -0
  249. agent_env/task_step/task_steps/deploy_env.py +197 -0
  250. agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
  251. agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
  252. agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
  253. agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
  254. agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
  255. agent_env/task_step/task_steps/install_agent.py +376 -0
  256. agent_env/task_step/task_steps/load_artifact.py +775 -0
  257. agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
  258. agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
  259. agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
  260. agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
  261. agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
  262. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
  263. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
  264. agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
  265. agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
  266. agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
  267. agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
  268. agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
  269. agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
  270. agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
  271. agent_env/task_step/task_steps/peer_agents.py +92 -0
  272. agent_env/task_step/task_steps/prompt_agent.py +900 -0
  273. agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
  274. agent_env/task_step/task_steps/register_env_triggers.py +97 -0
  275. agent_env/task_step/task_steps/reset_env.py +71 -0
  276. agent_env/task_step/task_steps/review.py +152 -0
  277. agent_env/task_step/task_steps/run_code.py +461 -0
  278. agent_env/task_step/task_steps/run_code_runner.py +52 -0
  279. agent_env/task_step/task_steps/run_docker_container.py +380 -0
  280. agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
  281. agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
  282. agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
  283. agent_env/task_step/task_steps/snapshot_env.py +637 -0
  284. agent_env/task_step/task_steps/sync_env_clock.py +132 -0
  285. agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
  286. agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
  287. agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
  288. agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
  289. agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
  290. agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
  291. agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
  292. agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
  293. agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
  294. agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
  295. agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
  296. agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
  297. agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
  298. agent_env/task_step/thread_work.py +61 -0
  299. agent_env/utils/__init__.py +0 -0
  300. agent_env/utils/card_naming.py +108 -0
  301. agent_env/utils/deprecation.py +109 -0
  302. agent_env/utils/docker_build.py +29 -0
  303. agent_env/utils/exec_retry.py +77 -0
  304. agent_env/utils/litellm_attribution.py +59 -0
  305. agent_env/utils/paths.py +20 -0
  306. agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
  307. agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
  308. agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
  309. agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
  310. agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
  311. agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
  312. agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
@@ -0,0 +1,1293 @@
1
+ """Registry of judge output formats: prompt templates, schemas, and parsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+ from functools import partial
10
+ from string import Template
11
+ from typing import Callable, Sequence
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ _SCAFFOLD_PATH = """An agent was given the following prompt and generated the trajectory and response below. Analyze the agent's trajectory and response against the following criteria.
16
+
17
+ ## Agent Prompt
18
+ <agent_prompt>
19
+ $agent_prompt
20
+ </agent_prompt>
21
+
22
+ ## Agent Trajectory
23
+ The agent's trajectory is available at $trajectory_path
24
+
25
+ ## Agent Response
26
+ <agent_response>
27
+ $agent_response
28
+ </agent_response>
29
+
30
+ ## Criteria
31
+ $criteria_json
32
+
33
+ """
34
+
35
+ _SCAFFOLD_INLINE = """An agent was given the following prompt and generated the trajectory and response below. Analyze the agent's trajectory and response against the following criteria.
36
+
37
+ ## Agent Prompt
38
+ <agent_prompt>
39
+ $agent_prompt
40
+ </agent_prompt>
41
+
42
+ ## Agent Trajectory
43
+ <agent_trajectory>
44
+ $trajectory_content
45
+ </agent_trajectory>
46
+
47
+ ## Agent Response
48
+ <agent_response>
49
+ $agent_response
50
+ </agent_response>
51
+
52
+ ## Criteria
53
+ $criteria_json
54
+
55
+ """
56
+
57
+ _SCAFFOLD_NO_TRAJECTORY = """An agent was given the following prompt and generated the response below. Analyze the agent's response against the following criteria.
58
+
59
+ ## Agent Prompt
60
+ <agent_prompt>
61
+ $agent_prompt
62
+ </agent_prompt>
63
+
64
+ ## Agent Response
65
+ <agent_response>
66
+ $agent_response
67
+ </agent_response>
68
+
69
+ ## Criteria
70
+ $criteria_json
71
+
72
+ """
73
+
74
+ # rubric_binary instructions — binary pass/fail. path/inline judge "behavior",
75
+ # no-trajectory judges "response"; everything above is the shared scaffold.
76
+ _BINARY_INSTRUCTIONS_BEHAVIOR = """## Instructions
77
+ For each criterion, determine whether the agent's behavior PASSES or FAILS.
78
+
79
+ For each criterion, return a result with:
80
+ - "id": the criterion's id
81
+ - "score": exactly 1.0 if the criterion is met, exactly 0.0 if it is not. Binary only — do NOT use partial scores like 0.5. If the criterion is partially met, choose the closer of 1.0 or 0.0 based on whether it would be considered "met" for grading purposes.
82
+ Exception — `"negative": true` criteria (read carefully; this is the single most common place graders slip): the criterion text describes an anti-pattern the response should NOT exhibit, so the score is INVERTED relative to your instinct. Decide in two explicit, ordered steps and do NOT collapse them:
83
+ 1. First judge ONLY whether the named anti-pattern is PRESENT or ABSENT in the agent's output, and state that verdict verbatim ("anti-pattern ABSENT" or "anti-pattern PRESENT") in your justification.
84
+ 2. Then map that verdict mechanically to the score: ABSENT → 1.0 (good — the agent avoided the anti-pattern), PRESENT → 0.0 (bad — the agent exhibited it).
85
+ Your score MUST match the verdict you wrote — absent ⇒ 1.0, present ⇒ 0.0, no exceptions. Never let a justification that concludes the anti-pattern is absent end on 0.0 (or one that concludes it is present end on 1.0). Grade only the anti-pattern the criterion names, and grade near-identical outputs identically. Same binary-only rule applies (exactly 1.0 or 0.0).
86
+ - "justification": a brief explanation of why you chose this score"""
87
+
88
+ _BINARY_INSTRUCTIONS_RESPONSE = """## Instructions
89
+ For each criterion, determine whether the agent's response PASSES or FAILS.
90
+
91
+ For each criterion, return a result with:
92
+ - "id": the criterion's id
93
+ - "score": exactly 1.0 if the criterion is met, exactly 0.0 if it is not. Binary only — do NOT use partial scores like 0.5. If the criterion is partially met, choose the closer of 1.0 or 0.0 based on whether it would be considered "met" for grading purposes.
94
+ Exception — `"negative": true` criteria (read carefully; this is the single most common place graders slip): the criterion text describes an anti-pattern the response should NOT exhibit, so the score is INVERTED relative to your instinct. Decide in two explicit, ordered steps and do NOT collapse them:
95
+ 1. First judge ONLY whether the named anti-pattern is PRESENT or ABSENT in the agent's output, and state that verdict verbatim ("anti-pattern ABSENT" or "anti-pattern PRESENT") in your justification.
96
+ 2. Then map that verdict mechanically to the score: ABSENT → 1.0 (good — the agent avoided the anti-pattern), PRESENT → 0.0 (bad — the agent exhibited it).
97
+ Your score MUST match the verdict you wrote — absent ⇒ 1.0, present ⇒ 0.0, no exceptions. Never let a justification that concludes the anti-pattern is absent end on 0.0 (or one that concludes it is present end on 1.0). Grade only the anti-pattern the criterion names, and grade near-identical outputs identically. Same binary-only rule applies (exactly 1.0 or 0.0).
98
+ - "justification": a brief explanation of why you chose this score"""
99
+
100
+ _RUBRIC_BINARY_PROMPT_PATH = Template(_SCAFFOLD_PATH + _BINARY_INSTRUCTIONS_BEHAVIOR)
101
+ _RUBRIC_BINARY_PROMPT_INLINE = Template(_SCAFFOLD_INLINE + _BINARY_INSTRUCTIONS_BEHAVIOR)
102
+ _RUBRIC_BINARY_PROMPT_NO_TRAJECTORY = Template(_SCAFFOLD_NO_TRAJECTORY + _BINARY_INSTRUCTIONS_RESPONSE)
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Rubric PARTIAL (partial-credit) templates.
107
+ #
108
+ # Unlike RUBRIC_BINARY, the judge may return any score in [0.0, 1.0] to express
109
+ # partial credit, or — when a criterion carries an `outcomes` list — must pick
110
+ # exactly one listed outcome and return its score (labeled/discrete grading).
111
+ # Score anchors are spelled out so the decimals stay calibrated across runs.
112
+ # ---------------------------------------------------------------------------
113
+ _RUBRIC_PARTIAL_INSTRUCTIONS = """## Instructions
114
+ For each criterion, assign a score reflecting HOW FULLY the agent met it. Partial credit is allowed.
115
+
116
+ For each criterion, return a result with:
117
+ - "id": the criterion's id
118
+ - "score": a numeric rating for the criterion, chosen as follows:
119
+ * DEFAULT (criterion has no "outcomes"): a number from 0.0 to 1.0 (inclusive). Anchor your value:
120
+ 1.0 = fully met/correct; ~0.75 = met with minor gaps; ~0.5 = partially met; ~0.25 = mostly unmet;
121
+ 0.0 = absent/incorrect.
122
+ * If "outcomes" is a LIST of labeled options: choose exactly one and return that outcome's "score"
123
+ value verbatim — do not invent a value between the listed outcomes.
124
+ * If "outcomes" is an OBJECT with "min" and "max" anchors (a continuous scale, e.g. min value
125
+ -1.0 labeled "ugly" to max value 1.0 labeled "beautiful"): return a number anywhere within that
126
+ [min, max] range using the anchors. Report it ON THAT SCALE — do NOT rescale to 0-1 yourself.
127
+ Exception — "negative": true criteria (read carefully; this is where graders most often slip): the
128
+ criterion text describes an anti-pattern the response should NOT exhibit, so the score is INVERTED
129
+ relative to your instinct. Decide in two ordered steps: (1) first judge how present the named
130
+ anti-pattern is and state that verdict in your justification; (2) then map it — fully ABSENT → 1.0
131
+ (desirable), fully PRESENT → 0.0 (undesirable), partial presence → an intermediate value where a
132
+ HIGHER score means MORE absent. Your score MUST agree with that verdict — never end a justification
133
+ that concludes the anti-pattern is absent on a low score (or vice versa). Grade near-identical
134
+ outputs identically.
135
+ - "justification": a brief explanation of why you chose this score"""
136
+
137
+ _RUBRIC_PARTIAL_PROMPT_PATH = Template(_SCAFFOLD_PATH + _RUBRIC_PARTIAL_INSTRUCTIONS)
138
+ _RUBRIC_PARTIAL_PROMPT_INLINE = Template(_SCAFFOLD_INLINE + _RUBRIC_PARTIAL_INSTRUCTIONS)
139
+ _RUBRIC_PARTIAL_PROMPT_NO_TRAJECTORY = Template(_SCAFFOLD_NO_TRAJECTORY + _RUBRIC_PARTIAL_INSTRUCTIONS)
140
+
141
+
142
+ # The mistake / botched / severity rules, shared by the trajectory_mistakes and rubric_evidence_with_mistakes
143
+ # formats. Platform-neutral on purpose: a product-specific rule (e.g. "an autocomplete shortcut is always a
144
+ # high-severity mistake") belongs in the task's ``grading_policy_prompt``, which every format appends as a
145
+ # "## Grading policy" section.
146
+ _MISTAKE_RULES = """Identify MISTAKES in the agent's trajectory — actions it should not have made, wrong
147
+ turns, ignored errors, redundant or looping behavior, premature stops, or fabricated
148
+ success — and assess whether the run was BOTCHED (the agent flailed without making real
149
+ progress). Report only real, defensible mistakes; do NOT invent problems in a clean run.
150
+
151
+ WHAT YOU CANNOT SEE IS NOT A MISTAKE. You get a SMALL SAMPLE of screens, and picker-set values
152
+ (date, guest count, size, filter) leave no trace in the actions. "The trajectory does not show
153
+ X" limits YOUR EVIDENCE — it is not evidence the agent failed.
154
+ - Never file a finding resting on absence ("should have verified X", "no confirmation of X")
155
+ when the end state is consistent with X having been done.
156
+ - Resolve circumstantial evidence IN THE RUN'S FAVOUR: "Mon, Oct 5 – Sat, Oct 10" matching the
157
+ requested year confirms it, it is not an open question.
158
+ - File a mistake only for something you can SEE go wrong. If you are writing "not clearly
159
+ demonstrated", drop the finding.
160
+
161
+ A HARNESS FAULT IS NOT THE AGENT'S MISTAKE. When a tool errors — "Server disconnected without
162
+ sending a response", a 500, a type reporting verified:false, a screenshot timing out — that is
163
+ infrastructure failing, not the agent behaving badly. The agent cannot avoid it and prompting
164
+ cannot fix it.
165
+ - Do NOT file a finding for the error itself, and do NOT count the retries it forced as
166
+ redundant/looping behaviour. A run that had to redo an action three times because the tool
167
+ failed three times is not a flailing run.
168
+ - verified:false in particular does NOT mean the text failed to land: the field just could not be
169
+ read back. The agent is told to treat it as entered, so doing so is CORRECT, not a mistake.
170
+ - What IS still a mistake: responding to an error by blindly repeating the same action many times
171
+ without checking the screen. The fault is free; an unthinking reaction to it is not.
172
+ - If a tool error changed what you would otherwise have concluded, say so in the finding you do
173
+ file, so a reader can tell agent behaviour from infrastructure noise.
174
+
175
+ SEVERITY — choose the rung by IMPACT ON THE RESULT, not by how odd the action looked. Each
176
+ finding subtracts a fixed penalty from the run's score and "high"/"critical" block the run from
177
+ being used as training data, so this choice decides whether an otherwise good run is thrown away:
178
+ - "critical": the run is unusable — the end state is wrong or the goal was defeated. Acted on the
179
+ wrong entity (wrong address, store, account, item), committed when told to stop short, ended
180
+ with nothing staged, or asserted an outcome the screens contradict.
181
+ - "high": the end state is broadly right, but a REQUIRED element is wrong or was never
182
+ established — a stated constraint (price cap, quantity, date, size, "closest"/"cheapest") went
183
+ unhonored or unchecked.
184
+ - "medium": the goal was met and the constraints hold, but the agent got there sloppily — a
185
+ skipped confirmation, an avoidable detour, or steps taken out of order.
186
+ - "low": cosmetic only — a few redundant taps or a needless scroll, with no bearing on the result.
187
+ Judge each finding on its own. When one fits two rungs, take the LOWER unless the end state is
188
+ itself affected; reserve "critical" for runs a reviewer would discard outright."""
189
+
190
+ # The response fields the rules produce; rubric_evidence_with_mistakes derives `coverage` from the evidence rows
191
+ # instead of asking for it (`trajectory_mistakes_rows_from_evidence`).
192
+ _FINDINGS_FIELD = """- "findings": array of mistakes. Each object: {"severity": one of "low"|"medium"|"high"|"critical",
193
+ "step": the 0-based action index where it occurred (or null), "should": what the agent
194
+ should have done instead, "description": what actually went wrong}. Empty array if clean."""
195
+ _COVERAGE_FIELD = """- "coverage": for each criterion listed above, {"id": the criterion id, "shown": true if the
196
+ trajectory clearly shows the agent doing/achieving it else false, "note": brief evidence}.
197
+ Empty array if no criteria were provided."""
198
+ _BOTCHED_SUMMARY_FIELDS = """- "botched": true if the agent flailed — repeated the same failing action, stalled for long
199
+ stretches, or never made real progress toward the goal — else false.
200
+ - "botched_reason": brief explanation when botched, else "".
201
+ - "summary": one or two sentences on overall trajectory quality."""
202
+
203
+ _TRAJECTORY_MISTAKES_INSTRUCTIONS = (
204
+ "## Instructions\n" + _MISTAKE_RULES + "\n\nReturn a JSON object with:\n"
205
+ + _FINDINGS_FIELD + "\n" + _COVERAGE_FIELD + "\n" + _BOTCHED_SUMMARY_FIELDS
206
+ )
207
+
208
+ _TRAJECTORY_MISTAKES_PROMPT_PATH = Template(_SCAFFOLD_PATH + _TRAJECTORY_MISTAKES_INSTRUCTIONS)
209
+ _TRAJECTORY_MISTAKES_PROMPT_INLINE = Template(_SCAFFOLD_INLINE + _TRAJECTORY_MISTAKES_INSTRUCTIONS)
210
+ _TRAJECTORY_MISTAKES_PROMPT_NO_TRAJECTORY = Template(_SCAFFOLD_NO_TRAJECTORY + _TRAJECTORY_MISTAKES_INSTRUCTIONS)
211
+
212
+
213
+ # Appended to a rubric_binary eval prompt ONLY when screenshots are attached to the
214
+ # judge (never mutates the templates above, so other consumers are unaffected).
215
+ # `.format(n=<num frames>)` before use.
216
+ SCREENSHOT_GROUNDING = """
217
+
218
+ ## Final-state screenshots
219
+ The final {n} screenshot(s) from the agent's trajectory are attached, in chronological \
220
+ order; the LAST image is the final on-screen state. Only the FINAL frames are attached — \
221
+ earlier screens the agent visited are not shown here.
222
+
223
+ Grounding rules:
224
+ - For a criterion tagged `"backend": "final_state"` (an OUTCOME): PREFER the screenshots. \
225
+ If the outcome IS visible in an attached frame, that frame is authoritative — trust it over \
226
+ the agent's narration. If the outcome is NOT visible in any attached frame, FALL BACK to the \
227
+ trajectory text / action log to decide; do NOT score it 0.0 solely because it isn't in the \
228
+ attached frames (the evidence may be on an earlier screen that wasn't attached).
229
+ - For a criterion tagged `"backend": "intermediate"`, `"backend": "process"` \
230
+ (deprecated alias), or with no backend tag (a BEHAVIOR the agent performed): judge it from \
231
+ the trajectory text / action log as usual; the screenshots are only supplementary for these.
232
+ - A frame showing a control MID-INTERACTION — a calendar open, a picker part-scrolled, a \
233
+ dropdown expanded — is a TRANSIENT state, not the outcome. Whatever it has highlighted is \
234
+ where the control happened to sit when the frame was taken, not what the agent finally chose. \
235
+ Never read a final selection off such a frame, and never let one override the trajectory."""
236
+
237
+
238
+ # Replaces SCREENSHOT_GROUNDING when the frames were chosen per criterion (each image preceded by a
239
+ # "FRAME: <label>" text block). `{frame_rule}` is filled by `per_criterion_grounding`.
240
+ _SCREENSHOT_GROUNDING_PER_CRITERION = """
241
+
242
+ ## Screenshots
243
+ {n} screenshot(s) from the agent's trajectory are attached, in chronological order. They were chosen \
244
+ across the WHOLE run for the criteria you are grading, not only from the end. Each image is preceded by \
245
+ a text block `FRAME: <label>`; a frame that serves several purposes carries every tag \
246
+ (`[c1][c2] final submitted action K`):
247
+ - `[cN] action K` — the frame after action K, chosen because action K most likely shows criterion cN \
248
+ (and the frame after it, since the effect of an action usually appears on the frame after it);
249
+ - `<label> action K` (e.g. `submitted action K`) — the screen right after an action the task configuration \
250
+ asked to always show; check what actually landed on screen against the action log's line K;
251
+ - `final action K` — the settled end state;
252
+ - `action K` — spread over the run for context.
253
+
254
+ Grounding rules:
255
+ {frame_rule}
256
+ - The action log is the record of what the agent DID (tool calls with their arguments and results) — use \
257
+ it for facts the pixels cannot show (the exact arguments passed, which application or page was opened and \
258
+ how). Lines starting `agent said:` are the agent's own words — claims to check against the frames, never \
259
+ evidence on their own.
260
+ - A frame showing a control MID-INTERACTION — a calendar open, a picker part-scrolled, a dropdown \
261
+ expanded — is a TRANSIENT state, not the outcome. Never read a final selection off such a frame."""
262
+
263
+ _PER_CRITERION_FRAME_RULE = """\
264
+ - Grade each criterion from the frames FIRST; when no attached frame shows it, decide from the \
265
+ trajectory text / action log — do NOT score it 0.0 solely because it is not in the attached frames."""
266
+
267
+ EVIDENCE_STATUSES = ["visible", "missing", "contradicted", "blocked", "unavailable", "ambiguous", "not_applicable"]
268
+ # Statuses that mean the criterion is NOT met whatever score the judge wrote.
269
+ BAD_EVIDENCE = frozenset({"missing", "contradicted", "blocked", "unavailable"})
270
+ # Every prompt that names the statuses derives its wording from these lists, so adding a status is one line.
271
+ _EVIDENCE_STATUS_GLOSS = {
272
+ "visible": "the outcome is on screen",
273
+ "missing": "a frame that should show it does not",
274
+ "contradicted": "a frame shows the opposite",
275
+ "blocked": "a dialog / error prevented it",
276
+ "unavailable": "no frame covers it",
277
+ }
278
+ assert set(_EVIDENCE_STATUS_GLOSS) <= set(EVIDENCE_STATUSES) and BAD_EVIDENCE <= set(EVIDENCE_STATUSES)
279
+ _BAD_EVIDENCE_ORDERED = [s for s in EVIDENCE_STATUSES if s in BAD_EVIDENCE]
280
+ _EVIDENCE_STATUS_LIST = " / ".join(EVIDENCE_STATUSES)
281
+
282
+
283
+ def _or_list(items: Sequence[str]) -> str:
284
+ """``"a, b or c"``."""
285
+ return ", ".join(items[:-1]) + " or " + items[-1] if len(items) > 1 else "".join(items)
286
+
287
+
288
+ _PER_CRITERION_EVIDENCE_RULE = (
289
+ "- Grade each criterion from the frames FIRST. In every result cite the label of the frame you relied "
290
+ "on in `frame`, or `NOT SHOWN` if no attached frame shows it.\n"
291
+ "- `evidence_status` says what the frames established: "
292
+ + ", ".join(f"`{s}` ({_EVIDENCE_STATUS_GLOSS[s]})" if s in _EVIDENCE_STATUS_GLOSS else f"`{s}`"
293
+ for s in EVIDENCE_STATUSES)
294
+ + ". A criterion with " + _or_list([f"`{s}`" for s in _BAD_EVIDENCE_ORDERED]) + " evidence is NOT met."
295
+ )
296
+
297
+
298
+ def per_criterion_grounding(n: int, *, cites_evidence: bool) -> str:
299
+ """The per-criterion screenshot section for ``n`` attached frames; only a format whose rows carry
300
+ `frame` / `evidence_status` (``JudgeOutputFormatSpec.cites_evidence``) is told to cite the labels."""
301
+ rule = _PER_CRITERION_EVIDENCE_RULE if cites_evidence else _PER_CRITERION_FRAME_RULE
302
+ return _SCREENSHOT_GROUNDING_PER_CRITERION.format(n=n, frame_rule=rule)
303
+
304
+
305
+ def _rubric_score_output_format() -> dict:
306
+ """Wire schema shared by rubric_binary and rubric_partial.
307
+
308
+ `score` is already a free `number`, so the binary-vs-partial difference lives
309
+ in the prompt and the result builder, not the schema — the judge is never
310
+ schema-blocked from emitting a fraction.
311
+ """
312
+ return {
313
+ "type": "json_schema",
314
+ "schema": {
315
+ "type": "object",
316
+ "properties": {
317
+ "results": {
318
+ "type": "array",
319
+ "items": {
320
+ "type": "object",
321
+ "properties": {
322
+ "id": {"type": "string"},
323
+ "score": {"type": "number"},
324
+ "justification": {"type": "string"},
325
+ },
326
+ "required": ["id", "score", "justification"],
327
+ "additionalProperties": False,
328
+ },
329
+ },
330
+ },
331
+ "required": ["results"],
332
+ "additionalProperties": False,
333
+ },
334
+ }
335
+
336
+
337
+ # An evidence_status outside EVIDENCE_STATUSES (possible without structured output) is stored as this.
338
+ _UNKNOWN_EVIDENCE_STATUS = "ambiguous"
339
+ # Caps on what the parser keeps from a rubric_evidence response (the verification entry is stored).
340
+ _MAX_REASONING_CHARS = 2000
341
+ _MAX_CHECKS = 12
342
+
343
+ # One mistake, as the trajectory_mistakes and rubric_evidence_with_mistakes formats both ask for it.
344
+ _FINDING_SCHEMA = {
345
+ "type": "object",
346
+ "properties": {
347
+ "severity": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
348
+ "step": {"type": ["integer", "null"]},
349
+ "should": {"type": "string"},
350
+ "description": {"type": "string"},
351
+ },
352
+ "required": ["severity", "step", "should", "description"],
353
+ "additionalProperties": False,
354
+ }
355
+
356
+
357
+ def _rubric_evidence_output_format(*, with_mistakes: bool = False) -> dict:
358
+ """Wire schema for rubric_evidence: binary rows that cite their evidence, plus `reasoning` and the
359
+ policy `checks` (unscored; they ride on the verification entry). Field order is load-bearing:
360
+ structured output is generated in schema order, so evidence comes before the verdict in every row and
361
+ `reasoning` before the rows. ``with_mistakes`` (rubric_evidence_with_mistakes) adds the trajectory_mistakes
362
+ fields after the rows."""
363
+ check = {
364
+ "type": "object",
365
+ "properties": {
366
+ "requirement": {"type": "string"},
367
+ "required_value": {"type": "string"},
368
+ "observed_value": {"type": "string"},
369
+ "frame": {"type": "string"},
370
+ "evidence_status": {"type": "string", "enum": EVIDENCE_STATUSES},
371
+ "note": {"type": "string"},
372
+ },
373
+ "required": ["requirement", "required_value", "observed_value", "frame", "evidence_status", "note"],
374
+ "additionalProperties": False,
375
+ }
376
+ properties: dict = {
377
+ "reasoning": {"type": "string"},
378
+ # No maxItems: not every provider's strict structured-output mode accepts it; the
379
+ # parser caps the list at _MAX_CHECKS instead.
380
+ "checks": {"type": "array", "items": check},
381
+ "results": {
382
+ "type": "array",
383
+ "items": {
384
+ "type": "object",
385
+ "properties": {
386
+ "id": {"type": "string"},
387
+ "frame": {"type": "string"},
388
+ "evidence_status": {"type": "string", "enum": EVIDENCE_STATUSES},
389
+ "justification": {"type": "string"},
390
+ "score": {"type": "number"},
391
+ },
392
+ "required": ["id", "frame", "evidence_status", "justification", "score"],
393
+ "additionalProperties": False,
394
+ },
395
+ },
396
+ }
397
+ if with_mistakes:
398
+ properties.update({
399
+ "findings": {"type": "array", "items": _FINDING_SCHEMA},
400
+ "botched": {"type": "boolean"},
401
+ "botched_reason": {"type": "string"},
402
+ "summary": {"type": "string"},
403
+ })
404
+ return {
405
+ "type": "json_schema",
406
+ "schema": {
407
+ "type": "object",
408
+ "properties": properties,
409
+ "required": list(properties),
410
+ "additionalProperties": False,
411
+ },
412
+ }
413
+
414
+
415
+ # rubric_evidence adds the evidence fields to the rubric_binary instructions; `$checks_instruction` is
416
+ # `evidence_checks_instruction`, filled by the verifier.
417
+ _EVIDENCE_FIELDS = f"""
418
+ - "frame": the label of the attached screenshot you relied on (exactly as written after `FRAME:`), or "NOT SHOWN"
419
+ - "evidence_status": one of {_EVIDENCE_STATUS_LIST} — what the frames established (see the screenshot rules). A criterion whose evidence is {_or_list(_BAD_EVIDENCE_ORDERED)} is NOT met: score it 0.0.
420
+
421
+ Also return:
422
+ - "reasoning": a short account of what the frames show, written BEFORE the results
423
+ - "checks": $checks_instruction"""
424
+
425
+ _CHECKS_INSTRUCTION_WITH_POLICY = (
426
+ "one policy check per requirement the grading policy below asks you to verify — each with the "
427
+ "requirement, the value it required, the value you observed, the frame you saw it in, its "
428
+ "evidence_status and a note. Return [] if it asks for none."
429
+ )
430
+ _CHECKS_INSTRUCTION_NO_POLICY = "[] (no grading policy was given)"
431
+
432
+
433
+ def evidence_checks_instruction(*, has_policy: bool) -> str:
434
+ """The `checks` instruction of the rubric_evidence prompt: only mentions a grading policy when one was given."""
435
+ return _CHECKS_INSTRUCTION_WITH_POLICY if has_policy else _CHECKS_INSTRUCTION_NO_POLICY
436
+
437
+
438
+ _RUBRIC_EVIDENCE_PROMPT_PATH = Template(_SCAFFOLD_PATH + _BINARY_INSTRUCTIONS_BEHAVIOR + _EVIDENCE_FIELDS)
439
+ _RUBRIC_EVIDENCE_PROMPT_INLINE = Template(_SCAFFOLD_INLINE + _BINARY_INSTRUCTIONS_BEHAVIOR + _EVIDENCE_FIELDS)
440
+ _RUBRIC_EVIDENCE_PROMPT_NO_TRAJECTORY = Template(
441
+ _SCAFFOLD_NO_TRAJECTORY + _BINARY_INSTRUCTIONS_RESPONSE + _EVIDENCE_FIELDS)
442
+
443
+ # rubric_evidence_with_mistakes: the same call also detects mistakes.
444
+ _EVIDENCE_MISTAKES_SECTION = (
445
+ "\n\n## Trajectory mistakes\n" + _MISTAKE_RULES + "\n\nAlso return, on the same JSON object:\n"
446
+ + _FINDINGS_FIELD + "\n" + _BOTCHED_SUMMARY_FIELDS
447
+ )
448
+ _RUBRIC_EVIDENCE_MISTAKES_PROMPT_PATH = Template(
449
+ _SCAFFOLD_PATH + _BINARY_INSTRUCTIONS_BEHAVIOR + _EVIDENCE_FIELDS + _EVIDENCE_MISTAKES_SECTION)
450
+ _RUBRIC_EVIDENCE_MISTAKES_PROMPT_INLINE = Template(
451
+ _SCAFFOLD_INLINE + _BINARY_INSTRUCTIONS_BEHAVIOR + _EVIDENCE_FIELDS + _EVIDENCE_MISTAKES_SECTION)
452
+ _RUBRIC_EVIDENCE_MISTAKES_PROMPT_NO_TRAJECTORY = Template(
453
+ _SCAFFOLD_NO_TRAJECTORY + _BINARY_INSTRUCTIONS_RESPONSE + _EVIDENCE_FIELDS + _EVIDENCE_MISTAKES_SECTION)
454
+
455
+
456
+ class ResultRows(list):
457
+ """The validated rows of a rubric_evidence response plus what rides on the verification entry: the
458
+ judge's ``reasoning`` and policy ``checks``, and for rubric_evidence_with_mistakes its ``mistakes``
459
+ (``findings`` / ``botched`` / ``botched_reason`` / ``summary``; None otherwise). Other formats return a
460
+ plain list."""
461
+
462
+ reasoning: str
463
+ checks: list[dict]
464
+ mistakes: dict | None
465
+
466
+ def __init__(self, rows: list, *, reasoning: str = "", checks: list[dict] | None = None,
467
+ mistakes: dict | None = None):
468
+ super().__init__(rows)
469
+ self.reasoning = reasoning
470
+ self.checks = list(checks or [])
471
+ self.mistakes = mistakes
472
+
473
+
474
+ # Default pass/fail threshold used to derive the boolean `result` from a partial
475
+ # score. `result` feeds all_pass/any_pass and the pass/fail display; partial
476
+ # rubrics should aggregate with `weighted_average`, which reads `score` directly.
477
+ PARTIAL_PASS_THRESHOLD = 0.5
478
+
479
+
480
+ def _clamp01(value: float) -> float:
481
+ return max(0.0, min(1.0, value))
482
+
483
+
484
+ def _continuous_range(criterion: dict) -> tuple[float, float] | None:
485
+ """Return (min, max) if the criterion declares a continuous `outcomes` range.
486
+
487
+ Mirrors the RFP shape ``outcomes: {"min": {"value": -1.0}, "max": {"value": 1.0}}``
488
+ and also tolerates a flat ``{"min": -1.0, "max": 1.0}``. A *list* `outcomes` is the
489
+ discrete/labeled case and returns None here (handled as-is, no rescaling).
490
+ """
491
+ outcomes = criterion.get("outcomes")
492
+ if not isinstance(outcomes, dict):
493
+ return None
494
+
495
+ def _val(x: object) -> object:
496
+ return x.get("value") if isinstance(x, dict) else x
497
+
498
+ try:
499
+ lo = float(_val(outcomes.get("min"))) # type: ignore[arg-type]
500
+ hi = float(_val(outcomes.get("max"))) # type: ignore[arg-type]
501
+ except (TypeError, ValueError):
502
+ return None
503
+ return (lo, hi)
504
+
505
+
506
+ def _discrete_outcome_scores(criterion: dict) -> list[float] | None:
507
+ """Return the allowed scores if the criterion lists discrete `outcomes`.
508
+
509
+ A *list* `outcomes` (e.g. `[{"label": "good", "score": 0.67}, ...]`) is the
510
+ discrete/labeled case; the judge must return one of these scores. Returns None
511
+ for the continuous cases (dict range or no `outcomes`).
512
+ """
513
+ outcomes = criterion.get("outcomes")
514
+ if not isinstance(outcomes, list):
515
+ return None
516
+ scores: list[float] = []
517
+ for o in outcomes:
518
+ if isinstance(o, dict) and "score" in o:
519
+ try:
520
+ scores.append(float(o["score"]))
521
+ except (TypeError, ValueError):
522
+ continue
523
+ return scores or None
524
+
525
+
526
+ def _pass_threshold(criterion: dict, rng: tuple[float, float] | None) -> float:
527
+ """Per-criterion pass cutoff for the boolean `result`, as a normalized [0,1] value.
528
+
529
+ An optional `pass_threshold` is read in the criterion's OWN units — the raw
530
+ min..max scale when the criterion declares a continuous range, else [0,1] — and
531
+ normalized the same way the score is, so threshold and score are always compared
532
+ on the same scale. Absent/invalid values fall back to the global default.
533
+ """
534
+ raw = criterion.get("pass_threshold")
535
+ if raw is None:
536
+ return PARTIAL_PASS_THRESHOLD
537
+ try:
538
+ raw = float(raw)
539
+ except (TypeError, ValueError):
540
+ return PARTIAL_PASS_THRESHOLD
541
+ if rng is not None and rng[1] > rng[0]:
542
+ lo, hi = rng
543
+ return _clamp01((raw - lo) / (hi - lo))
544
+ return _clamp01(raw)
545
+
546
+
547
+ _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS = 8000
548
+
549
+
550
+ @dataclass(frozen=True)
551
+ class JudgeResponseDiscrepancy:
552
+ expected_count: int
553
+ returned_count: int
554
+ expected_ids: list[str]
555
+ missing_ids: list[str]
556
+ duplicate_ids: list[str]
557
+ unknown_ids: list[str]
558
+ parse_error: str | None = None
559
+
560
+ def to_dict(self) -> dict:
561
+ out = {
562
+ "expected_count": self.expected_count,
563
+ "returned_count": self.returned_count,
564
+ "expected_ids": list(self.expected_ids),
565
+ "missing_ids": list(self.missing_ids),
566
+ "duplicate_ids": list(self.duplicate_ids),
567
+ "unknown_ids": list(self.unknown_ids),
568
+ }
569
+ if self.parse_error is not None:
570
+ out["parse_error"] = self.parse_error
571
+ return out
572
+
573
+ def __str__(self) -> str:
574
+ if self.parse_error:
575
+ return f"invalid JSON ({self.parse_error})"
576
+ return (
577
+ f"expected {self.expected_count} results but got {self.returned_count}"
578
+ f" (missing={self.missing_ids}, duplicate={self.duplicate_ids}, unknown={self.unknown_ids})"
579
+ )
580
+
581
+
582
+ def _default_failure_results(criteria: list[dict]) -> list[dict]:
583
+ return [
584
+ {**c, "score": 0.0, "result": False, "justification": ""}
585
+ for c in criteria
586
+ ]
587
+
588
+
589
+ def _parse_failure_discrepancy(criteria: list[dict], parse_error: str) -> JudgeResponseDiscrepancy:
590
+ return JudgeResponseDiscrepancy(
591
+ expected_count=len(criteria),
592
+ returned_count=0,
593
+ expected_ids=[c["id"] for c in criteria],
594
+ missing_ids=[],
595
+ duplicate_ids=[],
596
+ unknown_ids=[],
597
+ parse_error=parse_error,
598
+ )
599
+
600
+
601
+ def _extract_rubric_binary_results(parsed: object) -> list | None:
602
+ if isinstance(parsed, dict) and "results" in parsed:
603
+ return parsed["results"]
604
+ if isinstance(parsed, list):
605
+ return parsed
606
+ return None
607
+
608
+
609
+ def _analyze_result_ids(results: list, criteria: list[dict]) -> JudgeResponseDiscrepancy | None:
610
+ criteria_ids = {c["id"] for c in criteria}
611
+ result_ids = [item.get("id") for item in results]
612
+
613
+ seen: set[str] = set()
614
+ duplicate_ids: list[str] = []
615
+ for result_id in result_ids:
616
+ if result_id in seen and result_id not in duplicate_ids:
617
+ duplicate_ids.append(result_id)
618
+ if isinstance(result_id, str):
619
+ seen.add(result_id)
620
+
621
+ result_id_set = {rid for rid in result_ids if isinstance(rid, str)}
622
+ missing_ids = sorted(criteria_ids - result_id_set)
623
+ unknown_ids = sorted(result_id_set - criteria_ids)
624
+
625
+ if missing_ids or duplicate_ids or unknown_ids or len(results) != len(criteria):
626
+ return JudgeResponseDiscrepancy(
627
+ expected_count=len(criteria),
628
+ returned_count=len(results),
629
+ expected_ids=[c["id"] for c in criteria],
630
+ missing_ids=missing_ids,
631
+ duplicate_ids=duplicate_ids,
632
+ unknown_ids=unknown_ids,
633
+ )
634
+ return None
635
+
636
+
637
+ def _build_validated_results(results: list, criteria: list[dict]) -> list[dict]:
638
+ criteria_by_id = {c["id"]: c for c in criteria}
639
+ validated = []
640
+ for item in results:
641
+ score = item.get("score", 0.0)
642
+ criterion = criteria_by_id.get(item.get("id"), {})
643
+ entry = {**criterion, **item, "score": score, "result": score == 1.0}
644
+ validated.append(entry)
645
+ return validated
646
+
647
+
648
+ def _build_validated_results_partial(results: list, criteria: list[dict]) -> list[dict]:
649
+ """Like `_build_validated_results` but keeps partial-credit scores.
650
+
651
+ The normalized `score` is always in [0.0, 1.0] (so aggregation math is
652
+ unchanged); `result` is a threshold-derived boolean (partial rubrics should
653
+ aggregate via `weighted_average`, which uses `score`). The pass cutoff is the
654
+ criterion's own `pass_threshold` when set, else the global default.
655
+
656
+ If a criterion declares a continuous `outcomes` range (e.g. RFP's −1.0→1.0),
657
+ the judge's raw value on that scale is min-max normalized into [0,1] and the
658
+ original value is preserved under `raw_score` for display/debugging. An unusable
659
+ range (min >= max) logs a warning and falls back to a clamped raw score. If a
660
+ criterion lists discrete `outcomes`, an off-list score is snapped to the nearest
661
+ listed value (with a warning) to enforce the discrete constraint.
662
+ """
663
+ criteria_by_id = {c["id"]: c for c in criteria}
664
+ validated = []
665
+ for item in results:
666
+ criterion = criteria_by_id.get(item.get("id"), {})
667
+ try:
668
+ raw = float(item.get("score", 0.0))
669
+ except (TypeError, ValueError):
670
+ raw = 0.0
671
+
672
+ entry = {**criterion, **item}
673
+ rng = _continuous_range(criterion)
674
+ discrete_scores = _discrete_outcome_scores(criterion)
675
+ if rng is not None:
676
+ # A continuous range was declared, so the judge scored on that scale —
677
+ # always preserve its on-scale value, even if the range is unusable.
678
+ lo, hi = rng
679
+ entry["raw_score"] = raw
680
+ if hi > lo:
681
+ score = _clamp01((raw - lo) / (hi - lo))
682
+ else:
683
+ logger.warning(
684
+ "Rubric criterion %r declares an unusable continuous range "
685
+ "(min=%s, max=%s); cannot normalize, using clamped raw score.",
686
+ criterion.get("id"), lo, hi,
687
+ )
688
+ score = _clamp01(raw)
689
+ elif discrete_scores is not None:
690
+ # Enforce the discrete constraint: snap to the nearest listed outcome.
691
+ snapped = min(discrete_scores, key=lambda s: abs(s - raw))
692
+ if snapped != raw:
693
+ logger.warning(
694
+ "Rubric criterion %r: judge score %s is not one of the listed "
695
+ "outcome scores %s; snapping to nearest (%s).",
696
+ criterion.get("id"), raw, discrete_scores, snapped,
697
+ )
698
+ score = _clamp01(snapped)
699
+ else:
700
+ score = _clamp01(raw)
701
+ entry["score"] = score
702
+ entry["result"] = score >= _pass_threshold(criterion, rng)
703
+ validated.append(entry)
704
+ return validated
705
+
706
+
707
+ def _parse_judge_results(
708
+ response_text: str,
709
+ criteria: list[dict],
710
+ ) -> tuple[object, list | None, JudgeResponseDiscrepancy | None]:
711
+ """Shared parse/validate path: JSON -> results array -> id check. Returns ``(parsed, results,
712
+ discrepancy)`` — the parsed JSON so a format can read its other keys, and the id-checked results array
713
+ or the discrepancy."""
714
+ text = response_text.strip()
715
+
716
+ try:
717
+ parsed = json.loads(text)
718
+ except json.JSONDecodeError as e:
719
+ logger.error(f"Failed to parse judge response as JSON: {e}")
720
+ logger.error(f"Raw response: {response_text[:500]}")
721
+ return None, None, _parse_failure_discrepancy(criteria, str(e))
722
+
723
+ results = _extract_rubric_binary_results(parsed)
724
+ if results is None:
725
+ logger.error(f"Unexpected judge response shape: {type(parsed)}")
726
+ return parsed, None, _parse_failure_discrepancy(
727
+ criteria, f"unexpected response shape: {type(parsed).__name__}"
728
+ )
729
+
730
+ discrepancy = _analyze_result_ids(results, criteria)
731
+ if discrepancy is not None:
732
+ return parsed, None, discrepancy
733
+
734
+ return parsed, results, None
735
+
736
+
737
+ def _diagnose_response(
738
+ response_text: str,
739
+ criteria: list[dict],
740
+ build_results: Callable[[list, list[dict]], list[dict]],
741
+ ) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]:
742
+ """`_parse_judge_results` -> rows. `build_results` decides how each row's `score`/`result` are
743
+ derived, so binary and partial formats reuse the same JSON/id-integrity handling."""
744
+ _, results, discrepancy = _parse_judge_results(response_text, criteria)
745
+ if results is None:
746
+ return None, discrepancy
747
+ return build_results(results, criteria), None
748
+
749
+
750
+ def diagnose_rubric_binary_response(
751
+ response_text: str,
752
+ criteria: list[dict],
753
+ ) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]:
754
+ """Parse a rubric-binary judge response, returning validated rows or a discrepancy."""
755
+ return _diagnose_response(response_text, criteria, _build_validated_results)
756
+
757
+
758
+ def _evidence_status(item: dict) -> str:
759
+ status = str(item.get("evidence_status") or "").strip().lower()
760
+ return status if status in EVIDENCE_STATUSES else _UNKNOWN_EVIDENCE_STATUS
761
+
762
+
763
+ def _build_validated_results_evidence(results: list, criteria: list[dict]) -> list[dict]:
764
+ """rubric_binary rows that also carry ``frame`` / ``evidence_status``. The score is snapped to binary
765
+ (the entry is read as rubric_binary, and a stray 0.5 from a judge without structured output would earn
766
+ partial credit under a weighted average), the raw value kept under ``raw_score``; bad evidence forces
767
+ the row to fail whatever score the judge wrote."""
768
+ criteria_by_id = {c["id"]: c for c in criteria}
769
+ validated = []
770
+ for item in results:
771
+ try:
772
+ raw = float(item.get("score", 0.0))
773
+ except (TypeError, ValueError):
774
+ raw = 0.0
775
+ score = 1.0 if raw >= 1.0 - 1e-9 else 0.0
776
+ criterion = criteria_by_id.get(item.get("id"), {})
777
+ entry = {**criterion, **item, "evidence_status": _evidence_status(item)}
778
+ if raw != score:
779
+ logger.warning("Rubric criterion %r: judge score %s is not binary; snapping to %s.",
780
+ item.get("id"), raw, score)
781
+ entry["raw_score"] = raw
782
+ if entry["evidence_status"] in BAD_EVIDENCE:
783
+ score = 0.0
784
+ validated.append({**entry, "score": score, "result": score == 1.0})
785
+ return validated
786
+
787
+
788
+ def _mistakes_from_parsed(parsed: dict) -> tuple[dict | None, list[str]]:
789
+ """The mistakes part of a rubric_evidence_with_mistakes response, or ``(None, [missing or mistyped field
790
+ names])`` so the correction loop can ask again. ``botched_reason`` is optional."""
791
+ missing = [name for name, ok in (
792
+ ("findings", isinstance(parsed.get("findings"), list)),
793
+ ("botched", isinstance(parsed.get("botched"), bool)),
794
+ ("summary", isinstance(parsed.get("summary"), str)),
795
+ ) if not ok]
796
+ if missing:
797
+ return None, missing
798
+ return {
799
+ "findings": [f for f in parsed["findings"] if isinstance(f, dict)],
800
+ "botched": parsed["botched"],
801
+ "botched_reason": str(parsed.get("botched_reason") or ""),
802
+ "summary": parsed["summary"],
803
+ }, []
804
+
805
+
806
+ def diagnose_rubric_evidence_response(
807
+ response_text: str, criteria: list[dict], *, with_mistakes: bool = False,
808
+ ) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]:
809
+ """Parse a rubric_evidence judge response into ``ResultRows`` (rows + ``reasoning`` + ``checks``) or a
810
+ discrepancy. ``with_mistakes`` (rubric_evidence_with_mistakes) also requires ``findings`` / ``botched`` /
811
+ ``summary`` — a missing one is a discrepancy, retried like invalid JSON — and lands them on
812
+ ``ResultRows.mistakes``; otherwise those fields are ignored."""
813
+ parsed, results, discrepancy = _parse_judge_results(response_text, criteria)
814
+ if results is None:
815
+ return None, discrepancy
816
+ top = parsed if isinstance(parsed, dict) else {}
817
+ reasoning = top["reasoning"][:_MAX_REASONING_CHARS] if isinstance(top.get("reasoning"), str) else ""
818
+ checks = [c for c in top["checks"] if isinstance(c, dict)][:_MAX_CHECKS] if isinstance(top.get("checks"), list) else []
819
+ mistakes = None
820
+ if with_mistakes:
821
+ mistakes, missing = _mistakes_from_parsed(top)
822
+ if mistakes is None:
823
+ return None, _parse_failure_discrepancy(criteria, f"missing or mistyped field(s): {', '.join(missing)}")
824
+ rows = _build_validated_results_evidence(results, criteria)
825
+ return ResultRows(rows, reasoning=reasoning, checks=checks, mistakes=mistakes), None
826
+
827
+
828
+ diagnose_rubric_evidence_mistakes_response = partial(diagnose_rubric_evidence_response, with_mistakes=True)
829
+
830
+
831
+ # Evidence on which a passing row counts as SHOWN in a derived coverage row.
832
+ _SHOWN_EVIDENCE = frozenset({"visible", "not_applicable"})
833
+
834
+
835
+ def trajectory_mistakes_rows_from_evidence(rows: ResultRows) -> list[dict]:
836
+ """The trajectory_mistakes rows (the shape a standalone step writes) for a rubric_evidence_with_mistakes
837
+ response: the judge's findings / botched / summary plus one coverage item per evidence row — ``shown``
838
+ when the row passed on visible or not_applicable evidence, its ``note`` the row's justification. Coverage
839
+ rows are keyed by whatever id the evidence rows carry when this is called."""
840
+ if rows.mistakes is None:
841
+ raise ValueError("rows carry no mistakes: not a rubric_evidence_with_mistakes response")
842
+ coverage = [{
843
+ "id": r.get("id"),
844
+ "shown": r.get("result") is True and r.get("evidence_status") in _SHOWN_EVIDENCE,
845
+ "note": r.get("justification", ""),
846
+ } for r in rows]
847
+ return _trajectory_mistakes_rows({**rows.mistakes, "coverage": coverage})
848
+
849
+
850
+ def diagnose_rubric_partial_response(
851
+ response_text: str,
852
+ criteria: list[dict],
853
+ ) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]:
854
+ """Parse a rubric-partial (partial-credit) judge response into rows or a discrepancy."""
855
+ return _diagnose_response(response_text, criteria, _build_validated_results_partial)
856
+
857
+
858
+ _BINARY_SCORE_INSTRUCTION = '- "score": exactly 1.0 or 0.0'
859
+ _PARTIAL_SCORE_INSTRUCTION = (
860
+ '- "score": a numeric rating — 0.0 to 1.0 by default, one listed outcome\'s score, '
861
+ "or a value within the criterion's min/max range"
862
+ )
863
+
864
+
865
+ def format_judge_correction_prompt(
866
+ *,
867
+ eval_prompt: str,
868
+ previous_response: str,
869
+ discrepancy: JudgeResponseDiscrepancy,
870
+ max_previous_response_chars: int = _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS,
871
+ score_instruction: str = _BINARY_SCORE_INSTRUCTION,
872
+ extra_result_fields: Sequence[tuple[str, str]] = (),
873
+ extra_object_fields: Sequence[tuple[str, str]] = (),
874
+ ) -> str:
875
+ """Build a follow-up prompt asking the judge to fix its output. ``extra_result_fields`` /
876
+ ``extra_object_fields`` are ``(name, description)`` pairs a format requires beyond id / score /
877
+ justification on each result, or beyond `results` on the object."""
878
+ truncated_response = previous_response.strip()
879
+ if len(truncated_response) > max_previous_response_chars:
880
+ truncated_response = truncated_response[:max_previous_response_chars] + "\n... [truncated]"
881
+
882
+ object_shape = "a `results` array"
883
+ object_lines: list[str] = []
884
+ if extra_object_fields:
885
+ object_shape = ", ".join(f"`{name}`" for name, _ in extra_object_fields) + " and " + object_shape
886
+ object_lines = ["", "The object must also include:",
887
+ *[f'- "{name}": {description}' for name, description in extra_object_fields]]
888
+
889
+ if discrepancy.parse_error:
890
+ problems = [
891
+ f"Your response was not valid JSON: {discrepancy.parse_error}",
892
+ f"Return only a JSON object with {object_shape} — no preamble, markdown fences, or extra text.",
893
+ ]
894
+ else:
895
+ problems = [
896
+ f"You returned {discrepancy.returned_count} result(s) but there are "
897
+ f"{discrepancy.expected_count} criteria."
898
+ ]
899
+ if discrepancy.missing_ids:
900
+ problems.append(f"Missing result(s) for criterion id(s): {', '.join(discrepancy.missing_ids)}")
901
+ if discrepancy.duplicate_ids:
902
+ problems.append(f"Duplicate result(s) for criterion id(s): {', '.join(discrepancy.duplicate_ids)}")
903
+ if discrepancy.unknown_ids:
904
+ problems.append(f"Unknown criterion id(s) in your results: {', '.join(discrepancy.unknown_ids)}")
905
+
906
+ correction_block = "\n".join([
907
+ "## Correction Required",
908
+ "",
909
+ "Your previous response did not satisfy the output requirements:",
910
+ *[f"- {problem}" for problem in problems],
911
+ "",
912
+ f"Return JSON with {object_shape} containing exactly {discrepancy.expected_count} objects — "
913
+ "one per criterion, no duplicates, no extras.",
914
+ f"Required criterion ids (in any order): {', '.join(discrepancy.expected_ids)}",
915
+ "",
916
+ "Each result must include:",
917
+ '- "id": the criterion id',
918
+ score_instruction,
919
+ '- "justification": a brief explanation',
920
+ *[f'- "{name}": {description}' for name, description in extra_result_fields],
921
+ *object_lines,
922
+ "",
923
+ "## Your Previous Response",
924
+ truncated_response,
925
+ ])
926
+ return f"{eval_prompt.rstrip()}\n\n{correction_block}"
927
+
928
+
929
+ def format_partial_judge_correction_prompt(
930
+ *,
931
+ eval_prompt: str,
932
+ previous_response: str,
933
+ discrepancy: JudgeResponseDiscrepancy,
934
+ max_previous_response_chars: int = _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS,
935
+ ) -> str:
936
+ """Correction prompt variant for the partial format (allows [0,1] scores)."""
937
+ return format_judge_correction_prompt(
938
+ eval_prompt=eval_prompt,
939
+ previous_response=previous_response,
940
+ discrepancy=discrepancy,
941
+ max_previous_response_chars=max_previous_response_chars,
942
+ score_instruction=_PARTIAL_SCORE_INSTRUCTION,
943
+ )
944
+
945
+
946
+ _EVIDENCE_RESULT_FIELDS = (
947
+ ("frame", 'the label of the attached frame you relied on (as written after `FRAME:`), or "NOT SHOWN"'),
948
+ ("evidence_status", "one of " + _EVIDENCE_STATUS_LIST),
949
+ )
950
+ _EVIDENCE_OBJECT_FIELDS = (
951
+ ("reasoning", "a short account of what the frames show"),
952
+ ("checks", "the policy checks (an array; [] if there are none)"),
953
+ )
954
+ _MISTAKES_OBJECT_FIELDS = (
955
+ ("findings", "the mistakes (an array; [] if the run is clean), each with severity, step, should and description"),
956
+ ("botched", "true or false"),
957
+ ("botched_reason", 'a brief explanation when botched, else ""'),
958
+ ("summary", "one or two sentences on overall trajectory quality"),
959
+ )
960
+
961
+
962
+ def format_evidence_judge_correction_prompt(
963
+ *,
964
+ eval_prompt: str,
965
+ previous_response: str,
966
+ discrepancy: JudgeResponseDiscrepancy,
967
+ max_previous_response_chars: int = _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS,
968
+ with_mistakes: bool = False,
969
+ ) -> str:
970
+ """The rubric_evidence correction prompt: asks for the evidence fields too, and with ``with_mistakes``
971
+ (rubric_evidence_with_mistakes) the mistakes fields."""
972
+ return format_judge_correction_prompt(
973
+ eval_prompt=eval_prompt,
974
+ previous_response=previous_response,
975
+ discrepancy=discrepancy,
976
+ max_previous_response_chars=max_previous_response_chars,
977
+ extra_result_fields=_EVIDENCE_RESULT_FIELDS,
978
+ extra_object_fields=_EVIDENCE_OBJECT_FIELDS + (_MISTAKES_OBJECT_FIELDS if with_mistakes else ()),
979
+ )
980
+
981
+
982
+ def _rows_or_raise(diagnose: DiagnoseResponse, response_text: str, criteria: list[dict]) -> list[dict]:
983
+ """Verification rows from ``diagnose``: invalid JSON degrades to all-fail rows, a wrong row set
984
+ (missing / duplicate / unknown ids) raises."""
985
+ results, discrepancy = diagnose(response_text, criteria)
986
+ if discrepancy is not None:
987
+ if discrepancy.parse_error:
988
+ return _default_failure_results(criteria)
989
+ raise ValueError(
990
+ f"Judge returned {discrepancy.returned_count} results but expected "
991
+ f"{discrepancy.expected_count} criteria"
992
+ )
993
+ assert results is not None
994
+ return results
995
+
996
+
997
+ _parse_rubric_binary_response = partial(_rows_or_raise, diagnose_rubric_binary_response)
998
+ _parse_rubric_partial_response = partial(_rows_or_raise, diagnose_rubric_partial_response)
999
+ _parse_rubric_evidence_response = partial(_rows_or_raise, diagnose_rubric_evidence_response)
1000
+ _parse_rubric_evidence_mistakes_response = partial(_rows_or_raise, diagnose_rubric_evidence_mistakes_response)
1001
+
1002
+
1003
+ def _trajectory_mistakes_output_format() -> dict:
1004
+ return {
1005
+ "type": "json_schema",
1006
+ "schema": {
1007
+ "type": "object",
1008
+ "properties": {
1009
+ "findings": {"type": "array", "items": _FINDING_SCHEMA},
1010
+ "coverage": {
1011
+ "type": "array",
1012
+ "items": {
1013
+ "type": "object",
1014
+ "properties": {
1015
+ "id": {"type": "string"},
1016
+ "shown": {"type": "boolean"},
1017
+ "note": {"type": "string"},
1018
+ },
1019
+ "required": ["id", "shown", "note"],
1020
+ "additionalProperties": False,
1021
+ },
1022
+ },
1023
+ "botched": {"type": "boolean"},
1024
+ "botched_reason": {"type": "string"},
1025
+ "summary": {"type": "string"},
1026
+ },
1027
+ "required": ["findings", "coverage", "botched", "botched_reason", "summary"],
1028
+ "additionalProperties": False,
1029
+ },
1030
+ }
1031
+
1032
+
1033
+ def _strip_json_fences(text: str) -> str:
1034
+ t = text.strip()
1035
+ if t.startswith("```"):
1036
+ t = t.split("\n", 1)[-1] if "\n" in t else t[3:]
1037
+ if t.rstrip().endswith("```"):
1038
+ t = t.rstrip()[:-3]
1039
+ return t.strip()
1040
+
1041
+
1042
+ # Fallback only. How much each mistake severity subtracts from the coverage pass-rate,
1043
+ # applied via a NEGATIVE row weight (see below) so these are absolute penalties on the
1044
+ # final 0-1 score. The owning pipeline should pass its own table via the verifier step's
1045
+ # ``mistake_severity_weights`` — these numbers want calibrating against human review, and
1046
+ # that shouldn't need an agent-env release. This default exists so an unconfigured step
1047
+ # still prices severity rather than silently treating every finding alike.
1048
+ MISTAKE_SEVERITY_PENALTY = {
1049
+ "low": 0.02,
1050
+ "medium": 0.08,
1051
+ "high": 0.25,
1052
+ "critical": 1.0, # a critical finding alone floors the score
1053
+ }
1054
+ _DEFAULT_SEVERITY = "medium"
1055
+
1056
+
1057
+ def _trajectory_mistakes_rows(
1058
+ parsed: dict,
1059
+ severity_weights: dict[str, float] | None = None,
1060
+ ) -> list[dict]:
1061
+ """Map a parsed mistakes response to RUBRIC-SHAPED rows so the existing hub
1062
+ rubric renderer displays them unchanged (id/score/result/justification).
1063
+
1064
+ Scoring (WEIGHTED_AVERAGE, which the caller configures) is
1065
+ ``coverage_pass_rate - sum(severity penalties)``. Two properties matter:
1066
+
1067
+ * **Severity is priced.** Mistake rows previously scored a flat ``0.0`` at weight 1,
1068
+ so a ``low`` nitpick cost exactly what a ``critical`` did. They now carry a negative
1069
+ weight, which ``aggregate_score`` treats as a penalty instead of a zero-scored row
1070
+ dragging down the mean.
1071
+ * **The reachable maximum no longer depends on rubric size.** Because a zero-scored row
1072
+ also grew the denominator, the old ceiling was ``(C+1)/(C+2+M)`` — a task emitting
1073
+ C<=4 coverage items could not reach 0.75 with even one mistake (best 0.714), while a
1074
+ C=11 task absorbed three. Scaling the weight by ``pos_den`` cancels that division, so
1075
+ the penalty is the same absolute hit regardless of how many coverage items a rubric
1076
+ happens to emit.
1077
+
1078
+ ``severity_weights`` maps a severity to its penalty; the owning pipeline supplies it so
1079
+ the numbers can be tuned without an agent-env release. Falls back to
1080
+ ``MISTAKE_SEVERITY_PENALTY``, and an unrecognised severity falls back to the table's
1081
+ ``medium`` rather than scoring free.
1082
+
1083
+ ``severity``, ``result`` and the ``"[sev] ..."`` justification prefix are unchanged —
1084
+ a downstream gate greps that marker out of the justification.
1085
+ """
1086
+ weights = severity_weights or MISTAKE_SEVERITY_PENALTY
1087
+ fallback = weights.get(_DEFAULT_SEVERITY, MISTAKE_SEVERITY_PENALTY[_DEFAULT_SEVERITY])
1088
+ findings = parsed.get("findings") or []
1089
+ coverage = parsed.get("coverage") or []
1090
+ botched = bool(parsed.get("botched"))
1091
+ clean = not findings and not botched
1092
+
1093
+ # Positive rows: botched + one per coverage item. Mistake penalties are scaled by this
1094
+ # so that `(pos_num - penalty*pos_den) / pos_den` leaves the penalty undivided.
1095
+ pos_den = 1 + len(coverage)
1096
+
1097
+ rows: list[dict] = [
1098
+ {
1099
+ "id": "summary",
1100
+ "score": 1.0 if clean else 0.0,
1101
+ "result": clean,
1102
+ # Informational only (weight 0). It flips to 0.0 on ANY finding, so scoring it
1103
+ # charged for the same mistake twice — once here, once on the mistake row.
1104
+ "weight": 0.0,
1105
+ "justification": parsed.get("summary", ""),
1106
+ },
1107
+ {
1108
+ "id": "botched",
1109
+ "score": 0.0 if botched else 1.0,
1110
+ "result": not botched,
1111
+ "justification": parsed.get("botched_reason", "") or ("Run botched" if botched else "No flailing detected"),
1112
+ },
1113
+ ]
1114
+ for i, f in enumerate(findings):
1115
+ sev = (f.get("severity") or "medium").lower()
1116
+ should = f.get("should", "")
1117
+ desc = f.get("description", "")
1118
+ penalty = weights.get(sev, fallback)
1119
+ rows.append({
1120
+ "id": f"mistake_{i}",
1121
+ "score": 0.0,
1122
+ "result": False,
1123
+ "severity": sev,
1124
+ "step": f.get("step"),
1125
+ "weight": -(penalty * pos_den),
1126
+ "justification": f"[{sev}] {should} — {desc}".strip(" —"),
1127
+ })
1128
+ for c in coverage:
1129
+ shown = bool(c.get("shown"))
1130
+ rows.append({
1131
+ "id": f"coverage_{c.get('id', '?')}",
1132
+ "score": 1.0 if shown else 0.0,
1133
+ "result": shown,
1134
+ "justification": ("shown: " if shown else "MISSING: ") + (c.get("note", "") or ""),
1135
+ })
1136
+ return rows
1137
+
1138
+
1139
+ def diagnose_trajectory_mistakes_response(
1140
+ response_text: str,
1141
+ criteria: list[dict],
1142
+ severity_weights: dict[str, float] | None = None,
1143
+ ) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]:
1144
+ """Parse a trajectory-mistakes judge response. Unlike rubric_binary this does NOT
1145
+ id-match against criteria (findings are open-ended); it only flags invalid JSON so
1146
+ the correction loop can retry.
1147
+
1148
+ ``severity_weights`` is the caller's severity→penalty table (see
1149
+ ``_trajectory_mistakes_rows``); None uses the built-in fallback."""
1150
+ try:
1151
+ parsed = json.loads(_strip_json_fences(response_text))
1152
+ except json.JSONDecodeError as e:
1153
+ logger.error(f"Failed to parse trajectory-mistakes judge response as JSON: {e}")
1154
+ return None, _parse_failure_discrepancy(criteria, str(e))
1155
+ if not isinstance(parsed, dict):
1156
+ return None, _parse_failure_discrepancy(criteria, f"unexpected response shape: {type(parsed).__name__}")
1157
+ return _trajectory_mistakes_rows(parsed, severity_weights), None
1158
+
1159
+
1160
+ def _parse_trajectory_mistakes_response(
1161
+ response_text: str,
1162
+ criteria: list[dict],
1163
+ severity_weights: dict[str, float] | None = None,
1164
+ ) -> list[dict]:
1165
+ rows, discrepancy = diagnose_trajectory_mistakes_response(
1166
+ response_text, criteria, severity_weights)
1167
+ if discrepancy is not None:
1168
+ # Degrade to a single parse-error row rather than failing the task.
1169
+ return [{"id": "parse_error", "score": 0.0, "result": False,
1170
+ "justification": f"Judge output unparseable: {discrepancy.parse_error}"}]
1171
+ assert rows is not None
1172
+ return rows
1173
+
1174
+
1175
+ def format_trajectory_mistakes_correction(
1176
+ *,
1177
+ eval_prompt: str,
1178
+ previous_response: str,
1179
+ discrepancy: JudgeResponseDiscrepancy,
1180
+ max_previous_response_chars: int = _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS,
1181
+ ) -> str:
1182
+ truncated = previous_response.strip()
1183
+ if len(truncated) > max_previous_response_chars:
1184
+ truncated = truncated[:max_previous_response_chars] + "\n... [truncated]"
1185
+ correction_block = "\n".join([
1186
+ "## Correction Required",
1187
+ "",
1188
+ f"Your previous response was not valid JSON ({discrepancy.parse_error}).",
1189
+ "Return ONLY a JSON object with keys: findings, coverage, botched, botched_reason, summary.",
1190
+ "No preamble, no markdown fences, no extra text.",
1191
+ "",
1192
+ "## Your Previous Response",
1193
+ truncated,
1194
+ ])
1195
+ return f"{eval_prompt.rstrip()}\n\n{correction_block}"
1196
+
1197
+
1198
+ class JudgeOutputFormat(str, Enum):
1199
+ RUBRIC_BINARY = "rubric_binary"
1200
+ RUBRIC_PARTIAL = "rubric_partial"
1201
+ TRAJECTORY_MISTAKES = "trajectory_mistakes"
1202
+ # rubric_binary rows that cite their evidence (frame + evidence_status); stored as format "rubric_binary".
1203
+ RUBRIC_EVIDENCE = "rubric_evidence"
1204
+ # rubric_evidence whose judge call also detects trajectory mistakes (findings / botched / summary on the same
1205
+ # object); the entry is stored exactly as rubric_evidence's and the verifier writes a second,
1206
+ # trajectory_mistakes-shaped entry from the findings.
1207
+ RUBRIC_EVIDENCE_WITH_MISTAKES = "rubric_evidence_with_mistakes"
1208
+
1209
+
1210
+ DiagnoseResponse = Callable[[str, list[dict]], tuple[list[dict] | None, JudgeResponseDiscrepancy | None]]
1211
+ FormatCorrectionPrompt = Callable[..., str]
1212
+
1213
+
1214
+ @dataclass(frozen=True)
1215
+ class JudgeOutputFormatSpec:
1216
+ output_format: dict
1217
+ prompt_template_path: Template
1218
+ prompt_template_inline: Template
1219
+ prompt_template_no_trajectory: Template
1220
+ parse_response: Callable[[str, list[dict]], list[dict]]
1221
+ diagnose_response: DiagnoseResponse
1222
+ format_correction_prompt: FormatCorrectionPrompt
1223
+ # The `format` written on the verification entry when it differs from the enum value (rubric_binary-shaped
1224
+ # rows store themselves as rubric_binary so existing readers see no change); both evidence formats set it.
1225
+ stored_format: str | None = None
1226
+ # Rows carry `frame` / `evidence_status`, so the per-criterion grounding asks the judge to cite them; a format
1227
+ # with this set needs the labelled per-criterion frames (the verifier enforces the configuration).
1228
+ cites_evidence: bool = False
1229
+
1230
+
1231
+ JUDGE_OUTPUT_FORMAT_REGISTRY: dict[JudgeOutputFormat, JudgeOutputFormatSpec] = {
1232
+ JudgeOutputFormat.RUBRIC_BINARY: JudgeOutputFormatSpec(
1233
+ output_format=_rubric_score_output_format(),
1234
+ prompt_template_path=_RUBRIC_BINARY_PROMPT_PATH,
1235
+ prompt_template_inline=_RUBRIC_BINARY_PROMPT_INLINE,
1236
+ prompt_template_no_trajectory=_RUBRIC_BINARY_PROMPT_NO_TRAJECTORY,
1237
+ parse_response=_parse_rubric_binary_response,
1238
+ diagnose_response=diagnose_rubric_binary_response,
1239
+ format_correction_prompt=format_judge_correction_prompt,
1240
+ ),
1241
+ JudgeOutputFormat.RUBRIC_PARTIAL: JudgeOutputFormatSpec(
1242
+ output_format=_rubric_score_output_format(),
1243
+ prompt_template_path=_RUBRIC_PARTIAL_PROMPT_PATH,
1244
+ prompt_template_inline=_RUBRIC_PARTIAL_PROMPT_INLINE,
1245
+ prompt_template_no_trajectory=_RUBRIC_PARTIAL_PROMPT_NO_TRAJECTORY,
1246
+ parse_response=_parse_rubric_partial_response,
1247
+ diagnose_response=diagnose_rubric_partial_response,
1248
+ format_correction_prompt=format_partial_judge_correction_prompt,
1249
+ ),
1250
+ JudgeOutputFormat.RUBRIC_EVIDENCE: JudgeOutputFormatSpec(
1251
+ output_format=_rubric_evidence_output_format(),
1252
+ prompt_template_path=_RUBRIC_EVIDENCE_PROMPT_PATH,
1253
+ prompt_template_inline=_RUBRIC_EVIDENCE_PROMPT_INLINE,
1254
+ prompt_template_no_trajectory=_RUBRIC_EVIDENCE_PROMPT_NO_TRAJECTORY,
1255
+ parse_response=_parse_rubric_evidence_response,
1256
+ diagnose_response=diagnose_rubric_evidence_response,
1257
+ format_correction_prompt=format_evidence_judge_correction_prompt,
1258
+ stored_format=JudgeOutputFormat.RUBRIC_BINARY.value,
1259
+ cites_evidence=True,
1260
+ ),
1261
+ JudgeOutputFormat.RUBRIC_EVIDENCE_WITH_MISTAKES: JudgeOutputFormatSpec(
1262
+ output_format=_rubric_evidence_output_format(with_mistakes=True),
1263
+ prompt_template_path=_RUBRIC_EVIDENCE_MISTAKES_PROMPT_PATH,
1264
+ prompt_template_inline=_RUBRIC_EVIDENCE_MISTAKES_PROMPT_INLINE,
1265
+ prompt_template_no_trajectory=_RUBRIC_EVIDENCE_MISTAKES_PROMPT_NO_TRAJECTORY,
1266
+ parse_response=_parse_rubric_evidence_mistakes_response,
1267
+ diagnose_response=diagnose_rubric_evidence_mistakes_response,
1268
+ format_correction_prompt=partial(format_evidence_judge_correction_prompt, with_mistakes=True),
1269
+ stored_format=JudgeOutputFormat.RUBRIC_BINARY.value,
1270
+ cites_evidence=True,
1271
+ ),
1272
+ JudgeOutputFormat.TRAJECTORY_MISTAKES: JudgeOutputFormatSpec(
1273
+ output_format=_trajectory_mistakes_output_format(),
1274
+ prompt_template_path=_TRAJECTORY_MISTAKES_PROMPT_PATH,
1275
+ prompt_template_inline=_TRAJECTORY_MISTAKES_PROMPT_INLINE,
1276
+ prompt_template_no_trajectory=_TRAJECTORY_MISTAKES_PROMPT_NO_TRAJECTORY,
1277
+ parse_response=_parse_trajectory_mistakes_response,
1278
+ diagnose_response=diagnose_trajectory_mistakes_response,
1279
+ format_correction_prompt=format_trajectory_mistakes_correction,
1280
+ ),
1281
+ }
1282
+
1283
+
1284
+ def get_judge_output_format_spec(fmt: JudgeOutputFormat | str) -> JudgeOutputFormatSpec:
1285
+ if isinstance(fmt, str):
1286
+ try:
1287
+ fmt = JudgeOutputFormat(fmt)
1288
+ except ValueError as e:
1289
+ raise ValueError(f"Unknown judge output format: {fmt}") from e
1290
+ try:
1291
+ return JUDGE_OUTPUT_FORMAT_REGISTRY[fmt]
1292
+ except KeyError as e:
1293
+ raise ValueError(f"Unknown judge output format: {fmt}") from e