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,1105 @@
1
+ """LC1.26 — adapter family: IDE/rules harnesses (16 members).
2
+
3
+ Contract (Launch-Convergence Master Plan, R4 amendment, LC1.26):
4
+
5
+ DETECT -> INSTALL/REPAIR -> LIVE PROBE -> CONTINUOUS RECHECK
6
+
7
+ * only *detected* environments activate — `unknown` never becomes supported;
8
+ * IDE/extension/plugin hosts are **not** binary-only detection: every member
9
+ declares app-install, extension-dir, marketplace-metadata and settings/config
10
+ surfaces (binaries are supplementary evidence at most);
11
+ * file existence is not consumption: ``probe()`` claims ``consumed=True`` only
12
+ from an executed host-native echo surface, otherwise ``None`` with an
13
+ honest per-member evidence gap;
14
+ * activation is a safe idempotent merge (managed marker block, or key-merge
15
+ for JSON targets) — never a destructive overwrite of foreign content;
16
+ * ``deactivate()`` (uninstall/recovery), ``lifecycle()`` and ``health()``
17
+ provide recovery, event handling and a permanent regression probe.
18
+
19
+ Seam consumed by the coordinator's central adapter integration. This module
20
+ only *reads* ``tools/cosmos_project_adapters.py`` and ``catalogs/adapters.json``
21
+ and never edits them; it writes no governance ledger and invokes no
22
+ certification.
23
+
24
+ Target resolution: ``catalogs/adapters.json`` (the read-only 57-member
25
+ registry) remains the family's *read-surface* target authority for
26
+ ``deactivate()``/``probe()``/``bind()``/``health()``; ``health()`` still
27
+ surfaces the central/catalog divergence for ``cursor``/``windsurf`` as a note
28
+ for coordinator reconciliation. *Activation* (P0-02) is a forwarding wrapper
29
+ over the central canonical engine (``activate_adapter`` — the single
30
+ authoritative entrypoint): every doorway write executes through the central
31
+ BR-1/BR-2 primitives, and under D7b (EXPLICIT_P0_02_AUTHORIZED_DELTA) the
32
+ divergent catalog-target activation branch (``.cursorrules`` /
33
+ ``.windsurfrules``) is retired — ``cursor``/``windsurf`` activate to the
34
+ central production target. JSON-style targets (``continue``) are key-merged
35
+ by this module's read-only ``_merge_json_payload`` predicate executed inside
36
+ the central BR-2 primitive.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import json
41
+ import os
42
+ import re
43
+ import shutil
44
+ from tools import cosmos_proc as subprocess
45
+ import sys
46
+ from datetime import datetime, timezone
47
+ from pathlib import Path
48
+ from typing import Any
49
+
50
+ FAMILY = "ide-rules"
51
+ ADAPTERS: list[str] = [
52
+ "cursor",
53
+ "cursor-rules",
54
+ "windsurf",
55
+ "windsurf-rules",
56
+ "github-copilot",
57
+ "zed",
58
+ "roo-cline",
59
+ "continue",
60
+ "kiro",
61
+ "kilo-code",
62
+ "amazon-q",
63
+ "antigravity",
64
+ "antigravity-md",
65
+ "cline",
66
+ "trae",
67
+ "void",
68
+ ]
69
+
70
+ _REPO_ROOT = Path(__file__).resolve().parents[2]
71
+ CATALOG_PATH = _REPO_ROOT / "catalogs" / "adapters.json"
72
+
73
+ # Fixture seam for *detection roots only*: when set, absolute system candidates
74
+ # (/Applications/..., /usr/...) are evaluated under this prefix so hermetic
75
+ # tests never read (or depend on) the real machine. It never changes what counts
76
+ # as evidence and never promotes unknown -> supported. Unset on real machines.
77
+ _DETECT_ROOT_ENV = "COSMOS_IDE_RULES_DETECT_ROOT"
78
+
79
+ _SKIP = object() # signal not applicable on this platform (≠ unevaluable)
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Environment roots — read from the environment at call time so fixtures are
84
+ # hermetic; no implicit Path.home() fallback, so a cleared environment honestly
85
+ # yields "unknown" instead of silently probing the real profile.
86
+ # ---------------------------------------------------------------------------
87
+
88
+
89
+ def _roots() -> dict[str, str | None]:
90
+ home = os.environ.get("HOME") or os.environ.get("USERPROFILE") or None
91
+ local = os.environ.get("LOCALAPPDATA") or (f"{home}/AppData/Local" if home else None)
92
+ appdata = os.environ.get("APPDATA") or (f"{home}/AppData/Roaming" if home else None)
93
+ xdg = os.environ.get("XDG_CONFIG_HOME") or (f"{home}/.config" if home else None)
94
+ system = os.environ.get(_DETECT_ROOT_ENV) or ""
95
+ return {"home": home, "local": local, "appdata": appdata, "xdg": xdg,
96
+ "system": system}
97
+
98
+
99
+ def _resolve(template: str) -> Path | None:
100
+ """Expand a candidate template; None when a required root is unavailable."""
101
+ roots = _roots()
102
+ values: dict[str, str] = {}
103
+ for key in set(re.findall(r"\{(\w+)\}", template)):
104
+ value = roots.get(key)
105
+ if value is None:
106
+ return None
107
+ values[key] = value
108
+ return Path(template.format(**values))
109
+
110
+
111
+ def _win() -> tuple[str, ...]:
112
+ return ("win32",)
113
+
114
+
115
+ def _posix() -> tuple[str, ...]:
116
+ return ("darwin", "linux")
117
+
118
+
119
+ def _any() -> tuple[str, ...]:
120
+ return ("win32", "darwin", "linux")
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Detection surfaces (declarative, per member)
125
+ #
126
+ # kind: app | settings | user_dir | binary | vscode_extension | global_storage
127
+ # strength: strong -> hit means installed; weak -> hit alone means *unknown*
128
+ # (uninstall residue is not proof of an install).
129
+ # ---------------------------------------------------------------------------
130
+
131
+ _VSCODE_EXT_ROOTS = (
132
+ "{home}/.vscode/extensions",
133
+ "{home}/.vscode-insiders/extensions",
134
+ "{home}/.vscodium/extensions",
135
+ )
136
+
137
+ _GLOBAL_STORAGE_ROOTS = (
138
+ "{appdata}/Code/User/globalStorage",
139
+ "{appdata}/Code - Insiders/User/globalStorage",
140
+ "{appdata}/Cursor/User/globalStorage",
141
+ "{home}/Library/Application Support/Code/User/globalStorage",
142
+ "{home}/Library/Application Support/Cursor/User/globalStorage",
143
+ "{xdg}/Code/User/globalStorage",
144
+ "{xdg}/Cursor/User/globalStorage",
145
+ )
146
+
147
+
148
+ def _path(kind: str, label: str, template: str, platforms: tuple[str, ...],
149
+ strength: str = "strong") -> dict[str, Any]:
150
+ return {"kind": kind, "label": label, "template": template,
151
+ "platforms": platforms, "strength": strength}
152
+
153
+
154
+ def _binary(name: str) -> dict[str, Any]:
155
+ return {"kind": "binary", "label": f"binary:{name}", "name": name,
156
+ "platforms": _any(), "strength": "strong"}
157
+
158
+
159
+ def _extension(label: str, pattern: str) -> dict[str, Any]:
160
+ return {"kind": "vscode_extension", "label": label, "pattern": pattern,
161
+ "roots": _VSCODE_EXT_ROOTS, "platforms": _any(), "strength": "strong"}
162
+
163
+
164
+ def _storage(label: str, pattern: str) -> dict[str, Any]:
165
+ return {"kind": "global_storage", "label": label, "pattern": pattern,
166
+ "roots": _GLOBAL_STORAGE_ROOTS, "platforms": _any(), "strength": "weak"}
167
+
168
+
169
+ def _cursor_surfaces() -> list[dict[str, Any]]:
170
+ return [
171
+ _path("app", "app:cursor-exe", "{local}/Programs/cursor/Cursor.exe", _win()),
172
+ _path("app", "app:cursor-app", "{system}/Applications/Cursor.app", ("darwin",)),
173
+ _path("app", "app:cursor-linux", "{system}/usr/bin/cursor", ("linux",)),
174
+ _path("settings", "settings:cursor-win",
175
+ "{appdata}/Cursor/User/settings.json", _win()),
176
+ _path("settings", "settings:cursor-mac",
177
+ "{home}/Library/Application Support/Cursor/User/settings.json", ("darwin",)),
178
+ _path("settings", "settings:cursor-linux",
179
+ "{xdg}/Cursor/User/settings.json", ("linux",)),
180
+ _path("user_dir", "user-dir:.cursor", "{home}/.cursor", _any()),
181
+ _path("settings", "residue:cursor-win-roaming", "{appdata}/Cursor", _win(),
182
+ strength="weak"),
183
+ _path("settings", "residue:cursor-mac-support",
184
+ "{home}/Library/Application Support/Cursor", ("darwin",),
185
+ strength="weak"),
186
+ _binary("cursor"),
187
+ ]
188
+
189
+
190
+ def _windsurf_surfaces() -> list[dict[str, Any]]:
191
+ return [
192
+ _path("app", "app:windsurf-exe", "{local}/Programs/Windsurf/Windsurf.exe", _win()),
193
+ _path("app", "app:windsurf-app", "{system}/Applications/Windsurf.app", ("darwin",)),
194
+ _path("app", "app:windsurf-linux", "{system}/usr/bin/windsurf", ("linux",)),
195
+ _path("settings", "settings:windsurf-win",
196
+ "{appdata}/Windsurf/User/settings.json", _win()),
197
+ _path("settings", "settings:windsurf-mac",
198
+ "{home}/Library/Application Support/Windsurf/User/settings.json", ("darwin",)),
199
+ _path("settings", "settings:windsurf-linux",
200
+ "{xdg}/Windsurf/User/settings.json", ("linux",)),
201
+ _path("user_dir", "user-dir:.windsurf", "{home}/.windsurf", _any()),
202
+ _path("settings", "residue:windsurf-win-roaming", "{appdata}/Windsurf", _win(),
203
+ strength="weak"),
204
+ _path("settings", "residue:windsurf-mac-support",
205
+ "{home}/Library/Application Support/Windsurf", ("darwin",),
206
+ strength="weak"),
207
+ _binary("windsurf"),
208
+ ]
209
+
210
+
211
+ def _zed_surfaces() -> list[dict[str, Any]]:
212
+ return [
213
+ _path("app", "app:zed-exe", "{local}/Programs/Zed/zed.exe", _win()),
214
+ _path("app", "app:zed-app", "{system}/Applications/Zed.app", ("darwin",)),
215
+ _path("app", "app:zed-linux", "{system}/usr/bin/zed", ("linux",)),
216
+ _path("settings", "settings:zed", "{xdg}/zed/settings.json", _posix()),
217
+ _path("user_dir", "user-dir:config-zed", "{xdg}/zed", _any()),
218
+ _binary("zed"),
219
+ ]
220
+
221
+
222
+ def _antigravity_surfaces() -> list[dict[str, Any]]:
223
+ return [
224
+ _path("app", "app:antigravity-exe",
225
+ "{local}/Programs/antigravity/Antigravity.exe", _win()),
226
+ _path("app", "app:antigravity-ide-exe",
227
+ "{local}/Programs/Antigravity IDE/Antigravity IDE.exe", _win()),
228
+ _path("app", "app:antigravity-app",
229
+ "{system}/Applications/Antigravity.app", ("darwin",)),
230
+ _path("app", "app:antigravity-linux", "{system}/usr/bin/antigravity", ("linux",)),
231
+ _path("settings", "settings:antigravity-win", "{appdata}/Antigravity", _win()),
232
+ _path("settings", "settings:antigravity-mac",
233
+ "{home}/Library/Application Support/Antigravity", ("darwin",)),
234
+ _path("user_dir", "user-dir:.antigravity", "{home}/.antigravity", _any()),
235
+ _binary("antigravity"),
236
+ ]
237
+
238
+
239
+ _SURFACE_TABLE: dict[str, list[dict[str, Any]]] = {
240
+ "cursor": _cursor_surfaces(),
241
+ "cursor-rules": _cursor_surfaces(),
242
+ "windsurf": _windsurf_surfaces(),
243
+ "windsurf-rules": _windsurf_surfaces(),
244
+ "github-copilot": [
245
+ _extension("vscode-ext:github.copilot", "github.copilot"),
246
+ _path("app", "app:copilot-cli-win",
247
+ "{local}/Programs/GitHub Copilot", _win()),
248
+ _path("settings", "settings:copilot-mac",
249
+ "{home}/Library/Application Support/GitHub Copilot", ("darwin",)),
250
+ _storage("globalStorage:github.copilot-chat", "github.copilot-chat"),
251
+ ],
252
+ "zed": _zed_surfaces(),
253
+ "roo-cline": [
254
+ _extension("vscode-ext:roo-cline", "roo-cline"),
255
+ _storage("globalStorage:roo-cline", "roo-cline"),
256
+ ],
257
+ "continue": [
258
+ _extension("vscode-ext:continue", "continue.continue"),
259
+ _path("settings", "settings:continue-config", "{home}/.continue/config.json",
260
+ _any()),
261
+ _storage("globalStorage:continue", "continue.continue"),
262
+ ],
263
+ "kiro": [
264
+ _path("app", "app:kiro-exe", "{local}/Programs/Kiro/Kiro.exe", _win()),
265
+ _path("app", "app:kiro-app", "{system}/Applications/Kiro.app", ("darwin",)),
266
+ _path("app", "app:kiro-linux", "{system}/usr/bin/kiro", ("linux",)),
267
+ _path("settings", "settings:kiro-win", "{appdata}/Kiro/User/settings.json", _win()),
268
+ _path("settings", "settings:kiro-mac",
269
+ "{home}/Library/Application Support/Kiro/User/settings.json", ("darwin",)),
270
+ _path("settings", "settings:kiro-linux",
271
+ "{xdg}/Kiro/User/settings.json", ("linux",)),
272
+ _path("user_dir", "user-dir:.kiro", "{home}/.kiro", _any()),
273
+ ],
274
+ "kilo-code": [
275
+ _extension("vscode-ext:kilo-code", "kilo-code"),
276
+ _storage("globalStorage:kilo-code", "kilo-code"),
277
+ ],
278
+ "amazon-q": [
279
+ _extension("vscode-ext:amazon-q", "amazon-q"),
280
+ _path("settings", "settings:amazon-q-cli", "{home}/.aws/amazonq", _any()),
281
+ _path("settings", "settings:amazon-q-legacy", "{home}/.amazonq", _any()),
282
+ _storage("globalStorage:amazon-q", "amazon-q"),
283
+ ],
284
+ "antigravity": _antigravity_surfaces(),
285
+ "antigravity-md": _antigravity_surfaces(),
286
+ "cline": [
287
+ _extension("vscode-ext:cline", "claude-dev"),
288
+ _path("user_dir", "user-dir:.cline", "{home}/.cline", _any()),
289
+ _storage("globalStorage:cline", "claude-dev"),
290
+ ],
291
+ "trae": [
292
+ _path("app", "app:trae-exe", "{local}/Programs/Trae/Trae.exe", _win()),
293
+ _path("app", "app:trae-app", "{system}/Applications/Trae.app", ("darwin",)),
294
+ _path("app", "app:trae-linux", "{system}/usr/bin/trae", ("linux",)),
295
+ _path("settings", "settings:trae-win", "{appdata}/Trae", _win()),
296
+ _path("settings", "settings:trae-mac",
297
+ "{home}/Library/Application Support/Trae", ("darwin",)),
298
+ _path("user_dir", "user-dir:.trae", "{home}/.trae", _any()),
299
+ _binary("trae"),
300
+ ],
301
+ "void": [
302
+ _path("app", "app:void-exe", "{local}/Programs/Void/Void.exe", _win()),
303
+ _path("app", "app:void-app", "{system}/Applications/Void.app", ("darwin",)),
304
+ _path("app", "app:void-linux", "{system}/usr/bin/void", ("linux",)),
305
+ _path("settings", "settings:void-win", "{appdata}/Void", _win()),
306
+ _path("settings", "settings:void-mac",
307
+ "{home}/Library/Application Support/Void", ("darwin",)),
308
+ _path("user_dir", "user-dir:.void", "{home}/.void", _any()),
309
+ _binary("void"),
310
+ ],
311
+ }
312
+
313
+ # Best real integration surface per member (the documented host-native load
314
+ # path). probe() reports it verbatim and only claims consumption from an
315
+ # *executed* host-native echo — none of these 16 hosts exposes a verified
316
+ # headless one today, hence the honest default gap instead of a fabricated pass.
317
+ _PROBE_SURFACE: dict[str, str] = {
318
+ "cursor": ("Cursor reads .cursorrules (legacy) on every Composer/Agent "
319
+ "request — no headless echo/validate CLI exists"),
320
+ "cursor-rules": ("Cursor parses .cursor/rules/*.mdc YAML frontmatter "
321
+ "(alwaysApply) in-process per request — no headless "
322
+ "validation surface exists"),
323
+ "windsurf": ("Windsurf reads .windsurfrules (legacy) on every Cascade "
324
+ "invocation — no headless echo/validate CLI exists"),
325
+ "windsurf-rules": ("Windsurf loads .windsurf/rules/*.md on every Cascade "
326
+ "invocation — no headless validation surface exists"),
327
+ "github-copilot": ("GitHub Copilot ingests .github/copilot-instructions.md "
328
+ "in the chat host per request — no local echo surface"),
329
+ "zed": "Zed reads .rules as project context in-process — no headless CLI surface",
330
+ "roo-cline": ("Roo Code extension loads .roo/rules/** per task inside the VS "
331
+ "Code extension host — no headless echo surface"),
332
+ "continue": ("Continue parses .continuerc.json at startup (its own JSON load "
333
+ "path) — no headless echo of loaded content"),
334
+ "kiro": "Kiro auto-loads .kiro/steering/*.md (inclusion: always) per session — no CLI",
335
+ "kilo-code": ("Kilo Code extension reads .kilocode/rules/*.md per request inside "
336
+ "the VS Code extension host — no headless surface"),
337
+ "amazon-q": ("Amazon Q Developer reads .amazonq/rules/*.md per chat/inline "
338
+ "request — no headless echo/validate surface"),
339
+ "antigravity": ("Antigravity agent reads .antigravity/instructions.md per "
340
+ "invocation — no headless echo surface"),
341
+ "antigravity-md": ("Antigravity agent reads workspace ANTIGRAVITY.md per "
342
+ "invocation — no headless echo surface"),
343
+ "cline": ("Cline loads .clinerules at task start inside the VS Code extension "
344
+ "host — no headless echo/validate surface"),
345
+ "trae": "Trae reads .traerules per session — no headless echo surface",
346
+ "void": "Void reads .voidrules as project context — no headless surface",
347
+ }
348
+
349
+ # Host-native echo commands (argv templates with {target}/{env_id}). None of
350
+ # the 16 members has a *verified* headless echo surface today, so production
351
+ # values are None — an honest gap, never a fabricated probe. Tests patch one
352
+ # member here to exercise the echo machinery end to end. Echo commands should
353
+ # write raw bytes to stdout (see probe(): output is decoded UTF-8/replace) so
354
+ # proof does not depend on the child's locale.
355
+ ECHO_COMMANDS: dict[str, list[str] | None] = {name: None for name in ADAPTERS}
356
+
357
+
358
+ # ---------------------------------------------------------------------------
359
+ # Catalog / central registry (read-only)
360
+ # ---------------------------------------------------------------------------
361
+
362
+
363
+ def _catalog() -> dict[str, Any]:
364
+ return json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
365
+
366
+
367
+ def catalog_entry(adapter_id: str) -> dict[str, Any]:
368
+ entry = _catalog()["adapters"].get(adapter_id)
369
+ if entry is None:
370
+ raise KeyError(f"{adapter_id!r} is not a member of {CATALOG_PATH.name}")
371
+ return entry
372
+
373
+
374
+ def catalog_target(adapter_id: str) -> str:
375
+ return catalog_entry(adapter_id)["target"]
376
+
377
+
378
+ def _central() -> Any:
379
+ from tools import cosmos_project_adapters as central
380
+
381
+ return central
382
+
383
+
384
+ def _central_target(adapter_id: str) -> str:
385
+ return _central().get_adapter(adapter_id).target
386
+
387
+
388
+ # ---------------------------------------------------------------------------
389
+ # DETECT
390
+ # ---------------------------------------------------------------------------
391
+
392
+
393
+ def _platform_matches(platforms: tuple[str, ...]) -> bool:
394
+ return sys.platform in platforms
395
+
396
+
397
+ def _eval_signal(sig: dict[str, Any]) -> Any:
398
+ """-> bool | None (unevaluable) | _SKIP (not applicable on this platform)."""
399
+ if not _platform_matches(sig["platforms"]):
400
+ return _SKIP
401
+ kind = sig["kind"]
402
+ if kind == "binary":
403
+ if "PATH" not in os.environ:
404
+ return None
405
+ return shutil.which(sig["name"]) is not None
406
+ if kind in {"app", "settings", "user_dir"}:
407
+ path = _resolve(sig["template"])
408
+ if path is None:
409
+ return None
410
+ try:
411
+ return path.exists()
412
+ except OSError:
413
+ return None
414
+ if kind in {"vscode_extension", "global_storage"}:
415
+ roots: list[Path] = []
416
+ for template in sig["roots"]:
417
+ resolved = _resolve(template)
418
+ if resolved is not None:
419
+ roots.append(resolved)
420
+ for extra in (os.environ.get("VSCODE_EXTENSIONS") or "").split(os.pathsep):
421
+ if extra.strip():
422
+ roots.append(Path(extra.strip()))
423
+ if not roots:
424
+ return None
425
+ pattern = sig["pattern"].lower()
426
+ for root in roots:
427
+ try:
428
+ if not root.is_dir():
429
+ continue
430
+ for entry in root.iterdir():
431
+ if pattern in entry.name.lower():
432
+ return True
433
+ if kind == "vscode_extension":
434
+ meta = root / "extensions.json"
435
+ if meta.is_file():
436
+ try:
437
+ if pattern in meta.read_text(
438
+ encoding="utf-8", errors="replace").lower():
439
+ return True
440
+ except OSError:
441
+ pass
442
+ except OSError:
443
+ continue
444
+ return False # roots were resolvable; none contains the extension
445
+ raise ValueError(f"unknown signal kind: {kind!r}") # pragma: no cover
446
+
447
+
448
+ def detect(adapter_id: str, root: Path | str) -> dict[str, Any]:
449
+ """Tri-state host detection. status: installed | absent | unknown.
450
+
451
+ ``root`` is accepted for seam symmetry; host detection is machine-level.
452
+ """
453
+ if adapter_id not in _SURFACE_TABLE:
454
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
455
+ signals = _SURFACE_TABLE[adapter_id]
456
+ evaluated: list[dict[str, Any]] = []
457
+ strong_hit = binary_hit = weak_hit = False
458
+ deciding: str | None = None
459
+ primary_seen = primary_unevaluable = False
460
+ for sig in signals:
461
+ result = _eval_signal(sig)
462
+ if result is _SKIP:
463
+ continue
464
+ record: dict[str, Any] = {
465
+ "label": sig["label"],
466
+ "kind": sig["kind"],
467
+ "strength": sig["strength"],
468
+ "result": ("hit" if result is True
469
+ else "miss" if result is False else "unevaluable"),
470
+ }
471
+ if "template" in sig:
472
+ resolved = _resolve(sig["template"])
473
+ record["path"] = str(resolved) if resolved is not None else None
474
+ evaluated.append(record)
475
+ if result is None:
476
+ if sig["kind"] != "binary":
477
+ primary_unevaluable = True
478
+ continue
479
+ if sig["kind"] != "binary":
480
+ primary_seen = True
481
+ if result is True:
482
+ if sig["kind"] == "binary":
483
+ binary_hit = True
484
+ deciding = deciding or sig["label"]
485
+ elif sig["strength"] == "strong":
486
+ strong_hit = True
487
+ deciding = deciding or sig["label"]
488
+ else:
489
+ weak_hit = True
490
+ deciding = deciding or sig["label"]
491
+ evidence: dict[str, Any] = {
492
+ "platform": sys.platform,
493
+ "signals": evaluated,
494
+ "detect_root": os.environ.get(_DETECT_ROOT_ENV) or None,
495
+ }
496
+ if strong_hit or binary_hit:
497
+ return {"status": "installed", "method": f"surface-hit:{deciding}",
498
+ "evidence": evidence}
499
+ if weak_hit:
500
+ evidence["gap"] = ("only residue-grade surfaces hit (globalStorage/"
501
+ "uninstall leftovers); install not confirmable — "
502
+ "unknown never becomes supported")
503
+ return {"status": "unknown", "method": f"residue-only:{deciding}",
504
+ "evidence": evidence}
505
+ if primary_seen and not primary_unevaluable:
506
+ return {"status": "absent",
507
+ "method": f"surface-sweep:{len(evaluated)} surfaces, no hit",
508
+ "evidence": evidence}
509
+ evidence["gap"] = "primary detection surfaces could not be evaluated on this host"
510
+ return {"status": "unknown", "method": "surfaces-unevaluable",
511
+ "evidence": evidence}
512
+
513
+
514
+ def primary_surfaces(adapter_id: str) -> list[Path]:
515
+ """Env-rooted, platform-applicable *strong* candidate paths — the fixture
516
+ seam: tests create one of these to model an installed host. Never returns
517
+ raw system paths ({system}/...) so fixtures stay hermetic."""
518
+ if adapter_id not in _SURFACE_TABLE:
519
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
520
+ out: list[Path] = []
521
+ for sig in _SURFACE_TABLE[adapter_id]:
522
+ if sig.get("strength") != "strong":
523
+ continue
524
+ if not _platform_matches(sig["platforms"]):
525
+ continue
526
+ if "template" in sig:
527
+ if "{system}" in sig["template"]:
528
+ continue
529
+ resolved = _resolve(sig["template"])
530
+ if resolved is not None:
531
+ out.append(resolved)
532
+ elif sig["kind"] == "vscode_extension":
533
+ for template in sig["roots"]:
534
+ root = _resolve(template)
535
+ if root is not None:
536
+ out.append(root / f"{sig['pattern']}-fixture-1.0.0")
537
+ break
538
+ return out
539
+
540
+
541
+ # ---------------------------------------------------------------------------
542
+ # ACTIVATE / DEACTIVATE
543
+ # ---------------------------------------------------------------------------
544
+
545
+
546
+ def _manifest_env_id(root: Path) -> str | None:
547
+ manifest = root / "cosmos.environment.json"
548
+ if not manifest.is_file():
549
+ return None
550
+ try:
551
+ return json.loads(manifest.read_text(encoding="utf-8")).get("environment_id")
552
+ except (OSError, json.JSONDecodeError):
553
+ return None
554
+
555
+
556
+ def _merge_json_payload(existing: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
557
+ """Key-merge our Continue payload into a foreign config: our providers are
558
+ upserted by name, foreign providers/keys are preserved."""
559
+ merged = dict(existing)
560
+ for key in ("name", "version", "schema"):
561
+ if key in payload and key not in existing:
562
+ merged[key] = payload[key]
563
+ foreign_providers = existing.get("contextProviders")
564
+ providers: list[Any] = list(foreign_providers) if isinstance(foreign_providers, list) else []
565
+ for provider in payload.get("contextProviders", []):
566
+ name = provider.get("name") if isinstance(provider, dict) else None
567
+ providers = [p for p in providers
568
+ if not (isinstance(p, dict) and p.get("name") == name)]
569
+ providers.append(provider)
570
+ merged["contextProviders"] = providers
571
+ docs = list(existing.get("docs", []) if isinstance(existing.get("docs"), list) else [])
572
+ for doc in payload.get("docs", []):
573
+ if doc not in docs:
574
+ docs.append(doc)
575
+ if docs:
576
+ merged["docs"] = docs
577
+ return merged
578
+
579
+
580
+ def _strip_markers(text: str, start: str, end: str) -> str | None:
581
+ """Remove every managed block; None when markers are incomplete (refuse)."""
582
+ if text.count(start) != text.count(end):
583
+ return None
584
+ while start in text:
585
+ head = text.index(start)
586
+ try:
587
+ tail = text.index(end, head) + len(end)
588
+ except ValueError:
589
+ return None # end marker precedes start — refuse, manual repair
590
+ prefix = text[:head].rstrip()
591
+ suffix = text[tail:].lstrip()
592
+ parts = [part for part in (prefix, suffix) if part]
593
+ text = "\n\n".join(parts)
594
+ return text
595
+
596
+
597
+ def _ours_json(payload: Any) -> bool:
598
+ if not isinstance(payload, dict):
599
+ return False
600
+ providers = payload.get("contextProviders")
601
+ if not isinstance(providers, list):
602
+ return False
603
+ return any(isinstance(p, dict) and str(p.get("name", "")).startswith("cosmos-")
604
+ for p in providers)
605
+
606
+
607
+ def _failure_shape(adapter_id: str, root: Path, exc: BaseException,
608
+ before: bytes | None) -> dict[str, Any]:
609
+ """Legacy failure projection for a refusal raised before the engine's
610
+ planner ran (unbound world / non-Git root / unusable manifest) or for a
611
+ failure escaping it — same ``detail`` strings and ``safe`` byte-truth as
612
+ the legacy activation implementation."""
613
+ target = _central().get_adapter(adapter_id).target
614
+ target_path = root / target
615
+ after = target_path.read_bytes() if target_path.is_file() else None
616
+ if isinstance(exc, FileNotFoundError):
617
+ detail = f"no Cosmos world in root, nothing written ({exc})"
618
+ elif isinstance(exc, ValueError) and "Git repository" in str(exc):
619
+ detail = f"root is not a git repository, nothing written ({exc})"
620
+ elif isinstance(exc, ValueError):
621
+ detail = f"refused unsafe merge, manual repair required: {exc}"
622
+ else:
623
+ detail = f"activation failed: {type(exc).__name__}: {exc}"
624
+ return {"action": "noop",
625
+ "native_paths": [target] if after is not None else [],
626
+ "safe": before == after,
627
+ "detail": detail}
628
+
629
+
630
+ def _project_canonical(canonical: dict[str, Any]) -> dict[str, Any]:
631
+ """Project the canonical engine result to the legacy ide-rules shape
632
+ ``{action, native_paths, safe, detail}`` — reproducing every legacy
633
+ ``detail`` string exactly (absent / failure / success)."""
634
+ det = canonical["detection"]
635
+ code = canonical["reason_code"]
636
+ if code == "host_not_detected":
637
+ return {"action": "noop", "native_paths": [], "safe": True,
638
+ "detail": f"host {det['status']} ({det['method']}); activation is "
639
+ "gated on detected environments only"}
640
+ if code in ("refused", "activation_failed"):
641
+ return {"action": "noop",
642
+ "native_paths": canonical["native_paths"],
643
+ "safe": canonical["safe"],
644
+ "detail": canonical["reason"]}
645
+ # success (installed / repaired / noop)
646
+ return {"action": canonical["action"],
647
+ "native_paths": canonical["native_paths"],
648
+ "safe": canonical["safe"],
649
+ "detail": f"host detected via {det['method']}; wrote "
650
+ f"{canonical['target_file']}"}
651
+
652
+
653
+ def activate(adapter_id: str, root: Path | str) -> dict[str, Any]:
654
+ """P0-02 forwarding wrapper over the canonical activation engine.
655
+
656
+ Delegates to ``tools.cosmos_project_adapters.activate_adapter`` (the single
657
+ authoritative production activation entrypoint) and projects its canonical
658
+ result to the legacy ``{action, native_paths, safe, detail}`` shape —
659
+ reproducing every legacy detail string for parity.
660
+
661
+ * absent/unknown -> legacy ``host <status> (<method>); activation is
662
+ gated on detected environments only`` noop (no world load, no write).
663
+ * installed BR-1/BR-2 -> doorway written through the central BR-1/BR-2
664
+ primitives, classified installed/repaired/byte-stable-noop exactly as
665
+ before; refused/failed activations project the legacy failure shape
666
+ with byte-truth ``safe``.
667
+
668
+ D7b (EXPLICIT_P0_02_AUTHORIZED_DELTA): the divergent catalog-target
669
+ activation branch (``.cursorrules`` / ``.windsurfrules``) is retired —
670
+ ``cursor``/``windsurf`` activate to the central production target.
671
+ """
672
+ if adapter_id not in _SURFACE_TABLE:
673
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
674
+ root = Path(root).resolve()
675
+ adapter = _central().get_adapter(adapter_id) # KeyError propagates
676
+ target_path = root / adapter.target
677
+ before = target_path.read_bytes() if target_path.is_file() else None
678
+ try:
679
+ canonical = _central().activate_adapter(adapter_id, root)
680
+ except KeyError:
681
+ raise # member/registry contract errors are not activation refusals
682
+ except Exception as exc: # noqa: BLE001 — legacy never let a refusal escape
683
+ return _failure_shape(adapter_id, root, exc, before)
684
+ return _project_canonical(canonical)
685
+
686
+
687
+ def deactivate(adapter_id: str, root: Path | str) -> dict[str, Any]:
688
+ """Uninstall/recovery: remove only Cosmos-managed content; foreign content
689
+ survives; the file is removed only when nothing but our content remains."""
690
+ root = Path(root).resolve()
691
+ if adapter_id not in _SURFACE_TABLE:
692
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
693
+ target = catalog_target(adapter_id)
694
+ path = root / target
695
+ if not path.is_file():
696
+ return {"action": "noop", "native_paths": [], "safe": True,
697
+ "detail": "artifact absent, nothing to remove"}
698
+ try:
699
+ text = path.read_text(encoding="utf-8")
700
+ except (OSError, UnicodeDecodeError) as exc:
701
+ return {"action": "noop", "native_paths": [target], "safe": False,
702
+ "detail": f"unreadable artifact, refusing removal: {exc}"}
703
+ if target.endswith(".json"):
704
+ try:
705
+ payload = json.loads(text)
706
+ except json.JSONDecodeError:
707
+ return {"action": "noop", "native_paths": [target], "safe": False,
708
+ "detail": "invalid JSON artifact, refusing removal (manual repair)"}
709
+ if not _ours_json(payload):
710
+ return {"action": "noop", "native_paths": [target], "safe": True,
711
+ "detail": "artifact is not Cosmos-owned, left untouched"}
712
+ foreign_providers = [p for p in payload.get("contextProviders", [])
713
+ if not (isinstance(p, dict)
714
+ and str(p.get("name", "")).startswith("cosmos-"))]
715
+ docs = [d for d in payload.get("docs", [])
716
+ if d not in ("@cosmos.environment.json", "@.cosmos/CURRENT.md")]
717
+ residual = dict(payload)
718
+ if foreign_providers:
719
+ residual["contextProviders"] = foreign_providers
720
+ else:
721
+ residual.pop("contextProviders", None)
722
+ if docs:
723
+ residual["docs"] = docs
724
+ else:
725
+ residual.pop("docs", None)
726
+ ours_values = {"name": "Cosmos", "version": "1.5",
727
+ "schema": "continue-config-v1"}
728
+ foreign_only = {k: v for k, v in residual.items()
729
+ if not (k in ours_values and v == ours_values[k])}
730
+ if not foreign_only:
731
+ # Nothing remains but our own canonical metadata -> ours alone.
732
+ path.unlink()
733
+ return {"action": "removed", "native_paths": [target], "safe": True,
734
+ "detail": "removed Cosmos-owned config file"}
735
+ path.write_text(json.dumps(residual, indent=2, sort_keys=True) + "\n",
736
+ encoding="utf-8")
737
+ return {"action": "removed", "native_paths": [target], "safe": True,
738
+ "detail": "removed Cosmos keys, preserved foreign config"}
739
+ adapter = _central().get_adapter(adapter_id)
740
+ if adapter.start_marker not in text and adapter.end_marker not in text:
741
+ return {"action": "noop", "native_paths": [target], "safe": True,
742
+ "detail": "file carries no Cosmos block, left untouched"}
743
+ stripped = _strip_markers(text, adapter.start_marker, adapter.end_marker)
744
+ if stripped is None:
745
+ return {"action": "noop", "native_paths": [target], "safe": False,
746
+ "detail": "incomplete Cosmos markers, refusing removal (manual repair)"}
747
+ if not stripped.strip():
748
+ path.unlink()
749
+ return {"action": "removed", "native_paths": [target], "safe": True,
750
+ "detail": "removed Cosmos-owned file"}
751
+ path.write_text(stripped if stripped.endswith("\n") else stripped + "\n",
752
+ encoding="utf-8")
753
+ return {"action": "removed", "native_paths": [target], "safe": True,
754
+ "detail": "stripped managed block, preserved foreign content"}
755
+
756
+
757
+ # ---------------------------------------------------------------------------
758
+ # BIND (read-only)
759
+ # ---------------------------------------------------------------------------
760
+
761
+
762
+ def _git(root: Path, *args: str) -> str | None:
763
+ try:
764
+ proc = subprocess.run(["git", "-C", str(root), *args],
765
+ capture_output=True, text=True, timeout=20)
766
+ except (OSError, subprocess.SubprocessError):
767
+ return None
768
+ if proc.returncode != 0:
769
+ return None
770
+ return proc.stdout.strip()
771
+
772
+
773
+ def bind(adapter_id: str, root: Path | str) -> dict[str, Any]:
774
+ """Read-only binding projection for this adapter's native surface."""
775
+ root = Path(root).resolve()
776
+ if adapter_id not in _SURFACE_TABLE:
777
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
778
+ target = catalog_target(adapter_id)
779
+ manifest_path = root / "cosmos.environment.json"
780
+ env_id = _manifest_env_id(root)
781
+ head = _git(root, "rev-parse", "HEAD")
782
+ branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")
783
+ commit_msg = _git(root, "log", "-1", "--format=%B") or ""
784
+ plan_match = re.search(r"^Plan:\s*(.+?)\s*$", commit_msg, re.MULTILINE)
785
+ work_units = re.findall(r"^Work-Unit:\s*(.+?)\s*$", commit_msg, re.MULTILINE)
786
+
787
+ try:
788
+ from tools import cosmos_obligations as obl
789
+
790
+ status = obl.status(root)
791
+ obligations: dict[str, Any] = {
792
+ "available": True,
793
+ **{k: v for k, v in status.items()
794
+ if k in ("total", "unresolved", "by_state", "ledger_in_sync")},
795
+ }
796
+ except Exception as exc: # noqa: BLE001 — read-only, degrade visibly
797
+ obligations = {"available": False, "reason": f"{type(exc).__name__}: {exc}"}
798
+ try:
799
+ from tools import cosmos_obligations as obl
800
+
801
+ wave = obl.derive_waves(root).get("active_wave")
802
+ except Exception: # noqa: BLE001
803
+ wave = None
804
+
805
+ decisions_dir = root / "governance" / "decisions"
806
+ unattested: list[str] = []
807
+ records = 0
808
+ if decisions_dir.is_dir():
809
+ for path in sorted(decisions_dir.glob("DEC-*.md")):
810
+ records += 1
811
+ try:
812
+ text = path.read_text(encoding="utf-8", errors="replace")
813
+ except OSError:
814
+ continue
815
+ if not re.search(r"^\**Status:?\**:?\s*\**ATTESTED\b", text,
816
+ re.IGNORECASE | re.MULTILINE):
817
+ unattested.append(path.name)
818
+
819
+ artifact = root / target
820
+ artifact_present = artifact.is_file()
821
+ env_matches: bool | None = None
822
+ if artifact_present and env_id:
823
+ try:
824
+ env_matches = env_id in artifact.read_text(encoding="utf-8",
825
+ errors="replace")
826
+ except OSError:
827
+ env_matches = None
828
+
829
+ state_revision = None
830
+ state_path = root / ".cosmos" / "project-state.json"
831
+ if state_path.is_file():
832
+ try:
833
+ state_revision = json.loads(state_path.read_text(encoding="utf-8")).get("revision")
834
+ except (OSError, json.JSONDecodeError):
835
+ state_revision = None
836
+
837
+ det = detect(adapter_id, root)
838
+ binding = {
839
+ "adapter": adapter_id,
840
+ "family": FAMILY,
841
+ "target": target,
842
+ "detection": {"status": det["status"], "method": det["method"]},
843
+ "world": {
844
+ "environment_id": env_id,
845
+ "manifest": str(manifest_path) if manifest_path.is_file() else None,
846
+ "present": manifest_path.is_file(),
847
+ "bound": bool(env_id and artifact_present and env_matches),
848
+ },
849
+ "repo": {"root": str(root), "branch": branch},
850
+ "head": head,
851
+ "plan": plan_match.group(1) if plan_match else None,
852
+ "wave": wave,
853
+ "work_unit": work_units,
854
+ "obligations": obligations,
855
+ "decisions": {"records": records, "unattested": unattested},
856
+ "health": health(adapter_id, root),
857
+ "freshness": {
858
+ "checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
859
+ "world_stale": bool(head) and state_revision != head,
860
+ "artifact_present": artifact_present,
861
+ "artifact_env_matches": env_matches,
862
+ },
863
+ }
864
+ bound = bool(env_id and artifact_present and env_matches)
865
+ return {"bound": bound, "binding": binding}
866
+
867
+
868
+ # ---------------------------------------------------------------------------
869
+ # LIVE PROBE
870
+ # ---------------------------------------------------------------------------
871
+
872
+
873
+ def probe(adapter_id: str, root: Path | str) -> dict[str, Any]:
874
+ """Consumption probe: consumed=True only from an executed host-native echo;
875
+ structural file checks are prerequisites, explicitly not consumption."""
876
+ root = Path(root).resolve()
877
+ if adapter_id not in _SURFACE_TABLE:
878
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
879
+ target = catalog_target(adapter_id)
880
+ surface = _PROBE_SURFACE[adapter_id]
881
+ artifact = root / target
882
+ det = detect(adapter_id, root)
883
+ env_id = _manifest_env_id(root)
884
+ evidence: dict[str, Any] = {
885
+ "artifact": {"path": target, "present": artifact.is_file()},
886
+ "host": {"status": det["status"], "method": det["method"]},
887
+ "attempts": [],
888
+ "gap": None,
889
+ }
890
+ if not artifact.is_file():
891
+ evidence["gap"] = "artifact missing — nothing for a host to consume"
892
+ return {"consumed": False, "surface": surface, "evidence": evidence}
893
+
894
+ try:
895
+ text = artifact.read_text(encoding="utf-8")
896
+ evidence["artifact"]["readable"] = True
897
+ except (OSError, UnicodeDecodeError) as exc:
898
+ evidence["artifact"]["readable"] = False
899
+ evidence["gap"] = f"artifact unreadable: {exc}"
900
+ return {"consumed": None, "surface": surface, "evidence": evidence}
901
+ if target.endswith(".json"):
902
+ try:
903
+ json.loads(text)
904
+ evidence["artifact"]["valid_json"] = True
905
+ except json.JSONDecodeError as exc:
906
+ evidence["artifact"]["valid_json"] = False
907
+ evidence["gap"] = (f"artifact fails the host's own JSON parse: {exc}")
908
+ return {"consumed": False, "surface": surface, "evidence": evidence}
909
+ else:
910
+ adapter = _central().get_adapter(adapter_id)
911
+ complete = ((adapter.start_marker in text) == (adapter.end_marker in text))
912
+ evidence["artifact"]["markers_complete"] = complete
913
+ if not complete:
914
+ evidence["gap"] = "incomplete managed markers — host would see a broken block"
915
+ return {"consumed": False, "surface": surface, "evidence": evidence}
916
+ if env_id:
917
+ evidence["artifact"]["env_matches"] = env_id in text
918
+
919
+ if det["status"] == "absent":
920
+ evidence["gap"] = "host not installed on this machine — no consumer exists"
921
+ return {"consumed": False, "surface": surface, "evidence": evidence}
922
+ if det["status"] == "unknown":
923
+ evidence["gap"] = "host presence unknown (residue-only/unevaluable surfaces)"
924
+ return {"consumed": None, "surface": surface, "evidence": evidence}
925
+
926
+ command = ECHO_COMMANDS.get(adapter_id)
927
+ if command:
928
+ argv = [part.format(target=str(artifact), env_id=env_id or "")
929
+ for part in command]
930
+ attempt: dict[str, Any] = {"kind": "host_echo", "argv0": argv[0]}
931
+ evidence["attempts"].append(attempt)
932
+ try:
933
+ # Bytes mode on purpose: host output is evidence, decoded as UTF-8
934
+ # with replacement so a locale-limited child (POSIX C locale,
935
+ # PYTHONIOENCODING=ascii) can never fake a failed proof.
936
+ proc = subprocess.run(argv, capture_output=True, timeout=30)
937
+ except (OSError, subprocess.SubprocessError) as exc:
938
+ evidence["gap"] = f"host echo surface failed: {type(exc).__name__}: {exc}"
939
+ return {"consumed": None, "surface": surface, "evidence": evidence}
940
+ stdout = (proc.stdout or b"").decode("utf-8", errors="replace")
941
+ attempt.update({"returncode": proc.returncode,
942
+ "stdout_head": stdout[:400]})
943
+ token = env_id or target
944
+ if proc.returncode == 0 and token and token in stdout:
945
+ evidence["gap"] = None
946
+ return {"consumed": True, "surface": surface, "evidence": evidence}
947
+ evidence["gap"] = "host echo ran but did not echo this artifact's binding"
948
+ return {"consumed": None, "surface": surface, "evidence": evidence}
949
+
950
+ evidence["gap"] = (
951
+ f"no executed host-native consumption surface: {surface}; structural "
952
+ "validity above is a prerequisite, not proof of host loading"
953
+ )
954
+ return {"consumed": None, "surface": surface, "evidence": evidence}
955
+
956
+
957
+ # ---------------------------------------------------------------------------
958
+ # LIFECYCLE
959
+ # ---------------------------------------------------------------------------
960
+
961
+ _EVENTS = ("restart", "upgrade", "rebind", "host_installed", "host_removed")
962
+
963
+
964
+ def lifecycle(adapter_id: str, root: Path | str, event: str) -> dict[str, Any]:
965
+ """Event handling: restart | upgrade | rebind | host_installed | host_removed."""
966
+ if event not in _EVENTS:
967
+ raise ValueError(f"unknown lifecycle event {event!r}; expected one of {_EVENTS}")
968
+ root = Path(root).resolve()
969
+ if adapter_id not in _SURFACE_TABLE:
970
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
971
+ det = detect(adapter_id, root)
972
+ out: dict[str, Any] = {
973
+ "event": event,
974
+ "adapter": adapter_id,
975
+ "family": FAMILY,
976
+ "detect": {"status": det["status"], "method": det["method"]},
977
+ "action": "noop",
978
+ "detail": "",
979
+ "safe": True,
980
+ }
981
+ if event == "host_removed":
982
+ if det["status"] == "absent":
983
+ result = deactivate(adapter_id, root)
984
+ out["action"] = result["action"]
985
+ out["detail"] = result["detail"]
986
+ out["safe"] = result["safe"]
987
+ else:
988
+ out["detail"] = (f"host still {det['status']}; refusing to remove the "
989
+ "native artifact")
990
+ elif event in {"restart", "upgrade"}:
991
+ result = activate(adapter_id, root)
992
+ probe_result = probe(adapter_id, root)
993
+ out["action"] = result["action"]
994
+ out["safe"] = result.get("safe", True)
995
+ out["detail"] = (f"post-{event} recheck: activation {result['action']}; "
996
+ f"probe consumed={probe_result['consumed']}")
997
+ elif event == "host_installed":
998
+ if det["status"] == "installed":
999
+ result = activate(adapter_id, root)
1000
+ out["action"] = result["action"]
1001
+ out["safe"] = result.get("safe", True)
1002
+ out["detail"] = result["detail"]
1003
+ else:
1004
+ out["detail"] = f"host {det['status']} after install event; not activating"
1005
+ else: # rebind — refresh world/repo/HEAD content in an active artifact
1006
+ artifact = root / catalog_target(adapter_id)
1007
+ if artifact.is_file():
1008
+ result = activate(adapter_id, root)
1009
+ out["action"] = result["action"]
1010
+ out["safe"] = result.get("safe", True)
1011
+ out["detail"] = f"rebind refresh: {result['action']}"
1012
+ else:
1013
+ out["detail"] = "no artifact to rebind; run activate for a detected host"
1014
+ out["bound"] = bind(adapter_id, root)["bound"]
1015
+ return out
1016
+
1017
+
1018
+ # ---------------------------------------------------------------------------
1019
+ # HEALTH (permanent regression probe)
1020
+ # ---------------------------------------------------------------------------
1021
+
1022
+
1023
+ def health(adapter_id: str, root: Path | str) -> dict[str, Any]:
1024
+ """Permanent regression probe. regression=True only for breakage:
1025
+ registry drift, corrupt/stale/dormant artifacts."""
1026
+ root = Path(root).resolve()
1027
+ if adapter_id not in _SURFACE_TABLE:
1028
+ raise KeyError(f"unknown ide-rules member: {adapter_id!r}")
1029
+ issues: list[str] = []
1030
+ notes: list[str] = []
1031
+ target: str | None = None
1032
+ try:
1033
+ target = catalog_target(adapter_id)
1034
+ except KeyError:
1035
+ issues.append("member missing from catalogs/adapters.json")
1036
+ try:
1037
+ central_target = _central_target(adapter_id)
1038
+ if target is not None and central_target != target:
1039
+ notes.append(
1040
+ f"known central/catalog target divergence (coordinator "
1041
+ f"reconciliation): central writes {central_target!r}, catalog "
1042
+ f"declares {target!r}; activated on the catalog target"
1043
+ )
1044
+ except Exception as exc: # noqa: BLE001 — registry drift must surface
1045
+ issues.append(f"central adapter registry unusable: {type(exc).__name__}: {exc}")
1046
+
1047
+ det = detect(adapter_id, root)
1048
+ artifact = root / target if target else None
1049
+ if artifact is not None and artifact.is_file():
1050
+ try:
1051
+ text = artifact.read_text(encoding="utf-8", errors="replace")
1052
+ except OSError as exc:
1053
+ issues.append(f"artifact unreadable: {exc}")
1054
+ text = None
1055
+ if text is not None:
1056
+ if target.endswith(".json"):
1057
+ try:
1058
+ payload = json.loads(text)
1059
+ if not _ours_json(payload):
1060
+ issues.append("JSON artifact lost its Cosmos payload")
1061
+ except json.JSONDecodeError as exc:
1062
+ issues.append(f"JSON artifact corrupt: {exc}")
1063
+ else:
1064
+ adapter = _central().get_adapter(adapter_id)
1065
+ has_start = adapter.start_marker in text
1066
+ has_end = adapter.end_marker in text
1067
+ if has_start != has_end:
1068
+ issues.append("incomplete managed markers (broken block)")
1069
+ elif has_start:
1070
+ env_id = _manifest_env_id(root)
1071
+ if env_id and env_id not in text:
1072
+ issues.append("artifact binding is stale (environment id mismatch)")
1073
+ if det["status"] == "absent":
1074
+ notes.append("artifact present while host is absent (kept for teammates)")
1075
+ else:
1076
+ if det["status"] == "installed":
1077
+ issues.append("host detected but artifact missing (dormant — run activate)")
1078
+ if det["status"] == "unknown":
1079
+ notes.append("host detection unknown; unknown never becomes supported")
1080
+ regression = bool(issues)
1081
+ state = ("artifact active" if artifact is not None and artifact.is_file()
1082
+ else "no artifact expected")
1083
+ detail = (f"host {det['status']}; {state}")
1084
+ if issues:
1085
+ detail += " | ISSUES: " + "; ".join(issues)
1086
+ if notes:
1087
+ detail += " | notes: " + "; ".join(notes)
1088
+ return {"regression": regression, "detail": detail}
1089
+
1090
+
1091
+ __all__ = [
1092
+ "FAMILY",
1093
+ "ADAPTERS",
1094
+ "ECHO_COMMANDS",
1095
+ "activate",
1096
+ "bind",
1097
+ "catalog_entry",
1098
+ "catalog_target",
1099
+ "deactivate",
1100
+ "detect",
1101
+ "health",
1102
+ "lifecycle",
1103
+ "primary_surfaces",
1104
+ "probe",
1105
+ ]