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,3082 @@
1
+ """Cosmos filesystem-watcher daemon supervisor (LC1.23, DEC-2026-0927-01).
2
+
3
+ The AC-019 watcher (``tools/cosmos_fs_watcher.py run_daemon()``) existed only
4
+ as an opt-in process nobody installed or supervised — dormant, and therefore
5
+ not "completed automatic functionality". This module makes it an installed,
6
+ supervised service with honest lifecycle state and proactive health.
7
+
8
+ Install contract (Windows-first, user level — no admin rights):
9
+
10
+ install preflight (repo + graph + watchdog) → render the OS plan →
11
+ write ``<root>/.cosmos/watcher/install.json`` → execute the plan
12
+ through an injectable *runner* (default: subprocess.run).
13
+ Windows plan = a user-level ``schtasks`` ONLOGON task named
14
+ ``CosmosWatcher-<repo>-<hash8>`` whose action is a DIRECT
15
+ ``pythonw.exe cosmos_daemon_supervisor.py supervise --root <root>``
16
+ invocation (W3.04: never a ``.cmd`` wrapper — that produced a
17
+ cmd.exe console at every logon; ``pythonw.exe`` is the
18
+ GUI-subsystem build of the same interpreter and has no console).
19
+ ``--dry-run`` renders and records the plan without executing it
20
+ (``os_install: planned-not-executed``).
21
+ supervise internal restart loop: spawns the watcher, heartbeats
22
+ ``supervisor.json`` every tick, restarts a dead watcher with
23
+ bounded exponential backoff, honours ``stop.request``, and
24
+ stops the child GRACEFULLY (watcher stop file first, then
25
+ terminate/kill only as a last resort).
26
+ start spawn a detached ``supervise`` process (no schtasks needed).
27
+ stop write ``stop.request``, wait for the supervisor to exit, then
28
+ force-terminate only if it refuses.
29
+ restart stop + start.
30
+ status honest state machine (below), never "completed" while dormant.
31
+ health the proactive probe S2's run-monitor (or CI) can poll; also
32
+ runs environment-drift detection and alert sync (LC1.23 #4).
33
+ alerts read the durable environment-change alert record.
34
+
35
+ State files, all under ``<root>/.cosmos/watcher/`` (the watcher's own health
36
+ namespace; ``.cosmos/run-monitor`` belongs to the run-monitor and is never
37
+ written here):
38
+
39
+ install.json install contract: paths, task name, plan, os_install
40
+ mode, harness fingerprint recorded at install time
41
+ supervisor.json supervisor heartbeat: pid, child pid, ts, restarts
42
+ heartbeat.json watcher heartbeat: pid, ts, ticks (written by the watcher)
43
+ baseline.json harness-environment baseline the drift detector
44
+ compares against (rewritten on each fresh supervise
45
+ start; the watcher writes one for unsupervised runs)
46
+ alerts.jsonl DURABLE environment-change alert record (append-only,
47
+ OPENED/RESOLVED pairs for each drift kind + the
48
+ restart-budget-exhausted state)
49
+ crash-loop.json marker: the supervisor exhausted its restart budget
50
+ (absent = no crash loop); removed automatically once a
51
+ fresh watcher heartbeat proves recovery
52
+ stop.request stop signal file (supervisor)
53
+ watcher-stop.request stop signal file (watcher, supervisor-written)
54
+ supervisor.log supervised process output (append)
55
+
56
+ Honest lifecycle states (``status``/``health`` → ``report["state"]``, the
57
+ only four values the health probe ever reports; the granular pre-overlay
58
+ value is preserved in ``report["substate"]``):
59
+
60
+ running 0 watcher heartbeat fresh — automatic capture is live
61
+ (substates: running-healthy, running-unsupervised)
62
+ degraded 1 something is wrong while the service is engaged:
63
+ supervisor alive but watcher heartbeat stale/absent
64
+ (running-degraded), environment drift detected while
65
+ installed/running, or the restart budget was exhausted
66
+ stopped 1 installed (real OS install), nothing running —
67
+ automatic capture is INACTIVE (never "completed");
68
+ substate: installed-not-running
69
+ not-installed 2 no install contract (or a dry-run-only plan) — the
70
+ watcher is opt-in and dormant; a fully supported honest
71
+ state that reports so and prints the install command;
72
+ substate: not-installed | installed-dry-run-not-active
73
+
74
+ Environment-change detection (LC1.23 #4): ``detect_drift()`` reports
75
+ ``root-moved`` (install contract root/watched paths no longer exist),
76
+ ``graph-missing``, ``permissions-lost`` (cannot write the watcher state dir
77
+ or append-open graph.json) and ``harness-change`` (a harness-facing config
78
+ file — AGENTS.md, CLAUDE.md, cosmos.environment.json, .claude/settings.json —
79
+ changed, appeared or vanished relative to the baseline). While the service
80
+ is engaged (installed or running) any drift transitions health to
81
+ ``degraded`` and opens a durable alert in ``alerts.jsonl``; the alert
82
+ RESOLVES when the condition clears. The watcher re-checks on every heartbeat
83
+ and the supervisor re-checks every few ticks, so drift is detected
84
+ automatically, not only on demand. Env-var drift (CLAUDECODE/TERM_PROGRAM)
85
+ is recorded in the baseline and reported informationally in
86
+ ``report["harness"]["env_match"]`` but never triggers degraded on its own —
87
+ the probe can legitimately run in a different terminal/session than the
88
+ logon-started task, and false "degraded forever" alarms are worse than
89
+ silence; harness *configuration* files are the durable harness signal.
90
+
91
+ A dry-run install, a written plan, or an existing config file is never
92
+ reported as an active service.
93
+ """
94
+ from __future__ import annotations
95
+
96
+ import argparse
97
+ import calendar
98
+ import ctypes
99
+ import hashlib
100
+ import json
101
+ import os
102
+ import shlex
103
+ import shutil
104
+ import signal
105
+ import sys
106
+ import time
107
+ from collections.abc import Callable, Sequence
108
+ from pathlib import Path
109
+ from typing import Any
110
+
111
+ if str(Path(__file__).resolve().parents[1]) not in sys.path:
112
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
113
+
114
+ from tools import cosmos_background as bg # noqa: E402
115
+ from tools import cosmos_proc as subprocess # noqa: E402 - after the path bootstrap
116
+
117
+ SCHEMA_INSTALL = "cosmos.watcher-install/1"
118
+ SCHEMA_SUPERVISOR = "cosmos.watcher-supervisor/1"
119
+ SCHEMA_HEARTBEAT = "cosmos.watcher-heartbeat/1"
120
+ SCHEMA_HEALTH = "cosmos.watcher-health/1"
121
+ SCHEMA_ALERT = "cosmos.watcher-alert/1"
122
+ SCHEMA_BASELINE = "cosmos.watcher-baseline/1"
123
+ SCHEMA_CRASH_LOOP = "cosmos.watcher-crash-loop/1"
124
+
125
+ WATCHER_DIR = Path(".cosmos") / "watcher"
126
+ INSTALL_FILE = "install.json"
127
+ SUPERVISOR_FILE = "supervisor.json"
128
+ HEARTBEAT_FILE = "heartbeat.json"
129
+ STOP_FILE = "stop.request"
130
+ WATCHER_STOP_FILE = "watcher-stop.request"
131
+ LOG_FILE = "supervisor.log"
132
+ ALERTS_FILE = "alerts.jsonl"
133
+ BASELINE_FILE = "baseline.json"
134
+ CRASH_LOOP_FILE = "crash-loop.json"
135
+
136
+ DEFAULT_DEBOUNCE_MS = 1500
137
+ DEFAULT_HEARTBEAT_INTERVAL = 5.0
138
+ SUPERVISOR_TICK_S = 1.0
139
+ FRESH_WINDOW_S = 15.0
140
+ MAX_RESTARTS = 20
141
+ RESTART_BACKOFF_S = 2.0
142
+ # W3.04: bounded retry window for the atomic heartbeat publish. Measured on the
143
+ # operator's host: 167/200 os.replace calls were refused while a concurrent
144
+ # reader held the destination, so a single attempt is not a real attempt.
145
+ #
146
+ # Bounded well under the 15 s freshness window for the same reason as the
147
+ # watcher: blocking past it turns a slow publish into a false "degraded". The
148
+ # supervisor tick is 1 s and `_write_json_or_skip` already defers a locked tick
149
+ # to the next one, so a short window loses nothing.
150
+ _PUBLISH_ATTEMPTS = 4
151
+ _PUBLISH_BACKOFF_S = 0.05 # ~0.30s between attempts
152
+ RESTART_BACKOFF_MAX_S = 10.0
153
+ DRIFT_CHECK_PERIOD_S = 5.0
154
+
155
+ # The four (and only four) health-probe states (LC1.23 required outcome #3).
156
+ STATE_RUNNING = "running"
157
+ STATE_STOPPED = "stopped"
158
+ STATE_NOT_INSTALLED = "not-installed"
159
+ STATE_DEGRADED = "degraded"
160
+ STATE_VALUES = (STATE_RUNNING, STATE_STOPPED, STATE_NOT_INSTALLED, STATE_DEGRADED)
161
+
162
+ # Granular substate -> honest state.
163
+ _STATE_OF_SUBSTATE: dict[str, str] = {
164
+ "running-healthy": STATE_RUNNING,
165
+ "running-unsupervised": STATE_RUNNING,
166
+ # W3.04 Option A: a watcher that is publishing `state: "starting"` is alive
167
+ # but NOT running — preflight/observer initialization is still in flight,
168
+ # so capture is not operational. It must never map to STATE_RUNNING.
169
+ "running-starting": STATE_DEGRADED,
170
+ "running-degraded": STATE_DEGRADED,
171
+ "installed-not-running": STATE_STOPPED,
172
+ "installed-dry-run-not-active": STATE_NOT_INSTALLED,
173
+ "not-installed": STATE_NOT_INSTALLED,
174
+ }
175
+ # Drift kinds and their durable alert records (alerts.jsonl).
176
+ DRIFT_ROOT_MOVED = "root-moved"
177
+ DRIFT_GRAPH_MISSING = "graph-missing"
178
+ DRIFT_PERMISSIONS = "permissions-lost"
179
+ DRIFT_HARNESS = "harness-change"
180
+ DRIFT_KINDS = (DRIFT_ROOT_MOVED, DRIFT_GRAPH_MISSING, DRIFT_PERMISSIONS, DRIFT_HARNESS)
181
+ ALERT_RESTART_BUDGET = "restart-budget-exhausted"
182
+ # W3.04: an ALIVE-but-wedged watcher is a distinct condition from a crash loop
183
+ # (the process never exits, so the restart-budget alert never fires). It needs
184
+ # its own kind or the durable record is silently refused by append_alert's
185
+ # ALERT_KINDS gate.
186
+ ALERT_WATCHER_WEDGED = "watcher-wedged"
187
+ # P0-03 (DEC-2026-1006-01 K.4): durable ATTRIBUTION kinds for heartbeat publish
188
+ # failures, capture/publication failures, capture-path git subprocess correlation
189
+ # and child spawn/exit identity. These kinds are written ONLY with
190
+ # event="OBSERVED" (see append_observed) -- never OPENED/RESOLVED -- so
191
+ # open_alert_kinds() and everything derived from it (state, substate,
192
+ # alerts_open, the drift RESOLVED loop, the uninstall close-loop) is
193
+ # byte-identical with or without these rows present. They make a failure
194
+ # attributable (timestamp, PID, stage, error, fs/git correlation); they never
195
+ # classify it and never claim a cause.
196
+ ALERT_HEARTBEAT_PUBLISH_FAILED = "heartbeat-publish-failed"
197
+ ALERT_SUPERVISOR_PUBLISH_FAILED = "supervisor-publish-failed"
198
+ ALERT_CAPTURE_PUBLISH_FAILED = "capture-publish-failed"
199
+ ALERT_GIT_SUBPROCESS = "git-subprocess"
200
+ ALERT_CHILD_LIFECYCLE = "child-lifecycle"
201
+ ALERT_KINDS = (*DRIFT_KINDS, ALERT_RESTART_BUDGET, ALERT_WATCHER_WEDGED,
202
+ ALERT_HEARTBEAT_PUBLISH_FAILED, ALERT_SUPERVISOR_PUBLISH_FAILED,
203
+ ALERT_CAPTURE_PUBLISH_FAILED, ALERT_GIT_SUBPROCESS,
204
+ ALERT_CHILD_LIFECYCLE)
205
+
206
+ # Harness-facing configuration files whose change constitutes a harness change.
207
+ HARNESS_FILE_CANDIDATES = (
208
+ "AGENTS.md",
209
+ "CLAUDE.md",
210
+ "cosmos.environment.json",
211
+ ".claude/settings.json",
212
+ )
213
+ # Env vars recorded in the baseline for transparency (never a drift trigger).
214
+ HARNESS_ENV_KEYS = ("CLAUDECODE", "TERM_PROGRAM")
215
+
216
+ Runner = Callable[..., Any]
217
+
218
+ EX_HEALTHY = 0
219
+ EX_NOT_RUNNING = 1
220
+ EX_NOT_INSTALLED = 2
221
+ EX_ERROR = 3
222
+
223
+ # Honest state -> probe exit code. running=0; anything not healthy=1;
224
+ # not-installed is its own supported outcome, not a failure disguised as one.
225
+ _EXIT_OF_STATE: dict[str, int] = {
226
+ STATE_RUNNING: EX_HEALTHY,
227
+ STATE_DEGRADED: EX_NOT_RUNNING,
228
+ STATE_STOPPED: EX_NOT_RUNNING,
229
+ STATE_NOT_INSTALLED: EX_NOT_INSTALLED,
230
+ }
231
+
232
+ _THIS_FILE = Path(__file__).resolve()
233
+ _TOOLS_DIR = _THIS_FILE.parent
234
+ _WATCHER_SCRIPT = _TOOLS_DIR / "cosmos_fs_watcher.py"
235
+
236
+
237
+ # ---------------------------------------------------------------------------
238
+ # paths / io helpers
239
+ # ---------------------------------------------------------------------------
240
+ def watcher_dir(root: str | os.PathLike[str] | None) -> Path:
241
+ return Path(_resolve_root(root)) / WATCHER_DIR
242
+
243
+
244
+ def _resolve_root(root: str | os.PathLike[str] | None) -> Path:
245
+ if root is None:
246
+ root = os.environ.get("COSMOS_ROOT") or os.getcwd()
247
+ path = Path(root).resolve()
248
+ # accept a subdirectory of the repo, like the retrieval index does
249
+ for candidate in (path, *path.parents):
250
+ if (candidate / ".git").exists():
251
+ return candidate
252
+ return path
253
+
254
+
255
+ # Windows ``os.replace`` is atomic for the *writer*, but not for a concurrent
256
+ # *reader*: MoveFileEx may delete the destination before renaming over it, so
257
+ # the path is momentarily absent (or locked) even while the writer publishes
258
+ # continuously. Measured on this host with one writer and four readers over
259
+ # 36896 reads: 19 returned None -- 15 FileNotFoundError, 1 PermissionError and
260
+ # 3 transient parse failures, i.e. 0.05% of reads of a file that never stopped
261
+ # existing for any practical purpose.
262
+ #
263
+ # A single-shot read therefore cannot distinguish "there is no record" from "I
264
+ # looked during the swap", and :func:`health` turns that guess into a claim:
265
+ # "supervisor is alive but the watcher heartbeat is missing -- the watcher
266
+ # process is down or wedged". That is a false accusation of a healthy daemon,
267
+ # made worse by load (the collision window widens when four CI shards compete),
268
+ # and it is exactly the fail-wrong the honest state machine exists to prevent.
269
+ #
270
+ # Confirm absence across a short window before reporting it. A record that is
271
+ # really absent still reads as None -- no threshold, grace or freshness value
272
+ # changes; only a swap in flight is absorbed.
273
+ _READ_CONFIRM_WINDOW_S = 0.05
274
+ _READ_CONFIRM_BACKOFF_S = 0.005
275
+
276
+
277
+ def _read_json(path: Path) -> dict[str, Any] | None:
278
+ """Read a small JSON record, never reporting a mid-swap read as absence."""
279
+ deadline = time.monotonic() + _READ_CONFIRM_WINDOW_S
280
+ while True:
281
+ try:
282
+ data = json.loads(path.read_text(encoding="utf-8"))
283
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
284
+ data = None
285
+ transient = True
286
+ else:
287
+ transient = False
288
+ if isinstance(data, dict):
289
+ return data
290
+ if not transient or time.monotonic() >= deadline:
291
+ # A parsed non-object is a real, durable answer: never retried.
292
+ return None
293
+ time.sleep(_READ_CONFIRM_BACKOFF_S)
294
+
295
+
296
+ def _write_json(path: Path, payload: dict[str, Any]) -> None:
297
+ """Publish ``payload`` to ``path`` atomically, tolerating a Windows lock.
298
+
299
+ ``os.replace`` is the right primitive, but on Windows it fails with
300
+ ``PermissionError`` whenever ANY other handle holds the destination without
301
+ ``FILE_SHARE_DELETE`` — an indexer, a virus scanner, or any concurrent
302
+ reader of ``supervisor.json``. Measured on this host: under a reader that
303
+ merely opens and closes the file in a loop, 167 of 200 replaces were
304
+ refused. That collision used to kill the whole supervisor loop, and a stale
305
+ heartbeat is indistinguishable from a dead watcher.
306
+
307
+ Three changes, together:
308
+
309
+ * the staging file is unique per write, so two writers can never fight over
310
+ the same ``.tmp``;
311
+ * the replace is retried across a bounded window (~3 s), which clears a
312
+ momentary holder;
313
+ * :func:`_write_json_or_skip` is what the heartbeat loops use: a persistent
314
+ holder defers the write to the next tick instead of killing the daemon.
315
+ The write stays atomic whenever it succeeds — a partial heartbeat is
316
+ worse than a late one.
317
+ """
318
+ path.parent.mkdir(parents=True, exist_ok=True)
319
+ tmp = path.with_suffix(f"{path.suffix}.{os.getpid()}.tmp")
320
+ tmp.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
321
+ last: OSError | None = None
322
+ try:
323
+ for attempt in range(_PUBLISH_ATTEMPTS):
324
+ try:
325
+ os.replace(tmp, path)
326
+ return
327
+ except PermissionError as exc:
328
+ last = exc
329
+ if attempt == _PUBLISH_ATTEMPTS - 1:
330
+ break
331
+ time.sleep(_PUBLISH_BACKOFF_S * (attempt + 1))
332
+ raise last if last is not None else OSError(f"could not publish {path}")
333
+ finally:
334
+ try:
335
+ tmp.unlink(missing_ok=True)
336
+ except OSError:
337
+ pass
338
+
339
+
340
+ def _write_json_or_skip(path: Path, payload: dict[str, Any],
341
+ on_error: Callable[[OSError], None] | None = None) -> bool:
342
+ """Best-effort publish for a heartbeat loop. Never raises.
343
+
344
+ Returns True when the file was published. A False return means the payload
345
+ was dropped, not that the daemon is broken: the caller keeps running and the
346
+ next tick re-publishes. Used by the supervisor/watchers so an unattended
347
+ daemon cannot be killed by a file lock it does not own.
348
+
349
+ P0-03: ``on_error``, when provided, receives the caught OSError before
350
+ False is returned, so a caller can make the dropped tick durably
351
+ attributable with the genuine error class and message. The callback's own
352
+ failure is swallowed and can never affect publication behaviour; callers
353
+ that pass nothing get the exact pre-P0-03 contract.
354
+ """
355
+ try:
356
+ _write_json(path, payload)
357
+ return True
358
+ except OSError as exc:
359
+ if on_error is not None:
360
+ try:
361
+ on_error(exc)
362
+ except Exception: # noqa: BLE001 - callback cannot affect publish
363
+ pass
364
+ return False
365
+
366
+
367
+ def _utcnow() -> str:
368
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
369
+
370
+
371
+ def _age_seconds(stamp: str | None) -> float | None:
372
+ if not stamp:
373
+ return None
374
+ try:
375
+ then = calendar.timegm(time.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ"))
376
+ except (ValueError, OverflowError):
377
+ return None
378
+ return max(0.0, time.time() - then)
379
+
380
+
381
+ def pid_alive(pid: Any) -> bool:
382
+ """Cross-platform liveness. Never uses os.kill(pid, 0) on Windows
383
+ (there it unconditionally terminates the process)."""
384
+ try:
385
+ pid = int(pid)
386
+ except (TypeError, ValueError):
387
+ return False
388
+ if pid <= 0:
389
+ return False
390
+ if os.name == "nt":
391
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
392
+ STILL_ACTIVE = 259
393
+ k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
394
+ handle = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
395
+ if not handle:
396
+ return False
397
+ try:
398
+ code = ctypes.c_ulong()
399
+ if not k32.GetExitCodeProcess(handle, ctypes.byref(code)):
400
+ return False
401
+ return code.value == STILL_ACTIVE
402
+ finally:
403
+ k32.CloseHandle(handle)
404
+ try:
405
+ os.kill(pid, 0)
406
+ except ProcessLookupError:
407
+ return False
408
+ except PermissionError:
409
+ return True
410
+ except OSError:
411
+ return False
412
+ return True
413
+
414
+
415
+ def task_name_for(root: Path) -> str:
416
+ digest = hashlib.sha1(str(root).encode("utf-8")).hexdigest()[:8]
417
+ safe = "".join(ch for ch in root.name if ch.isalnum() or ch in "-_") or "repo"
418
+ return f"CosmosWatcher-{safe}-{digest}"
419
+
420
+
421
+ # ---------------------------------------------------------------------------
422
+ # harness baseline + environment-drift detection (LC1.23 required #4)
423
+ # ---------------------------------------------------------------------------
424
+ def harness_files_fingerprint(root: str | os.PathLike[str]) -> dict[str, str | None]:
425
+ """Content hash (or None when absent) for each harness-facing config file."""
426
+ base = Path(root)
427
+ out: dict[str, str | None] = {}
428
+ for rel in HARNESS_FILE_CANDIDATES:
429
+ path = base / rel
430
+ try:
431
+ if path.is_file():
432
+ out[rel] = hashlib.sha256(path.read_bytes()).hexdigest()
433
+ else:
434
+ out[rel] = None
435
+ except OSError:
436
+ out[rel] = None
437
+ return out
438
+
439
+
440
+ def harness_env_snapshot() -> dict[str, str | None]:
441
+ """Env-var snapshot for transparency only (never a drift trigger)."""
442
+ return {key: os.environ.get(key) for key in HARNESS_ENV_KEYS}
443
+
444
+
445
+ def _record_firing(
446
+ root_path: Path,
447
+ *,
448
+ result: str,
449
+ source: str,
450
+ detail: dict[str, Any] | None = None,
451
+ ) -> None:
452
+ """Append one G3 auto-trigger firing record (best-effort, never raises).
453
+
454
+ Writes ``.cosmos/triggers/continuous-daemon.jsonl`` through the shared
455
+ ``record_trigger`` writer (LC1.33 LP3 handoff to C5b). Best-effort by
456
+ contract: a record that cannot be appended must never break the caller,
457
+ so every failure — including the lazy import — is swallowed.
458
+ """
459
+ try:
460
+ from tools.cosmos_session_start import record_trigger
461
+
462
+ record_trigger(
463
+ Path(root_path),
464
+ "continuous-daemon",
465
+ "daemon:supervisor-heartbeat",
466
+ result,
467
+ source=source,
468
+ detail=detail,
469
+ )
470
+ except Exception: # noqa: BLE001 - firing records are best-effort by contract
471
+ pass
472
+
473
+
474
+ def write_baseline(root: str | os.PathLike[str], *, source: str) -> dict[str, Any]:
475
+ """(Re)record the harness baseline. Called at install and at every fresh
476
+ supervise start — a deliberate restart is the documented remediation that
477
+ re-baselines the environment."""
478
+ root_path = _resolve_root(root)
479
+ payload: dict[str, Any] = {
480
+ "schema": SCHEMA_BASELINE,
481
+ "root": str(root_path),
482
+ "source": source,
483
+ "recorded_at": _utcnow(),
484
+ "files": harness_files_fingerprint(root_path),
485
+ "env": harness_env_snapshot(),
486
+ }
487
+ _write_json(watcher_dir(root_path) / BASELINE_FILE, payload)
488
+ # G3 firing record (LC1.33 LP3 handoff → C5b): one machine-matched line
489
+ # per real baseline write — i.e. per install / supervise start.
490
+ _record_firing(
491
+ root_path,
492
+ result="daemon-running",
493
+ source="tools/cosmos_daemon_supervisor.py write_baseline",
494
+ detail={"pid": os.getpid(), "baseline_source": source},
495
+ )
496
+ return payload
497
+
498
+
499
+ def ensure_baseline(root: str | os.PathLike[str], *, source: str) -> dict[str, Any]:
500
+ """Write a baseline only if none exists (never masks live drift)."""
501
+ root_path = _resolve_root(root)
502
+ existing = _read_json(watcher_dir(root_path) / BASELINE_FILE)
503
+ if existing and isinstance(existing.get("files"), dict):
504
+ return existing
505
+ return write_baseline(root_path, source=source)
506
+
507
+
508
+ def effective_baseline(
509
+ root_path: Path, config: dict[str, Any] | None
510
+ ) -> tuple[str, dict[str, Any] | None, dict[str, Any] | None]:
511
+ """Baseline in force: baseline.json (fresh) else install-time fingerprint."""
512
+ baseline = _read_json(watcher_dir(root_path) / BASELINE_FILE)
513
+ if baseline and isinstance(baseline.get("files"), dict):
514
+ return "baseline", baseline.get("files"), baseline.get("env")
515
+ fp = (config or {}).get("harness_fingerprint")
516
+ if isinstance(fp, dict) and isinstance(fp.get("files"), dict):
517
+ return "install", fp.get("files"), fp.get("env")
518
+ return "none", None, None
519
+
520
+
521
+ def _read_alerts(root: str | os.PathLike[str], *, limit: int = 2000) -> list[dict[str, Any]]:
522
+ path = watcher_dir(root) / ALERTS_FILE
523
+ try:
524
+ lines = path.read_text(encoding="utf-8").splitlines()[-limit:]
525
+ except (OSError, UnicodeDecodeError):
526
+ return []
527
+ records: list[dict[str, Any]] = []
528
+ for line in lines:
529
+ line = line.strip()
530
+ if not line:
531
+ continue
532
+ try:
533
+ rec = json.loads(line)
534
+ except json.JSONDecodeError:
535
+ continue
536
+ if isinstance(rec, dict):
537
+ records.append(rec)
538
+ return records
539
+
540
+
541
+ def open_alert_kinds(root: str | os.PathLike[str]) -> set[str]:
542
+ """Kinds with an OPENED record and no later RESOLVED record."""
543
+ opened: set[str] = set()
544
+ for rec in _read_alerts(root):
545
+ kind = rec.get("kind")
546
+ if not kind:
547
+ continue
548
+ if rec.get("event") == "OPENED":
549
+ opened.add(kind)
550
+ elif rec.get("event") == "RESOLVED":
551
+ opened.discard(kind)
552
+ return opened
553
+
554
+
555
+ def append_alert(
556
+ root: str | os.PathLike[str],
557
+ *,
558
+ event: str,
559
+ kind: str,
560
+ detail: str,
561
+ source: str,
562
+ state_from: str | None = None,
563
+ state_to: str | None = None,
564
+ evidence: Any = None,
565
+ ) -> dict[str, Any] | None:
566
+ """Append one durable alert record to <root>/.cosmos/watcher/alerts.jsonl.
567
+
568
+ Append-only JSONL: the record IS the durable evidence of the health
569
+ transition (state_from/state_to), so it survives state-file rewrites.
570
+ """
571
+ if kind not in ALERT_KINDS:
572
+ return None
573
+ root_path = _resolve_root(root)
574
+ wdir = watcher_dir(root_path)
575
+ rec: dict[str, Any] = {
576
+ "schema": SCHEMA_ALERT,
577
+ "event": event,
578
+ "kind": kind,
579
+ "ts": _utcnow(),
580
+ "root": str(root_path),
581
+ "source": source,
582
+ "state_from": state_from,
583
+ "state_to": state_to,
584
+ "detail": detail,
585
+ }
586
+ if evidence is not None:
587
+ rec["evidence"] = evidence
588
+ try:
589
+ wdir.mkdir(parents=True, exist_ok=True)
590
+ with open(wdir / ALERTS_FILE, "a", encoding="utf-8") as fh:
591
+ fh.write(json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n")
592
+ except OSError as exc: # never crash the probe/loop over alert I/O
593
+ print(f"[cosmos-supervisor] alert write failed: {exc}", file=sys.stderr)
594
+ return None
595
+ return rec
596
+
597
+
598
+ def append_observed(
599
+ root: str | os.PathLike[str],
600
+ *,
601
+ kind: str,
602
+ stage: str,
603
+ detail: str,
604
+ source: str,
605
+ evidence: dict[str, Any] | None = None,
606
+ ) -> dict[str, Any] | None:
607
+ """Append one durable P0-03 OBSERVED attribution record (K.4).
608
+
609
+ Attribution, not speculation: the record carries the contract fields --
610
+ UTC timestamp (via append_alert), producer PID, stage, concrete error
611
+ class and message, and the relevant fs/git correlation data where it is
612
+ cheaply available -- and nothing causal. Temporal adjacency is reported
613
+ as correlation (``claim: "correlation-only"``), never as cause.
614
+
615
+ ``event="OBSERVED"`` is deliberate and load-bearing:
616
+ :func:`open_alert_kinds` counts only OPENED/RESOLVED, so an OBSERVED row
617
+ can never open, close or perturb a health classification -- the P0-03
618
+ behavioural non-interference requirement holds by construction.
619
+
620
+ Telemetry must never break the producer: any failure here is printed to
621
+ stderr and returns ``None``; nothing raises.
622
+ """
623
+ try:
624
+ payload: dict[str, Any] = {
625
+ # Durable correlation/event ID linking related rows: producer pid
626
+ # + wall-clock nanoseconds is unique per row on this host.
627
+ "event_uid": f"{os.getpid()}-{time.time_ns()}",
628
+ "producer_pid": os.getpid(),
629
+ "stage": str(stage),
630
+ }
631
+ if evidence:
632
+ payload.update(evidence)
633
+ return append_alert(
634
+ root,
635
+ event="OBSERVED",
636
+ kind=kind,
637
+ detail=detail,
638
+ source=source,
639
+ evidence=payload,
640
+ )
641
+ except Exception as exc: # noqa: BLE001 - telemetry never propagates
642
+ print(f"[cosmos-supervisor] observed record write failed: {exc}", file=sys.stderr)
643
+ return None
644
+
645
+
646
+ # Git outcomes that terminate an observed operation (a row with outcome=in-flight
647
+ # is the START row; any row whose outcome is one of these is its terminal).
648
+ _GIT_TERMINAL_OUTCOMES = ("ok", "nonzero-exit", "timeout", "spawn-failed", "error")
649
+
650
+
651
+ def wedge_git_correlation(
652
+ root: str | os.PathLike[str],
653
+ child_pid: Any,
654
+ ) -> dict[str, Any] | None:
655
+ """P0-03 (K.4): durable, read-only git correlation for WEDGE evidence.
656
+
657
+ The supervisor is a DIFFERENT process from the watcher, so it cannot see
658
+ the watcher's in-memory operation registry. It can only read the durable
659
+ observations in ``.cosmos/watcher/alerts.jsonl`` through the existing
660
+ ``_read_alerts`` path.
661
+
662
+ Selection rule (honest overlap only):
663
+ * consider only event == "OBSERVED", kind == git-subprocess rows;
664
+ * rows must carry a valid ``operation_id`` in evidence;
665
+ * ``evidence.producer_pid`` must match the current ``child_pid``;
666
+ * an operation is *unmatched* when a START row (stage=git-start,
667
+ outcome=in-flight) exists for its operation_id but NO terminal row
668
+ (outcome in _GIT_TERMINAL_OUTCOMES) exists for the same id;
669
+ * if more than one unmatched operation matches the current child, the
670
+ one with the most recent durable START row wins (deterministic, by the
671
+ row's file order which is append-only).
672
+
673
+ Returns sanitized correlation evidence -- never raw argv, tokens, env, or
674
+ file contents. ``claim`` is always "correlation-only": temporal overlap
675
+ between a watcher-visible in-flight git operation and the wedge is
676
+ recorded as correlation, never as cause. Returns ``None`` when no
677
+ unmatched current-child operation exists.
678
+ """
679
+ try:
680
+ starts: dict[str, dict[str, Any]] = {}
681
+ terminals: set[str] = set()
682
+ for rec in _read_alerts(root):
683
+ if rec.get("event") != "OBSERVED":
684
+ continue
685
+ if rec.get("kind") != ALERT_GIT_SUBPROCESS:
686
+ continue
687
+ ev = rec.get("evidence") or {}
688
+ op_id = ev.get("operation_id")
689
+ if not op_id:
690
+ continue
691
+ if str(ev.get("producer_pid")) != str(child_pid):
692
+ continue
693
+ outcome = ev.get("outcome")
694
+ if outcome == "in-flight" or ev.get("stage") == "git-start":
695
+ starts[op_id] = ev # later rows overwrite: keeps the most recent
696
+ elif outcome in _GIT_TERMINAL_OUTCOMES:
697
+ terminals.add(op_id)
698
+ # Unmatched: has a START row and no terminal row.
699
+ unmatched = [ev for op_id, ev in starts.items() if op_id not in terminals]
700
+ if not unmatched:
701
+ return None
702
+ # Deterministic: the LAST start row in durable file order wins.
703
+ ev = unmatched[-1]
704
+ return {
705
+ "operation_id": ev.get("operation_id"),
706
+ "command_class": ev.get("command_class"),
707
+ "purpose": ev.get("purpose"),
708
+ "started_at": ev.get("started_at"),
709
+ "status": "in-flight",
710
+ "producer_pid": ev.get("producer_pid"),
711
+ "fs_context": ev.get("fs_context"),
712
+ "correlation_id": ev.get("correlation_id"),
713
+ "claim": "correlation-only",
714
+ }
715
+ except Exception: # noqa: BLE001 - correlation is best-effort by design
716
+ return None
717
+
718
+
719
+ def _state_write_probe(directory: Path) -> str | None:
720
+ """Try to create+remove a probe file; return the error text or None."""
721
+ try:
722
+ directory.mkdir(parents=True, exist_ok=True)
723
+ probe = directory / f".perm-probe-{os.getpid()}-{time.time_ns()}"
724
+ probe.write_text("probe\n", encoding="utf-8")
725
+ probe.unlink()
726
+ return None
727
+ except OSError as exc:
728
+ return f"{type(exc).__name__}: {exc}"
729
+
730
+
731
+ def _graph_write_probe(graph: Path) -> str | None:
732
+ """Append-open the graph (writes zero bytes) to prove write permission."""
733
+ try:
734
+ with open(graph, "a", encoding="utf-8"):
735
+ pass
736
+ return None
737
+ except OSError as exc:
738
+ return f"{type(exc).__name__}: {exc}"
739
+
740
+
741
+ def _same_path(a: str, b: str) -> bool:
742
+ try:
743
+ na = os.path.normcase(os.path.realpath(str(a)))
744
+ nb = os.path.normcase(os.path.realpath(str(b)))
745
+ except OSError: # pragma: no cover - realpath on broken paths
746
+ return str(a) == str(b)
747
+ return na == nb
748
+
749
+
750
+ def detect_drift(
751
+ root: str | os.PathLike[str] | None = None,
752
+ *,
753
+ config: dict[str, Any] | None = None,
754
+ baseline_files: dict[str, Any] | None = None,
755
+ ) -> list[dict[str, Any]]:
756
+ """Detect configuration/environment drift. Pure observation: no writes,
757
+ no state changes — every finding is {kind, detail, evidence}.
758
+
759
+ Kinds: root-moved, graph-missing, permissions-lost, harness-change.
760
+ """
761
+ root_path = _resolve_root(root)
762
+ wdir = watcher_dir(root_path)
763
+ findings: list[dict[str, Any]] = []
764
+ graph = root_path / ".cosmos" / "graph.json"
765
+
766
+ if not graph.is_file():
767
+ findings.append(
768
+ {
769
+ "kind": DRIFT_GRAPH_MISSING,
770
+ "detail": f".cosmos/graph.json is missing under {root_path}",
771
+ "evidence": {"graph": str(graph)},
772
+ }
773
+ )
774
+ else:
775
+ err = _graph_write_probe(graph)
776
+ if err:
777
+ findings.append(
778
+ {
779
+ "kind": DRIFT_PERMISSIONS,
780
+ "detail": f"cannot write graph.json: {err}",
781
+ "evidence": {"path": str(graph), "error": err},
782
+ }
783
+ )
784
+
785
+ if wdir.is_dir():
786
+ err = _state_write_probe(wdir)
787
+ if err:
788
+ findings.append(
789
+ {
790
+ "kind": DRIFT_PERMISSIONS,
791
+ "detail": f"cannot write watcher state dir {wdir}: {err}",
792
+ "evidence": {"path": str(wdir), "error": err},
793
+ }
794
+ )
795
+ elif (root_path / ".cosmos").exists() and not (root_path / ".cosmos").is_dir():
796
+ findings.append(
797
+ {
798
+ "kind": DRIFT_PERMISSIONS,
799
+ "detail": f".cosmos exists but is not a directory under {root_path}",
800
+ "evidence": {"path": str(root_path / ".cosmos")},
801
+ }
802
+ )
803
+
804
+ if config:
805
+ recorded_root = config.get("root")
806
+ if recorded_root and not _same_path(str(recorded_root), str(root_path)):
807
+ findings.append(
808
+ {
809
+ "kind": DRIFT_ROOT_MOVED,
810
+ "detail": (
811
+ f"install contract root {recorded_root} != current root "
812
+ f"{root_path} (repository moved or re-pointed)"
813
+ ),
814
+ "evidence": {"contract_root": str(recorded_root), "current_root": str(root_path)},
815
+ }
816
+ )
817
+ missing_paths = [
818
+ str(p) for p in (config.get("paths") or []) if not Path(str(p)).is_dir()
819
+ ]
820
+ if missing_paths:
821
+ findings.append(
822
+ {
823
+ "kind": DRIFT_ROOT_MOVED,
824
+ "detail": "watched path(s) no longer exist: " + ", ".join(missing_paths),
825
+ "evidence": {"missing_paths": missing_paths},
826
+ }
827
+ )
828
+
829
+ if baseline_files is not None:
830
+ current = harness_files_fingerprint(root_path)
831
+ changed = {
832
+ rel: {"baseline": baseline_files.get(rel), "current": current.get(rel)}
833
+ for rel in HARNESS_FILE_CANDIDATES
834
+ if baseline_files.get(rel) != current.get(rel)
835
+ }
836
+ if changed:
837
+ findings.append(
838
+ {
839
+ "kind": DRIFT_HARNESS,
840
+ "detail": "harness configuration changed: " + ", ".join(sorted(changed)),
841
+ "evidence": {"changed": changed},
842
+ }
843
+ )
844
+ return findings
845
+
846
+
847
+ def read_crash_loop(root: str | os.PathLike[str]) -> dict[str, Any] | None:
848
+ return _read_json(watcher_dir(root) / CRASH_LOOP_FILE)
849
+
850
+
851
+ def note_supervisor_gave_up(
852
+ root: str | os.PathLike[str],
853
+ *,
854
+ restarts: int,
855
+ last_exit: int | None,
856
+ state_from: str,
857
+ ) -> dict[str, Any]:
858
+ """Durable evidence that the restart budget was exhausted (LC1.23 #2).
859
+
860
+ Writes ``crash-loop.json`` and opens the matching alert, so a supervisor
861
+ that gives up surfaces as ``degraded`` instead of silently looking
862
+ ``stopped``.
863
+ """
864
+ root_path = _resolve_root(root)
865
+ marker: dict[str, Any] = {
866
+ "schema": SCHEMA_CRASH_LOOP,
867
+ "root": str(root_path),
868
+ "restarts": restarts,
869
+ "last_exit_code": last_exit,
870
+ "ts": _utcnow(),
871
+ }
872
+ already = read_crash_loop(root_path)
873
+ _write_json(watcher_dir(root_path) / CRASH_LOOP_FILE, marker)
874
+ if not already:
875
+ append_alert(
876
+ root_path,
877
+ event="OPENED",
878
+ kind=ALERT_RESTART_BUDGET,
879
+ detail=(
880
+ f"supervisor gave up after {restarts} restarts (last exit={last_exit}); "
881
+ f"automatic capture is degraded until a healthy run resumes"
882
+ ),
883
+ source="supervise",
884
+ state_from=state_from,
885
+ state_to=STATE_DEGRADED,
886
+ evidence=marker,
887
+ )
888
+ return marker
889
+
890
+
891
+ # ---------------------------------------------------------------------------
892
+ # preflight
893
+ # ---------------------------------------------------------------------------
894
+ def preflight(root: Path) -> dict[str, Any]:
895
+ checks: dict[str, Any] = {"root_exists": root.is_dir()}
896
+ graph = root / ".cosmos" / "graph.json"
897
+ checks["graph_exists"] = graph.is_file()
898
+ try:
899
+ import watchdog # noqa: F401
900
+
901
+ checks["watchdog"] = True
902
+ checks["watchdog_reason"] = "installed"
903
+ except ImportError as exc: # pragma: no cover - depends on host
904
+ checks["watchdog"] = False
905
+ checks["watchdog_reason"] = f"watchdog not importable: {exc}"
906
+ checks["watcher_script"] = str(_WATCHER_SCRIPT)
907
+ checks["watcher_script_exists"] = _WATCHER_SCRIPT.is_file()
908
+ ok = (
909
+ checks["root_exists"]
910
+ and checks["graph_exists"]
911
+ and checks["watchdog"]
912
+ and checks["watcher_script_exists"]
913
+ )
914
+ checks["ok"] = ok
915
+ if not ok:
916
+ missing = [
917
+ name
918
+ for name in ("root_exists", "graph_exists", "watchdog", "watcher_script_exists")
919
+ if not checks[name]
920
+ ]
921
+ checks["reason"] = "preflight failed: " + ", ".join(missing)
922
+ return checks
923
+
924
+
925
+ # ---------------------------------------------------------------------------
926
+ # plan rendering (what install would execute — visible before execution)
927
+ # ---------------------------------------------------------------------------
928
+ def render_plan(
929
+ root: Path,
930
+ *,
931
+ paths: Sequence[str],
932
+ debounce_ms: int,
933
+ heartbeat_interval: float,
934
+ python_exe: str | None = None,
935
+ platform: str | None = None,
936
+ systemctl_path: str | None = None,
937
+ ) -> list[dict[str, Any]]:
938
+ """Return the ordered OS commands for installing the supervised service.
939
+
940
+ Each entry: {id, platform, argv, description, execute: bool}.
941
+ Only entries for the active platform with execute=True are run.
942
+ """
943
+ platform = platform or ("windows" if os.name == "nt" else "posix")
944
+ python_exe = python_exe or sys.executable
945
+ wdir = watcher_dir(root)
946
+ supervisor_argv = [
947
+ python_exe,
948
+ str(_THIS_FILE),
949
+ "supervise",
950
+ "--root",
951
+ str(root),
952
+ "--debounce-ms",
953
+ str(debounce_ms),
954
+ "--heartbeat-interval",
955
+ str(heartbeat_interval),
956
+ ]
957
+ if paths:
958
+ supervisor_argv += ["--paths", *[str(p) for p in paths]]
959
+ plan: list[dict[str, Any]] = []
960
+ if platform == "windows":
961
+ # W3.04: the scheduled action points DIRECTLY at a GUI-subsystem
962
+ # pythonw.exe invocation. The previous design wrote and scheduled
963
+ # start-supervisor.cmd, which meant every logon flashed a cmd.exe
964
+ # console — the exact user-disruption this policy forbids. The
965
+ # provenance text file is still rendered (readable record of what the
966
+ # task runs); it is not what gets executed.
967
+ silent_launcher = windows_silent_launcher(python_exe)
968
+ task_argv = ([silent_launcher, *supervisor_argv[1:]] if silent_launcher
969
+ else supervisor_argv)
970
+ provenance = wdir / "start-supervisor.txt"
971
+ provenance_body = "Cosmos filesystem watcher supervisor (scheduled task action)\r\n" + \
972
+ " ".join(_win_quote(a) for a in task_argv) + "\r\n"
973
+ plan.append(
974
+ {
975
+ "id": "write-launcher",
976
+ "platform": "windows",
977
+ "argv": None,
978
+ "render_file": str(provenance),
979
+ "render_content": provenance_body,
980
+ "description": "provenance record of the scheduled task action (never executed)",
981
+ "execute": True,
982
+ }
983
+ )
984
+ if silent_launcher:
985
+ task_command = " ".join(_win_quote(a) for a in task_argv)
986
+ plan.append(
987
+ {
988
+ "id": "schtasks-create",
989
+ "platform": "windows",
990
+ "argv": [
991
+ "schtasks",
992
+ "/Create",
993
+ "/F",
994
+ "/TN",
995
+ task_name_for(root),
996
+ "/TR",
997
+ f'"{task_command}"',
998
+ "/SC",
999
+ "ONLOGON",
1000
+ "/RL",
1001
+ "LIMITED",
1002
+ ],
1003
+ "description": (
1004
+ "user-level ONLOGON scheduled task (no admin rights) launching "
1005
+ "pythonw.exe directly — no .cmd wrapper, no console window"
1006
+ ),
1007
+ "execute": True,
1008
+ }
1009
+ )
1010
+ else:
1011
+ plan.append(
1012
+ {
1013
+ "id": "schtasks-create",
1014
+ "platform": "windows",
1015
+ "argv": None,
1016
+ "description": (
1017
+ "REFUSED: no pythonw.exe beside "
1018
+ f"{python_exe!r}. A scheduled task cannot be installed with a "
1019
+ "console-producing launcher, so none is created — a silent "
1020
+ "watcher is preferable to a flashing one."
1021
+ ),
1022
+ "execute": False,
1023
+ "skipped": "no-silent-launcher",
1024
+ }
1025
+ )
1026
+ else:
1027
+ wrapper = wdir / "start-supervisor.sh"
1028
+ plan.append(
1029
+ {
1030
+ "id": "write-launcher",
1031
+ "platform": "posix",
1032
+ "argv": None,
1033
+ "render_file": str(wrapper),
1034
+ "render_content": "#!/bin/sh\nexec " + " ".join(shlex.quote(a) for a in supervisor_argv) + "\n",
1035
+ "description": "launcher script",
1036
+ "execute": True,
1037
+ }
1038
+ )
1039
+ systemctl = systemctl_path if systemctl_path is not None else shutil.which("systemctl")
1040
+ if systemctl:
1041
+ unit = wdir / "cosmos-fs-watcher.service"
1042
+ unit_body = (
1043
+ "[Unit]\nDescription=Cosmos filesystem watcher supervisor\n\n"
1044
+ "[Service]\nType=simple\nExecStart="
1045
+ + " ".join(shlex.quote(a) for a in supervisor_argv)
1046
+ + "\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n"
1047
+ )
1048
+ plan.append(
1049
+ {
1050
+ "id": "write-unit",
1051
+ "platform": "posix",
1052
+ "argv": None,
1053
+ "render_file": str(unit),
1054
+ "render_content": unit_body,
1055
+ "description": "systemd user unit",
1056
+ "execute": True,
1057
+ }
1058
+ )
1059
+ plan.append(
1060
+ {
1061
+ "id": "systemd-enable",
1062
+ "platform": "posix",
1063
+ "argv": [systemctl, "--user", "daemon-reload"],
1064
+ "description": "reload user units",
1065
+ "execute": True,
1066
+ }
1067
+ )
1068
+ plan.append(
1069
+ {
1070
+ "id": "systemd-enable",
1071
+ "platform": "posix",
1072
+ "argv": [systemctl, "--user", "enable", "--now", str(unit)],
1073
+ "description": "enable + start the supervised service",
1074
+ "execute": True,
1075
+ }
1076
+ )
1077
+ else:
1078
+ plan.append(
1079
+ {
1080
+ "id": "systemd-missing",
1081
+ "platform": "posix",
1082
+ "argv": None,
1083
+ "description": "no systemctl found: automatic OS-level install is NOT available here; "
1084
+ "run `start` manually or install systemd",
1085
+ "execute": False,
1086
+ }
1087
+ )
1088
+ return plan
1089
+
1090
+
1091
+ def _win_quote(arg: str) -> str:
1092
+ if not arg or any(ch in arg for ch in ' \t"'):
1093
+ return '"' + arg.replace('"', '\\"') + '"'
1094
+ return arg
1095
+
1096
+
1097
+ def windows_silent_launcher(python_exe: str) -> str | None:
1098
+ """The windowless sibling interpreter for ``python_exe``, or ``None``.
1099
+
1100
+ W3.04: a scheduled task must never launch a ``.cmd`` wrapper. ``cmd.exe``
1101
+ is a console-subsystem process, so the task created a real console window
1102
+ at every logon. ``pythonw.exe`` is the GUI-subsystem build of the same
1103
+ interpreter: it runs the identical module with no console at all. Falls
1104
+ back to ``None`` when the host has no ``pythonw.exe`` beside the
1105
+ interpreter, which callers must treat as "cannot install silently".
1106
+ """
1107
+ candidate = Path(python_exe).with_name("pythonw.exe")
1108
+ return str(candidate) if candidate.is_file() else None
1109
+
1110
+
1111
+ def _default_runner(argv: Sequence[str], **kwargs: Any) -> Any:
1112
+ # W3.04: every plan step (schtasks, systemctl) is autonomous background
1113
+ # work — windowless, and marked so anything it launches inherits the policy.
1114
+ return subprocess.run(list(argv), capture_output=True, text=True, timeout=120,
1115
+ **bg.spawn_kwargs(background=True),
1116
+ **{k: v for k, v in kwargs.items()
1117
+ if k not in ("creationflags", "startupinfo", "env")})
1118
+
1119
+
1120
+ def _execute_plan(
1121
+ plan: list[dict[str, Any]], *, runner: Runner, active_platform: str, dry_run: bool
1122
+ ) -> list[dict[str, Any]]:
1123
+ results: list[dict[str, Any]] = []
1124
+ for entry in plan:
1125
+ record: dict[str, Any] = {
1126
+ "id": entry["id"],
1127
+ "description": entry.get("description"),
1128
+ "argv": entry.get("argv"),
1129
+ "executed": False,
1130
+ }
1131
+ if entry.get("render_file") is not None:
1132
+ path = Path(entry["render_file"])
1133
+ record["render_file"] = str(path)
1134
+ if dry_run:
1135
+ record["skipped"] = "dry-run"
1136
+ else:
1137
+ path.parent.mkdir(parents=True, exist_ok=True)
1138
+ path.write_text(entry["render_content"], encoding="utf-8", newline="\n")
1139
+ if entry["id"] == "write-launcher" and os.name != "nt":
1140
+ path.chmod(0o755)
1141
+ record["executed"] = True
1142
+ record["detail"] = f"wrote {path}"
1143
+ results.append(record)
1144
+ continue
1145
+ argv = entry.get("argv")
1146
+ if not argv or not entry.get("execute") or entry.get("platform") != active_platform:
1147
+ record["skipped"] = "not active platform or not executable"
1148
+ results.append(record)
1149
+ continue
1150
+ if dry_run:
1151
+ record["skipped"] = "dry-run"
1152
+ results.append(record)
1153
+ continue
1154
+ try:
1155
+ proc = runner(list(argv))
1156
+ record["executed"] = True
1157
+ record["returncode"] = getattr(proc, "returncode", None)
1158
+ stdout = getattr(proc, "stdout", "") or ""
1159
+ stderr = getattr(proc, "stderr", "") or ""
1160
+ record["stdout_tail"] = stdout[-400:]
1161
+ record["stderr_tail"] = stderr[-400:]
1162
+ record["ok"] = record["returncode"] == 0
1163
+ except Exception as exc: # noqa: BLE001 - install reports, never crashes
1164
+ record["executed"] = True
1165
+ record["ok"] = False
1166
+ record["error"] = f"{type(exc).__name__}: {exc}"
1167
+ results.append(record)
1168
+ return results
1169
+
1170
+
1171
+ # ---------------------------------------------------------------------------
1172
+ # install / uninstall
1173
+ # ---------------------------------------------------------------------------
1174
+ def install(
1175
+ root: str | os.PathLike[str] | None = None,
1176
+ *,
1177
+ paths: Sequence[str] | None = None,
1178
+ debounce_ms: int = DEFAULT_DEBOUNCE_MS,
1179
+ heartbeat_interval: float = DEFAULT_HEARTBEAT_INTERVAL,
1180
+ dry_run: bool = False,
1181
+ runner: Runner | None = None,
1182
+ platform: str | None = None,
1183
+ python_exe: str | None = None,
1184
+ systemctl_path: str | None = None,
1185
+ ) -> dict[str, Any]:
1186
+ """Install the supervised watcher service (see module docstring)."""
1187
+ root_path = _resolve_root(root)
1188
+ platform = platform or ("windows" if os.name == "nt" else "posix")
1189
+ runner = runner or _default_runner
1190
+ report: dict[str, Any] = {
1191
+ "schema": SCHEMA_INSTALL,
1192
+ "root": str(root_path),
1193
+ "platform": platform,
1194
+ "dry_run": dry_run,
1195
+ "state": "not-installed",
1196
+ "preflight": preflight(root_path),
1197
+ "plan": [],
1198
+ "results": [],
1199
+ "os_install": "planned-not-executed",
1200
+ "reason": "",
1201
+ "hint": f"python { _THIS_FILE } status --root {root_path}",
1202
+ }
1203
+ if not report["preflight"]["ok"]:
1204
+ report["state"] = "cannot-install"
1205
+ report["reason"] = report["preflight"]["reason"]
1206
+ return report
1207
+
1208
+ watched = [str(Path(p)) for p in (paths or [str(root_path)])]
1209
+ plan = render_plan(
1210
+ root_path,
1211
+ paths=watched,
1212
+ debounce_ms=debounce_ms,
1213
+ heartbeat_interval=heartbeat_interval,
1214
+ python_exe=python_exe,
1215
+ platform=platform,
1216
+ systemctl_path=systemctl_path,
1217
+ )
1218
+ report["plan"] = plan
1219
+ results = _execute_plan(plan, runner=runner, active_platform=platform, dry_run=dry_run)
1220
+ report["results"] = results
1221
+
1222
+ executable_ids = [r["id"] for r in results if r.get("argv")]
1223
+ failed = [r for r in results if r.get("argv") and r.get("executed") and r.get("ok") is False]
1224
+ if dry_run:
1225
+ report["os_install"] = "planned-not-executed"
1226
+ report["reason"] = (
1227
+ "dry run: the plan was rendered and recorded, but NO OS task was created — "
1228
+ "automatic start is NOT active"
1229
+ )
1230
+ elif failed:
1231
+ report["os_install"] = "failed"
1232
+ report["reason"] = "OS install command(s) failed: " + "; ".join(
1233
+ f"{r['id']} rc={r.get('returncode')} {r.get('stderr_tail') or r.get('error') or ''}".strip()
1234
+ for r in failed
1235
+ )
1236
+ if not executable_ids:
1237
+ report["reason"] = "no executable install command for this platform"
1238
+ else:
1239
+ ran = [r for r in results if r.get("argv") and r.get("executed")]
1240
+ if ran:
1241
+ report["os_install"] = "executed"
1242
+ report["reason"] = (
1243
+ f"OS-level install executed ({len(ran)} command(s)); "
1244
+ f"task starts the supervisor at user logon"
1245
+ )
1246
+ else:
1247
+ report["os_install"] = "planned-not-executed"
1248
+ report["reason"] = (
1249
+ "no OS command executed on this platform — the plan is recorded but "
1250
+ "automatic start is NOT active; run `start` to run it now"
1251
+ )
1252
+
1253
+ config = {
1254
+ "schema": SCHEMA_INSTALL,
1255
+ "root": str(root_path),
1256
+ "paths": watched,
1257
+ "debounce_ms": int(debounce_ms),
1258
+ "heartbeat_interval": float(heartbeat_interval),
1259
+ "task_name": task_name_for(root_path),
1260
+ "platform": platform,
1261
+ "os_install": report["os_install"],
1262
+ "installed_at": _utcnow(),
1263
+ "dry_run": dry_run,
1264
+ "python": python_exe or sys.executable,
1265
+ "supervisor_script": str(_THIS_FILE),
1266
+ "watcher_script": str(_WATCHER_SCRIPT),
1267
+ "harness_fingerprint": {
1268
+ "files": harness_files_fingerprint(root_path),
1269
+ "env": harness_env_snapshot(),
1270
+ "recorded_at": _utcnow(),
1271
+ },
1272
+ "plan": [
1273
+ {"id": e["id"], "argv": e.get("argv"), "description": e.get("description"), "execute": e.get("execute")}
1274
+ for e in plan
1275
+ ],
1276
+ "results": results,
1277
+ }
1278
+ _write_json(watcher_dir(root_path) / INSTALL_FILE, config)
1279
+ # Install (re)baselines the environment: reinstalling is an explicit
1280
+ # operator action and therefore a legitimate drift remediation.
1281
+ write_baseline(root_path, source="install")
1282
+ report["state"] = "installed" if report["os_install"] in ("executed", "planned-not-executed", "failed") else "not-installed"
1283
+ report["install"] = config
1284
+ return report
1285
+
1286
+
1287
+ def uninstall(
1288
+ root: str | os.PathLike[str] | None = None,
1289
+ *,
1290
+ dry_run: bool = False,
1291
+ runner: Runner | None = None,
1292
+ ) -> dict[str, Any]:
1293
+ """Remove the OS registration and the install contract (never the graph)."""
1294
+ root_path = _resolve_root(root)
1295
+ runner = runner or _default_runner
1296
+ wdir = watcher_dir(root_path)
1297
+ config = _read_json(wdir / INSTALL_FILE)
1298
+ report: dict[str, Any] = {
1299
+ "schema": SCHEMA_INSTALL,
1300
+ "root": str(root_path),
1301
+ "state": "not-installed",
1302
+ "dry_run": dry_run,
1303
+ "results": [],
1304
+ "removed": [],
1305
+ "reason": "",
1306
+ }
1307
+ if config is None:
1308
+ report["reason"] = "nothing to uninstall: no install.json (service was never installed)"
1309
+ return report
1310
+ # stop first so we never deregister a live service
1311
+ if not dry_run:
1312
+ stop_report = stop(root_path, runner=runner)
1313
+ report["stop"] = stop_report.get("state")
1314
+ if config.get("platform") == "windows":
1315
+ argv = ["schtasks", "/Delete", "/TN", config.get("task_name", task_name_for(root_path)), "/F"]
1316
+ if config.get("os_install") != "executed":
1317
+ report["results"].append(
1318
+ {
1319
+ "id": "schtasks-delete",
1320
+ "argv": argv,
1321
+ "executed": False,
1322
+ "skipped": f"os_install={config.get('os_install')}: no OS task was created, so none is deleted",
1323
+ }
1324
+ )
1325
+ elif dry_run:
1326
+ report["results"].append({"id": "schtasks-delete", "argv": argv, "executed": False, "skipped": "dry-run"})
1327
+ else:
1328
+ proc = runner(list(argv))
1329
+ report["results"].append(
1330
+ {
1331
+ "id": "schtasks-delete",
1332
+ "argv": argv,
1333
+ "executed": True,
1334
+ "returncode": getattr(proc, "returncode", None),
1335
+ "ok": getattr(proc, "returncode", 0) == 0,
1336
+ "stdout_tail": (getattr(proc, "stdout", "") or "")[-400:],
1337
+ "stderr_tail": (getattr(proc, "stderr", "") or "")[-400:],
1338
+ }
1339
+ )
1340
+ elif config.get("platform") == "posix":
1341
+ systemctl = shutil.which("systemctl")
1342
+ if systemctl and not dry_run:
1343
+ proc = runner([systemctl, "--user", "disable", "--now", "cosmos-fs-watcher.service"])
1344
+ report["results"].append(
1345
+ {"id": "systemd-disable", "executed": True, "returncode": getattr(proc, "returncode", None)}
1346
+ )
1347
+ if not dry_run:
1348
+ for name in (
1349
+ INSTALL_FILE,
1350
+ SUPERVISOR_FILE,
1351
+ STOP_FILE,
1352
+ WATCHER_STOP_FILE,
1353
+ BASELINE_FILE,
1354
+ CRASH_LOOP_FILE,
1355
+ "start-supervisor.txt", # W3.04: provenance record, never executed
1356
+ "start-supervisor.cmd", # legacy pre-W3.04 console-producing launcher
1357
+ "start-supervisor.sh",
1358
+ "cosmos-fs-watcher.service",
1359
+ ):
1360
+ path = wdir / name
1361
+ if path.is_file():
1362
+ path.unlink()
1363
+ report["removed"].append(name)
1364
+ # Clean uninstall also closes any open alert: nothing engaged remains
1365
+ # to be degraded, and alerts.jsonl keeps the historical OPENED/RESOLVED
1366
+ # pair as durable evidence.
1367
+ for kind in sorted(open_alert_kinds(root_path)):
1368
+ append_alert(
1369
+ root_path,
1370
+ event="RESOLVED",
1371
+ kind=kind,
1372
+ detail="service uninstalled; alert closed by uninstall",
1373
+ source="uninstall",
1374
+ state_from=STATE_DEGRADED,
1375
+ state_to=STATE_NOT_INSTALLED,
1376
+ )
1377
+ report["state"] = "not-installed"
1378
+ report["reason"] = "service deregistered and install contract removed"
1379
+ else:
1380
+ report["state"] = "installed"
1381
+ report["reason"] = "dry run: nothing removed"
1382
+ return report
1383
+
1384
+
1385
+ # ---------------------------------------------------------------------------
1386
+ # H3b installation trigger (SessionStart refresh path; call site C3-owned)
1387
+ # ---------------------------------------------------------------------------
1388
+ def _in_test_process() -> bool:
1389
+ """True inside this repo's test suites — never in a real session/hook.
1390
+
1391
+ A test must NEVER create a real OS scheduled task/service on the
1392
+ operator's machine (LC1.23 brief), so the install trigger self-guards
1393
+ here in the file that owns the guard, whatever the caller is.
1394
+
1395
+ W3.04: the guard previously recognised only the ``runtime.tests.*`` module
1396
+ prefix. ``python -m unittest discover -s runtime/tests`` — how CI and the
1397
+ check runner actually invoke the suite — imports those same files as
1398
+ top-level ``test_*`` modules, so the guard returned False and a discovered
1399
+ test run could have driven a real install/activation. Detection is now by
1400
+ where the executing test modules actually live, not by one import name.
1401
+ """
1402
+ if "pytest" in sys.modules or os.environ.get("PYTEST_CURRENT_TEST"):
1403
+ return True
1404
+ if "runtime.tests" in sys.modules:
1405
+ return True
1406
+ for module in list(sys.modules.values()):
1407
+ origin = getattr(module, "__file__", None)
1408
+ if not origin:
1409
+ continue
1410
+ try:
1411
+ resolved = Path(origin).resolve()
1412
+ except (OSError, ValueError):
1413
+ continue
1414
+ parts = {part.lower() for part in resolved.parts}
1415
+ # Any module loaded from this repository's runtime/tests tree.
1416
+ if "runtime" in parts and "tests" in parts:
1417
+ tests_dir = _THIS_FILE.resolve().parent.parent / "runtime" / "tests"
1418
+ try:
1419
+ resolved.relative_to(tests_dir)
1420
+ return True
1421
+ except (ValueError, OSError):
1422
+ continue
1423
+ return False
1424
+
1425
+
1426
+ def _registration_missing(root_path: Path, config: dict[str, Any], *, runner: Runner | None = None) -> bool:
1427
+ """True when the install contract exists but the OS registration is gone.
1428
+
1429
+ Best-effort: if the query itself cannot run, assume the registration is
1430
+ intact (never destructively re-create on an unverifiable host).
1431
+ """
1432
+ runner = runner or _default_runner
1433
+ if config.get("platform") == "windows":
1434
+ try:
1435
+ proc = runner(
1436
+ ["schtasks", "/Query", "/TN", str(config.get("task_name") or task_name_for(root_path))]
1437
+ )
1438
+ return getattr(proc, "returncode", 1) != 0
1439
+ except Exception: # noqa: BLE001
1440
+ return False
1441
+ wdir = watcher_dir(root_path)
1442
+ return not ((wdir / "start-supervisor.sh").is_file() or (wdir / "cosmos-fs-watcher.service").is_file())
1443
+
1444
+
1445
+ def registration_disposition(root_path: Path) -> dict[str, Any]:
1446
+ """The truthful OS-registration posture, derived only from install state.
1447
+
1448
+ Never mutates anything. Separates the two questions that were previously
1449
+ conflated: whether the operator's logon lane is registered (a persistence
1450
+ property) and whether the background supervisor is running now (a liveness
1451
+ property). A refused registration must never be laundered into "installed",
1452
+ and it must never be allowed to prevent session-scoped operation either.
1453
+ """
1454
+ config = _read_json(watcher_dir(root_path) / INSTALL_FILE)
1455
+ os_install = str((config or {}).get("os_install") or "absent")
1456
+ if os_install == "executed":
1457
+ persistence, reason = "CONNECTED", "scheduled task registered"
1458
+ elif os_install in ("failed", "planned-not-executed"):
1459
+ persistence = "NOT_CONNECTED"
1460
+ reason = ("scheduled task registration did not complete "
1461
+ f"(os_install={os_install}); automatic-logon persistence is unavailable")
1462
+ else:
1463
+ persistence, reason = "NOT_INSTALLED", "no install contract"
1464
+ return {
1465
+ "automatic_logon_persistence": persistence,
1466
+ "session_scoped_activation": "available",
1467
+ "os_install": os_install,
1468
+ "reason": reason,
1469
+ "task_name": (config or {}).get("task_name"),
1470
+ "last_attempt_ts": (config or {}).get("installed_at"),
1471
+ "explicit_install_required_to_retry": True,
1472
+ }
1473
+
1474
+
1475
+ def ensure_installed_on_session_start(
1476
+ root: str | os.PathLike[str] | None = None,
1477
+ *,
1478
+ runner: Runner | None = None,
1479
+ allow_in_test_process: bool = False,
1480
+ start_fallback: bool = True,
1481
+ ) -> dict[str, Any]:
1482
+ """Installation + activation trigger for the SessionStart path (LC1.23 H3b).
1483
+
1484
+ Idempotent at every step. Self-guarded: never raises, never fires from a
1485
+ test process (unless the caller explicitly passes ``allow_in_test_process``),
1486
+ and never fires when ``COSMOS_DAEMON_NO_INSTALL`` is set.
1487
+
1488
+ The decision ladder, in order:
1489
+
1490
+ 1. already installed AND OS-registered -> no-op, nothing spawned;
1491
+ 2. no install contract, or the OS registration was lost -> attempt install
1492
+ (an *explicit* attempt, not a retry of one already known to be refused);
1493
+ 3. registration refused or unavailable -> do NOT retry it on every session.
1494
+ Record the truthful NOT_CONNECTED persistence state and fall back to
1495
+ session-scoped activation: start the SAME supervisor through the same
1496
+ :func:`start` path, windowless and detached, for this user session.
1497
+
1498
+ Step 3 is the point. Automatic-logon persistence being NOT_CONNECTED must
1499
+ not mean "Cosmos has no background lifecycle" -- an operator who starts a
1500
+ Cosmos session must silently get a healthy supervisor without being asked
1501
+ to run anything. Nothing here registers a Run key, a Startup entry, or
1502
+ mutates PATH/environment: SessionStart is an activation boundary Cosmos
1503
+ already owns, not a persistence workaround.
1504
+
1505
+ The call site belongs to C3's ``tools/cosmos_session_start.py``; the
1506
+ integration contract is::
1507
+
1508
+ try:
1509
+ from tools.cosmos_daemon_supervisor import ensure_installed_on_session_start
1510
+ ensure_installed_on_session_start(root)
1511
+ except Exception:
1512
+ pass
1513
+ """
1514
+ try:
1515
+ if os.environ.get("COSMOS_DAEMON_NO_INSTALL"):
1516
+ return {"state": "skipped", "reason": "COSMOS_DAEMON_NO_INSTALL set"}
1517
+ if not allow_in_test_process and _in_test_process():
1518
+ return {
1519
+ "state": "skipped",
1520
+ "reason": "test process: never create a real OS task from tests",
1521
+ }
1522
+ root_path = _resolve_root(root)
1523
+ config = _read_json(watcher_dir(root_path) / INSTALL_FILE)
1524
+ if (
1525
+ config
1526
+ and config.get("os_install") == "executed"
1527
+ and not _registration_missing(root_path, config, runner=runner)
1528
+ ):
1529
+ return {
1530
+ "state": "installed",
1531
+ "reason": "already installed and OS-registered (idempotent)",
1532
+ "task_name": config.get("task_name"),
1533
+ "registration": registration_disposition(root_path),
1534
+ "session_activation": "not-needed",
1535
+ }
1536
+ disposition = registration_disposition(root_path)
1537
+ if disposition["automatic_logon_persistence"] == "NOT_CONNECTED":
1538
+ # A registration already known to be refused is not retried here:
1539
+ # hammering a denied OS call on every session start is pointless and
1540
+ # hides the real state. An explicit `install`/recheck retries it.
1541
+ if not start_fallback:
1542
+ return {
1543
+ "state": "not-connected",
1544
+ "reason": disposition["reason"],
1545
+ "registration": disposition,
1546
+ "session_activation": "skipped",
1547
+ }
1548
+ live = _ensure_session_supervisor(root_path)
1549
+ return {
1550
+ "state": "session-activated" if live.get("started") else "session-active",
1551
+ "reason": (
1552
+ "automatic-logon persistence is NOT_CONNECTED ("
1553
+ f"{disposition['reason']}); activated the supervisor for this "
1554
+ "user session instead"
1555
+ ),
1556
+ "registration": disposition,
1557
+ "session_activation": live.get("state"),
1558
+ "supervisor_pid": live.get("supervisor_pid"),
1559
+ "watcher_pid": live.get("watcher_pid"),
1560
+ "substate": live.get("substate"),
1561
+ }
1562
+ report = install(root_path, runner=runner)
1563
+ if report.get("os_install") == "executed":
1564
+ return {
1565
+ "state": "installed",
1566
+ "reason": report.get("reason"),
1567
+ "task_name": (report.get("install") or {}).get("task_name"),
1568
+ "registration": registration_disposition(root_path),
1569
+ "session_activation": "not-needed",
1570
+ }
1571
+ if report.get("state") == "cannot-install":
1572
+ # Preflight refused the install outright (not a directory, no graph,
1573
+ # no watchdog). There is nothing to activate and nothing to fall
1574
+ # back to: this verdict must stay distinct from a refused OS
1575
+ # registration, which is exactly what the fallback below handles.
1576
+ return {
1577
+ "state": "cannot-install",
1578
+ "reason": report.get("reason"),
1579
+ "registration": registration_disposition(root_path),
1580
+ "session_activation": "not-applicable",
1581
+ }
1582
+ # Install was attempted and the OS refused it. Same fallback as step 3,
1583
+ # now with a fresh truthful disposition.
1584
+ disposition = registration_disposition(root_path)
1585
+ live = _ensure_session_supervisor(root_path) if start_fallback else {"state": "skipped"}
1586
+ return {
1587
+ "state": "session-activated" if live.get("started") else "session-active",
1588
+ "reason": (
1589
+ "scheduled-task registration refused; activated the supervisor for "
1590
+ f"this user session instead ({disposition['reason']})"
1591
+ ),
1592
+ "registration": disposition,
1593
+ "session_activation": live.get("state"),
1594
+ "supervisor_pid": live.get("supervisor_pid"),
1595
+ "watcher_pid": live.get("watcher_pid"),
1596
+ "install_reason": report.get("reason"),
1597
+ }
1598
+ except Exception as exc: # noqa: BLE001 - a session hook must never break
1599
+ return {"state": "error", "reason": f"{type(exc).__name__}: {exc}"}
1600
+
1601
+
1602
+ def _ensure_session_supervisor(root_path: Path) -> dict[str, Any]:
1603
+ """Session-scoped activation through the EXISTING lifecycle (:func:`start`).
1604
+
1605
+ Claims exactly what is implemented, nothing more:
1606
+
1607
+ * a healthy supervisor + healthy watcher is a no-op — ``start()`` reports
1608
+ "already running and healthy" without spawning anything;
1609
+ * a fresh supervisor whose watcher is missing or wedged is ALSO a no-op —
1610
+ ``start()`` reports that the supervisor's own recovery owns the child, so
1611
+ a second supervisor is never created;
1612
+ * no supervisor, or a dead one — ``start()`` spawns exactly one supervisor,
1613
+ which then owns its own watcher (and its own wedge recovery).
1614
+
1615
+ Recovery of a wedged child is the SUPERVISOR's job inside ``supervise()``,
1616
+ not this function's: this only ever decides whether a supervisor is needed.
1617
+ """
1618
+ report = start(root_path)
1619
+ supervisor = report.get("health", {}).get("supervisor") or {}
1620
+ watcher = report.get("health", {}).get("watcher") or {}
1621
+ return {
1622
+ "state": report.get("substate") or report.get("state"),
1623
+ "reason": report.get("reason"),
1624
+ "started": "supervisor started" in str(report.get("reason") or ""),
1625
+ "supervisor_pid": supervisor.get("pid"),
1626
+ "watcher_pid": watcher.get("pid"),
1627
+ "idempotent_noop": "idempotent start" in str(report.get("reason") or ""),
1628
+ }
1629
+
1630
+
1631
+ # ---------------------------------------------------------------------------
1632
+ # start / stop / restart
1633
+ # ---------------------------------------------------------------------------
1634
+ # Keep spawned supervisor handles referenced so their Popen.__del__ never
1635
+ # warns while the detached child is still running.
1636
+ _SPAWNED: list[Any] = []
1637
+
1638
+
1639
+ def _spawn_detached(argv: Sequence[str], log_path: Path) -> int:
1640
+ # W3.04: contain this process's subtree (supervisor -> watcher -> anything
1641
+ # either spawns) before it starts.
1642
+ bg.enforce_containment()
1643
+ log_path.parent.mkdir(parents=True, exist_ok=True)
1644
+ log_fh = open(log_path, "a", encoding="utf-8", errors="replace") # noqa: SIM115 - long-lived handle
1645
+ kwargs: dict[str, Any] = {
1646
+ "stdin": subprocess.DEVNULL,
1647
+ "stdout": log_fh,
1648
+ "stderr": log_fh,
1649
+ "close_fds": True,
1650
+ }
1651
+ if os.name == "nt":
1652
+ # W3.04: detached supervisor root — no console, and it marks its own
1653
+ # environment so its watcher child and every git/python/node descendant
1654
+ # stays headless.
1655
+ kwargs.update(bg.spawn_kwargs(background=True, detached=True))
1656
+ else:
1657
+ kwargs["start_new_session"] = True
1658
+ try:
1659
+ proc = subprocess.Popen(list(argv), **kwargs)
1660
+ finally:
1661
+ log_fh.close()
1662
+ _SPAWNED.append(proc)
1663
+ return proc.pid
1664
+
1665
+
1666
+ def start(
1667
+ root: str | os.PathLike[str] | None = None,
1668
+ *,
1669
+ timeout: float = 20.0,
1670
+ child_argv: Sequence[str] | None = None,
1671
+ ) -> dict[str, Any]:
1672
+ """Start the detached supervisor loop (does not create any OS task)."""
1673
+ root_path = _resolve_root(root)
1674
+ wdir = watcher_dir(root_path)
1675
+ config = _read_json(wdir / INSTALL_FILE)
1676
+ report: dict[str, Any] = {
1677
+ "schema": SCHEMA_INSTALL,
1678
+ "root": str(root_path),
1679
+ "state": "not-installed",
1680
+ "reason": "",
1681
+ }
1682
+ if config is None:
1683
+ report["reason"] = (
1684
+ "not installed: run "
1685
+ f"`python {_THIS_FILE} install --root {root_path}` first"
1686
+ )
1687
+ return report
1688
+ before = health(root_path)
1689
+ sup_fresh = bool(before["supervisor"].get("fresh"))
1690
+ if before["substate"] == "running-healthy" and sup_fresh:
1691
+ report["state"] = before["state"]
1692
+ report["substate"] = before["substate"]
1693
+ report["reason"] = (
1694
+ "already running and healthy (idempotent start)"
1695
+ + (
1696
+ "; environment drift open — run `restart` to re-baseline"
1697
+ if before["state"] != STATE_RUNNING
1698
+ else ""
1699
+ )
1700
+ )
1701
+ report["health"] = before
1702
+ return report
1703
+ if sup_fresh:
1704
+ # W3.04: the supervisor is alive and publishing, but its watcher is not
1705
+ # (substate running-degraded). That is exactly the state supervise() now
1706
+ # recovers on its own, inside its bounded restart budget. Spawning a
1707
+ # SECOND supervisor here would be the duplicate that SessionStart
1708
+ # fallback activation explicitly promises never to create, and it would
1709
+ # abandon the child already being recovered. So: report, do not spawn.
1710
+ report["state"] = before["state"]
1711
+ report["substate"] = before["substate"]
1712
+ report["reason"] = (
1713
+ "supervisor already running and fresh; its watcher is being recovered by "
1714
+ "the supervisor's own wedge recovery — no second supervisor spawned"
1715
+ )
1716
+ report["health"] = before
1717
+ return report
1718
+ if before["watcher"].get("fresh") and not sup_fresh:
1719
+ # A watcher is running but unsupervised: stop it gracefully first so
1720
+ # the new supervisor does not duplicate it.
1721
+ stop(root_path)
1722
+
1723
+ argv = [sys.executable, str(_THIS_FILE), "supervise", "--root", str(root_path)]
1724
+ if child_argv:
1725
+ argv += ["--child-json", json.dumps(list(child_argv))]
1726
+ pid = _spawn_detached(argv, wdir / LOG_FILE)
1727
+ deadline = time.monotonic() + timeout
1728
+ seen: dict[str, Any] | None = None
1729
+ while time.monotonic() < deadline:
1730
+ time.sleep(0.25)
1731
+ seen = _read_json(wdir / SUPERVISOR_FILE)
1732
+ if seen and pid_alive(seen.get("pid")):
1733
+ hb = _read_json(wdir / HEARTBEAT_FILE)
1734
+ # Only a `running` beat proves the watcher finished starting:
1735
+ # `starting` is live but the observer is not initialised yet, so
1736
+ # returning here would report a half-started daemon as up.
1737
+ if (
1738
+ hb
1739
+ and str(hb.get("state", "running")) == "running"
1740
+ and (_age_seconds(hb.get("ts")) or 999) <= FRESH_WINDOW_S
1741
+ ):
1742
+ break
1743
+ after = health(root_path)
1744
+ report["state"] = after["state"]
1745
+ report["substate"] = after["substate"]
1746
+ report["health"] = after
1747
+ if after["state"] in (STATE_RUNNING, STATE_DEGRADED):
1748
+ report["reason"] = f"supervisor started (pid {pid}); {after['substate']}"
1749
+ else:
1750
+ report["reason"] = (
1751
+ f"supervisor spawn pid {pid} did not become healthy within {timeout}s — "
1752
+ f"see {wdir / LOG_FILE}"
1753
+ )
1754
+ return report
1755
+
1756
+
1757
+ def stop(root: str | os.PathLike[str] | None = None, *, timeout: float = 15.0, runner: Runner | None = None) -> dict[str, Any]:
1758
+ """Graceful stop: stop.request first, force only as a last resort."""
1759
+ root_path = _resolve_root(root)
1760
+ wdir = watcher_dir(root_path)
1761
+ runner = runner or _default_runner
1762
+ report: dict[str, Any] = {
1763
+ "schema": SCHEMA_INSTALL,
1764
+ "root": str(root_path),
1765
+ "state": "not-installed",
1766
+ "forced": False,
1767
+ "reason": "",
1768
+ }
1769
+ config = _read_json(wdir / INSTALL_FILE)
1770
+ supervisor = _read_json(wdir / SUPERVISOR_FILE)
1771
+ heartbeat = _read_json(wdir / HEARTBEAT_FILE)
1772
+ if config is None and supervisor is None and heartbeat is None:
1773
+ report["reason"] = "not installed and nothing running — nothing to stop"
1774
+ return report
1775
+
1776
+ supervisor_pid = (supervisor or {}).get("pid")
1777
+ child_pid = (supervisor or {}).get("child_pid") or (heartbeat or {}).get("pid")
1778
+ if supervisor_pid and pid_alive(supervisor_pid):
1779
+ _write_json(wdir / STOP_FILE, {"schema": SCHEMA_INSTALL, "requested_at": _utcnow()})
1780
+ deadline = time.monotonic() + timeout
1781
+ while time.monotonic() < deadline and pid_alive(supervisor_pid):
1782
+ time.sleep(0.25)
1783
+ if pid_alive(supervisor_pid):
1784
+ _terminate_pid(supervisor_pid, runner=runner)
1785
+ report["forced"] = True
1786
+ if child_pid and pid_alive(child_pid):
1787
+ deadline = time.monotonic() + 5
1788
+ while time.monotonic() < deadline and pid_alive(child_pid):
1789
+ time.sleep(0.2)
1790
+ if pid_alive(child_pid):
1791
+ _terminate_pid(child_pid, runner=runner)
1792
+ report["forced"] = True
1793
+ report["reason"] = "supervisor stopped" + (" (forced)" if report["forced"] else " (graceful)")
1794
+ elif child_pid and pid_alive(child_pid):
1795
+ # Orphaned watcher (no supervisor): give it the same graceful stop
1796
+ # signal the supervisor would use, then force only if it refuses.
1797
+ try:
1798
+ (wdir / WATCHER_STOP_FILE).write_text(
1799
+ json.dumps({"schema": SCHEMA_INSTALL, "requested_at": _utcnow()}) + "\n",
1800
+ encoding="utf-8",
1801
+ )
1802
+ except OSError:
1803
+ pass
1804
+ deadline = time.monotonic() + 8.0
1805
+ while time.monotonic() < deadline and pid_alive(child_pid):
1806
+ time.sleep(0.2)
1807
+ if pid_alive(child_pid):
1808
+ _terminate_pid(child_pid, runner=runner)
1809
+ report["forced"] = True
1810
+ report["reason"] = (
1811
+ "orphaned watcher stopped"
1812
+ + (" (forced)" if report["forced"] else " (graceful)")
1813
+ )
1814
+ else:
1815
+ report["reason"] = "installed but nothing running"
1816
+ for path in (wdir / STOP_FILE, wdir / WATCHER_STOP_FILE, wdir / SUPERVISOR_FILE):
1817
+ try:
1818
+ if path.is_file():
1819
+ path.unlink()
1820
+ except OSError:
1821
+ pass
1822
+ report["state"] = "installed-stopped"
1823
+ return report
1824
+
1825
+
1826
+ def _terminate_pid(pid: Any, *, runner: Runner) -> None:
1827
+ try:
1828
+ pid = int(pid)
1829
+ except (TypeError, ValueError):
1830
+ return
1831
+ if os.name == "nt":
1832
+ try:
1833
+ subprocess.kill_tree(pid) # in-process Win32 (tools/cosmos_proc), no taskkill process
1834
+ except Exception: # noqa: BLE001
1835
+ pass
1836
+ else:
1837
+ for sig in (signal.SIGTERM, signal.SIGKILL):
1838
+ try:
1839
+ os.kill(pid, sig)
1840
+ except OSError:
1841
+ return
1842
+ time.sleep(1.0)
1843
+ if not pid_alive(pid):
1844
+ return
1845
+
1846
+
1847
+ def restart(root: str | os.PathLike[str] | None = None, **kwargs: Any) -> dict[str, Any]:
1848
+ root_path = _resolve_root(root)
1849
+ stop_report = stop(root_path)
1850
+ start_kwargs = {k: v for k, v in kwargs.items() if k in ("timeout", "child_argv")}
1851
+ start_report = start(root_path, **start_kwargs)
1852
+ return {
1853
+ "schema": SCHEMA_INSTALL,
1854
+ "root": str(root_path),
1855
+ "stop": stop_report,
1856
+ "start": start_report,
1857
+ "state": start_report["state"],
1858
+ "substate": start_report.get("substate"),
1859
+ "reason": start_report["reason"],
1860
+ }
1861
+
1862
+
1863
+ # ---------------------------------------------------------------------------
1864
+ # health / status (the honest state machine)
1865
+ # ---------------------------------------------------------------------------
1866
+ def health(
1867
+ root: str | os.PathLike[str] | None = None, *, sync_alerts: bool = True
1868
+ ) -> dict[str, Any]:
1869
+ """Proactive process/heartbeat/environment probe (LC1.23 #3 + #4).
1870
+
1871
+ Reports the honest four-state ``state`` — one of running | stopped |
1872
+ not-installed | degraded — plus the granular ``substate`` describing the
1873
+ process/install view underneath it. With ``sync_alerts`` (default) the
1874
+ probe also maintains the durable alert record: environment drift opens
1875
+ (and later resolves) an ``alerts.jsonl`` entry carrying the health
1876
+ transition, and a crash-loop marker closes once a fresh heartbeat proves
1877
+ recovery.
1878
+ """
1879
+ root_path = _resolve_root(root)
1880
+ wdir = watcher_dir(root_path)
1881
+ config = _read_json(wdir / INSTALL_FILE)
1882
+ supervisor = _read_json(wdir / SUPERVISOR_FILE)
1883
+ heartbeat = _read_json(wdir / HEARTBEAT_FILE)
1884
+ crash_loop = _read_json(wdir / CRASH_LOOP_FILE)
1885
+
1886
+ hb_age = _age_seconds((heartbeat or {}).get("ts"))
1887
+ sup_age = _age_seconds((supervisor or {}).get("ts"))
1888
+ hb_pid = (heartbeat or {}).get("pid")
1889
+ sup_pid = (supervisor or {}).get("pid")
1890
+ hb_state = (heartbeat or {}).get("state", "running")
1891
+ hb_running = hb_state == "running"
1892
+ sup_alive = bool(supervisor) and pid_alive(sup_pid)
1893
+ # Current-child identity (W3.04 Option A): a live supervisor names the child
1894
+ # that IS current. A heartbeat carrying any other pid — the previous
1895
+ # watcher, which stays fresh for a whole freshness window after it dies, or
1896
+ # a stray — must not prove health for a child that has published nothing
1897
+ # yet, and must not be mistaken for liveness.
1898
+ sup_child_pid = (supervisor or {}).get("child_pid")
1899
+ hb_is_current_child = not (sup_alive and sup_child_pid) or (
1900
+ hb_pid is not None and str(hb_pid) == str(sup_child_pid)
1901
+ )
1902
+ hb_alive = (
1903
+ bool(heartbeat) and hb_running and pid_alive(hb_pid) and hb_is_current_child
1904
+ )
1905
+ fresh_window = FRESH_WINDOW_S
1906
+ hb_fresh = hb_alive and hb_age is not None and hb_age <= max(3.0 * DEFAULT_HEARTBEAT_INTERVAL, fresh_window)
1907
+ if config:
1908
+ try:
1909
+ fresh_window = max(3.0 * float(config.get("heartbeat_interval", DEFAULT_HEARTBEAT_INTERVAL)), FRESH_WINDOW_S)
1910
+ except (TypeError, ValueError):
1911
+ pass
1912
+ hb_fresh = hb_alive and hb_age is not None and hb_age <= fresh_window
1913
+ sup_fresh = sup_alive and sup_age is not None and sup_age <= fresh_window
1914
+ # W3.04 Option A: `starting` is live liveness, never health. It is believed
1915
+ # only while it belongs to the current child, that child is alive, and the
1916
+ # record is still fresh — and even then it reports a NON-ready condition.
1917
+ hb_starting = (
1918
+ bool(heartbeat)
1919
+ and hb_state == "starting"
1920
+ and pid_alive(hb_pid)
1921
+ and hb_is_current_child
1922
+ and hb_age is not None
1923
+ and hb_age <= fresh_window
1924
+ )
1925
+
1926
+ # A crash-loop marker is honest only while the watcher is actually down.
1927
+ # A fresh heartbeat proves recovery: drop the marker (the alert sync
1928
+ # below then appends the matching RESOLVED record).
1929
+ if crash_loop is not None and hb_fresh:
1930
+ try:
1931
+ (wdir / CRASH_LOOP_FILE).unlink()
1932
+ except OSError:
1933
+ pass
1934
+ crash_loop = None
1935
+
1936
+ report: dict[str, Any] = {
1937
+ "schema": SCHEMA_HEALTH,
1938
+ "root": str(root_path),
1939
+ "checked_at": _utcnow(),
1940
+ "installed": config is not None,
1941
+ "os_install": (config or {}).get("os_install"),
1942
+ "task_name": (config or {}).get("task_name"),
1943
+ "automatic_capture": "inactive",
1944
+ "state": STATE_NOT_INSTALLED,
1945
+ "state_values": list(STATE_VALUES),
1946
+ "substate": "not-installed",
1947
+ "process_state": STATE_NOT_INSTALLED,
1948
+ "engaged": False,
1949
+ "reasons": [],
1950
+ "drift": [],
1951
+ "drift_kinds": [],
1952
+ "crash_loop": crash_loop is not None,
1953
+ "alerts_open": [],
1954
+ "harness": {
1955
+ "baseline_source": "none",
1956
+ "files_match": None,
1957
+ "env_match": None,
1958
+ },
1959
+ "supervisor": {
1960
+ "pid": sup_pid,
1961
+ "alive": sup_alive,
1962
+ "fresh": sup_fresh,
1963
+ "age_seconds": sup_age,
1964
+ "restarts": (supervisor or {}).get("restarts"),
1965
+ "child_pid": (supervisor or {}).get("child_pid"),
1966
+ },
1967
+ "watcher": {
1968
+ "pid": hb_pid,
1969
+ "alive": hb_alive,
1970
+ "fresh": hb_fresh,
1971
+ "starting": hb_starting,
1972
+ "state": hb_state,
1973
+ "matches_current_child": hb_is_current_child,
1974
+ "age_seconds": hb_age,
1975
+ "ticks": (heartbeat or {}).get("ticks"),
1976
+ "last_event_at": (heartbeat or {}).get("last_event_at"),
1977
+ },
1978
+ "exit_code": EX_NOT_INSTALLED,
1979
+ }
1980
+
1981
+ # --- process/install verdict -> substate --------------------------------
1982
+ substate = "not-installed"
1983
+ if hb_starting:
1984
+ # W3.04 Option A: the watcher process is alive and publishing, but
1985
+ # preflight/observer initialization has not finished, so capture is NOT
1986
+ # operational. This branch comes FIRST so a `starting` heartbeat can
1987
+ # never fall through to `running-healthy` (capture ready) or be
1988
+ # reported as "down or wedged" — both would be lies about the same
1989
+ # process.
1990
+ substate = "running-starting"
1991
+ report["reasons"].append(
1992
+ f"watcher STARTING (pid {hb_pid}, {hb_age:.1f}s old): phase "
1993
+ f"{(heartbeat or {}).get('phase', 'startup')} — startup liveness "
1994
+ f"only; the observer is not initialised yet, so capture is NOT "
1995
+ f"operational"
1996
+ )
1997
+ report["hint"] = (
1998
+ f"python {_THIS_FILE} health --root {root_path} # starting is "
1999
+ f"transient; re-check once it reports running"
2000
+ )
2001
+ elif config is None:
2002
+ if sup_fresh or hb_fresh:
2003
+ substate = "running-unsupervised"
2004
+ report["automatic_capture"] = "active-unsupervised"
2005
+ report["reasons"].append(
2006
+ "watcher process is alive but the service is NOT installed — it will not "
2007
+ "survive logoff/reboot; install to make it supervised"
2008
+ )
2009
+ else:
2010
+ report["reasons"].append(
2011
+ "watcher not installed: the continuous daemon is opt-in and currently "
2012
+ "INACTIVE (not an automatic capability)"
2013
+ )
2014
+ report["hint"] = f"python {_THIS_FILE} install --root {root_path}"
2015
+ elif (config or {}).get("os_install") == "planned-not-executed" and not (sup_fresh or hb_fresh):
2016
+ substate = "installed-dry-run-not-active"
2017
+ report["reasons"].append(
2018
+ "install was a dry run: no OS task exists, so the watcher will NOT start "
2019
+ "automatically (recorded honestly, never as completed)"
2020
+ )
2021
+ report["hint"] = f"python {_THIS_FILE} install --root {root_path} # without --dry-run"
2022
+ elif hb_fresh and (sup_fresh or not sup_alive):
2023
+ substate = "running-healthy"
2024
+ report["automatic_capture"] = "active"
2025
+ report["reasons"].append(
2026
+ f"watcher heartbeat fresh ({hb_age:.1f}s old, pid {hb_pid})"
2027
+ + (f"; supervisor fresh ({sup_age:.1f}s old, pid {sup_pid})" if sup_fresh else "; unsupervised run")
2028
+ )
2029
+ elif sup_fresh and not hb_fresh:
2030
+ substate = "running-degraded"
2031
+ report["reasons"].append(
2032
+ "supervisor is alive but the watcher heartbeat is "
2033
+ + (f"stale ({hb_age:.1f}s old)" if hb_age is not None else "missing")
2034
+ + " — the watcher process is down or wedged"
2035
+ )
2036
+ report["hint"] = f"python {_THIS_FILE} restart --root {root_path}"
2037
+ elif (config or {}).get("os_install") == "planned-not-executed":
2038
+ substate = "installed-dry-run-not-active"
2039
+ report["reasons"].append("dry-run install and nothing is running")
2040
+ else:
2041
+ substate = "installed-not-running"
2042
+ report["reasons"].append(
2043
+ "installed, but no live supervisor or watcher heartbeat — automatic capture is "
2044
+ "INACTIVE until started"
2045
+ )
2046
+ report["hint"] = f"python {_THIS_FILE} start --root {root_path}"
2047
+
2048
+ process_state = _STATE_OF_SUBSTATE[substate]
2049
+ engaged = process_state != STATE_NOT_INSTALLED
2050
+
2051
+ # --- environment drift (LC1.23 #4) --------------------------------------
2052
+ baseline_source, baseline_files, baseline_env = effective_baseline(root_path, config)
2053
+ drift = detect_drift(root_path, config=config, baseline_files=baseline_files)
2054
+ report["drift"] = drift
2055
+ report["drift_kinds"] = [d["kind"] for d in drift]
2056
+ current_files = harness_files_fingerprint(root_path) if baseline_files is not None else None
2057
+ harness_info: dict[str, Any] = {
2058
+ "baseline_source": baseline_source,
2059
+ "files_match": (
2060
+ None
2061
+ if baseline_files is None or current_files is None
2062
+ else baseline_files == current_files
2063
+ ),
2064
+ "baseline_env": baseline_env,
2065
+ "current_env": harness_env_snapshot() if baseline_env is not None else None,
2066
+ "env_match": (
2067
+ None
2068
+ if baseline_env is None
2069
+ else {k: baseline_env.get(k) for k in HARNESS_ENV_KEYS} == harness_env_snapshot()
2070
+ ),
2071
+ }
2072
+ report["harness"] = harness_info
2073
+ for finding in drift:
2074
+ report["reasons"].append(f"drift[{finding['kind']}]: {finding['detail']}")
2075
+
2076
+ final_state = process_state
2077
+ if drift and engaged:
2078
+ final_state = STATE_DEGRADED
2079
+ report["hint"] = report.get("hint") or f"python {_THIS_FILE} restart --root {root_path}"
2080
+
2081
+ if crash_loop is not None:
2082
+ if engaged:
2083
+ final_state = STATE_DEGRADED
2084
+ report["reasons"].append(
2085
+ "restart budget exhausted: the supervisor gave up after "
2086
+ f"{crash_loop.get('restarts')} restarts (last exit="
2087
+ f"{crash_loop.get('last_exit_code')}) — automatic capture is DEGRADED"
2088
+ )
2089
+ report["hint"] = report.get("hint") or f"python {_THIS_FILE} restart --root {root_path}"
2090
+ else:
2091
+ # stale marker (service no longer installed): close it.
2092
+ try:
2093
+ (wdir / CRASH_LOOP_FILE).unlink()
2094
+ except OSError:
2095
+ pass
2096
+ report["crash_loop"] = False
2097
+
2098
+ report["process_state"] = process_state
2099
+ report["engaged"] = engaged
2100
+ report["substate"] = substate
2101
+ report["state"] = final_state
2102
+ report["exit_code"] = _EXIT_OF_STATE[final_state]
2103
+ if final_state == STATE_RUNNING:
2104
+ report["automatic_capture"] = (
2105
+ "active-unsupervised" if substate == "running-unsupervised" else "active"
2106
+ )
2107
+ elif final_state in (STATE_STOPPED, STATE_NOT_INSTALLED):
2108
+ report["automatic_capture"] = "inactive"
2109
+ elif substate == "running-starting":
2110
+ # Starting is NOT capture: the observer has not been initialised yet,
2111
+ # so there is nothing to report as even partially active.
2112
+ report["automatic_capture"] = "inactive"
2113
+ else:
2114
+ report["automatic_capture"] = "degraded"
2115
+
2116
+ # --- durable alert record (OPENED/RESOLVED) ------------------------------
2117
+ want: set[str] = set(report["drift_kinds"]) if engaged else set()
2118
+ if report["crash_loop"] and engaged:
2119
+ want.add(ALERT_RESTART_BUDGET)
2120
+ if sync_alerts:
2121
+ existing = open_alert_kinds(root_path)
2122
+ if engaged:
2123
+ for kind in sorted(want - existing):
2124
+ finding = next(
2125
+ (d for d in drift if d["kind"] == kind),
2126
+ {"detail": "restart budget exhausted", "evidence": None},
2127
+ )
2128
+ append_alert(
2129
+ root_path,
2130
+ event="OPENED",
2131
+ kind=kind,
2132
+ detail=finding["detail"],
2133
+ source="health",
2134
+ state_from=process_state,
2135
+ state_to=final_state,
2136
+ evidence=finding.get("evidence"),
2137
+ )
2138
+ for kind in sorted(existing - want):
2139
+ if engaged and kind == ALERT_WATCHER_WEDGED:
2140
+ # W3.04: do NOT close a wedge alert from the drift re-check.
2141
+ # "no drift" says nothing about whether the replacement
2142
+ # watcher has published a fresh heartbeat, and this path
2143
+ # used to emit RESOLVED ~4 s after OPENED -- before the
2144
+ # replacement had even started. While a supervisor is
2145
+ # engaged it owns wedge resolution (see supervise(), which
2146
+ # closes the alert only once the replacement heartbeat is
2147
+ # genuinely fresh). The not-engaged branch below still
2148
+ # closes it when there is no supervisor left to recover it.
2149
+ continue
2150
+ append_alert(
2151
+ root_path,
2152
+ event="RESOLVED",
2153
+ kind=kind,
2154
+ detail="condition cleared (live re-check found no drift)",
2155
+ source="health",
2156
+ state_from=STATE_DEGRADED,
2157
+ state_to=final_state,
2158
+ )
2159
+ else:
2160
+ for kind in sorted(existing):
2161
+ append_alert(
2162
+ root_path,
2163
+ event="RESOLVED",
2164
+ kind=kind,
2165
+ detail="nothing engaged remains; alert closed",
2166
+ source="health",
2167
+ state_from=STATE_DEGRADED,
2168
+ state_to=final_state,
2169
+ )
2170
+ report["alerts_open"] = sorted(want) if engaged else []
2171
+ return report
2172
+
2173
+
2174
+ def status(root: str | os.PathLike[str] | None = None) -> dict[str, Any]:
2175
+ """Health plus the install contract (what was installed, and how)."""
2176
+ report = health(root)
2177
+ config = _read_json(watcher_dir(_resolve_root(root)) / INSTALL_FILE)
2178
+ report["install"] = config
2179
+ if config:
2180
+ report["paths"] = config.get("paths")
2181
+ report["debounce_ms"] = config.get("debounce_ms")
2182
+ report["installed_at"] = config.get("installed_at")
2183
+ return report
2184
+
2185
+
2186
+ # ---------------------------------------------------------------------------
2187
+ # supervise loop (internal)
2188
+ # ---------------------------------------------------------------------------
2189
+ def _stop_child_graceful(child: subprocess.Popen[bytes], stop_file: Path, *, timeout: float = 8.0) -> str:
2190
+ """Stop the watcher child gracefully, escalate only if it refuses.
2191
+
2192
+ Belt and braces (works for a detached/console-less supervisor too):
2193
+ write the watcher stop file AND send a console interrupt. The watcher
2194
+ honours both. Escalate terminate -> kill only past the bounded timeout.
2195
+ Returns the level reached: graceful | terminated | killed.
2196
+ """
2197
+ if child.poll() is not None:
2198
+ return "already-exited"
2199
+ try:
2200
+ stop_file.write_text(
2201
+ json.dumps({"schema": SCHEMA_INSTALL, "requested_at": _utcnow()}) + "\n",
2202
+ encoding="utf-8",
2203
+ )
2204
+ except OSError:
2205
+ pass
2206
+ try:
2207
+ if os.name == "nt":
2208
+ child.send_signal(signal.CTRL_BREAK_EVENT)
2209
+ else:
2210
+ child.send_signal(signal.SIGINT)
2211
+ except (OSError, ValueError):
2212
+ pass
2213
+ deadline = time.monotonic() + timeout
2214
+ while time.monotonic() < deadline and child.poll() is None:
2215
+ time.sleep(0.2)
2216
+ if child.poll() is not None:
2217
+ return "graceful"
2218
+ try:
2219
+ child.terminate()
2220
+ child.wait(timeout=5.0)
2221
+ return "terminated"
2222
+ except (OSError, subprocess.TimeoutExpired):
2223
+ pass
2224
+ try:
2225
+ child.kill()
2226
+ child.wait(timeout=5.0)
2227
+ except (OSError, subprocess.TimeoutExpired): # pragma: no cover
2228
+ pass
2229
+ return "killed"
2230
+
2231
+
2232
+ def _child_spawn_kwargs(platform: str | None = None) -> dict[str, Any]:
2233
+ """Spawn kwargs so the child gets its own group/session: the supervisor
2234
+ can then target it with CTRL_BREAK/SIGINT without hitting anything else.
2235
+
2236
+ W3.04: on Windows the child is *also* windowless. Group separation alone
2237
+ left the watcher with a real console when the supervisor had none — the
2238
+ popup this policy exists to stop."""
2239
+ kwargs: dict[str, Any] = {}
2240
+ if (platform or ("windows" if os.name == "nt" else "posix")) == "windows":
2241
+ # CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP: the pairing takes effect
2242
+ # (CREATE_NO_WINDOW is only ignored alongside DETACHED_PROCESS or
2243
+ # CREATE_NEW_CONSOLE), so the child stays signal-targetable *and*
2244
+ # console-free.
2245
+ policy = bg.spawn_kwargs(background=True)
2246
+ kwargs["creationflags"] = (
2247
+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
2248
+ | int(policy.get("creationflags", 0))
2249
+ )
2250
+ kwargs.update({k: v for k, v in policy.items() if k != "creationflags"})
2251
+ else:
2252
+ kwargs["start_new_session"] = True
2253
+ return kwargs
2254
+
2255
+
2256
+ #: W3.04 wedge detection. A watcher that is ALIVE but stops advancing its
2257
+ #: heartbeat is indistinguishable, from health(), from a dead one — yet
2258
+ #: ``supervise()`` only ever restarted a child that EXITED. These constants
2259
+ #: make the wedge test deterministic and immune to the three benign causes of a
2260
+ #: late heartbeat:
2261
+ #:
2262
+ #: * startup grace -- a fresh child has not published yet at all;
2263
+ #: * publish retry -- the atomic write retries ~0.30 s under a Windows
2264
+ #: file lock, so a lock delays one tick, not many;
2265
+ #: * transient scheduling -- a busy host can stretch one tick.
2266
+ #:
2267
+ #: THE ACTION CONTRACT, stated exactly as implemented (conservative by design):
2268
+ #:
2269
+ #: A single stale observation is NEVER a wedge. ``wedge_verdict`` is called
2270
+ #: with the ALREADY-ACCUMULATED count and only reports ``"wedged"`` once that
2271
+ #: count reaches ``WEDGE_STALE_OBSERVATIONS``; the count is incremented
2272
+ #: afterwards. The count therefore starts at 0, so:
2273
+ #:
2274
+ #: obs #1 -> count 1 -> "stale" obs #3 -> count 3 -> "stale"
2275
+ #: obs #2 -> count 2 -> "stale" obs #4 -> count 4 was >= 3 -> "wedged"
2276
+ #:
2277
+ #: **Action is taken on the 4th observed stale tick, after 3 previously
2278
+ #: accumulated stale observations.** It is NOT taken "at x3".
2279
+ #:
2280
+ #: Observations are one SUPERVISOR_TICK_S (1.0 s) apart, NOT 15 s apart, so
2281
+ #: the delay is NOT ``15 x 3 = 45 s``. The first stale observation can only
2282
+ #: occur once the heartbeat age first exceeds ``FRESH_WINDOW_S`` (15 s), and
2283
+ #: the three further tick intervals follow at 1 s each. The honest floor is
2284
+ #: therefore ``FRESH_WINDOW_S + WEDGE_STALE_OBSERVATIONS * SUPERVISOR_TICK_S``
2285
+ #: = 15 + 3 x 1 = **~18 s of continuous silence** (see
2286
+ #: :func:`wedge_min_silence_s`). Still far above the ~0.30 s publish-retry
2287
+ #: budget, so a momentary lock can never trigger it.
2288
+ #:
2289
+ #: Elapsed time from SPAWN is a different number because startup grace is a
2290
+ #: third, independent dimension: :func:`wedge_min_action_age_s` =
2291
+ #: ``WEDGE_STARTUP_GRACE_S + WEDGE_STALE_OBSERVATIONS * SUPERVISOR_TICK_S``
2292
+ #: = 30 + 3 x 1 = **33.0 s**. 15 s of freshness sits INSIDE the 30 s grace, so
2293
+ #: freshness can never be the binding term in production; grace is.
2294
+ WEDGE_STARTUP_GRACE_S = 30.0
2295
+ #: Stale observations that must ALREADY be accumulated before action; the
2296
+ #: action itself lands on the following (4th) observation. Kept deliberately
2297
+ #: conservative: acting on a false wedge costs a restart, missing a real wedge
2298
+ #: costs automatic capture.
2299
+ WEDGE_STALE_OBSERVATIONS = 3
2300
+
2301
+
2302
+ def wedge_min_silence_s(
2303
+ *,
2304
+ freshness_window_s: float = FRESH_WINDOW_S,
2305
+ observations: int = WEDGE_STALE_OBSERVATIONS,
2306
+ tick_s: float = SUPERVISOR_TICK_S,
2307
+ ) -> float:
2308
+ """Minimum continuous heartbeat silence before a wedge is acted on.
2309
+
2310
+ Truthful arithmetic for the conservative contract documented above: the
2311
+ heartbeat must first age past ``freshness_window_s`` (that is observation
2312
+ #1), and then ``observations`` further supervisor ticks elapse before the
2313
+ verdict reports ``"wedged"``.
2314
+
2315
+ NOTE: this is deliberately NOT ``freshness_window_s * observations``.
2316
+ Supervisor ticks are 1 s apart, so multiplying the freshness window by the
2317
+ observation count would overstate the delay by ~2.5x.
2318
+ """
2319
+ return freshness_window_s + observations * tick_s
2320
+
2321
+
2322
+ def wedge_min_action_age_s(
2323
+ *,
2324
+ startup_grace_s: float = WEDGE_STARTUP_GRACE_S,
2325
+ freshness_window_s: float = FRESH_WINDOW_S,
2326
+ observations: int = WEDGE_STALE_OBSERVATIONS,
2327
+ tick_s: float = SUPERVISOR_TICK_S,
2328
+ ) -> float:
2329
+ """Earliest elapsed time from child spawn at which a wedge is acted on.
2330
+
2331
+ Three independent dimensions, stated exactly as implemented:
2332
+
2333
+ * the child is untouchable for ``startup_grace_s`` (30.0 s);
2334
+ * a published heartbeat is fresh for ``freshness_window_s`` (15.0 s);
2335
+ * ``observations`` (3) stale observations must ACCUMULATE, and action
2336
+ lands on observation ``observations + 1`` — the 4th — one ``tick_s``
2337
+ (1.0 s) after each prior one.
2338
+
2339
+ The first stale observation comes from one of two places: a heartbeat that
2340
+ never arrived (judged the instant grace expires) or one that aged past
2341
+ freshness (never earlier than ``max(grace, freshness)``). The earliest of
2342
+ the two wins, so the floor is ``startup_grace_s + observations * tick_s``
2343
+ = 30 + 3 x 1 = **33.0 s**.
2344
+
2345
+ That is why freshness is NOT the binding term here: 15 s of freshness sits
2346
+ inside the 30 s grace, so both readings collapse to the same 33.0 s in
2347
+ production. Compare :func:`wedge_min_silence_s` (18.0 s), which measures
2348
+ *continuous silence* rather than time since spawn.
2349
+ """
2350
+ never_published = startup_grace_s + observations * tick_s
2351
+ published_then_frozen = (
2352
+ max(startup_grace_s, freshness_window_s) + observations * tick_s
2353
+ )
2354
+ return min(never_published, published_then_frozen)
2355
+
2356
+
2357
+ def wedge_verdict(
2358
+ *,
2359
+ heartbeat_age_s: float | None,
2360
+ child_alive: bool,
2361
+ uptime_s: float,
2362
+ consecutive_stale: int,
2363
+ required: int = WEDGE_STALE_OBSERVATIONS,
2364
+ startup_grace_s: float = WEDGE_STARTUP_GRACE_S,
2365
+ freshness_window_s: float = FRESH_WINDOW_S,
2366
+ ) -> str:
2367
+ """Classify one supervision tick. Pure function, so it is directly testable.
2368
+
2369
+ Returns ``"healthy"``, ``"grace"`` (too early to judge), ``"stale"`` (still
2370
+ accumulating consecutive observations) or ``"wedged"`` (act now).
2371
+
2372
+ ``consecutive_stale`` is the count ALREADY accumulated BEFORE this tick.
2373
+ It is compared, not incremented, here -- so ``"wedged"`` is returned on the
2374
+ tick where the pre-existing count first reaches ``required``, i.e. action
2375
+ lands on observed stale tick ``required + 1``. See the module constants for
2376
+ the full statement of that contract and of :func:`wedge_min_silence_s`.
2377
+ """
2378
+ if not child_alive:
2379
+ return "healthy" # a dead child is the crash path's business
2380
+ if uptime_s < startup_grace_s:
2381
+ return "grace"
2382
+ if heartbeat_age_s is None:
2383
+ # Never published for the CURRENT child. The grace band has already
2384
+ # elapsed above, so this IS a qualifying stale observation -- but it is
2385
+ # still only ONE observation, and the x3/x4 contract applies to a
2386
+ # missing heartbeat exactly as it does to an aged one. Without this the
2387
+ # accumulation rule was silently skipped and a child that never
2388
+ # published could never be recovered at all.
2389
+ return "wedged" if consecutive_stale >= required else "stale"
2390
+ if heartbeat_age_s <= freshness_window_s:
2391
+ return "healthy"
2392
+ return "wedged" if consecutive_stale >= required else "stale"
2393
+
2394
+
2395
+ def supervise(
2396
+ root: str | os.PathLike[str] | None = None,
2397
+ *,
2398
+ paths: Sequence[str] | None = None,
2399
+ debounce_ms: int | None = None,
2400
+ heartbeat_interval: float | None = None,
2401
+ child_argv: Sequence[str] | None = None,
2402
+ max_restarts: int = MAX_RESTARTS,
2403
+ backoff_base_s: float = RESTART_BACKOFF_S,
2404
+ backoff_max_s: float = RESTART_BACKOFF_MAX_S,
2405
+ tick_s: float = SUPERVISOR_TICK_S,
2406
+ wedge_startup_grace_s: float = WEDGE_STARTUP_GRACE_S,
2407
+ wedge_stale_observations: int = WEDGE_STALE_OBSERVATIONS,
2408
+ wedge_freshness_window_s: float = FRESH_WINDOW_S,
2409
+ ) -> int:
2410
+ # W3.04: an autonomous supervisor must contain its whole subtree (itself ->
2411
+ # watcher -> anything either spawns), not just the one watcher call site.
2412
+ bg.enforce_containment()
2413
+ root_path = _resolve_root(root)
2414
+ wdir = watcher_dir(root_path)
2415
+ wdir.mkdir(parents=True, exist_ok=True)
2416
+ config = _read_json(wdir / INSTALL_FILE) or {}
2417
+ if debounce_ms is None:
2418
+ debounce_ms = int(config.get("debounce_ms", DEFAULT_DEBOUNCE_MS))
2419
+ if heartbeat_interval is None:
2420
+ heartbeat_interval = float(config.get("heartbeat_interval", DEFAULT_HEARTBEAT_INTERVAL))
2421
+ if paths is None:
2422
+ paths = config.get("paths") or [str(root_path)]
2423
+
2424
+ stop_marker = wdir / STOP_FILE
2425
+ child_stop_marker = wdir / WATCHER_STOP_FILE
2426
+ for marker in (stop_marker, child_stop_marker):
2427
+ try:
2428
+ marker.unlink()
2429
+ except OSError:
2430
+ pass
2431
+
2432
+ # A fresh supervisor start is a deliberate run: re-baseline the harness
2433
+ # environment (documented remediation for an open harness-change drift).
2434
+ write_baseline(root_path, source="supervise")
2435
+
2436
+ if child_argv is None:
2437
+ check = preflight(root_path)
2438
+ if not check["ok"]:
2439
+ print(f"[cosmos-supervisor] refusing to supervise: {check['reason']}", file=sys.stderr)
2440
+ return EX_ERROR
2441
+ child_argv = [
2442
+ config.get("python") or sys.executable,
2443
+ str(config.get("watcher_script") or _WATCHER_SCRIPT),
2444
+ "--repo",
2445
+ str(root_path),
2446
+ "--paths",
2447
+ *[str(p) for p in paths],
2448
+ "--debounce-ms",
2449
+ str(debounce_ms),
2450
+ "--heartbeat-interval",
2451
+ str(heartbeat_interval),
2452
+ ]
2453
+
2454
+ my_pid = os.getpid()
2455
+ restarts = 0
2456
+ last_exit: int | None = None
2457
+ first_seen_at = _utcnow()
2458
+ child: subprocess.Popen[bytes] | None = None
2459
+ stopping = {"flag": False}
2460
+ drift_every_n = max(1, int(round(DRIFT_CHECK_PERIOD_S / max(tick_s, 0.01))))
2461
+ loops = 0
2462
+ # W3.04 wedge recovery state.
2463
+ # stale_streak consecutive stale observations this child has served;
2464
+ # drives the deterministic wedge threshold.
2465
+ # wedged_recoveries CUMULATIVE, never reset: truthful lifetime accounting
2466
+ # of how many wedge recoveries this supervisor has paid
2467
+ # for out of the shared restart budget.
2468
+ # recovery_pending TRANSIENT, one bit: set when a wedge is acted on,
2469
+ # cleared the moment its replacement publishes a fresh
2470
+ # heartbeat. It -- not the cumulative counter -- gates
2471
+ # RESOLVED and the success log, so a wedge yields
2472
+ # exactly one OPENED, one RESOLVED and one log line,
2473
+ # and every subsequent healthy tick is silent.
2474
+ stale_streak = 0
2475
+ wedged_recoveries = 0
2476
+ recovery_pending = False
2477
+ child_started = time.monotonic()
2478
+ # P0-03 attribution state (observability only -- no lifecycle effect):
2479
+ # child_generation increments at every SUCCESSFUL child spawn, so a
2480
+ # durable row can never be confused with the
2481
+ # replacement that inherits the pid slot later;
2482
+ # sup_publish_onset burst latch for supervisor-heartbeat publish
2483
+ # failures: one durable onset row, then silence
2484
+ # until a publish succeeds again, so a persistently
2485
+ # locked file cannot flood the durable sink.
2486
+ child_generation = 0
2487
+ sup_publish_onset = False
2488
+
2489
+ def _note_sup_publish_error(exc: OSError) -> None:
2490
+ """P0-03: make a dropped supervisor heartbeat tick durably attributable.
2491
+
2492
+ Burst latch: the FIRST failed publish of a burst emits one onset row
2493
+ carrying the genuine OSError class and message; subsequent failures
2494
+ are suppressed until a successful publish resets the latch, so a
2495
+ persistently locked file cannot flood the durable sink. The callback's
2496
+ own failure is swallowed by ``_write_json_or_skip`` and can never
2497
+ affect publication behaviour.
2498
+ """
2499
+ nonlocal sup_publish_onset
2500
+ if sup_publish_onset:
2501
+ return
2502
+ sup_publish_onset = True
2503
+ append_observed(
2504
+ root_path,
2505
+ kind=ALERT_SUPERVISOR_PUBLISH_FAILED,
2506
+ stage="supervisor-heartbeat-publish",
2507
+ detail=("supervisor heartbeat publish failed (onset of a failure "
2508
+ "burst; later failures are suppressed until a publish "
2509
+ "succeeds again)"),
2510
+ source="supervise",
2511
+ evidence={"supervisor_pid": my_pid,
2512
+ "child_pid": child.pid if child is not None else None,
2513
+ "generation": child_generation,
2514
+ "target": str(wdir / SUPERVISOR_FILE),
2515
+ "error_class": type(exc).__name__,
2516
+ "error": str(exc)},
2517
+ )
2518
+
2519
+ def _reset_child_state() -> None:
2520
+ """Every child creation starts from a clean child-relative baseline.
2521
+
2522
+ W3.04 Option A / current-child identity: startup, stale-observation and
2523
+ recovery bookkeeping all describe THE CHILD, so none of it may leak
2524
+ from a dead watcher into the one that replaces it. The crash path used
2525
+ to reset only ``stale_streak``, so an ordinary crash-restart inherited
2526
+ its predecessor's ``child_started`` — the30 s startup grace had already
2527
+ expired before the replacement ever ran — and its ``recovery_pending``
2528
+ bit.
2529
+
2530
+ ``recovery_pending`` is re-derived rather than blanked: a wedge recovery
2531
+ is pending exactly while THIS supervisor has acted on a wedge
2532
+ (``wedged_recoveries > 0``) and the durable alert is still open. That
2533
+ keeps the bit transient, keeps it child-relative, and makes the RESOLVED
2534
+ append and its one success log structurally impossible to separate —
2535
+ while still refusing to claim a recovery for a fresh supervisor that
2536
+ never performed one.
2537
+ """
2538
+ nonlocal child_started, stale_streak, recovery_pending
2539
+ child_started = time.monotonic()
2540
+ stale_streak = 0
2541
+ recovery_pending = (
2542
+ wedged_recoveries > 0
2543
+ and ALERT_WATCHER_WEDGED in open_alert_kinds(root_path)
2544
+ )
2545
+
2546
+ def _handle(signum: int, frame: Any) -> None: # pragma: no cover - signal path
2547
+ stopping["flag"] = True
2548
+
2549
+ for sig in (signal.SIGINT, signal.SIGTERM):
2550
+ try:
2551
+ signal.signal(sig, _handle)
2552
+ except (ValueError, OSError): # pragma: no cover
2553
+ pass
2554
+
2555
+ print(f"[cosmos-supervisor] supervise up pid={my_pid} root={root_path}", file=sys.stderr, flush=True)
2556
+ exit_code = EX_HEALTHY
2557
+ gave_up = False
2558
+ try:
2559
+ while not stopping["flag"] and not stop_marker.is_file():
2560
+ if child is None or child.poll() is not None:
2561
+ if child is not None:
2562
+ last_exit = child.returncode
2563
+ prior_child_pid = child.pid
2564
+ restarts += 1
2565
+ # P0-03: durable attribution for an ordinary child exit --
2566
+ # previously stderr-only, surviving only inside
2567
+ # supervisor.json which `finally` deletes at exit.
2568
+ append_observed(
2569
+ root_path,
2570
+ kind=ALERT_CHILD_LIFECYCLE,
2571
+ stage="child-exit",
2572
+ detail=(f"watcher pid {prior_child_pid} exited rc={last_exit}; "
2573
+ f"restart {restarts} of {max_restarts} follows "
2574
+ f"(attribution record, not a classification)"),
2575
+ source="supervise",
2576
+ evidence={"supervisor_pid": my_pid,
2577
+ "child_pid": prior_child_pid,
2578
+ "generation": child_generation,
2579
+ "exit_code": last_exit,
2580
+ "restarts": restarts,
2581
+ "max_restarts": max_restarts},
2582
+ )
2583
+ if restarts > max_restarts:
2584
+ print(
2585
+ f"[cosmos-supervisor] watcher exited {restarts} times "
2586
+ f"(last rc={last_exit}); giving up honestly",
2587
+ file=sys.stderr,
2588
+ flush=True,
2589
+ )
2590
+ exit_code = EX_NOT_RUNNING
2591
+ gave_up = True
2592
+ break
2593
+ # bounded exponential backoff: base * 2^(n-1), capped
2594
+ delay = min(backoff_base_s * (2 ** min(restarts - 1, 16)), backoff_max_s)
2595
+ time.sleep(delay)
2596
+ if stop_marker.is_file() or stopping["flag"]:
2597
+ break
2598
+ try:
2599
+ child = subprocess.Popen(list(child_argv), **_child_spawn_kwargs())
2600
+ except OSError as exc:
2601
+ print(f"[cosmos-supervisor] cannot spawn watcher: {exc}", file=sys.stderr, flush=True)
2602
+ last_exit = -1
2603
+ restarts += 1
2604
+ # P0-03: a spawn failure is durable and attributable
2605
+ # (timestamp/PID/stage/error), not just a stderr line.
2606
+ append_observed(
2607
+ root_path,
2608
+ kind=ALERT_CHILD_LIFECYCLE,
2609
+ stage="spawn-failed",
2610
+ detail=(f"watcher spawn failed: {type(exc).__name__}: {exc} "
2611
+ f"(attempted generation {child_generation + 1})"),
2612
+ source="supervise",
2613
+ evidence={"supervisor_pid": my_pid,
2614
+ "attempted_generation": child_generation + 1,
2615
+ "error_class": type(exc).__name__,
2616
+ "error": str(exc),
2617
+ "prior_exit_code": last_exit,
2618
+ "restarts": restarts},
2619
+ )
2620
+ time.sleep(min(backoff_base_s, backoff_max_s))
2621
+ continue
2622
+ child_generation += 1
2623
+ append_observed(
2624
+ root_path,
2625
+ kind=ALERT_CHILD_LIFECYCLE,
2626
+ stage="spawn",
2627
+ detail=(f"watcher spawned pid {child.pid} as generation "
2628
+ f"{child_generation} "
2629
+ + ("(initial)" if restarts == 0
2630
+ else f"(after {restarts} restart(s))")),
2631
+ source="supervise",
2632
+ evidence={"supervisor_pid": my_pid,
2633
+ "child_pid": child.pid,
2634
+ "generation": child_generation,
2635
+ "restarts": restarts,
2636
+ "prior_exit_code": last_exit},
2637
+ )
2638
+ # Ordinary crash-restart: the PREVIOUS child's startup grace,
2639
+ # stale streak and recovery bit must not survive into this one.
2640
+ _reset_child_state()
2641
+ # ---- W3.04: alive-but-wedged child recovery --------------------
2642
+ # The child is running but its heartbeat stopped advancing. Health
2643
+ # already reports this truthfully ("running-degraded / watcher down
2644
+ # or wedged"); before this, nothing acted on it, so the daemon stayed
2645
+ # lost until a human noticed. Recover INSIDE the existing loop, so a
2646
+ # wedge never requires a second supervisor.
2647
+ elif child is not None:
2648
+ hb = _read_json(wdir / HEARTBEAT_FILE)
2649
+ # Current-child identity: only the CURRENT child's heartbeat is
2650
+ # evidence about the current child. A previous child's record
2651
+ # stays fresh for a whole freshness window after it dies and,
2652
+ # unfiltered, would keep this one "healthy", reset its stale
2653
+ # streak and defer a legitimate recovery indefinitely.
2654
+ if hb is not None and str(hb.get("pid")) != str(child.pid):
2655
+ hb = None
2656
+ child_alive = child.poll() is None
2657
+ hb_age = _age_seconds((hb or {}).get("ts"))
2658
+ verdict = wedge_verdict(
2659
+ heartbeat_age_s=hb_age,
2660
+ child_alive=child_alive,
2661
+ uptime_s=time.monotonic() - child_started,
2662
+ consecutive_stale=stale_streak,
2663
+ # Passed explicitly (not left to wedge_verdict's defaults)
2664
+ # so the wedge contract is a single injectable set of
2665
+ # parameters: production uses the module constants, while a
2666
+ # regression test can drive a whole wedge -> recover ->
2667
+ # stay-healthy cycle in seconds without weakening the
2668
+ # thresholds the CLI actually runs with.
2669
+ required=wedge_stale_observations,
2670
+ startup_grace_s=wedge_startup_grace_s,
2671
+ freshness_window_s=wedge_freshness_window_s,
2672
+ )
2673
+ if verdict in ("stale", "wedged"):
2674
+ stale_streak += 1
2675
+ else:
2676
+ if verdict == "healthy":
2677
+ # The replacement has published a FRESH heartbeat, so the
2678
+ # wedge condition is genuinely over. The open-alert set
2679
+ # is the latch: it holds this kind until this very append,
2680
+ # so one wedge yields exactly one RESOLVED and every later
2681
+ # healthy tick is a no-op. (Gating on recovery_pending
2682
+ # alone would strand the alert if the supervisor itself
2683
+ # were ever restarted mid-recovery.)
2684
+ recovered_pid = child.pid if child is not None else None
2685
+ if ALERT_WATCHER_WEDGED in open_alert_kinds(root_path):
2686
+ append_alert(
2687
+ root_path, event="RESOLVED", kind=ALERT_WATCHER_WEDGED,
2688
+ detail=(f"watcher pid {recovered_pid} heartbeat advancing "
2689
+ f"again after wedge recovery "
2690
+ f"#{wedged_recoveries} (cumulative)"),
2691
+ source="supervise", state_from=STATE_DEGRADED, state_to=STATE_RUNNING,
2692
+ evidence={"child_pid": recovered_pid,
2693
+ "recoveries_cumulative": wedged_recoveries},
2694
+ )
2695
+ if recovery_pending:
2696
+ # One log line per recovery, never one per tick.
2697
+ recovery_pending = False
2698
+ print(f"[cosmos-supervisor] watcher healthy again after wedge "
2699
+ f"recovery #{wedged_recoveries} pid={recovered_pid}",
2700
+ file=sys.stderr, flush=True)
2701
+ stale_streak = 0
2702
+ if verdict == "wedged":
2703
+ recovery_pending = True
2704
+ wedged_recoveries += 1
2705
+ restarts += 1
2706
+ # `stale_streak` was just incremented for THIS tick, so it
2707
+ # now names the observation that crossed the threshold: the
2708
+ # (required + 1)th — the 4th, after 3 already accumulated.
2709
+ stale_txt = (
2710
+ f"heartbeat stale {hb_age:.1f}s"
2711
+ if hb_age is not None
2712
+ else "no heartbeat published by the current child"
2713
+ )
2714
+ stale_origin = (
2715
+ (f"({wedge_stale_observations} prior observations "
2716
+ f"already accumulated, each > "
2717
+ f"{wedge_freshness_window_s}s old)")
2718
+ if hb_age is not None else
2719
+ (f"({wedge_stale_observations} prior observations "
2720
+ f"already accumulated with no heartbeat at all from "
2721
+ f"the current child)")
2722
+ )
2723
+ append_alert(
2724
+ root_path, event="OPENED", kind=ALERT_WATCHER_WEDGED,
2725
+ detail=(f"watcher pid {child.pid} alive but {stale_txt}; "
2726
+ f"observed at stale tick #{stale_streak} "
2727
+ f"{stale_origin}"),
2728
+ source="supervise", state_from=STATE_RUNNING, state_to=STATE_DEGRADED,
2729
+ evidence={"child_pid": child.pid, "heartbeat_age_s": hb_age,
2730
+ "observed_at_stale_tick": stale_streak,
2731
+ "threshold_prior_observations": wedge_stale_observations,
2732
+ "action_lands_on_observed_stale_tick": (
2733
+ wedge_stale_observations + 1),
2734
+ "freshness_window_s": wedge_freshness_window_s,
2735
+ "startup_grace_s": wedge_startup_grace_s,
2736
+ "tick_s": tick_s,
2737
+ "min_silence_before_action_s": (
2738
+ wedge_min_silence_s(
2739
+ freshness_window_s=wedge_freshness_window_s,
2740
+ observations=wedge_stale_observations,
2741
+ tick_s=tick_s,
2742
+ )
2743
+ ),
2744
+ "min_action_age_from_spawn_s": (
2745
+ wedge_min_action_age_s(
2746
+ startup_grace_s=wedge_startup_grace_s,
2747
+ freshness_window_s=(
2748
+ wedge_freshness_window_s),
2749
+ observations=wedge_stale_observations,
2750
+ tick_s=tick_s,
2751
+ )
2752
+ ),
2753
+ # P0-03: honest durable git correlation -- an
2754
+ # unmatched in-flight git subprocess started by
2755
+ # THIS child is observable overlap evidence;
2756
+ # never a causal claim. Read-only enrichment.
2757
+ **({"git_correlation": _wg_corr}
2758
+ if (_wg_corr := wedge_git_correlation(
2759
+ root_path, child.pid)) is not None
2760
+ else {})},
2761
+ )
2762
+ print(f"[cosmos-supervisor] WATCHER_WEDGED pid={child.pid} "
2763
+ f"{stale_txt}; observed at stale tick "
2764
+ f"#{stale_streak} -> bounded stop",
2765
+ file=sys.stderr, flush=True)
2766
+ # The existing bounded stop path (graceful -> terminate ->
2767
+ # kill), then the SAME restart budget as a crashed child.
2768
+ level = _stop_child_graceful(child, child_stop_marker)
2769
+ prior_wedge_pid = child.pid
2770
+ child = None
2771
+ if restarts > max_restarts:
2772
+ print(f"[cosmos-supervisor] restart budget exhausted after "
2773
+ f"{restarts} restarts (last rc={last_exit}); giving up honestly",
2774
+ file=sys.stderr, flush=True)
2775
+ exit_code = EX_NOT_RUNNING
2776
+ gave_up = True
2777
+ break
2778
+ delay = min(backoff_base_s * (2 ** min(restarts - 1, 16)), backoff_max_s)
2779
+ print(f"[cosmos-supervisor] wedge replacement: child stop={level}, "
2780
+ f"backoff {delay:.1f}s", file=sys.stderr, flush=True)
2781
+ time.sleep(delay)
2782
+ if stop_marker.is_file() or stopping["flag"]:
2783
+ break
2784
+ try:
2785
+ child = subprocess.Popen(list(child_argv), **_child_spawn_kwargs())
2786
+ except OSError as exc:
2787
+ print(f"[cosmos-supervisor] cannot spawn replacement watcher: {exc}",
2788
+ file=sys.stderr, flush=True)
2789
+ last_exit = -1
2790
+ # P0-03: spawn-failure attribution for the wedge path.
2791
+ append_observed(
2792
+ root_path,
2793
+ kind=ALERT_CHILD_LIFECYCLE,
2794
+ stage="spawn-failed",
2795
+ detail=(f"watcher spawn failed during wedge replacement: "
2796
+ f"{type(exc).__name__}: {exc} "
2797
+ f"(attempted generation {child_generation + 1})"),
2798
+ source="supervise",
2799
+ evidence={"supervisor_pid": my_pid,
2800
+ "attempted_generation": child_generation + 1,
2801
+ "prior_child_pid": prior_wedge_pid,
2802
+ "reason": "wedge-replacement",
2803
+ "error_class": type(exc).__name__,
2804
+ "error": str(exc),
2805
+ "restarts": restarts},
2806
+ )
2807
+ continue
2808
+ child_generation += 1
2809
+ # P0-03: the replacement's identity is durable: old pid ->
2810
+ # new pid -> generation, so an old-PID failure row can
2811
+ # never be attributed to this replacement.
2812
+ append_observed(
2813
+ root_path,
2814
+ kind=ALERT_CHILD_LIFECYCLE,
2815
+ stage="wedge-replacement",
2816
+ detail=(f"watcher replaced after wedge: pid {prior_wedge_pid} "
2817
+ f"-> pid {child.pid} (generation {child_generation}, "
2818
+ f"stop level {level})"),
2819
+ source="supervise",
2820
+ evidence={"supervisor_pid": my_pid,
2821
+ "child_pid": child.pid,
2822
+ "prior_child_pid": prior_wedge_pid,
2823
+ "generation": child_generation,
2824
+ "restarts": restarts,
2825
+ "stop_level": level},
2826
+ )
2827
+ # Wedge replacement: full child-relative reset — fresh
2828
+ # startup grace, cleared stale counter, recovery bit
2829
+ # re-derived. The OPENED alert above is still open, so the
2830
+ # bit comes back True: this replacement exists precisely to
2831
+ # finish that recovery, and it is what pairs the single
2832
+ # RESOLVED with the single success log.
2833
+ _reset_child_state()
2834
+ loops += 1
2835
+ if loops % drift_every_n == 0:
2836
+ # automatic environment-change detection (LC1.23 #4): the
2837
+ # health probe maintains the durable alert record too.
2838
+ try:
2839
+ probe = health(root_path)
2840
+ if probe["drift_kinds"] or probe["crash_loop"]:
2841
+ print(
2842
+ f"[cosmos-supervisor] drift/health: {probe['state']} "
2843
+ f"{probe['drift_kinds']}",
2844
+ file=sys.stderr,
2845
+ flush=True,
2846
+ )
2847
+ except Exception as exc: # noqa: BLE001 - never die over a probe
2848
+ print(f"[cosmos-supervisor] health probe failed: {exc}", file=sys.stderr, flush=True)
2849
+ # W3.04: an unattended daemon must not die because its own heartbeat
2850
+ # file was momentarily locked by a reader. A dropped tick is
2851
+ # re-published on the next one; the alternative — dying — looks
2852
+ # identical to a dead watcher.
2853
+ # P0-03: the drop is now DURABLY attributable (onset row per
2854
+ # failure burst) through the on_error callback, while the publish
2855
+ # semantics stay exactly the `_write_json_or_skip` contract.
2856
+ if _write_json_or_skip(
2857
+ wdir / SUPERVISOR_FILE,
2858
+ {
2859
+ "schema": SCHEMA_SUPERVISOR,
2860
+ "pid": my_pid,
2861
+ "child_pid": child.pid,
2862
+ "child_alive": child.poll() is None,
2863
+ "ts": _utcnow(),
2864
+ "started_at": first_seen_at,
2865
+ "restarts": restarts,
2866
+ "last_exit_code": last_exit,
2867
+ "state": "running",
2868
+ "root": str(root_path),
2869
+ "watcher_script": str(child_argv[1]) if len(child_argv) > 1 else None,
2870
+ },
2871
+ on_error=_note_sup_publish_error,
2872
+ ):
2873
+ sup_publish_onset = False
2874
+ # poll cadence: responsive to stop.request, cheap enough for 24/7
2875
+ for _ in range(max(1, int(tick_s / 0.25))):
2876
+ if stop_marker.is_file() or stopping["flag"]:
2877
+ break
2878
+ time.sleep(min(0.25, tick_s))
2879
+ finally:
2880
+ if child is not None and child.poll() is None:
2881
+ level = _stop_child_graceful(child, child_stop_marker)
2882
+ print(f"[cosmos-supervisor] child stop: {level}", file=sys.stderr, flush=True)
2883
+ if gave_up:
2884
+ # Durable degraded evidence: a supervisor that exhausts its
2885
+ # restart budget must not look like a clean `stopped` service.
2886
+ try:
2887
+ prior_state = health(root_path, sync_alerts=False)["process_state"]
2888
+ except Exception: # noqa: BLE001 - reporting must never block evidence
2889
+ prior_state = STATE_STOPPED
2890
+ note_supervisor_gave_up(
2891
+ root_path, restarts=restarts, last_exit=last_exit, state_from=prior_state
2892
+ )
2893
+ sup = _read_json(wdir / SUPERVISOR_FILE)
2894
+ if sup and sup.get("pid") == my_pid:
2895
+ try:
2896
+ (wdir / SUPERVISOR_FILE).unlink()
2897
+ except OSError:
2898
+ pass
2899
+ for marker in (stop_marker, child_stop_marker):
2900
+ try:
2901
+ marker.unlink()
2902
+ except OSError:
2903
+ pass
2904
+ print("[cosmos-supervisor] stopped", file=sys.stderr, flush=True)
2905
+ return exit_code
2906
+
2907
+
2908
+ # ---------------------------------------------------------------------------
2909
+ # rendering / CLI
2910
+ # ---------------------------------------------------------------------------
2911
+ def render_health(report: dict[str, Any]) -> str:
2912
+ lines = [
2913
+ f"watcher: {report['state']} (substate: {report.get('substate')}) "
2914
+ f"(automatic capture: {report['automatic_capture']})"
2915
+ ]
2916
+ if report.get("installed"):
2917
+ lines.append(
2918
+ f" install: os_install={report.get('os_install')} task={report.get('task_name')} "
2919
+ f"at={report.get('installed_at') or (report.get('install') or {}).get('installed_at')}"
2920
+ )
2921
+ else:
2922
+ lines.append(" install: absent (opt-in service never installed)")
2923
+ sup = report.get("supervisor") or {}
2924
+ wch = report.get("watcher") or {}
2925
+ lines.append(
2926
+ f" supervisor: pid={sup.get('pid')} alive={sup.get('alive')} fresh={sup.get('fresh')} "
2927
+ f"age={sup.get('age_seconds')} restarts={sup.get('restarts')}"
2928
+ )
2929
+ lines.append(
2930
+ f" watcher: pid={wch.get('pid')} alive={wch.get('alive')} fresh={wch.get('fresh')} "
2931
+ f"age={wch.get('age_seconds')} ticks={wch.get('ticks')}"
2932
+ )
2933
+ if report.get("drift_kinds"):
2934
+ lines.append(f" drift: {', '.join(report['drift_kinds'])}")
2935
+ if report.get("alerts_open"):
2936
+ lines.append(f" alerts: open={', '.join(report['alerts_open'])}")
2937
+ if report.get("crash_loop"):
2938
+ lines.append(" crash-loop marker present (restart budget exhausted)")
2939
+ for reason in report.get("reasons", []):
2940
+ lines.append(f" reason: {reason}")
2941
+ if report.get("hint"):
2942
+ lines.append(f" hint: {report['hint']}")
2943
+ return "\n".join(lines)
2944
+
2945
+
2946
+ def _exit_for_state(state: str) -> int:
2947
+ """CLI exit code for an action report carrying an honest state."""
2948
+ return int(_EXIT_OF_STATE.get(state, EX_ERROR))
2949
+
2950
+
2951
+ def build_parser() -> argparse.ArgumentParser:
2952
+ parser = argparse.ArgumentParser(
2953
+ prog="cosmos-daemon-supervisor",
2954
+ description="Install, supervise and health-check the Cosmos filesystem watcher (LC1.23).",
2955
+ )
2956
+ sub = parser.add_subparsers(dest="action", required=True)
2957
+
2958
+ def common(p: argparse.ArgumentParser) -> None:
2959
+ p.add_argument("--root", type=Path, default=None, help="project (git) root; default: cwd")
2960
+ p.add_argument("--json", action="store_true")
2961
+
2962
+ ins = sub.add_parser("install", help="install the supervised service (user-level scheduled task)")
2963
+ common(ins)
2964
+ ins.add_argument("--paths", nargs="+", default=None)
2965
+ ins.add_argument("--debounce-ms", type=int, default=DEFAULT_DEBOUNCE_MS)
2966
+ ins.add_argument("--heartbeat-interval", type=float, default=DEFAULT_HEARTBEAT_INTERVAL)
2967
+ ins.add_argument("--dry-run", action="store_true", help="render the plan without executing it")
2968
+
2969
+ un = sub.add_parser("uninstall", help="stop, deregister and remove the install contract")
2970
+ common(un)
2971
+ un.add_argument("--dry-run", action="store_true")
2972
+
2973
+ st = sub.add_parser("start", help="start the detached supervisor (no OS task change)")
2974
+ common(st)
2975
+
2976
+ sp = sub.add_parser("stop", help="graceful stop (stop.request, then force if needed)")
2977
+ common(sp)
2978
+
2979
+ rs = sub.add_parser("restart", help="stop then start")
2980
+ common(rs)
2981
+
2982
+ common(sub.add_parser("status", help="honest lifecycle state + install contract"))
2983
+ common(sub.add_parser("health", help="health probe for process/heartbeat/drift monitoring"))
2984
+ common(sub.add_parser("alerts", help="durable environment-change alert record (alerts.jsonl)"))
2985
+
2986
+ sv = sub.add_parser("supervise", help="internal: supervised restart loop for the watcher")
2987
+ common(sv)
2988
+ sv.add_argument("--paths", nargs="+", default=None)
2989
+ sv.add_argument("--debounce-ms", type=int, default=None)
2990
+ sv.add_argument("--heartbeat-interval", type=float, default=None)
2991
+ sv.add_argument("--child-json", default=None, help="JSON array: alternate child command (tests)")
2992
+ sv.add_argument("--max-restarts", type=int, default=MAX_RESTARTS)
2993
+ return parser
2994
+
2995
+
2996
+ def main(argv: Sequence[str] | None = None) -> int:
2997
+ args = build_parser().parse_args(list(argv) if argv is not None else None)
2998
+ for stream in (sys.stdout, sys.stderr):
2999
+ reconfigure = getattr(stream, "reconfigure", None)
3000
+ if reconfigure is not None:
3001
+ try:
3002
+ reconfigure(errors="replace")
3003
+ except (ValueError, OSError):
3004
+ pass
3005
+ root = args.root
3006
+ if args.action == "install":
3007
+ report = install(
3008
+ root,
3009
+ paths=args.paths,
3010
+ debounce_ms=args.debounce_ms,
3011
+ heartbeat_interval=args.heartbeat_interval,
3012
+ dry_run=args.dry_run,
3013
+ )
3014
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else _render_install(report))
3015
+ if report["state"] == "cannot-install":
3016
+ return EX_ERROR
3017
+ return EX_HEALTHY if report["os_install"] == "executed" else EX_NOT_RUNNING
3018
+ if args.action == "uninstall":
3019
+ report = uninstall(root, dry_run=args.dry_run)
3020
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else _render_install(report))
3021
+ return EX_HEALTHY
3022
+ if args.action == "start":
3023
+ report = start(root)
3024
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else _render_install(report))
3025
+ return _exit_for_state(report["state"])
3026
+ if args.action == "stop":
3027
+ report = stop(root)
3028
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else _render_install(report))
3029
+ return EX_HEALTHY
3030
+ if args.action == "restart":
3031
+ report = restart(root)
3032
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else _render_install(report))
3033
+ return _exit_for_state(report["state"])
3034
+ if args.action in ("status", "health"):
3035
+ report = status(root) if args.action == "status" else health(root)
3036
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else render_health(report))
3037
+ return int(report["exit_code"])
3038
+ if args.action == "alerts":
3039
+ records = _read_alerts(root)
3040
+ if args.json:
3041
+ print(json.dumps(records, indent=2, sort_keys=True))
3042
+ elif not records:
3043
+ print("alerts: none recorded")
3044
+ else:
3045
+ for rec in records:
3046
+ print(
3047
+ f"{rec.get('ts')} {rec.get('event')} {rec.get('kind')} "
3048
+ f"{rec.get('state_from')}->{rec.get('state_to')} {rec.get('detail')}"
3049
+ )
3050
+ return EX_HEALTHY
3051
+ if args.action == "supervise":
3052
+ child = json.loads(args.child_json) if args.child_json else None
3053
+ return supervise(
3054
+ root,
3055
+ paths=args.paths,
3056
+ debounce_ms=args.debounce_ms,
3057
+ heartbeat_interval=args.heartbeat_interval,
3058
+ child_argv=child,
3059
+ max_restarts=args.max_restarts,
3060
+ )
3061
+ return EX_ERROR
3062
+
3063
+
3064
+ def _render_install(report: dict[str, Any]) -> str:
3065
+ lines = [f"install: {report.get('state')} — {report.get('reason', '')}"]
3066
+ for result in report.get("results", []):
3067
+ argv = result.get("argv")
3068
+ if argv:
3069
+ status = "executed" if result.get("executed") else result.get("skipped", "skipped")
3070
+ lines.append(f" [{result['id']}] {status}: {' '.join(str(a) for a in argv)}")
3071
+ if result.get("stderr_tail") and result.get("ok") is False:
3072
+ lines.append(f" stderr: {result['stderr_tail'][:200]}")
3073
+ if report.get("plan") and not report.get("results"):
3074
+ for entry in report["plan"]:
3075
+ lines.append(f" plan [{entry['id']}]: {entry.get('description')}")
3076
+ if report.get("hint"):
3077
+ lines.append(f" hint: {report['hint']}")
3078
+ return "\n".join(lines)
3079
+
3080
+
3081
+ if __name__ == "__main__":
3082
+ raise SystemExit(main())