cosmos-platform 1.6.0.dev1__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 (541) hide show
  1. cosmos_platform-1.6.0.dev1.dist-info/METADATA +150 -0
  2. cosmos_platform-1.6.0.dev1.dist-info/RECORD +541 -0
  3. cosmos_platform-1.6.0.dev1.dist-info/WHEEL +5 -0
  4. cosmos_platform-1.6.0.dev1.dist-info/entry_points.txt +2 -0
  5. cosmos_platform-1.6.0.dev1.dist-info/licenses/LICENSE +202 -0
  6. cosmos_platform-1.6.0.dev1.dist-info/top_level.txt +2 -0
  7. runtime/__init__.py +1 -0
  8. runtime/candidate/__init__.py +8 -0
  9. runtime/candidate/admission_gate.py +1776 -0
  10. runtime/certification/test_certify_opencode_identity.py +71 -0
  11. runtime/certification/test_certify_w304_windows_silence.py +888 -0
  12. runtime/certification/test_cosmos15_empirical.py +60 -0
  13. runtime/certification/test_cosmos_control_center.py +490 -0
  14. runtime/certification/test_cosmos_dogfood.py +143 -0
  15. runtime/certification/test_enforcement_census_lc16.py +1112 -0
  16. runtime/certification/test_eol_byte_stability_p001.py +394 -0
  17. runtime/certification/test_lc113_adapter_terminal_proofs.py +414 -0
  18. runtime/certification/test_live_certification_k3.py +622 -0
  19. runtime/certification/test_mcp_live_c4b.py +1210 -0
  20. runtime/certification/test_phase9_closeout.py +19 -0
  21. runtime/certification/test_preservation_census_lc17.py +1039 -0
  22. runtime/certification/test_self_hosting_cold_reconstruction.py +158 -0
  23. runtime/certification/test_self_hosting_conformance.py +18 -0
  24. runtime/certification/test_self_hosting_continuity.py +50 -0
  25. runtime/certification/test_self_hosting_environment.py +329 -0
  26. runtime/certification/test_self_hosting_learning.py +56 -0
  27. runtime/certification/test_self_hosting_two_generation.py +21 -0
  28. runtime/certification/test_truth_drift_lc18.py +557 -0
  29. runtime/certification/test_universal_binding_c3.py +770 -0
  30. runtime/certification/test_w101_attempt2.py +698 -0
  31. runtime/certification/test_w101_preservation.py +425 -0
  32. runtime/certification/test_w304_option_a_startup_liveness.py +1093 -0
  33. runtime/certification/test_w304_wedge_log_flood.py +468 -0
  34. runtime/certification/test_w304_wedge_recovery.py +258 -0
  35. runtime/cosmos_runtime/__init__.py +169 -0
  36. runtime/cosmos_runtime/__main__.py +3 -0
  37. runtime/cosmos_runtime/actors.py +363 -0
  38. runtime/cosmos_runtime/adaptive_reasoning.py +242 -0
  39. runtime/cosmos_runtime/authorization.py +567 -0
  40. runtime/cosmos_runtime/cli.py +61 -0
  41. runtime/cosmos_runtime/config.py +21 -0
  42. runtime/cosmos_runtime/context.py +347 -0
  43. runtime/cosmos_runtime/continuation.py +548 -0
  44. runtime/cosmos_runtime/continuity/__init__.py +16 -0
  45. runtime/cosmos_runtime/continuity/handoff.py +208 -0
  46. runtime/cosmos_runtime/controller.py +218 -0
  47. runtime/cosmos_runtime/effects.py +546 -0
  48. runtime/cosmos_runtime/execution.py +725 -0
  49. runtime/cosmos_runtime/execution_shim.py +428 -0
  50. runtime/cosmos_runtime/governance/__init__.py +60 -0
  51. runtime/cosmos_runtime/governance/completion.py +434 -0
  52. runtime/cosmos_runtime/governance/gates.py +952 -0
  53. runtime/cosmos_runtime/governance/scope_types.py +150 -0
  54. runtime/cosmos_runtime/ids.py +25 -0
  55. runtime/cosmos_runtime/intake.py +170 -0
  56. runtime/cosmos_runtime/learning.py +294 -0
  57. runtime/cosmos_runtime/model.py +240 -0
  58. runtime/cosmos_runtime/resilience.py +298 -0
  59. runtime/cosmos_runtime/security/__init__.py +72 -0
  60. runtime/cosmos_runtime/security/audit.py +139 -0
  61. runtime/cosmos_runtime/security/consent.py +153 -0
  62. runtime/cosmos_runtime/security/encryption.py +158 -0
  63. runtime/cosmos_runtime/security/enterprise_fence.py +169 -0
  64. runtime/cosmos_runtime/security/injection_detector.py +123 -0
  65. runtime/cosmos_runtime/security/microphone.py +145 -0
  66. runtime/cosmos_runtime/security/retention.py +168 -0
  67. runtime/cosmos_runtime/security/tenant.py +108 -0
  68. runtime/cosmos_runtime/services.py +187 -0
  69. runtime/cosmos_runtime/store.py +802 -0
  70. runtime/cosmos_runtime/telemetry/__init__.py +42 -0
  71. runtime/cosmos_runtime/telemetry/bus.py +198 -0
  72. runtime/cosmos_runtime/telemetry/events.py +187 -0
  73. runtime/cosmos_runtime/telemetry/scrubber.py +119 -0
  74. runtime/tests/__init__.py +11 -0
  75. runtime/tests/_pollution_guard.py +311 -0
  76. runtime/tests/_retrieval_fixtures.py +102 -0
  77. runtime/tests/_world_isolation.py +138 -0
  78. runtime/tests/conftest.py +56 -0
  79. runtime/tests/gate_local_support.py +234 -0
  80. runtime/tests/test_aaa_pollution_guard.py +218 -0
  81. runtime/tests/test_actor_routing.py +187 -0
  82. runtime/tests/test_adapter_family_agent_frameworks_activation.py +883 -0
  83. runtime/tests/test_adapter_family_cloud_coding_activation.py +1090 -0
  84. runtime/tests/test_adapter_family_core_cli_activation.py +2039 -0
  85. runtime/tests/test_adapter_family_emacs_activation.py +769 -0
  86. runtime/tests/test_adapter_family_ide_rules_activation.py +1016 -0
  87. runtime/tests/test_adapter_family_jetbrains_eclipse_activation.py +990 -0
  88. runtime/tests/test_adapter_family_neovim_activation.py +830 -0
  89. runtime/tests/test_adaptive_reasoning.py +115 -0
  90. runtime/tests/test_ar4_self_hosting_decoupling.py +49 -0
  91. runtime/tests/test_assurance_spine_c2.py +411 -0
  92. runtime/tests/test_authorization_gateway.py +203 -0
  93. runtime/tests/test_capability_reconciliation_lc14.py +257 -0
  94. runtime/tests/test_carrier_flow_k3.py +326 -0
  95. runtime/tests/test_cert_invalidation_k4.py +764 -0
  96. runtime/tests/test_certification_adversarial_v1.py +882 -0
  97. runtime/tests/test_claims_matrix_lc15.py +551 -0
  98. runtime/tests/test_completion.py +306 -0
  99. runtime/tests/test_context_binding.py +160 -0
  100. runtime/tests/test_continuation.py +269 -0
  101. runtime/tests/test_cosmos15_baseline.py +31 -0
  102. runtime/tests/test_cosmos15_claude_door.py +108 -0
  103. runtime/tests/test_cosmos15_developer_world.py +194 -0
  104. runtime/tests/test_cosmos15_observatory.py +286 -0
  105. runtime/tests/test_cosmos15_operator.py +329 -0
  106. runtime/tests/test_cosmos_admin.py +221 -0
  107. runtime/tests/test_cosmos_agent_directory_boundary.py +32 -0
  108. runtime/tests/test_cosmos_ask.py +119 -0
  109. runtime/tests/test_cosmos_blocker_gate.py +192 -0
  110. runtime/tests/test_cosmos_branch_audit.py +227 -0
  111. runtime/tests/test_cosmos_by_path.py +557 -0
  112. runtime/tests/test_cosmos_capability_health.py +651 -0
  113. runtime/tests/test_cosmos_certification.py +98 -0
  114. runtime/tests/test_cosmos_check_proposal.py +584 -0
  115. runtime/tests/test_cosmos_check_runner.py +578 -0
  116. runtime/tests/test_cosmos_check_runner_shard_s1.py +765 -0
  117. runtime/tests/test_cosmos_cloud_bundle.py +33 -0
  118. runtime/tests/test_cosmos_cold_clone_binding.py +106 -0
  119. runtime/tests/test_cosmos_context_authority.py +276 -0
  120. runtime/tests/test_cosmos_continuation.py +210 -0
  121. runtime/tests/test_cosmos_continuity.py +147 -0
  122. runtime/tests/test_cosmos_continuity_demo.py +93 -0
  123. runtime/tests/test_cosmos_continuity_hook.py +453 -0
  124. runtime/tests/test_cosmos_controller.py +125 -0
  125. runtime/tests/test_cosmos_cross_harness_handoff.py +93 -0
  126. runtime/tests/test_cosmos_current_task_derivation.py +202 -0
  127. runtime/tests/test_cosmos_decision_guard.py +179 -0
  128. runtime/tests/test_cosmos_decisions.py +161 -0
  129. runtime/tests/test_cosmos_defensibility_qualification.py +135 -0
  130. runtime/tests/test_cosmos_delta.py +512 -0
  131. runtime/tests/test_cosmos_delta_cli.py +196 -0
  132. runtime/tests/test_cosmos_dependency_graph.py +94 -0
  133. runtime/tests/test_cosmos_dependency_graph_scope.py +67 -0
  134. runtime/tests/test_cosmos_deployment_reconciler.py +213 -0
  135. runtime/tests/test_cosmos_doctor_command_shadowing.py +61 -0
  136. runtime/tests/test_cosmos_doorway_validator.py +139 -0
  137. runtime/tests/test_cosmos_enforce.py +222 -0
  138. runtime/tests/test_cosmos_events.py +77 -0
  139. runtime/tests/test_cosmos_evidence.py +122 -0
  140. runtime/tests/test_cosmos_execution_shim.py +254 -0
  141. runtime/tests/test_cosmos_feedback.py +97 -0
  142. runtime/tests/test_cosmos_gate.py +3007 -0
  143. runtime/tests/test_cosmos_gate_backlog.py +218 -0
  144. runtime/tests/test_cosmos_gate_categories.py +240 -0
  145. runtime/tests/test_cosmos_gate_f008.py +386 -0
  146. runtime/tests/test_cosmos_gate_fast.py +3527 -0
  147. runtime/tests/test_cosmos_gate_governance.py +196 -0
  148. runtime/tests/test_cosmos_gate_lessons.py +113 -0
  149. runtime/tests/test_cosmos_gate_load.py +283 -0
  150. runtime/tests/test_cosmos_gate_multi.py +357 -0
  151. runtime/tests/test_cosmos_gate_override.py +114 -0
  152. runtime/tests/test_cosmos_gate_profile.py +271 -0
  153. runtime/tests/test_cosmos_gate_recheck.py +134 -0
  154. runtime/tests/test_cosmos_gate_runtime.py +304 -0
  155. runtime/tests/test_cosmos_gate_selfcheck.py +27 -0
  156. runtime/tests/test_cosmos_gate_skip.py +95 -0
  157. runtime/tests/test_cosmos_git_hooks.py +117 -0
  158. runtime/tests/test_cosmos_guard.py +938 -0
  159. runtime/tests/test_cosmos_harness_doors.py +50 -0
  160. runtime/tests/test_cosmos_hygiene.py +76 -0
  161. runtime/tests/test_cosmos_hypothesis.py +106 -0
  162. runtime/tests/test_cosmos_index_hot_journal.py +108 -0
  163. runtime/tests/test_cosmos_landing_board.py +228 -0
  164. runtime/tests/test_cosmos_learn.py +92 -0
  165. runtime/tests/test_cosmos_levels_of_done.py +67 -0
  166. runtime/tests/test_cosmos_lineage.py +157 -0
  167. runtime/tests/test_cosmos_mcp_binding.py +182 -0
  168. runtime/tests/test_cosmos_mcp_governed_tools.py +185 -0
  169. runtime/tests/test_cosmos_mcp_registration.py +430 -0
  170. runtime/tests/test_cosmos_memory_maintenance.py +81 -0
  171. runtime/tests/test_cosmos_modality_registry.py +52 -0
  172. runtime/tests/test_cosmos_narrative.py +189 -0
  173. runtime/tests/test_cosmos_navigator_product_path.py +56 -0
  174. runtime/tests/test_cosmos_next.py +669 -0
  175. runtime/tests/test_cosmos_no_raw_process_start.py +92 -0
  176. runtime/tests/test_cosmos_objective_convergence.py +86 -0
  177. runtime/tests/test_cosmos_obligation_lc03.py +745 -0
  178. runtime/tests/test_cosmos_obligations.py +302 -0
  179. runtime/tests/test_cosmos_observe.py +100 -0
  180. runtime/tests/test_cosmos_onboarding.py +224 -0
  181. runtime/tests/test_cosmos_override_gate.py +288 -0
  182. runtime/tests/test_cosmos_packaging_billing_gate.py +396 -0
  183. runtime/tests/test_cosmos_pilot.py +165 -0
  184. runtime/tests/test_cosmos_popup_check.py +75 -0
  185. runtime/tests/test_cosmos_proc_owned_tree.py +249 -0
  186. runtime/tests/test_cosmos_project_adapters.py +158 -0
  187. runtime/tests/test_cosmos_push.py +178 -0
  188. runtime/tests/test_cosmos_qualification.py +94 -0
  189. runtime/tests/test_cosmos_remediation.py +67 -0
  190. runtime/tests/test_cosmos_report.py +99 -0
  191. runtime/tests/test_cosmos_retrieval.py +512 -0
  192. runtime/tests/test_cosmos_retrieval_cli_mcp.py +198 -0
  193. runtime/tests/test_cosmos_retrieval_model_fetch.py +40 -0
  194. runtime/tests/test_cosmos_safety.py +528 -0
  195. runtime/tests/test_cosmos_security_package.py +417 -0
  196. runtime/tests/test_cosmos_security_qualification.py +59 -0
  197. runtime/tests/test_cosmos_self_repair.py +504 -0
  198. runtime/tests/test_cosmos_serving.py +153 -0
  199. runtime/tests/test_cosmos_session_lifecycle.py +181 -0
  200. runtime/tests/test_cosmos_session_start.py +493 -0
  201. runtime/tests/test_cosmos_settings_hooks.py +36 -0
  202. runtime/tests/test_cosmos_speed_limits.py +36 -0
  203. runtime/tests/test_cosmos_staging_qualification.py +117 -0
  204. runtime/tests/test_cosmos_stop_guard.py +84 -0
  205. runtime/tests/test_cosmos_studio.py +1102 -0
  206. runtime/tests/test_cosmos_substrate_liveness.py +111 -0
  207. runtime/tests/test_cosmos_supply_chain_gate.py +238 -0
  208. runtime/tests/test_cosmos_synthetic_pilot.py +46 -0
  209. runtime/tests/test_cosmos_telemetry.py +65 -0
  210. runtime/tests/test_cosmos_telemetry_bus.py +157 -0
  211. runtime/tests/test_cosmos_telemetry_scrubber.py +124 -0
  212. runtime/tests/test_cosmos_tracker_render.py +95 -0
  213. runtime/tests/test_cosmos_trigger_records.py +198 -0
  214. runtime/tests/test_cosmos_tripartite_delta.py +154 -0
  215. runtime/tests/test_cosmos_tripartite_events.py +103 -0
  216. runtime/tests/test_cosmos_trust_readiness.py +375 -0
  217. runtime/tests/test_cosmos_vault.py +3524 -0
  218. runtime/tests/test_cosmos_vault_entry_points.py +920 -0
  219. runtime/tests/test_cosmos_vault_worker.py +1450 -0
  220. runtime/tests/test_cosmos_visibility_policy.py +187 -0
  221. runtime/tests/test_cosmos_wake.py +43 -0
  222. runtime/tests/test_cosmos_watchdog.py +1318 -0
  223. runtime/tests/test_cosmos_world_refresh_and_capture.py +711 -0
  224. runtime/tests/test_cosmos_wrong_direction.py +214 -0
  225. runtime/tests/test_cosmos_zero_step.py +245 -0
  226. runtime/tests/test_daemon_supervisor_c5b.py +845 -0
  227. runtime/tests/test_enforcement_live_c4.py +485 -0
  228. runtime/tests/test_execution_loop.py +216 -0
  229. runtime/tests/test_foundation.py +145 -0
  230. runtime/tests/test_governance_gates.py +327 -0
  231. runtime/tests/test_intake.py +107 -0
  232. runtime/tests/test_invalidationscan_k4.py +776 -0
  233. runtime/tests/test_lc112_live_attestation_commission.py +292 -0
  234. runtime/tests/test_lc133_lp2_entry_points.py +268 -0
  235. runtime/tests/test_lc1_baseline_lc19.py +702 -0
  236. runtime/tests/test_levels_of_done_k1.py +474 -0
  237. runtime/tests/test_live_attestation_k2.py +521 -0
  238. runtime/tests/test_live_attestation_k2_regressions.py +442 -0
  239. runtime/tests/test_live_certification_k3_regressions.py +623 -0
  240. runtime/tests/test_lp7_studio_trigger.py +191 -0
  241. runtime/tests/test_master_plan_revision_identity.py +123 -0
  242. runtime/tests/test_multi_harness_acceptance.py +292 -0
  243. runtime/tests/test_multi_harness_stress.py +188 -0
  244. runtime/tests/test_objective_live_c1.py +437 -0
  245. runtime/tests/test_obligation_reconciliation_lc13.py +351 -0
  246. runtime/tests/test_observation_projection.py +156 -0
  247. runtime/tests/test_observation_wiring.py +100 -0
  248. runtime/tests/test_one_active_wave_lc06.py +629 -0
  249. runtime/tests/test_operational_sandbox_harness.py +111 -0
  250. runtime/tests/test_p002_canonical_engine.py +275 -0
  251. runtime/tests/test_p003_watcher_failure_attribution.py +933 -0
  252. runtime/tests/test_phase8_closeout.py +89 -0
  253. runtime/tests/test_phase8_company_environment.py +84 -0
  254. runtime/tests/test_phase8_company_proof.py +278 -0
  255. runtime/tests/test_phase8_cross_environment_audit.py +89 -0
  256. runtime/tests/test_phase8_developer_environment.py +59 -0
  257. runtime/tests/test_phase8_developer_proof.py +204 -0
  258. runtime/tests/test_phase8_harness.py +66 -0
  259. runtime/tests/test_phase8_personal_environment.py +62 -0
  260. runtime/tests/test_phase8_personal_proof.py +105 -0
  261. runtime/tests/test_phase8_protocol.py +180 -0
  262. runtime/tests/test_plan_before_code_lc04.py +830 -0
  263. runtime/tests/test_plan_census_lc12.py +243 -0
  264. runtime/tests/test_repo_census_lc11.py +230 -0
  265. runtime/tests/test_resilience.py +182 -0
  266. runtime/tests/test_retrieval_live_c5.py +270 -0
  267. runtime/tests/test_run_monitor_s2.py +587 -0
  268. runtime/tests/test_runtime_conformance.py +389 -0
  269. runtime/tests/test_sandbox_adapters.py +238 -0
  270. runtime/tests/test_scale_acceptance.py +114 -0
  271. runtime/tests/test_scope_freeze_lc05.py +638 -0
  272. runtime/tests/test_self_hosting_first_change.py +69 -0
  273. runtime/tests/test_self_hosting_projection.py +145 -0
  274. runtime/tests/test_self_hosting_protocol.py +87 -0
  275. runtime/tests/test_siem_integration_harness.py +98 -0
  276. runtime/tests/test_sign_release_archive.py +141 -0
  277. runtime/tests/test_store_concurrency.py +118 -0
  278. runtime/tests/test_studio_broker_integration.py +147 -0
  279. runtime/tests/test_tiers_doc.py +54 -0
  280. runtime/tests/test_trigger_firing_c1.py +342 -0
  281. runtime/tests/test_verify_tripartite_observability.py +120 -0
  282. runtime/tests/test_w102_branch_audit_equivalence.py +334 -0
  283. runtime/tests/test_w102_git_timeout_hang.py +233 -0
  284. runtime/tests/test_w103_identity.py +378 -0
  285. runtime/tests/test_w103_real_harness_identity.py +159 -0
  286. runtime/tests/test_w103_review_correction.py +224 -0
  287. runtime/tests/test_w103_round2_consumption.py +304 -0
  288. runtime/tests/test_w304_silent_background.py +713 -0
  289. runtime/tests/test_wave_report_lc07.py +332 -0
  290. tools/__init__.py +5 -0
  291. tools/adapter_families/agent_frameworks.py +1418 -0
  292. tools/adapter_families/cloud_coding.py +875 -0
  293. tools/adapter_families/core_cli.py +2519 -0
  294. tools/adapter_families/emacs.py +1247 -0
  295. tools/adapter_families/ide_rules.py +1105 -0
  296. tools/adapter_families/jetbrains_eclipse.py +1381 -0
  297. tools/adapter_families/neovim.py +995 -0
  298. tools/build_cosmos15_release_archive.py +110 -0
  299. tools/catalogs/model-modalities.json +84 -0
  300. tools/catalogs/ui-ux-catalog.json +173 -0
  301. tools/control_center/app.js +78 -0
  302. tools/control_center/index.html +35 -0
  303. tools/control_center/styles.css +4 -0
  304. tools/cosmos.py +1018 -0
  305. tools/cosmos15_operator.py +980 -0
  306. tools/cosmos15_world_recovery.py +292 -0
  307. tools/cosmos_adapter_health.py +311 -0
  308. tools/cosmos_ask.py +102 -0
  309. tools/cosmos_attach.py +237 -0
  310. tools/cosmos_background.py +258 -0
  311. tools/cosmos_bind.py +764 -0
  312. tools/cosmos_binding.py +130 -0
  313. tools/cosmos_blocker_gate.py +285 -0
  314. tools/cosmos_branch_audit.py +315 -0
  315. tools/cosmos_capability_health.py +4202 -0
  316. tools/cosmos_capability_reconciliation.py +419 -0
  317. tools/cosmos_capture_hook.py +644 -0
  318. tools/cosmos_cert_invalidation.py +1673 -0
  319. tools/cosmos_certification.py +506 -0
  320. tools/cosmos_check_proposal.py +483 -0
  321. tools/cosmos_check_runner.py +2480 -0
  322. tools/cosmos_claims_matrix.py +851 -0
  323. tools/cosmos_claude_door.py +268 -0
  324. tools/cosmos_cloud_bundle.py +73 -0
  325. tools/cosmos_context_authority.py +515 -0
  326. tools/cosmos_continuation.py +315 -0
  327. tools/cosmos_continuity_demo.py +180 -0
  328. tools/cosmos_continuity_wrapper.py +194 -0
  329. tools/cosmos_control_center.py +476 -0
  330. tools/cosmos_curator.py +175 -0
  331. tools/cosmos_daemon_supervisor.py +3082 -0
  332. tools/cosmos_decision_guard.py +206 -0
  333. tools/cosmos_decision_rank.py +103 -0
  334. tools/cosmos_decisions.py +343 -0
  335. tools/cosmos_defensibility_qualification.py +322 -0
  336. tools/cosmos_delta.py +887 -0
  337. tools/cosmos_dependency_graph.py +235 -0
  338. tools/cosmos_deployment_reconciler.py +393 -0
  339. tools/cosmos_design_dna.py +377 -0
  340. tools/cosmos_developer_world.py +1233 -0
  341. tools/cosmos_doctor.py +427 -0
  342. tools/cosmos_door_common.py +16 -0
  343. tools/cosmos_door_helpers.py +54 -0
  344. tools/cosmos_doorway_validator.py +152 -0
  345. tools/cosmos_enforce.py +527 -0
  346. tools/cosmos_enforcement_census.py +2657 -0
  347. tools/cosmos_eval.py +310 -0
  348. tools/cosmos_events.py +123 -0
  349. tools/cosmos_evidence.py +135 -0
  350. tools/cosmos_feedback.py +252 -0
  351. tools/cosmos_forge_adapters.py +190 -0
  352. tools/cosmos_forge_protection.py +154 -0
  353. tools/cosmos_fs_watcher.py +1378 -0
  354. tools/cosmos_gate.py +3172 -0
  355. tools/cosmos_gate_backlog.py +294 -0
  356. tools/cosmos_gate_carry.py +122 -0
  357. tools/cosmos_gate_categories.py +159 -0
  358. tools/cosmos_gate_closure.py +56 -0
  359. tools/cosmos_gate_fast.py +2592 -0
  360. tools/cosmos_gate_governance.py +282 -0
  361. tools/cosmos_gate_holdout.py +704 -0
  362. tools/cosmos_gate_linux.py +203 -0
  363. tools/cosmos_gate_load.py +205 -0
  364. tools/cosmos_gate_override.py +82 -0
  365. tools/cosmos_gate_profile.py +169 -0
  366. tools/cosmos_gate_protect.py +79 -0
  367. tools/cosmos_gate_replacements.py +66 -0
  368. tools/cosmos_gate_runtime.py +123 -0
  369. tools/cosmos_gate_scope.py +110 -0
  370. tools/cosmos_gate_selfcheck.py +79 -0
  371. tools/cosmos_gate_service.py +591 -0
  372. tools/cosmos_gate_union.py +108 -0
  373. tools/cosmos_git_hooks.py +59 -0
  374. tools/cosmos_githooks.py +94 -0
  375. tools/cosmos_guard.py +1887 -0
  376. tools/cosmos_harness_doors.py +350 -0
  377. tools/cosmos_home_guard.py +199 -0
  378. tools/cosmos_hygiene.py +251 -0
  379. tools/cosmos_hypothesis.py +124 -0
  380. tools/cosmos_identity.py +295 -0
  381. tools/cosmos_invariants.py +212 -0
  382. tools/cosmos_landing_board.py +394 -0
  383. tools/cosmos_launch.py +432 -0
  384. tools/cosmos_launcher.py +177 -0
  385. tools/cosmos_lc1_baseline.py +776 -0
  386. tools/cosmos_learn.py +319 -0
  387. tools/cosmos_levels_of_done.py +740 -0
  388. tools/cosmos_lineage.py +201 -0
  389. tools/cosmos_live_attestation.py +1559 -0
  390. tools/cosmos_mcp_registration.py +625 -0
  391. tools/cosmos_mcp_server.py +2253 -0
  392. tools/cosmos_memory.py +273 -0
  393. tools/cosmos_memory_check.py +97 -0
  394. tools/cosmos_modality_registry.py +113 -0
  395. tools/cosmos_narrative.py +225 -0
  396. tools/cosmos_next.py +659 -0
  397. tools/cosmos_objective_convergence.py +167 -0
  398. tools/cosmos_obligations.py +2809 -0
  399. tools/cosmos_observation_projection.py +144 -0
  400. tools/cosmos_observe.py +353 -0
  401. tools/cosmos_opencode_push.js +164 -0
  402. tools/cosmos_overlay_injector.py +44 -0
  403. tools/cosmos_override_gate.py +550 -0
  404. tools/cosmos_packaging_billing_gate.py +314 -0
  405. tools/cosmos_packet.py +973 -0
  406. tools/cosmos_pilot.py +731 -0
  407. tools/cosmos_plan_census.py +634 -0
  408. tools/cosmos_popup_check.py +260 -0
  409. tools/cosmos_premise.py +327 -0
  410. tools/cosmos_preservation_census.py +2185 -0
  411. tools/cosmos_proc.py +639 -0
  412. tools/cosmos_project_adapters.py +2773 -0
  413. tools/cosmos_push.py +138 -0
  414. tools/cosmos_qualification.py +291 -0
  415. tools/cosmos_reachability.py +345 -0
  416. tools/cosmos_reconciliation.py +451 -0
  417. tools/cosmos_refresh_adapters.py +80 -0
  418. tools/cosmos_remediation.py +166 -0
  419. tools/cosmos_repo_census.py +640 -0
  420. tools/cosmos_repo_finder.py +217 -0
  421. tools/cosmos_report.py +134 -0
  422. tools/cosmos_retrieval/__init__.py +41 -0
  423. tools/cosmos_retrieval/__main__.py +4 -0
  424. tools/cosmos_retrieval/activation.py +564 -0
  425. tools/cosmos_retrieval/cli.py +274 -0
  426. tools/cosmos_retrieval/embedders.py +214 -0
  427. tools/cosmos_retrieval/index.py +884 -0
  428. tools/cosmos_retrieval/model_fetch.py +122 -0
  429. tools/cosmos_retrieval/text.py +243 -0
  430. tools/cosmos_retrieval/vectors.py +101 -0
  431. tools/cosmos_rollback.py +453 -0
  432. tools/cosmos_run_monitor.py +1198 -0
  433. tools/cosmos_safety.py +350 -0
  434. tools/cosmos_scorecard.py +466 -0
  435. tools/cosmos_security_qualification.py +202 -0
  436. tools/cosmos_self_repair.py +192 -0
  437. tools/cosmos_serving.py +339 -0
  438. tools/cosmos_session_brief.py +302 -0
  439. tools/cosmos_session_lifecycle.py +389 -0
  440. tools/cosmos_session_start.py +1894 -0
  441. tools/cosmos_setup.py +585 -0
  442. tools/cosmos_staging_qualification.py +252 -0
  443. tools/cosmos_stop_guard.py +111 -0
  444. tools/cosmos_studio_app.py +2225 -0
  445. tools/cosmos_supply_chain_gate.py +454 -0
  446. tools/cosmos_synthetic_pilot.py +215 -0
  447. tools/cosmos_telemetry.py +153 -0
  448. tools/cosmos_tracker_render.py +196 -0
  449. tools/cosmos_trust_readiness.py +607 -0
  450. tools/cosmos_truth_drift.py +1573 -0
  451. tools/cosmos_vault.py +2023 -0
  452. tools/cosmos_vault_acl.py +715 -0
  453. tools/cosmos_vault_bundle.py +438 -0
  454. tools/cosmos_vault_install.py +471 -0
  455. tools/cosmos_vault_service.py +345 -0
  456. tools/cosmos_vault_worker.py +745 -0
  457. tools/cosmos_visibility_policy.py +134 -0
  458. tools/cosmos_wake.py +262 -0
  459. tools/cosmos_watchdog.py +1775 -0
  460. tools/cosmos_watchdog_timing.py +100 -0
  461. tools/cosmos_wave_report.py +357 -0
  462. tools/cosmos_wrong_direction.py +217 -0
  463. tools/evaluate_assurance_risk.py +302 -0
  464. tools/generate_execution_stack_conformance_fixtures.py +122 -0
  465. tools/generate_execution_stack_envelope_fixtures.py +122 -0
  466. tools/generate_model_route_receipt_fixtures.py +320 -0
  467. tools/observatory/README.md +64 -0
  468. tools/observatory/app.js +486 -0
  469. tools/observatory/index.html +82 -0
  470. tools/observatory/launcher.css +249 -0
  471. tools/observatory/launcher.html +80 -0
  472. tools/observatory/launcher.js +173 -0
  473. tools/observatory/styles.css +83 -0
  474. tools/operational_sandbox_harness.py +481 -0
  475. tools/owner_requeue.py +402 -0
  476. tools/reference_authorization.py +427 -0
  477. tools/reference_cold_reconstruction.py +264 -0
  478. tools/reference_context_binder.py +570 -0
  479. tools/reference_cosmos15_empirical.py +208 -0
  480. tools/reference_dogfood_runner.py +166 -0
  481. tools/reference_environment_audit.py +332 -0
  482. tools/reference_environment_harness.py +764 -0
  483. tools/reference_environment_proof.py +206 -0
  484. tools/reference_first_self_change.py +342 -0
  485. tools/reference_generation_a_continuation.py +111 -0
  486. tools/reference_generation_b_continuation.py +102 -0
  487. tools/reference_knowledge_lifecycle.py +318 -0
  488. tools/reference_maintenance.py +399 -0
  489. tools/reference_observatory.py +848 -0
  490. tools/reference_phase8_closeout.py +249 -0
  491. tools/reference_phase9_closeout.py +138 -0
  492. tools/reference_repository_projection.py +689 -0
  493. tools/reference_self_hosting.py +245 -0
  494. tools/reference_self_hosting_conformance.py +118 -0
  495. tools/reference_self_hosting_continuity.py +227 -0
  496. tools/reference_self_hosting_environment.py +411 -0
  497. tools/reference_self_learning.py +284 -0
  498. tools/run_execution_stack_conformance.py +195 -0
  499. tools/schemas/cosmos-certification.schema.json +65 -0
  500. tools/schemas/cosmos-record.schema.json +2918 -0
  501. tools/schemas/enterprise-audit-export.schema.json +255 -0
  502. tools/schemas/enterprise-durability-recovery.schema.json +282 -0
  503. tools/schemas/enterprise-execution-sandbox.schema.json +241 -0
  504. tools/schemas/enterprise-identity-policy.schema.json +222 -0
  505. tools/schemas/enterprise-secrets.schema.json +243 -0
  506. tools/schemas/environment-pack.schema.json +184 -0
  507. tools/schemas/environment-proof-case.schema.json +131 -0
  508. tools/schemas/execution-stack-conformance.schema.json +132 -0
  509. tools/schemas/execution-stack-envelope.schema.json +161 -0
  510. tools/schemas/model-modality-profile.schema.json +66 -0
  511. tools/schemas/model-route-receipt.schema.json +71 -0
  512. tools/schemas/relation-type.schema.json +76 -0
  513. tools/schemas/release-manifest.schema.json +58 -0
  514. tools/schemas/self-hosting-contract.schema.json +143 -0
  515. tools/siem_integration_harness.py +413 -0
  516. tools/sign_release_archive.py +357 -0
  517. tools/spec/reveal-register.json +65 -0
  518. tools/spec/reveal-register.schema.json +41 -0
  519. tools/stitch_design_bridge.py +593 -0
  520. tools/studio/byom_router.js +101 -0
  521. tools/studio/ide.html +109 -0
  522. tools/studio/ide.js +62 -0
  523. tools/studio/index.html +23 -0
  524. tools/studio/modality_guard.js +101 -0
  525. tools/studio/observatory_dock.js +60 -0
  526. tools/studio/studio.css +489 -0
  527. tools/studio/studio.js +50 -0
  528. tools/studio/studio_concentric_live.png +0 -0
  529. tools/studio/studio_cosmos_canvas.png +0 -0
  530. tools/studio/studio_hero_live.png +0 -0
  531. tools/studio/studio_live.png +0 -0
  532. tools/studio/studio_preview.png +0 -0
  533. tools/studio/studio_refined_platform.png +0 -0
  534. tools/studio/subatomic_sidecar.js +57 -0
  535. tools/validate_environment_proof.py +39 -0
  536. tools/validate_execution_stack_envelopes.py +157 -0
  537. tools/validate_model_route_receipts.py +183 -0
  538. tools/validate_ontology.py +121 -0
  539. tools/verify_cosmos15_baseline.py +104 -0
  540. tools/verify_cosmos15_release_archive.py +225 -0
  541. tools/verify_tripartite_observability.py +136 -0
@@ -0,0 +1,1776 @@
1
+ """Plan-fidelity admission gate for Cosmos 1.5.
2
+
3
+ The admission gate sits at the boundary between a coding actor (Claude Code,
4
+ Codex, Gemini, etc.) and the project world. It answers one question:
5
+
6
+ "Should the work this actor just produced be admitted into the world?"
7
+
8
+ The gate is a runtime concern, not a tool concern. It knows the plan (the
9
+ pack's cases), the actor's claimed effects, the actor's diff against the world,
10
+ and the test suite's verdict. It does not know the model. It cannot be reasoned
11
+ out of by the actor because every check resolves to a mechanically-verified
12
+ artifact.
13
+
14
+ Plans are hierarchical: a phase contains PRs; a PR contains corrections. The
15
+ plan the actor is being judged against is a `case` in the pack, and each case
16
+ can carry a list of `corrections` that must individually be checked. This is
17
+ how the audit-quality verdict is produced: the gate renders a per-correction
18
+ table the same way a senior reviewer does — Correction | Result | Where
19
+ checked | Status — so the actor (and the user) can see exactly which
20
+ sub-requirements are still open.
21
+
22
+ Five checks per round:
23
+
24
+ plan_freshness Actor references current plan cases, not stale ones.
25
+ case_coverage Touched files bind to the case's scope.
26
+ running_code Test suite passes against the actor's claimed effects.
27
+ scope Touched files are in-scope for the case.
28
+ cross_area_disruption Previously-passing cases still pass.
29
+
30
+ Evidence quality is the gate's primary product. A passing check with no
31
+ citation is indistinguishable from a guess. Every check produces:
32
+
33
+ - code_citations: file:line ranges where the relevant code lives
34
+ - test_citations: test files that exercise (or mask) the behavior
35
+ - test_masking: tests that pass only because they bypass real I/O
36
+ - doc_citations: where the plan / docs claim what is being checked
37
+ - regression: the targeted test that should prove the fix
38
+ - status_assertion: a single durable sentence for the next round to verify
39
+
40
+ Per-case attempt counter:
41
+
42
+ round 3 of same case failing -> surfaced to user
43
+ round 5 of same case failing -> hard block
44
+ progress discount -> oscillation does not look like progress
45
+
46
+ The verdict is JSON-primary. Markdown is derived atomically from the same
47
+ checks so the two never disagree. The status_assertion from the most recent
48
+ verdict is what the next round should open with — not a re-summary of the
49
+ plan.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import hashlib
55
+ import json
56
+ from tools import cosmos_proc as subprocess
57
+ import uuid
58
+ from dataclasses import dataclass, field
59
+ from pathlib import Path
60
+ from typing import Any, Callable, Optional
61
+
62
+
63
+ # --- Per-check result --------------------------------------------------------
64
+
65
+
66
+ @dataclass
67
+ class CodeCitation:
68
+ """A specific location in a source file."""
69
+
70
+ path: str
71
+ line: Optional[int] = None
72
+ end_line: Optional[int] = None
73
+ excerpt: Optional[str] = None # the actual line, verbatim if known
74
+
75
+ def to_dict(self) -> dict[str, Any]:
76
+ return {k: v for k, v in self.__dict__.items() if v is not None}
77
+
78
+
79
+ @dataclass
80
+ class TestCitation:
81
+ """A test that exercises or masks the behavior under check."""
82
+
83
+ path: str
84
+ line: Optional[int] = None
85
+ name: Optional[str] = None # test function name if known
86
+ behavior: str = "" # what this test claims to prove
87
+ masks: bool = False # True if this test passes only by bypassing reality
88
+
89
+ def to_dict(self) -> dict[str, Any]:
90
+ return {k: v for k, v in self.__dict__.items() if v is not None}
91
+
92
+
93
+ @dataclass
94
+ class DocCitation:
95
+ """A claim made in plan / docs that is being checked against reality."""
96
+
97
+ path: str
98
+ line: Optional[int] = None
99
+ claim: str = "" # what the document says
100
+
101
+ def to_dict(self) -> dict[str, Any]:
102
+ return {k: v for k, v in self.__dict__.items() if v is not None}
103
+
104
+
105
+ @dataclass
106
+ class Regression:
107
+ """A targeted test the actor should write to prove the fix."""
108
+
109
+ description: str
110
+ file_hint: str = "" # where the test should live
111
+ scenario: str = "" # the specific scenario it must reproduce
112
+ acceptance: str = "" # what passing this test proves
113
+
114
+ def to_dict(self) -> dict[str, Any]:
115
+ return {k: v for k, v in self.__dict__.items() if v is not None}
116
+
117
+
118
+ @dataclass
119
+ class Correction:
120
+ """One sub-requirement inside a case (a PR).
121
+
122
+ Plans are hierarchical: a phase contains PRs, a PR contains corrections.
123
+ Each correction is independently checkable. The gate renders a
124
+ per-correction table the same way a senior reviewer does — Correction |
125
+ Result | Where checked | Status — so the actor can see which sub-requirements
126
+ are still open.
127
+ """
128
+
129
+ id: str # e.g. "PR-012.1"
130
+ requirement: str # what must be true
131
+ evidence_artifact: str = "" # what proves it (test, doc, log)
132
+ status: str = "open" # open | passed | failed | partial
133
+ notes: str = ""
134
+
135
+ def to_dict(self) -> dict[str, Any]:
136
+ # Drop empty/None values and the default status="open" so the row
137
+ # only shows fields that carry signal. The gate then overlays the
138
+ # resolved status separately when it renders the per-correction
139
+ # table (so "open" still appears when the case is failing).
140
+ out: dict[str, Any] = {}
141
+ for k, v in self.__dict__.items():
142
+ if v in (None, ""):
143
+ continue
144
+ if k == "status" and v == "open":
145
+ continue
146
+ out[k] = v
147
+ return out
148
+
149
+
150
+ def corrections_from_case(case: dict[str, Any]) -> list[Correction]:
151
+ """Pull the `corrections` list from a case dict (the plan file).
152
+
153
+ Supports two shapes for backward compat:
154
+
155
+ 1. `case["corrections"]` is already a list of dicts with the contract:
156
+ {"id": str, "requirement": str, "evidence_artifact": str, ...}
157
+ 2. `case["task"]["corrections"]` is the legacy location.
158
+
159
+ Returns [] if the case has no corrections. Empty is fine — the gate still
160
+ works against the 5 main checks; corrections just add finer granularity.
161
+ """
162
+ raw = case.get("corrections") or case.get("task", {}).get("corrections") or []
163
+ out: list[Correction] = []
164
+ for item in raw:
165
+ if not isinstance(item, dict):
166
+ continue
167
+ if "id" not in item or "requirement" not in item:
168
+ continue
169
+ out.append(
170
+ Correction(
171
+ id=str(item["id"]),
172
+ requirement=str(item["requirement"]),
173
+ evidence_artifact=str(item.get("evidence_artifact", "")),
174
+ status=str(item.get("status", "open")),
175
+ notes=str(item.get("notes", "")),
176
+ )
177
+ )
178
+ return out
179
+
180
+
181
+ def synthesize_status_assertion(
182
+ case_id: str,
183
+ correction_results: list[tuple[Correction, str | bool]],
184
+ ) -> str:
185
+ """Produce the single durable sentence the next round opens with.
186
+
187
+ Each entry is (Correction, outcome) where outcome is the resolution
188
+ status string from `_resolve_correction_status` ("passed" | "partial"
189
+ | "open" | "failed") OR a bool for legacy callers (True = passed).
190
+
191
+ Examples:
192
+ "PR-012 remains PARTIAL on PR-012.2. Do not start PR-013."
193
+ "PR-014 PASSED. Proceed to PR-015."
194
+ "PR-009 still FAILING on PR-009.3. Round 4 of 5."
195
+ """
196
+ if not correction_results:
197
+ return f"{case_id} has no corrections defined."
198
+
199
+ def _status_of(entry: tuple[Correction, str | bool]) -> str:
200
+ corr, outcome = entry
201
+ if isinstance(outcome, bool):
202
+ return "passed" if outcome else "failed"
203
+ return str(outcome or "")
204
+
205
+ # Still-actionable rows: anything that isn't a clean "passed".
206
+ outstanding = [
207
+ (corr, _status_of(entry))
208
+ for entry in correction_results
209
+ for corr in [entry[0]]
210
+ if _status_of(entry) != "passed"
211
+ ]
212
+ if not outstanding:
213
+ return f"{case_id} PASSED. Proceed to next case."
214
+
215
+ # Name the highest-priority outstanding correction (failed > open > partial).
216
+ priority = {"failed": 0, "open": 1, "partial": 2}
217
+ outstanding.sort(key=lambda pair: priority.get(pair[1], 3))
218
+ worst_id, worst_status = outstanding[0][0].id, outstanding[0][1]
219
+
220
+ if worst_status == "partial" or any(s == "partial" for _, s in outstanding):
221
+ return (
222
+ f"{case_id} remains PARTIAL on {worst_id}. "
223
+ f"Do not start next case."
224
+ )
225
+ return (
226
+ f"{case_id} still FAILING on {worst_id}. "
227
+ f"{len(outstanding)} correction(s) outstanding."
228
+ )
229
+
230
+
231
+ @dataclass
232
+ class CheckResult:
233
+ """Result of a single admission check.
234
+
235
+ Every CheckResult carries the full evidence chain so the actor — and
236
+ any future reviewer — can audit *why* this check passed or failed
237
+ without re-running anything. Reasons are short. Evidence is dense.
238
+ """
239
+
240
+ check: str
241
+ passed: bool
242
+ reason: str # one sentence, suitable for a verdict table cell
243
+ remedy: str # what the actor should do about it
244
+ code_citations: list[CodeCitation] = field(default_factory=list)
245
+ test_citations: list[TestCitation] = field(default_factory=list)
246
+ doc_citations: list[DocCitation] = field(default_factory=list)
247
+ test_masking_warnings: list[str] = field(default_factory=list)
248
+ regression: Optional[Regression] = None
249
+ status_assertion: str = "" # durable sentence for the next round
250
+ # Legacy: pre-structured check results passed an ad-hoc evidence dict.
251
+ # Preserved here so call sites that haven't been upgraded still surface
252
+ # their data in the verdict JSON. Also accepted as `evidence=` kwarg.
253
+ legacy_evidence: dict[str, Any] = field(default_factory=dict)
254
+
255
+ def __init__(
256
+ self,
257
+ check: str = "",
258
+ passed: bool = False,
259
+ reason: str = "",
260
+ remedy: str = "",
261
+ code_citations: list["CodeCitation"] | None = None,
262
+ test_citations: list["TestCitation"] | None = None,
263
+ doc_citations: list["DocCitation"] | None = None,
264
+ test_masking_warnings: list[str] | None = None,
265
+ regression: "Regression | None" = None,
266
+ status_assertion: str = "",
267
+ legacy_evidence: dict[str, Any] | None = None,
268
+ evidence: dict[str, Any] | None = None,
269
+ ):
270
+ # `evidence=` is the public alias for `legacy_evidence=`.
271
+ # Whichever is provided wins; if both, `evidence=` wins.
272
+ if evidence is not None:
273
+ legacy_evidence = dict(evidence)
274
+ elif legacy_evidence is None:
275
+ legacy_evidence = {}
276
+ self.check = check
277
+ self.passed = passed
278
+ self.reason = reason
279
+ self.remedy = remedy
280
+ self.code_citations = code_citations or []
281
+ self.test_citations = test_citations or []
282
+ self.doc_citations = doc_citations or []
283
+ self.test_masking_warnings = test_masking_warnings or []
284
+ self.regression = regression
285
+ self.status_assertion = status_assertion
286
+ self.legacy_evidence = legacy_evidence
287
+
288
+ def to_dict(self) -> dict[str, Any]:
289
+ d: dict[str, Any] = {
290
+ "check": self.check,
291
+ "passed": self.passed,
292
+ "reason": self.reason,
293
+ "remedy": self.remedy,
294
+ }
295
+ if self.code_citations:
296
+ d["code_citations"] = [c.to_dict() for c in self.code_citations]
297
+ if self.test_citations:
298
+ d["test_citations"] = [c.to_dict() for c in self.test_citations]
299
+ if self.doc_citations:
300
+ d["doc_citations"] = [c.to_dict() for c in self.doc_citations]
301
+ if self.test_masking_warnings:
302
+ d["test_masking_warnings"] = list(self.test_masking_warnings)
303
+ if self.regression is not None:
304
+ d["regression"] = self.regression.to_dict()
305
+ if self.status_assertion:
306
+ d["status_assertion"] = self.status_assertion
307
+ if self.legacy_evidence:
308
+ d["evidence"] = self.legacy_evidence
309
+ return d
310
+
311
+
312
+ # --- Actor submission -------------------------------------------------------
313
+
314
+
315
+ @dataclass
316
+ class ActorSubmission:
317
+ """What an actor claims it did this round.
318
+
319
+ `referenced_case_ids` - case IDs the actor's prompt / response mentioned
320
+ `touched_files` - files the actor claims to have written
321
+ `effects` - list of performed effects from actor's run
322
+ `diff_summary` - human description of changes
323
+ """
324
+
325
+ referenced_case_ids: list[str] = field(default_factory=list)
326
+ touched_files: list[str] = field(default_factory=list)
327
+ effects: list[dict[str, Any]] = field(default_factory=list)
328
+ diff_summary: str = ""
329
+ # Optional: corrections the actor claims to have addressed this round.
330
+ # The gate uses these together with the case's `corrections` list to
331
+ # produce the per-correction verdict table.
332
+ claimed_correction_ids: list[str] = field(default_factory=list)
333
+
334
+
335
+ # --- Per-case attempt counter -----------------------------------------------
336
+
337
+
338
+ @dataclass
339
+ class CaseAttemptState:
340
+ """Tracks attempts for a single case across rounds."""
341
+
342
+ case_id: str
343
+ attempts: int = 0
344
+ consecutive_failures: int = 0
345
+ last_failed_checks: set[str] = field(default_factory=set)
346
+ last_verdict: dict[str, Any] | None = None
347
+ history: list[dict[str, Any]] = field(default_factory=list)
348
+ # Diff interpretation of the most recent round. One of:
349
+ # "pass" — all checks passed
350
+ # "progress" — still failing but fewer checks failing than last round
351
+ # "regression" — new failures appeared this round
352
+ # "swap" — A now passes, B now fails (oscillation, not progress)
353
+ # "no_progress" — same checks still failing (stuck)
354
+ last_interpretation: str = ""
355
+ # Which corrections the actor claimed to have addressed in the most
356
+ # recent round. Drives the partial/failed split in the per-correction
357
+ # table.
358
+ last_claimed_corrections: list[str] = field(default_factory=list)
359
+ # Full structured diff from the most recent round: the verdict_diff()
360
+ # output (newly_failing / newly_passing / still_failing / swap_detected
361
+ # / interpretation). Persisted for the Observatory so every round has
362
+ # an auditable artifact of what moved.
363
+ last_verdict_diff: dict[str, Any] | None = None
364
+
365
+ def record_outcome(
366
+ self,
367
+ checks: list[CheckResult],
368
+ diff_interpretation: str = "",
369
+ verdict_diff_payload: dict[str, Any] | None = None,
370
+ ) -> None:
371
+ self.attempts += 1
372
+ failed = {c.check for c in checks if not c.passed}
373
+ self.last_interpretation = diff_interpretation
374
+ if verdict_diff_payload is not None:
375
+ self.last_verdict_diff = verdict_diff_payload
376
+
377
+ if not failed:
378
+ # Clean pass — reset everything.
379
+ self.consecutive_failures = 0
380
+ self.last_failed_checks = set()
381
+ elif diff_interpretation == "progress":
382
+ # Still partial, but improving (fewer fails than last round).
383
+ # Do NOT advance the escalation counter — keep iterating quietly.
384
+ self.last_failed_checks = failed
385
+ elif diff_interpretation == "swap":
386
+ # A→B→A oscillation. Real progress is not happening; count it
387
+ # as a stuck round.
388
+ self.consecutive_failures += 1
389
+ self.last_failed_checks = failed
390
+ else:
391
+ # "no_progress", "regression", or any first failure.
392
+ self.consecutive_failures += 1
393
+ self.last_failed_checks = failed
394
+
395
+ self.history.append(
396
+ {
397
+ "round": self.attempts,
398
+ "failed_checks": sorted(failed),
399
+ "consecutive_failures": self.consecutive_failures,
400
+ "interpretation": diff_interpretation or "n/a",
401
+ }
402
+ )
403
+
404
+ @property
405
+ def surface_to_user(self) -> bool:
406
+ """User should be alerted (round 3 of same case stuck/swap/regression).
407
+
408
+ NOT triggered by "progress" — partial-but-improving rounds keep
409
+ iterating between the gate and the actor without bothering the user.
410
+ """
411
+ if self.consecutive_failures != 3:
412
+ return False
413
+ return self.last_interpretation in {"no_progress", "swap", "regression", ""}
414
+
415
+ @property
416
+ def hard_block(self) -> bool:
417
+ """Actor should be hard-blocked (round 5 of same case stuck)."""
418
+ return self.consecutive_failures >= 5
419
+
420
+ @property
421
+ def oscillating(self) -> bool:
422
+ """Same checks failing 3+ times = stuck, not progressing."""
423
+ return (
424
+ self.consecutive_failures >= 3
425
+ and len(self.last_failed_checks) > 0
426
+ )
427
+
428
+
429
+ # --- Plan hash ---------------------------------------------------------------
430
+
431
+
432
+ def _pack_cases(pack: Any) -> dict:
433
+ """Return the pack's cases as a dict keyed by case_id.
434
+
435
+ Tolerant of both shapes:
436
+ - None (caller didn't provide a pack) -> empty dict
437
+ - dict-shaped pack (e.g. from JSON manifest): pack["cases"] is the dict
438
+ - object/dataclass-shaped pack: pack.cases is the dict
439
+ """
440
+ if pack is None:
441
+ return {}
442
+ cases = pack["cases"] if isinstance(pack, dict) else pack.cases
443
+ # Some test fixtures pass cases as a list; normalize to dict.
444
+ if isinstance(cases, list):
445
+ return {c.get("case_id") or c.get("id"): c for c in cases}
446
+ return cases or {}
447
+
448
+
449
+ def plan_hash(pack: Any) -> str:
450
+ """Stable hash of the pack's plan content.
451
+
452
+ Used to detect stale plans. If the actor is reading a different plan than
453
+ what Cosmos knows about, the gate will flag it.
454
+ """
455
+ case_payload = json.dumps(
456
+ sorted(
457
+ (
458
+ {
459
+ "id": c.get("case_id"),
460
+ "task": c.get("task"),
461
+ "expected": c.get("expected"),
462
+ }
463
+ for c in _pack_cases(pack).values()
464
+ ),
465
+ key=lambda d: str(d.get("id") or ""),
466
+ ),
467
+ sort_keys=True,
468
+ default=str,
469
+ ).encode("utf-8")
470
+ return f"plan_{hashlib.sha256(case_payload).hexdigest()[:16]}"
471
+
472
+
473
+ # --- Five checks ------------------------------------------------------------
474
+
475
+
476
+ def check_plan_freshness(
477
+ pack: Any,
478
+ submission: ActorSubmission,
479
+ current_plan_hash: str,
480
+ ) -> CheckResult:
481
+ """Actor references current plan cases, not stale ones."""
482
+ referenced = set(submission.referenced_case_ids)
483
+ valid = set(_pack_cases(pack).keys())
484
+
485
+ if not referenced:
486
+ return CheckResult(
487
+ check="plan_freshness",
488
+ passed=False,
489
+ reason="Actor did not reference any case IDs in its submission.",
490
+ remedy=(
491
+ "Reference the case_id from the active case file (look in "
492
+ "the pack's cases/ directory). If no case applies, the work "
493
+ "is out of scope — see scope check."
494
+ ),
495
+ evidence={"referenced_case_ids": [], "valid_case_ids": sorted(valid)},
496
+ )
497
+
498
+ stale = referenced - valid
499
+ if stale:
500
+ return CheckResult(
501
+ check="plan_freshness",
502
+ passed=False,
503
+ reason=(
504
+ f"Actor referenced case ID(s) that do not exist in the "
505
+ f"current plan: {sorted(stale)}."
506
+ ),
507
+ remedy=(
508
+ "Re-read the active case file. The plan may have been "
509
+ "updated since the actor's last read."
510
+ ),
511
+ evidence={
512
+ "stale_case_ids": sorted(stale),
513
+ "valid_case_ids": sorted(valid),
514
+ "current_plan_hash": current_plan_hash,
515
+ },
516
+ )
517
+
518
+ return CheckResult(
519
+ check="plan_freshness",
520
+ passed=True,
521
+ reason=f"Actor references valid case(s): {sorted(referenced)}.",
522
+ remedy="",
523
+ evidence={
524
+ "referenced_case_ids": sorted(referenced),
525
+ "current_plan_hash": current_plan_hash,
526
+ },
527
+ )
528
+
529
+
530
+ def check_case_coverage(
531
+ pack: Any,
532
+ case_id: str,
533
+ submission: ActorSubmission,
534
+ ) -> CheckResult:
535
+ """Touched files match the case's task scope_refs.
536
+
537
+ A case's `task.scope_refs` lists the cosmos IDs of in-scope resources.
538
+ Every file the actor touched should be attributable to one of those
539
+ resources — either directly, or by traceable path mapping.
540
+ """
541
+ case = _pack_cases(pack).get(case_id)
542
+ if case is None:
543
+ return CheckResult(
544
+ check="case_coverage",
545
+ passed=False,
546
+ reason=f"Case {case_id!r} not found in pack.",
547
+ remedy="Use a case_id from the active plan.",
548
+ evidence={"case_id": case_id},
549
+ )
550
+
551
+ task = case.get("task", {})
552
+ scope_refs = set(task.get("scope_refs", []))
553
+
554
+ # The actor's touched files should bind to scope_refs via file path ->
555
+ # cosmos ID mapping. The launch wrapper's adapter layer produces this
556
+ # mapping; for now we accept the actor's claim that touched files are
557
+ # covered by the case's scope. The stronger guarantee comes from
558
+ # check_scope (in-scope) and the authorization gateway (allowed).
559
+ if not submission.touched_files:
560
+ return CheckResult(
561
+ check="case_coverage",
562
+ passed=True,
563
+ reason="No files touched this round.",
564
+ remedy="",
565
+ evidence={"touched_files": [], "scope_refs": sorted(scope_refs)},
566
+ )
567
+
568
+ return CheckResult(
569
+ check="case_coverage",
570
+ passed=True,
571
+ reason=(
572
+ f"{len(submission.touched_files)} file(s) touched, "
573
+ f"bound to case {case_id!r} with {len(scope_refs)} scope ref(s)."
574
+ ),
575
+ remedy="",
576
+ evidence={
577
+ "touched_files": submission.touched_files,
578
+ "scope_refs": sorted(scope_refs),
579
+ },
580
+ )
581
+
582
+
583
+ def check_running_code(
584
+ pack: Any,
585
+ case_id: str,
586
+ submission: ActorSubmission,
587
+ test_runner: dict[str, Any] | None,
588
+ baseline_path: Path | None,
589
+ workspace: Path | None,
590
+ ) -> CheckResult:
591
+ """Test suite passes against the actor's claimed effects.
592
+
593
+ The test runner is pack-declared. The actor's claimed effects are applied
594
+ to a scratch workspace, the test command is run, and the result compared
595
+ to the baseline (which was captured when the case was authored and is
596
+ pack-admin-only — the actor cannot overwrite it).
597
+ """
598
+ if test_runner is None:
599
+ return CheckResult(
600
+ check="running_code",
601
+ passed=False,
602
+ reason=(
603
+ f"Case {case_id!r} has no test runner declared in the pack. "
604
+ "Cannot verify running code."
605
+ ),
606
+ remedy=(
607
+ "Add a `tests` block to the pack manifest with runner, "
608
+ "command, and baseline. See OPERATOR-GUIDE.md §Admission gate."
609
+ ),
610
+ evidence={"case_id": case_id},
611
+ )
612
+
613
+ if workspace is None or baseline_path is None:
614
+ return CheckResult(
615
+ check="running_code",
616
+ passed=False,
617
+ reason="Test runner declared but no workspace/baseline provided.",
618
+ remedy=(
619
+ "Run the gate through cosmos_launch with --enforce-running-code; "
620
+ "the wrapper provides workspace and baseline paths."
621
+ ),
622
+ evidence={
623
+ "runner": test_runner.get("runner"),
624
+ "command": test_runner.get("command"),
625
+ },
626
+ )
627
+
628
+ runner_kind = test_runner.get("runner", "command")
629
+ if runner_kind != "command":
630
+ return CheckResult(
631
+ check="running_code",
632
+ passed=False,
633
+ reason=f"Unsupported test runner kind: {runner_kind!r}.",
634
+ remedy="Only 'command' runner is supported in Cosmos 1.5.",
635
+ evidence={"runner": runner_kind},
636
+ )
637
+
638
+ command = test_runner.get("command")
639
+ if not command:
640
+ return CheckResult(
641
+ check="running_code",
642
+ passed=False,
643
+ reason="Test runner command is empty.",
644
+ remedy="Set `tests.command` in the pack manifest.",
645
+ evidence={"case_id": case_id},
646
+ )
647
+
648
+ timeout = int(test_runner.get("timeout_seconds", 120))
649
+
650
+ try:
651
+ completed = subprocess.run(
652
+ command,
653
+ shell=True,
654
+ cwd=str(workspace),
655
+ capture_output=True,
656
+ text=True,
657
+ timeout=timeout,
658
+ )
659
+ except subprocess.TimeoutExpired as e:
660
+ return CheckResult(
661
+ check="running_code",
662
+ passed=False,
663
+ reason=f"Test runner timed out after {timeout}s.",
664
+ remedy=(
665
+ "Reduce the test scope, increase timeout_seconds in the pack, "
666
+ "or fix the actor's work to not cause test hangs."
667
+ ),
668
+ evidence={"command": command, "timeout_seconds": timeout},
669
+ )
670
+
671
+ # Compare against baseline
672
+ actual_hash = _hash_test_output(completed.stdout, completed.stderr, completed.returncode)
673
+ baseline_data = _read_baseline(baseline_path)
674
+
675
+ if baseline_data is None:
676
+ # No baseline yet — accept the first run as baseline (admin only
677
+ # writes it on first run; this branch should not be hit in normal flow
678
+ # because the pack admin is expected to seed the baseline).
679
+ return CheckResult(
680
+ check="running_code",
681
+ passed=True,
682
+ reason=(
683
+ "No test baseline recorded. First run accepted as baseline. "
684
+ "Pack admin should record this output as the baseline."
685
+ ),
686
+ remedy="",
687
+ evidence={
688
+ "returncode": completed.returncode,
689
+ "output_hash": actual_hash,
690
+ "stdout_tail": completed.stdout[-500:],
691
+ },
692
+ )
693
+
694
+ expected_hash = baseline_data.get("output_hash")
695
+ if actual_hash == expected_hash:
696
+ return CheckResult(
697
+ check="running_code",
698
+ passed=True,
699
+ reason="Test output matches baseline.",
700
+ remedy="",
701
+ evidence={
702
+ "output_hash": actual_hash,
703
+ "returncode": completed.returncode,
704
+ },
705
+ )
706
+
707
+ return CheckResult(
708
+ check="running_code",
709
+ passed=False,
710
+ reason=(
711
+ f"Test output diverged from baseline. "
712
+ f"Expected {expected_hash[:12]}, got {actual_hash[:12]}."
713
+ ),
714
+ remedy=(
715
+ "If the divergence is intentional (the case is meant to change "
716
+ "test output), the pack admin must update the baseline. "
717
+ "Otherwise, fix the actor's work to restore expected output."
718
+ ),
719
+ evidence={
720
+ "expected_hash": expected_hash,
721
+ "actual_hash": actual_hash,
722
+ "returncode": completed.returncode,
723
+ "stdout_tail": completed.stdout[-500:],
724
+ "stderr_tail": completed.stderr[-500:],
725
+ },
726
+ )
727
+
728
+
729
+ def check_scope(
730
+ pack: Any,
731
+ case_id: str,
732
+ submission: ActorSubmission,
733
+ scope_to_paths: Callable[[list[str]], set[str]] | None = None,
734
+ ) -> CheckResult:
735
+ """Touched files are in-scope for the case.
736
+
737
+ The case's `task.scope_refs` lists cosmos IDs of in-scope resources. The
738
+ actor's touched files (paths) must all be attributable to one of those
739
+ resources. The mapping function `scope_to_paths` is supplied by the
740
+ caller (typically from the graph's resource -> location mapping).
741
+ """
742
+ case = _pack_cases(pack).get(case_id)
743
+ if case is None:
744
+ return CheckResult(
745
+ check="scope",
746
+ passed=False,
747
+ reason=f"Case {case_id!r} not found in pack.",
748
+ remedy="Use a case_id from the active plan.",
749
+ evidence={"case_id": case_id},
750
+ )
751
+
752
+ if scope_to_paths is None:
753
+ # Without a mapping, we can't verify scope mechanically. Treat as
754
+ # inconclusive and let the user/operator decide.
755
+ return CheckResult(
756
+ check="scope",
757
+ passed=True,
758
+ reason=(
759
+ "No scope->path mapping provided; cannot verify mechanically. "
760
+ "Scope check deferred to operator review."
761
+ ),
762
+ remedy="",
763
+ evidence={"touched_files": submission.touched_files},
764
+ )
765
+
766
+ task = case.get("task", {})
767
+ scope_refs = task.get("scope_refs", [])
768
+ in_scope_paths = scope_to_paths(scope_refs)
769
+
770
+ out_of_scope = [
771
+ f for f in submission.touched_files if f not in in_scope_paths
772
+ ]
773
+ if out_of_scope:
774
+ return CheckResult(
775
+ check="scope",
776
+ passed=False,
777
+ reason=(
778
+ f"{len(out_of_scope)} file(s) are out of scope for case "
779
+ f"{case_id!r}: {out_of_scope}"
780
+ ),
781
+ remedy=(
782
+ "Move these files into the case's scope_refs (update the "
783
+ "case), or remove these changes from the actor's submission."
784
+ ),
785
+ evidence={
786
+ "out_of_scope": out_of_scope,
787
+ "in_scope_paths": sorted(in_scope_paths),
788
+ },
789
+ )
790
+
791
+ return CheckResult(
792
+ check="scope",
793
+ passed=True,
794
+ reason=(
795
+ f"All {len(submission.touched_files)} touched file(s) are in "
796
+ f"scope for case {case_id!r}."
797
+ ),
798
+ remedy="",
799
+ evidence={"in_scope_paths": sorted(in_scope_paths)},
800
+ )
801
+
802
+
803
+ def check_cross_area_disruption(
804
+ pack: Any,
805
+ case_id: str,
806
+ submission: ActorSubmission,
807
+ previously_passing_cases: list[str] | None = None,
808
+ re_run_case: Callable[[str], bool] | None = None,
809
+ ) -> CheckResult:
810
+ """Previously-passing cases still pass.
811
+
812
+ Catches the "fix A by breaking B" pattern. If the actor claims to have
813
+ changed something, every case that was previously passing should still
814
+ pass after the change.
815
+ """
816
+ if not previously_passing_cases:
817
+ return CheckResult(
818
+ check="cross_area_disruption",
819
+ passed=True,
820
+ reason="No previously-passing cases to re-check.",
821
+ remedy="",
822
+ evidence={"previously_passing_cases": []},
823
+ )
824
+
825
+ if re_run_case is None:
826
+ return CheckResult(
827
+ check="cross_area_disruption",
828
+ passed=False,
829
+ reason=(
830
+ "Cross-area disruption check requires a re-run function but "
831
+ "none was provided."
832
+ ),
833
+ remedy=(
834
+ "Operator: ensure the gate is invoked with a re_run_case "
835
+ "callback (typically re-running check_running_code for each "
836
+ "previously-passing case)."
837
+ ),
838
+ evidence={"previously_passing_cases": previously_passing_cases},
839
+ )
840
+
841
+ broken: list[str] = []
842
+ for other_case_id in previously_passing_cases:
843
+ if other_case_id == case_id:
844
+ continue
845
+ try:
846
+ still_passes = re_run_case(other_case_id)
847
+ except Exception as e: # noqa: BLE001
848
+ broken.append(other_case_id)
849
+ continue
850
+ if not still_passes:
851
+ broken.append(other_case_id)
852
+
853
+ if broken:
854
+ return CheckResult(
855
+ check="cross_area_disruption",
856
+ passed=False,
857
+ reason=(
858
+ f"Actor's changes broke {len(broken)} previously-passing "
859
+ f"case(s): {broken}. This is the 'fix A by breaking B' "
860
+ f"pattern."
861
+ ),
862
+ remedy=(
863
+ "Revert the actor's changes that touched the broken cases' "
864
+ "scope, or update the broken cases' plan to accommodate the "
865
+ "new state (this is a plan change and must be recorded)."
866
+ ),
867
+ evidence={"broken_cases": broken},
868
+ )
869
+
870
+ return CheckResult(
871
+ check="cross_area_disruption",
872
+ passed=True,
873
+ reason=(
874
+ f"All {len(previously_passing_cases)} previously-passing case(s) "
875
+ f"still pass."
876
+ ),
877
+ remedy="",
878
+ evidence={"previously_passing_cases": previously_passing_cases},
879
+ )
880
+
881
+
882
+ # --- Verdict rendering ------------------------------------------------------
883
+
884
+
885
+ def render_verdict(
886
+ case_id: str,
887
+ checks: list[CheckResult],
888
+ plan_hash_value: str,
889
+ case_state: CaseAttemptState,
890
+ pack: Any,
891
+ corrections: list[Correction] | None = None,
892
+ ) -> dict[str, Any]:
893
+ """Render the verdict as JSON (markdown is derived atomically).
894
+
895
+ Always returns the same shape regardless of pass/fail so downstream
896
+ consumers (observatory, audit log) don't have to branch.
897
+ """
898
+ verdict_id = f"verdict_{uuid.uuid4().hex[:16]}"
899
+ overall_pass = all(c.passed for c in checks)
900
+ failed_checks = [c for c in checks if not c.passed]
901
+
902
+ # --- Per-correction table ------------------------------------------------
903
+ # Map correction_id -> CheckResult check name that examined it, by
904
+ # matching the correction id against the case_id and the actor's claim.
905
+ # A correction is "verified" if the case overall passed and the actor
906
+ # claimed it this round, OR if a specific check explicitly cited it.
907
+ correction_rows: list[dict[str, Any]] = []
908
+ corrs = corrections or []
909
+ claimed: list[str] = []
910
+ if corrs:
911
+ # submission may not be available here; fall back to case_state
912
+ # (which records what was claimed last round).
913
+ sub_claims = getattr(case_state, "last_claimed_corrections", None)
914
+ if sub_claims:
915
+ claimed = sub_claims
916
+ for c in corrs:
917
+ row = c.to_dict()
918
+ row["status"] = _resolve_correction_status(
919
+ c, checks, case_state, claimed
920
+ )
921
+ correction_rows.append(row)
922
+
923
+ # --- Status assertion ----------------------------------------------------
924
+ overall_status_label = _derive_overall_status_label(correction_rows, case_state)
925
+
926
+ return {
927
+ "verdict_id": verdict_id,
928
+ "case_id": case_id,
929
+ "plan_hash": plan_hash_value,
930
+ "round": case_state.attempts,
931
+ "verdict": "pass" if overall_pass else "fail",
932
+ "overall_status_label": overall_status_label,
933
+ "per_check": [c.to_dict() for c in checks],
934
+ "corrections": correction_rows,
935
+ "summary": {
936
+ "passed": sum(1 for c in checks if c.passed),
937
+ "failed": len(failed_checks),
938
+ "total": len(checks),
939
+ "corrections_passed": sum(
940
+ 1 for r in correction_rows if r.get("status") == "passed"
941
+ ),
942
+ # "failed" bucket covers any row that isn't claimed-and-resolved.
943
+ # That includes explicit "failed" rows (rare — only when a check
944
+ # targets this correction) and "open" rows (unclaimed corrections
945
+ # when the case is failing). Both are still-actionable items the
946
+ # actor owes work on, so they share a single summary counter.
947
+ "corrections_failed": sum(
948
+ 1 for r in correction_rows
949
+ if r.get("status") in ("failed", "open")
950
+ ),
951
+ "corrections_partial": sum(
952
+ 1 for r in correction_rows if r.get("status") == "partial"
953
+ ),
954
+ "corrections_total": len(correction_rows),
955
+ },
956
+ "attempts_for_case": case_state.attempts,
957
+ "consecutive_failures": case_state.consecutive_failures,
958
+ "oscillating": case_state.oscillating,
959
+ "surface_to_user": case_state.surface_to_user,
960
+ "hard_block": case_state.hard_block,
961
+ "actor_guidance": _actor_guidance(failed_checks, case_state),
962
+ "pack_environment_id": getattr(pack, "environment_id", None),
963
+ }
964
+
965
+
966
+ def _resolve_correction_status(
967
+ correction: Correction,
968
+ checks: list[CheckResult],
969
+ case_state: CaseAttemptState,
970
+ claimed_corrections: list[str] | None = None,
971
+ ) -> str:
972
+ """Resolve a correction's status for this round.
973
+
974
+ The resolution rules (matching the comment in test 12):
975
+ - "passed" if the case overall passed (all checks green), or if the
976
+ correction was claimed this round and no failing check
977
+ specifically targets it.
978
+ - "partial" if the correction was claimed this round and a failing
979
+ check explicitly targets it (the actor worked on it but
980
+ a related check still fails).
981
+ - "open" if the correction was not claimed this round (regardless
982
+ of which checks failed) — the actor didn't even address
983
+ it, so it remains open work.
984
+ """
985
+ if not checks:
986
+ return correction.status or "open"
987
+ overall_pass = all(c.passed for c in checks)
988
+ if overall_pass:
989
+ return "passed"
990
+ claimed = bool(correction.id in (claimed_corrections or []))
991
+ if not claimed:
992
+ return "open"
993
+ # Claimed but case still failed. Partial only if a failing check
994
+ # explicitly targets this correction id; otherwise the failure was
995
+ # somewhere else and this correction is effectively done.
996
+ failing = [c for c in checks if not c.passed]
997
+ failed_ids: set[str] = set()
998
+ for c in failing:
999
+ # CheckResult doesn't currently carry per-correction targets, so
1000
+ # by default no failing check is correction-specific. Hook left
1001
+ # here for future per-check correction targeting.
1002
+ target = getattr(c, "targets_correction_ids", None) or []
1003
+ failed_ids.update(target)
1004
+ if correction.id in failed_ids:
1005
+ return "partial"
1006
+ return "passed"
1007
+
1008
+
1009
+ def _derive_overall_status_label(
1010
+ correction_rows: list[dict[str, Any]],
1011
+ case_state: CaseAttemptState,
1012
+ ) -> str:
1013
+ """Derive the durable status label the next round opens with.
1014
+
1015
+ Same logic as `synthesize_status_assertion` but works off the rendered
1016
+ verdict rows.
1017
+ """
1018
+ if not correction_rows:
1019
+ return ""
1020
+ # Anything that isn't "passed" is still-actionable. "open" rows are
1021
+ # unclaimed corrections when the case is failing, and they should
1022
+ # pull the overall label off PASS just like "failed" / "partial" do.
1023
+ failed = [
1024
+ r for r in correction_rows
1025
+ if r.get("status") in ("failed", "partial", "open")
1026
+ ]
1027
+ if not failed:
1028
+ return "PASS"
1029
+ if any(r.get("status") == "partial" for r in failed):
1030
+ return "PARTIAL"
1031
+ return "FAIL"
1032
+
1033
+
1034
+ def _format_citation_short(cite: dict[str, Any]) -> str:
1035
+ """Compact `path:line` string from a citation dict. Falls back to path only."""
1036
+ path = cite.get("path", "?")
1037
+ line = cite.get("line")
1038
+ return f"`{path}:{line}`" if line else f"`{path}`"
1039
+
1040
+
1041
+ def _ci_package_counts(verdict: dict[str, Any]) -> list[tuple[str, int, int]]:
1042
+ """Aggregate test_citations across per_check into (package, passing, total).
1043
+
1044
+ We count each test_citation as one assertion. Passing/Total is currently
1045
+ a coarse per-package count derived from the citation's `masks` flag and
1046
+ the verdict's overall pass status. Returns [] when there are no test
1047
+ citations.
1048
+ """
1049
+ counts: dict[str, list[int]] = {}
1050
+ overall_pass = all(c["passed"] for c in verdict["per_check"])
1051
+ for c in verdict["per_check"]:
1052
+ for cite in c.get("test_citations", []) or []:
1053
+ pkg = cite.get("package") or "tests"
1054
+ entry = counts.setdefault(pkg, [0, 0])
1055
+ entry[1] += 1 # total
1056
+ # Heuristic: a citation is "passing" if the parent check passes,
1057
+ # unless the citation is itself flagged as a masker (masks=True).
1058
+ if overall_pass and not cite.get("masks"):
1059
+ entry[0] += 1
1060
+ return sorted(((pkg, p, t) for pkg, (p, t) in counts.items()))
1061
+
1062
+
1063
+ def _concrete_action(
1064
+ overall_label: str,
1065
+ interpretation: str,
1066
+ hard_block: bool,
1067
+ surface_to_user: bool,
1068
+ oscillating: bool,
1069
+ ) -> str:
1070
+ """One-line concrete directive that an agent (Claude Code) can act on."""
1071
+ if hard_block:
1072
+ return (
1073
+ "🛑 HARD BLOCK — do not proceed. Same case has failed 5 rounds in a "
1074
+ "row. Re-plan the case before re-running."
1075
+ )
1076
+ if overall_label == "PASS":
1077
+ if interpretation == "swap":
1078
+ return (
1079
+ "✅ PASS — but a swap was detected. Merge is allowed; the diff "
1080
+ "below shows what was exchanged."
1081
+ )
1082
+ if interpretation == "progress":
1083
+ return (
1084
+ "✅ PASS with progress — at least one previously-failing check "
1085
+ "now passes. Safe to proceed to the next case."
1086
+ )
1087
+ if interpretation in ("", "pass"):
1088
+ return (
1089
+ "✅ PASS — all checks green this round. Safe to proceed to the "
1090
+ "next case."
1091
+ )
1092
+ return "✅ PASS — proceed to the next case."
1093
+ if overall_label == "PARTIAL":
1094
+ return (
1095
+ "⚠️ PARTIAL — some checks still fail. Do not start the next case; "
1096
+ "address the remaining issues and re-run this case."
1097
+ )
1098
+ # FAIL
1099
+ if surface_to_user:
1100
+ return (
1101
+ "❌ FAIL — user attention required (round 3+ of the same case). "
1102
+ "See per-issue table for blockers and remedies."
1103
+ )
1104
+ if oscillating:
1105
+ return (
1106
+ "❌ FAIL — oscillating. The same checks are failing repeatedly. "
1107
+ "Try a different strategy before re-running."
1108
+ )
1109
+ if interpretation == "swap":
1110
+ return (
1111
+ "❌ FAIL — regression / swap detected. New failures appeared or "
1112
+ "previously-passing checks now fail. Do not proceed; re-derive "
1113
+ "the failing check before re-running."
1114
+ )
1115
+ if interpretation == "regression":
1116
+ return (
1117
+ "❌ FAIL — regression. A previously-passing check now fails. Do "
1118
+ "not proceed; re-derive the failing check before re-running."
1119
+ )
1120
+ return (
1121
+ "❌ FAIL — re-run the failing checks and stop. Do not start the "
1122
+ "next case until this case is green."
1123
+ )
1124
+
1125
+
1126
+ def render_verdict_markdown(verdict: dict[str, Any]) -> str:
1127
+ """Render the verdict as a senior-reviewer-style markdown report.
1128
+
1129
+ Always derived from the JSON verdict, so the JSON and the markdown
1130
+ cannot disagree. Sections (in order):
1131
+
1132
+ 1. Concrete-action header line ("✅ PASS — proceed to next case", etc.)
1133
+ 2. Run summary table (verdict_id, case_id, plan_hash, round, totals)
1134
+ 3. Escalation flags (oscillating / surface_to_user / hard_block) when set
1135
+ 4. Per-issue table (failed check -> requirement, code ref, status, why)
1136
+ 5. CI section (per-package test_citation counts)
1137
+ 6. Non-blocking discrepancies (from verdict["non_blocking"] or
1138
+ per-check test_masking_warnings)
1139
+ 7. Per-check deep-dive (code refs, test refs, masking, regression, docs)
1140
+ 8. Verdict diff interpretation table (when verdict_diff is present)
1141
+ 9. Mandatory stop release (when overall PASS and next_case is known)
1142
+ 10. Actor guidance (preserved as last section)
1143
+ """
1144
+ lines: list[str] = []
1145
+ overall_label = verdict.get("overall_status_label") or verdict["verdict"].upper()
1146
+ interpretation = verdict.get("interpretation", "")
1147
+ hard_block = bool(verdict.get("hard_block"))
1148
+ surface_to_user = bool(verdict.get("surface_to_user"))
1149
+ oscillating = bool(verdict.get("oscillating"))
1150
+
1151
+ # 1. Concrete-action header line ---------------------------------------
1152
+ lines.append(
1153
+ f"**Verdict: {_concrete_action(overall_label, interpretation, hard_block, surface_to_user, oscillating)}**"
1154
+ )
1155
+ lines.append("")
1156
+
1157
+ # 2. Run summary -------------------------------------------------------
1158
+ lines.append("## Run summary")
1159
+ lines.append("")
1160
+ lines.append("| Field | Value |")
1161
+ lines.append("|---|---|")
1162
+ lines.append(f"| verdict_id | `{verdict['verdict_id']}` |")
1163
+ lines.append(f"| case_id | `{verdict['case_id']}` |")
1164
+ lines.append(f"| plan_hash | `{verdict['plan_hash']}` |")
1165
+ lines.append(f"| round | {verdict['round']} |")
1166
+ lines.append(
1167
+ f"| checks | {verdict['summary']['passed']}/"
1168
+ f"{verdict['summary']['total']} passed |"
1169
+ )
1170
+ if verdict["summary"].get("corrections_total", 0):
1171
+ lines.append(
1172
+ f"| corrections | "
1173
+ f"{verdict['summary']['corrections_passed']}/"
1174
+ f"{verdict['summary']['corrections_total']} passed |"
1175
+ )
1176
+ lines.append(f"| consecutive_failures | {verdict['consecutive_failures']} |")
1177
+ lines.append(f"| interpretation | `{interpretation or '(none)'}` |")
1178
+ if verdict.get("pack_environment_id"):
1179
+ lines.append(f"| pack_environment_id | `{verdict['pack_environment_id']}` |")
1180
+ lines.append("")
1181
+
1182
+ # 3. Escalation flags --------------------------------------------------
1183
+ escalation: list[str] = []
1184
+ if oscillating:
1185
+ escalation.append("⚠️ oscillating (same checks failing repeatedly)")
1186
+ if surface_to_user:
1187
+ escalation.append("📢 surface_to_user (round 3 of same case)")
1188
+ if hard_block:
1189
+ escalation.append("🛑 hard_block (round 5 of same case)")
1190
+ if escalation:
1191
+ lines.append("**Escalation**: " + " · ".join(escalation))
1192
+ lines.append("")
1193
+
1194
+ # --- Per-correction table (the reviewer-style table) -------------------
1195
+ if verdict.get("corrections"):
1196
+ lines.append("## Per-correction table")
1197
+ lines.append("")
1198
+ lines.append("| Correction | Requirement | Where checked | Status |")
1199
+ lines.append("|---|---|---|---|")
1200
+ for row in verdict["corrections"]:
1201
+ status = row.get("status", "open")
1202
+ icon = {
1203
+ "passed": "✅ PASS",
1204
+ "failed": "❌ FAIL",
1205
+ "partial": "⚠️ PARTIAL",
1206
+ "open": "🟡 OPEN",
1207
+ }.get(status, status)
1208
+ req = row.get("requirement", "").replace("|", "\\|")
1209
+ where = row.get("evidence_artifact", "—") or "—"
1210
+ where = where.replace("|", "\\|")
1211
+ lines.append(
1212
+ f"| `{row.get('id', '?')}` | {req} | {where} | {icon} |"
1213
+ )
1214
+ lines.append("")
1215
+
1216
+ # 4. Per-issue table (failed check -> requirement / code ref / why) ---
1217
+ failed_checks = [c for c in verdict["per_check"] if not c["passed"]]
1218
+ if failed_checks:
1219
+ lines.append("## Per-issue table")
1220
+ lines.append("")
1221
+ lines.append(
1222
+ "| Issue | Requirement | Where checked | Status | Reason |"
1223
+ )
1224
+ lines.append("|---|---|---|---|---|")
1225
+ for c in failed_checks:
1226
+ check = (c.get("check", "?") or "?").replace("|", "\\|")
1227
+ reason = (c.get("reason", "") or "").replace("|", "\\|")
1228
+ status_assertion = c.get("status_assertion") or ""
1229
+ requirement = status_assertion.replace("|", "\\|") if status_assertion else check
1230
+ first_cite = ""
1231
+ if c.get("code_citations"):
1232
+ first_cite = _format_citation_short(c["code_citations"][0])
1233
+ elif c.get("test_citations"):
1234
+ first_cite = _format_citation_short(c["test_citations"][0])
1235
+ elif c.get("doc_citations"):
1236
+ first_cite = _format_citation_short(c["doc_citations"][0])
1237
+ first_cite = first_cite or "—"
1238
+ lines.append(
1239
+ f"| `{check}` | {requirement} | {first_cite} | "
1240
+ f"❌ FAIL | {reason} |"
1241
+ )
1242
+ lines.append("")
1243
+
1244
+ # 5. CI section -------------------------------------------------------
1245
+ pkg_counts = _ci_package_counts(verdict)
1246
+ if pkg_counts:
1247
+ lines.append("## CI")
1248
+ lines.append("")
1249
+ lines.append("| Package | Pass | Total |")
1250
+ lines.append("|---|---|---|")
1251
+ for pkg, p, t in pkg_counts:
1252
+ lines.append(f"| `{pkg}` | {p} | {t} |")
1253
+ lines.append("")
1254
+ if all(c["passed"] for c in verdict["per_check"]):
1255
+ lines.append("Typecheck ✅ · Lint ✅ · Tests ✅ · Build ✅")
1256
+ else:
1257
+ lines.append("Typecheck ❌ / pending · Lint ❌ / pending · Tests ❌ / pending · Build ❌ / pending")
1258
+ lines.append("")
1259
+
1260
+ # 6. Non-blocking discrepancies --------------------------------------
1261
+ non_blocking: list[str] = list(verdict.get("non_blocking") or [])
1262
+ for c in verdict["per_check"]:
1263
+ for w in c.get("test_masking_warnings", []) or []:
1264
+ non_blocking.append(f"`{c.get('check', '?')}`: {w}")
1265
+ if non_blocking:
1266
+ lines.append("## Non-blocking discrepancies")
1267
+ lines.append("")
1268
+ lines.append(
1269
+ "These do not block merge. Fix them in a follow-up if convenient, "
1270
+ "or leave for the next pass."
1271
+ )
1272
+ lines.append("")
1273
+ for n in non_blocking:
1274
+ lines.append(f"- {n}")
1275
+ lines.append("")
1276
+
1277
+ # --- Per-check results (with code refs, masking, regression) ------------
1278
+ lines.append("## Per-check results")
1279
+ lines.append("")
1280
+ for c in verdict["per_check"]:
1281
+ icon = "✅" if c["passed"] else "❌"
1282
+ lines.append(f"### {icon} {c['check']}")
1283
+ lines.append("")
1284
+ lines.append(f"**Reason**: {c['reason']}")
1285
+ if c.get("status_assertion"):
1286
+ lines.append("")
1287
+ lines.append(f"**Status assertion**: {c['status_assertion']}")
1288
+ if not c["passed"] and c["remedy"]:
1289
+ lines.append("")
1290
+ lines.append(f"**Remedy**: {c['remedy']}")
1291
+
1292
+ # Code citations
1293
+ if c.get("code_citations"):
1294
+ lines.append("")
1295
+ lines.append("**Code references**:")
1296
+ for cite in c["code_citations"]:
1297
+ loc = cite.get("path", "?")
1298
+ if cite.get("line"):
1299
+ loc += f":{cite['line']}"
1300
+ excerpt = cite.get("excerpt", "")
1301
+ lines.append(f"- `{loc}` — {excerpt}" if excerpt else f"- `{loc}`")
1302
+
1303
+ # Test citations
1304
+ if c.get("test_citations"):
1305
+ lines.append("")
1306
+ lines.append("**Test references**:")
1307
+ for cite in c["test_citations"]:
1308
+ loc = cite.get("path", "?")
1309
+ if cite.get("line"):
1310
+ loc += f":{cite['line']}"
1311
+ name = cite.get("name", "")
1312
+ behavior = cite.get("behavior", "")
1313
+ mask_note = " _(masks)_" if cite.get("masks") else ""
1314
+ ref = f"`{loc}`"
1315
+ if name:
1316
+ ref += f" :: `{name}`"
1317
+ lines.append(f"- {ref} — {behavior}{mask_note}")
1318
+
1319
+ # Test masking warnings
1320
+ if c.get("test_masking_warnings"):
1321
+ lines.append("")
1322
+ lines.append("**Test masking warnings**:")
1323
+ for w in c["test_masking_warnings"]:
1324
+ lines.append(f"- ⚠️ {w}")
1325
+
1326
+ # Regression spec
1327
+ if c.get("regression"):
1328
+ reg = c["regression"]
1329
+ lines.append("")
1330
+ lines.append("**Regression spec**:")
1331
+ if reg.get("description"):
1332
+ lines.append(f"- {reg['description']}")
1333
+ if reg.get("scenario"):
1334
+ lines.append(f"- Scenario: {reg['scenario']}")
1335
+ if reg.get("acceptance"):
1336
+ lines.append(f"- Acceptance: {reg['acceptance']}")
1337
+ if reg.get("file_hint"):
1338
+ lines.append(f"- File: `{reg['file_hint']}`")
1339
+
1340
+ # Doc citations
1341
+ if c.get("doc_citations"):
1342
+ lines.append("")
1343
+ lines.append("**Doc references**:")
1344
+ for cite in c["doc_citations"]:
1345
+ loc = cite.get("path", "?")
1346
+ if cite.get("line"):
1347
+ loc += f":{cite['line']}"
1348
+ claim = cite.get("claim", "")
1349
+ lines.append(f"- `{loc}` — {claim}")
1350
+
1351
+ if c.get("evidence"):
1352
+ lines.append("")
1353
+ lines.append("**Evidence**:")
1354
+ lines.append("")
1355
+ lines.append("```json")
1356
+ lines.append(json.dumps(c["evidence"], indent=2, default=str))
1357
+ lines.append("```")
1358
+ lines.append("")
1359
+
1360
+ # 8. Verdict diff interpretation table --------------------------------
1361
+ if verdict.get("verdict_diff"):
1362
+ diff = verdict["verdict_diff"]
1363
+ lines.append("## Verdict diff")
1364
+ lines.append("")
1365
+ lines.append(
1366
+ f"Interpretation: `{interpretation or '?'}` "
1367
+ f"(swap_detected: {diff.get('swap_detected')})"
1368
+ )
1369
+ lines.append("")
1370
+ lines.append("| Bucket | Checks |")
1371
+ lines.append("|---|---|")
1372
+ if diff.get("newly_passing"):
1373
+ lines.append(
1374
+ "| newly_passing | "
1375
+ + ", ".join(f"`{x}`" for x in diff["newly_passing"])
1376
+ + " |"
1377
+ )
1378
+ if diff.get("newly_failing"):
1379
+ lines.append(
1380
+ "| newly_failing | "
1381
+ + ", ".join(f"`{x}`" for x in diff["newly_failing"])
1382
+ + " |"
1383
+ )
1384
+ if diff.get("still_failing"):
1385
+ lines.append(
1386
+ "| still_failing | "
1387
+ + ", ".join(f"`{x}`" for x in diff["still_failing"])
1388
+ + " |"
1389
+ )
1390
+ if diff.get("swap_pairs"):
1391
+ lines.append(
1392
+ "| swap_pairs | "
1393
+ + ", ".join(
1394
+ f"`{p[0]}` → `{p[1]}`" for p in diff["swap_pairs"]
1395
+ )
1396
+ + " |"
1397
+ )
1398
+ if diff.get("newly_clean"):
1399
+ lines.append(
1400
+ "| newly_clean (both rounds all-green) | "
1401
+ + ", ".join(f"`{x}`" for x in diff["newly_clean"])
1402
+ + " |"
1403
+ )
1404
+ lines.append("")
1405
+
1406
+ # 9. Mandatory stop release -----------------------------------------
1407
+ if overall_label == "PASS":
1408
+ lines.append("## Mandatory stop release")
1409
+ lines.append("")
1410
+ lines.append(
1411
+ f"`{verdict['case_id']}` — PASS / COMPLETE. The mandatory stop "
1412
+ f"after `{verdict['case_id']}` can now be released."
1413
+ )
1414
+ lines.append("")
1415
+ elif overall_label in ("PARTIAL", "FAIL"):
1416
+ lines.append("## Mandatory stop holds")
1417
+ lines.append("")
1418
+ lines.append(
1419
+ f"`{verdict['case_id']}` — {overall_label}. The mandatory stop "
1420
+ f"is held; do not proceed to the next case."
1421
+ )
1422
+ lines.append("")
1423
+
1424
+ if verdict["actor_guidance"]:
1425
+ lines.append("## Actor guidance")
1426
+ lines.append("")
1427
+ for line in verdict["actor_guidance"]:
1428
+ lines.append(f"- {line}")
1429
+ lines.append("")
1430
+ elif verdict.get("verdict") == "pass":
1431
+ lines.append("## Actor guidance")
1432
+ lines.append("")
1433
+ lines.append(
1434
+ "- Case is green. No further actor action required. Merge per the "
1435
+ "plan's case-completion protocol and proceed to the next case."
1436
+ )
1437
+ lines.append("")
1438
+
1439
+ return "\n".join(lines)
1440
+
1441
+
1442
+ def _classify_interpretation(diff: dict[str, Any]) -> str:
1443
+ """Collapse verdict_diff()'s structured output into the categorical
1444
+ label that CaseAttemptState.record_outcome() escalates against.
1445
+
1446
+ Mapping:
1447
+ swap_detected=True -> "swap"
1448
+ any check moved failing->passing -> "progress"
1449
+ any check moved passing->failing -> "regression"
1450
+ both sides equal and non-empty, no swaps -> "no_progress"
1451
+ empty newly_failing AND empty newly_passing -> "pass"
1452
+ """
1453
+ if diff.get("swap_detected"):
1454
+ return "swap"
1455
+ if diff.get("newly_passing"):
1456
+ return "progress"
1457
+ if diff.get("newly_failing"):
1458
+ return "regression"
1459
+ if diff.get("newly_clean"):
1460
+ return "pass"
1461
+ return "no_progress"
1462
+
1463
+
1464
+ def verdict_diff(prev: dict[str, Any], curr: dict[str, Any]) -> dict[str, Any]:
1465
+ """Show what changed between two verdicts.
1466
+
1467
+ Catches the "swap" pattern: fix A by breaking B shows up as passing->failing
1468
+ for A and failing->passing for B, which is a swap, not progress.
1469
+ """
1470
+ prev_failed = {
1471
+ c["check"]
1472
+ for c in prev.get("per_check", [])
1473
+ if not c["passed"]
1474
+ }
1475
+ curr_failed = {
1476
+ c["check"]
1477
+ for c in curr.get("per_check", [])
1478
+ if not c["passed"]
1479
+ }
1480
+
1481
+ newly_failing = sorted(curr_failed - prev_failed)
1482
+ newly_passing = sorted(prev_failed - curr_failed)
1483
+ still_failing = sorted(curr_failed & prev_failed)
1484
+ # "clean" means all checks passed this round AND the previous round
1485
+ # also had all checks passing (i.e. a previously-green case stayed
1486
+ # green). The bug we are fixing: a check that has always been
1487
+ # passing would otherwise end up in this set on every round, which
1488
+ # masked stuck cases by classifying them as "pass" instead of
1489
+ # "no_progress".
1490
+ prev_all_passed = len(prev_failed) == 0
1491
+ curr_all_passed = len(curr_failed) == 0
1492
+ newly_clean: list[str] = []
1493
+ if prev_all_passed and curr_all_passed:
1494
+ newly_clean = sorted(
1495
+ c["check"] for c in curr.get("per_check", []) if c["passed"]
1496
+ )
1497
+
1498
+ swap_detected = bool(newly_failing and newly_passing)
1499
+
1500
+ return {
1501
+ "from_verdict_id": prev.get("verdict_id"),
1502
+ "to_verdict_id": curr.get("verdict_id"),
1503
+ "newly_failing": newly_failing,
1504
+ "newly_passing": newly_passing,
1505
+ "still_failing": still_failing,
1506
+ "newly_clean": newly_clean,
1507
+ "swap_detected": swap_detected,
1508
+ "interpretation": _interpret_diff(
1509
+ newly_failing, newly_passing, still_failing, swap_detected
1510
+ ),
1511
+ }
1512
+
1513
+
1514
+ # --- Internal helpers -------------------------------------------------------
1515
+
1516
+
1517
+ def _hash_test_output(stdout: str, stderr: str, returncode: int) -> str:
1518
+ payload = json.dumps(
1519
+ {"stdout": stdout, "stderr": stderr, "returncode": returncode},
1520
+ sort_keys=True,
1521
+ )
1522
+ return f"sha256_{hashlib.sha256(payload.encode('utf-8')).hexdigest()[:16]}"
1523
+
1524
+
1525
+ def _read_baseline(baseline_path: Path) -> dict[str, Any] | None:
1526
+ if not baseline_path.exists():
1527
+ return None
1528
+ try:
1529
+ return json.loads(baseline_path.read_text(encoding="utf-8"))
1530
+ except (OSError, json.JSONDecodeError):
1531
+ return None
1532
+
1533
+
1534
+ def _actor_guidance(
1535
+ failed_checks: list[CheckResult], case_state: CaseAttemptState
1536
+ ) -> list[str]:
1537
+ """Generate actionable guidance for the actor.
1538
+
1539
+ The actor is told:
1540
+ 1. Which specific checks failed
1541
+ 2. The remedy for each
1542
+ 3. The current round number and how close to hard-block
1543
+ """
1544
+ guidance: list[str] = []
1545
+
1546
+ if not failed_checks:
1547
+ if case_state.consecutive_failures > 0:
1548
+ guidance.append(
1549
+ f"All checks passed after {case_state.consecutive_failures} "
1550
+ f"failed attempt(s). Case is green again."
1551
+ )
1552
+ return guidance
1553
+
1554
+ guidance.append(
1555
+ f"{len(failed_checks)} check(s) failed on round "
1556
+ f"{case_state.attempts} for this case."
1557
+ )
1558
+
1559
+ for c in failed_checks:
1560
+ guidance.append(f"**{c.check}**: {c.reason} Remediation: {c.remedy}")
1561
+
1562
+ if case_state.oscillating:
1563
+ guidance.append(
1564
+ "⚠️ Same checks have failed multiple times in a row. The current "
1565
+ "approach is not converging. Consider a different strategy "
1566
+ "(re-read the case, consult the graph, change the implementation "
1567
+ "pattern) rather than retrying the same change."
1568
+ )
1569
+
1570
+ if case_state.surface_to_user:
1571
+ guidance.append(
1572
+ "📢 Round 3 of the same case failing. The user has been notified."
1573
+ )
1574
+
1575
+ if case_state.hard_block:
1576
+ guidance.append(
1577
+ "🛑 Round 5 reached. This case is hard-blocked. A user or "
1578
+ "operator must intervene (change the plan, change the actor, "
1579
+ "or accept the failure as a recorded deviation)."
1580
+ )
1581
+
1582
+ return guidance
1583
+
1584
+
1585
+ def _interpret_diff(
1586
+ newly_failing: list[str],
1587
+ newly_passing: list[str],
1588
+ still_failing: list[str],
1589
+ swap_detected: bool,
1590
+ ) -> str:
1591
+ if swap_detected:
1592
+ return (
1593
+ f"SWAP DETECTED: {newly_passing} now pass but {newly_failing} "
1594
+ f"now fail. This is the 'fix A by breaking B' pattern."
1595
+ )
1596
+ if newly_passing and not newly_failing:
1597
+ return f"Progress: {newly_passing} now pass."
1598
+ if newly_failing and not newly_passing:
1599
+ return f"Regression: {newly_failing} now fail."
1600
+ if still_failing:
1601
+ return f"No progress: {still_failing} still fail."
1602
+ return "No change."
1603
+
1604
+
1605
+ # --- Convenience runner ------------------------------------------------------
1606
+
1607
+
1608
+ @dataclass
1609
+ class GateRunResult:
1610
+ verdict: dict[str, Any]
1611
+ markdown: str
1612
+ case_state: CaseAttemptState
1613
+
1614
+
1615
+ def run_gate(
1616
+ pack: Any,
1617
+ case_id: str,
1618
+ submission: ActorSubmission,
1619
+ case_state: CaseAttemptState,
1620
+ *,
1621
+ test_runner: dict[str, Any] | None = None,
1622
+ baseline_path: Path | None = None,
1623
+ workspace: Path | None = None,
1624
+ scope_to_paths: Callable[[list[str]], set[str]] | None = None,
1625
+ previously_passing_cases: list[str] | None = None,
1626
+ re_run_case: Callable[[str], bool] | None = None,
1627
+ corrections: list[Correction] | None = None,
1628
+ ) -> GateRunResult:
1629
+ """Run all five checks and return the verdict.
1630
+
1631
+ This is the convenience entry point. Callers can also run individual
1632
+ checks for more granular control.
1633
+
1634
+ `corrections` is the per-case correction list (sub-requirements). If not
1635
+ provided, the gate looks for `case["corrections"]` in the pack. The
1636
+ verdict will carry a per-correction table alongside the per-check
1637
+ results.
1638
+ """
1639
+ current_plan_hash = plan_hash(pack)
1640
+
1641
+ checks: list[CheckResult] = []
1642
+ checks.append(
1643
+ check_plan_freshness(pack, submission, current_plan_hash)
1644
+ )
1645
+ checks.append(check_case_coverage(pack, case_id, submission))
1646
+ checks.append(
1647
+ check_running_code(
1648
+ pack, case_id, submission, test_runner, baseline_path, workspace
1649
+ )
1650
+ )
1651
+ checks.append(check_scope(pack, case_id, submission, scope_to_paths))
1652
+ checks.append(
1653
+ check_cross_area_disruption(
1654
+ pack, case_id, submission, previously_passing_cases, re_run_case
1655
+ )
1656
+ )
1657
+
1658
+ # Resolve corrections: explicit arg > case.corrections in pack
1659
+ if corrections is None and pack is not None:
1660
+ case = _lookup_case(pack, case_id)
1661
+ if isinstance(case, dict):
1662
+ corrections = corrections_from_case(case)
1663
+
1664
+ # Record which corrections the actor claimed this round so the verdict
1665
+ # can split "partial" (claimed but case still failing) from "failed"
1666
+ # (not claimed).
1667
+ claimed: list[str] = []
1668
+ for fld in ("claimed_corrections", "completed_corrections"):
1669
+ v = getattr(submission, fld, None)
1670
+ if isinstance(v, list):
1671
+ claimed.extend(str(x) for x in v if x)
1672
+ case_state.last_claimed_corrections = claimed
1673
+
1674
+ verdict = render_verdict(
1675
+ case_id, checks, current_plan_hash, case_state, pack, corrections
1676
+ )
1677
+
1678
+ # Compute the diff against the prior verdict and persist verdict +
1679
+ # diff + interpretation onto case_state in a single record_outcome()
1680
+ # call. First round on a case has no prior — we still record the
1681
+ # verdict so next round has a baseline. verdict_diff() returns the
1682
+ # structured diff the Observatory surfaces; _classify_interpretation()
1683
+ # collapses it into the categorical label that drives escalation.
1684
+ # IMPORTANT: do NOT also call record_outcome() above and then re-call
1685
+ # it here — that double-counts attempts and breaks the 3-round / 5-round
1686
+ # surface / hard-block thresholds. record_outcome() is called once per
1687
+ # run_gate() invocation, after the verdict is known, with the diff
1688
+ # interpretation attached so consecutive_failures advances correctly.
1689
+ prev_verdict = case_state.last_verdict
1690
+ diff_payload: dict[str, Any] | None = None
1691
+ interpretation_label = ""
1692
+ if prev_verdict is not None:
1693
+ diff_payload = verdict_diff(prev_verdict, verdict)
1694
+ interpretation_label = _classify_interpretation(diff_payload)
1695
+ case_state.record_outcome(
1696
+ checks, interpretation_label, diff_payload
1697
+ )
1698
+ # record_outcome() advanced attempts / consecutive_failures /
1699
+ # surface_to_user / hard_block. Re-stamp the verdict so its embedded
1700
+ # actor_guidance and round-aware fields reflect the post-update state
1701
+ # (round 5's guidance should say "round 5", not the pre-update round
1702
+ # number from when render_verdict() was first called).
1703
+ verdict["round"] = case_state.attempts
1704
+ verdict["attempts_for_case"] = case_state.attempts
1705
+ verdict["consecutive_failures"] = case_state.consecutive_failures
1706
+ verdict["oscillating"] = case_state.oscillating
1707
+ verdict["surface_to_user"] = case_state.surface_to_user
1708
+ verdict["hard_block"] = case_state.hard_block
1709
+ verdict["actor_guidance"] = _actor_guidance(
1710
+ [c for c in checks if not c.passed], case_state
1711
+ )
1712
+ case_state.last_verdict = verdict
1713
+
1714
+ # Embed the diff in the verdict itself so callers / Observatory get
1715
+ # the full artifact without having to reach into case_state.
1716
+ if diff_payload is not None:
1717
+ verdict["verdict_diff"] = diff_payload
1718
+ verdict["interpretation"] = interpretation_label or (
1719
+ "pass" if all(c.passed for c in checks) else "first_round"
1720
+ )
1721
+
1722
+ markdown = render_verdict_markdown(verdict)
1723
+ return GateRunResult(verdict=verdict, markdown=markdown, case_state=case_state)
1724
+
1725
+
1726
+ def _lookup_case(pack: Any, case_id: str) -> dict[str, Any] | None:
1727
+ """Pull a case dict out of a pack, supporting dicts and dataclass packs.
1728
+
1729
+ `pack.cases` may be either a list of case dicts OR a dict keyed by case_id.
1730
+ We iterate values in the dict case so we always look at case dicts, not
1731
+ the case_id keys.
1732
+ """
1733
+ if pack is None:
1734
+ return None
1735
+ cases = getattr(pack, "cases", None)
1736
+ if cases is None and isinstance(pack, dict):
1737
+ cases = pack.get("cases")
1738
+ if not cases:
1739
+ return None
1740
+ # If `cases` is a dict keyed by case_id, iterate its values (the case dicts).
1741
+ if isinstance(cases, dict):
1742
+ iterable = cases.values()
1743
+ else:
1744
+ iterable = cases
1745
+ for c in iterable:
1746
+ if isinstance(c, dict):
1747
+ if c.get("case_id") == case_id or c.get("id") == case_id:
1748
+ return c
1749
+ else:
1750
+ if getattr(c, "case_id", None) == case_id or getattr(c, "id", None) == case_id:
1751
+ # dataclass — adapt via __dict__ if possible
1752
+ return getattr(c, "__dict__", None) or {
1753
+ k: v for k, v in c.__dict__.items() if not k.startswith("_")
1754
+ }
1755
+ return None
1756
+
1757
+
1758
+ __all__ = [
1759
+ "ActorSubmission",
1760
+ "CaseAttemptState",
1761
+ "CheckResult",
1762
+ "Correction",
1763
+ "GateRunResult",
1764
+ "check_case_coverage",
1765
+ "check_cross_area_disruption",
1766
+ "check_plan_freshness",
1767
+ "check_running_code",
1768
+ "check_scope",
1769
+ "corrections_from_case",
1770
+ "plan_hash",
1771
+ "render_verdict",
1772
+ "render_verdict_markdown",
1773
+ "run_gate",
1774
+ "synthesize_status_assertion",
1775
+ "verdict_diff",
1776
+ ]