@team-agent/installer 0.5.128 → 0.6.0

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 (436) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +37 -20
  5. package/skills/team-agent/command-coverage.json +169 -183
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +64 -30
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +64 -30
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1288
  15. package/crates/team-agent/src/cli/arguments.rs +0 -405
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1721
  18. package/crates/team-agent/src/cli/emit.rs +0 -2930
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1216
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -912
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -689
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6545
  29. package/crates/team-agent/src/cli/models.rs +0 -1206
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/schedule.rs +0 -175
  34. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  35. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  36. package/crates/team-agent/src/cli/send/persist.rs +0 -156
  37. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  38. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  39. package/crates/team-agent/src/cli/send.rs +0 -199
  40. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  41. package/crates/team-agent/src/cli/spec.rs +0 -165
  42. package/crates/team-agent/src/cli/status.rs +0 -280
  43. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  44. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  45. package/crates/team-agent/src/cli/status_port/brief.rs +0 -1981
  46. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  47. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  48. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  49. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  50. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  51. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  52. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  53. package/crates/team-agent/src/cli/status_port.rs +0 -92
  54. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  55. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  56. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  57. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -322
  58. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  59. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  60. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  61. package/crates/team-agent/src/cli/tests/named_address.rs +0 -761
  62. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  63. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -484
  64. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  65. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  66. package/crates/team-agent/src/cli/tests/status_send.rs +0 -888
  67. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  68. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  69. package/crates/team-agent/src/cli/triage.rs +0 -234
  70. package/crates/team-agent/src/cli/types.rs +0 -591
  71. package/crates/team-agent/src/codex_app_server.rs +0 -546
  72. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  73. package/crates/team-agent/src/compiler/tests.rs +0 -827
  74. package/crates/team-agent/src/compiler.rs +0 -890
  75. package/crates/team-agent/src/conpty/backend.rs +0 -829
  76. package/crates/team-agent/src/conpty/mod.rs +0 -33
  77. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1744
  78. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  79. package/crates/team-agent/src/contract_runtime/config.rs +0 -364
  80. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -76
  81. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -449
  82. package/crates/team-agent/src/contract_runtime/fork.rs +0 -361
  83. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  84. package/crates/team-agent/src/contract_runtime/framework.rs +0 -367
  85. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -394
  86. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  87. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  88. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  89. package/crates/team-agent/src/contract_runtime/registry.rs +0 -553
  90. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  91. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  92. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  93. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  94. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  95. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  96. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  97. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  98. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  99. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  101. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  102. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  104. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  105. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  106. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  107. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -300
  108. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  109. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  110. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  111. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -503
  112. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  113. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  114. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  115. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  116. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  117. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  118. package/crates/team-agent/src/coordinator/tick.rs +0 -3024
  119. package/crates/team-agent/src/coordinator/types.rs +0 -540
  120. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  121. package/crates/team-agent/src/db/message_store.rs +0 -1527
  122. package/crates/team-agent/src/db/migration.rs +0 -984
  123. package/crates/team-agent/src/db/mod.rs +0 -26
  124. package/crates/team-agent/src/db/schema.rs +0 -663
  125. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  126. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  127. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  128. package/crates/team-agent/src/direct_delivery.rs +0 -368
  129. package/crates/team-agent/src/event_log.rs +0 -502
  130. package/crates/team-agent/src/fake_worker.rs +0 -303
  131. package/crates/team-agent/src/inbox_store.rs +0 -169
  132. package/crates/team-agent/src/kill_audit.rs +0 -106
  133. package/crates/team-agent/src/layout/manager.rs +0 -248
  134. package/crates/team-agent/src/layout/mod.rs +0 -36
  135. package/crates/team-agent/src/layout/overlay.rs +0 -134
  136. package/crates/team-agent/src/layout/placement.rs +0 -52
  137. package/crates/team-agent/src/layout/recovery.rs +0 -106
  138. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  139. package/crates/team-agent/src/layout/sessions.rs +0 -294
  140. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  141. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  142. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  143. package/crates/team-agent/src/leader/helpers.rs +0 -178
  144. package/crates/team-agent/src/leader/incident.rs +0 -6
  145. package/crates/team-agent/src/leader/lease.rs +0 -3356
  146. package/crates/team-agent/src/leader/mod.rs +0 -104
  147. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  148. package/crates/team-agent/src/leader/prompt.rs +0 -905
  149. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  150. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  151. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  152. package/crates/team-agent/src/leader/registry.rs +0 -888
  153. package/crates/team-agent/src/leader/start.rs +0 -4501
  154. package/crates/team-agent/src/leader/takeover.rs +0 -65
  155. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  156. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  157. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  158. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  159. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  160. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  161. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  162. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  163. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  164. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  165. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -268
  166. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  167. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  168. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  169. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  170. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  171. package/crates/team-agent/src/leader/types.rs +0 -534
  172. package/crates/team-agent/src/lib.rs +0 -147
  173. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  174. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -881
  175. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -598
  176. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  177. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -204
  178. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -107
  179. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -144
  180. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  181. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  182. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  183. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -160
  184. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  185. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -899
  186. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -225
  187. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  188. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5200
  189. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  190. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  191. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  192. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -473
  193. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  194. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  195. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  196. package/crates/team-agent/src/lifecycle/launch.rs +0 -557
  197. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  198. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  199. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  200. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -1067
  201. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  202. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2199
  203. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1798
  204. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +0 -163
  205. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2362
  206. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  207. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  208. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  209. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  210. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  211. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  212. package/crates/team-agent/src/lifecycle/restart.rs +0 -227
  213. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1230
  214. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  215. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  216. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  217. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  218. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  219. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  220. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -447
  221. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1638
  222. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  223. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -770
  224. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -419
  225. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2035
  226. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1327
  227. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  228. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  229. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  230. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -72
  231. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  232. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  233. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -512
  234. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  235. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  236. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  237. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3983
  238. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  239. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  240. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  241. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  242. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  243. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  244. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -164
  245. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -200
  246. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  247. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -527
  248. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -1062
  249. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1419
  250. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -98
  251. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -550
  252. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -226
  253. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -332
  254. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  255. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  256. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  257. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  258. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  259. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  260. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  261. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  262. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  263. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  264. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  265. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  266. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -342
  267. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  268. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  269. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  270. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  271. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  272. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  273. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  274. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -995
  275. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -836
  276. package/crates/team-agent/src/lifecycle/tests.rs +0 -105
  277. package/crates/team-agent/src/lifecycle/types.rs +0 -877
  278. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -363
  279. package/crates/team-agent/src/main.rs +0 -52
  280. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  281. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  282. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  283. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  284. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  285. package/crates/team-agent/src/mcp_server/readiness.rs +0 -527
  286. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -348
  287. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  288. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  289. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -158
  290. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -353
  291. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -341
  292. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  293. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  294. package/crates/team-agent/src/mcp_server/tools.rs +0 -889
  295. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  296. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  297. package/crates/team-agent/src/messaging/activity.rs +0 -461
  298. package/crates/team-agent/src/messaging/address.rs +0 -87
  299. package/crates/team-agent/src/messaging/delivery.rs +0 -3727
  300. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  301. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  302. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  303. package/crates/team-agent/src/messaging/helpers.rs +0 -336
  304. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  305. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  306. package/crates/team-agent/src/messaging/mod.rs +0 -167
  307. package/crates/team-agent/src/messaging/persist.rs +0 -377
  308. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  309. package/crates/team-agent/src/messaging/reminders.rs +0 -316
  310. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  311. package/crates/team-agent/src/messaging/results.rs +0 -1415
  312. package/crates/team-agent/src/messaging/scheduler.rs +0 -223
  313. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  314. package/crates/team-agent/src/messaging/send.rs +0 -981
  315. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  316. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -657
  317. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  318. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  319. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  320. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  321. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  322. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3549
  323. package/crates/team-agent/src/messaging/tests/spine.rs +0 -853
  324. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  325. package/crates/team-agent/src/messaging/trust.rs +0 -215
  326. package/crates/team-agent/src/messaging/types.rs +0 -472
  327. package/crates/team-agent/src/messaging/wait.rs +0 -366
  328. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  329. package/crates/team-agent/src/model/enums.rs +0 -356
  330. package/crates/team-agent/src/model/errors.rs +0 -18
  331. package/crates/team-agent/src/model/ids.rs +0 -165
  332. package/crates/team-agent/src/model/mod.rs +0 -29
  333. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  334. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  335. package/crates/team-agent/src/model/paths.rs +0 -257
  336. package/crates/team-agent/src/model/routing.rs +0 -387
  337. package/crates/team-agent/src/model/spec.rs +0 -1184
  338. package/crates/team-agent/src/model/task_graph.rs +0 -321
  339. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  340. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  341. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  342. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  343. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  344. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  345. package/crates/team-agent/src/model/yaml.rs +0 -802
  346. package/crates/team-agent/src/os_probe.rs +0 -280
  347. package/crates/team-agent/src/packaging/install.rs +0 -219
  348. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  349. package/crates/team-agent/src/packaging/mod.rs +0 -91
  350. package/crates/team-agent/src/packaging/repair.rs +0 -33
  351. package/crates/team-agent/src/packaging/tests.rs +0 -822
  352. package/crates/team-agent/src/packaging/types.rs +0 -417
  353. package/crates/team-agent/src/platform/argv.rs +0 -331
  354. package/crates/team-agent/src/platform/errors.rs +0 -104
  355. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  356. package/crates/team-agent/src/platform/mod.rs +0 -5
  357. package/crates/team-agent/src/platform/process.rs +0 -545
  358. package/crates/team-agent/src/provider/adapter.rs +0 -1150
  359. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  360. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  361. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  362. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  363. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  364. package/crates/team-agent/src/provider/adapters/mod.rs +0 -30
  365. package/crates/team-agent/src/provider/adapters/pi.rs +0 -106
  366. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  367. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  368. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  369. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  370. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  371. package/crates/team-agent/src/provider/classify.rs +0 -708
  372. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  373. package/crates/team-agent/src/provider/faults.rs +0 -165
  374. package/crates/team-agent/src/provider/helpers.rs +0 -52
  375. package/crates/team-agent/src/provider/mod.rs +0 -78
  376. package/crates/team-agent/src/provider/model_catalog.rs +0 -910
  377. package/crates/team-agent/src/provider/session/capture.rs +0 -2731
  378. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  379. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -172
  380. package/crates/team-agent/src/provider/session/context_fork.rs +0 -396
  381. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  382. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  383. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  384. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  385. package/crates/team-agent/src/provider/session_scan/common.rs +0 -654
  386. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  387. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -185
  388. package/crates/team-agent/src/provider/session_scan.rs +0 -71
  389. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  390. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  391. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  392. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  393. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  394. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  395. package/crates/team-agent/src/provider/tests/adapter.rs +0 -441
  396. package/crates/team-agent/src/provider/tests/classify.rs +0 -148
  397. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -35
  398. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  399. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  400. package/crates/team-agent/src/provider/tests/idle.rs +0 -177
  401. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  402. package/crates/team-agent/src/provider/tests.rs +0 -32
  403. package/crates/team-agent/src/provider/types.rs +0 -529
  404. package/crates/team-agent/src/provider/wire.rs +0 -394
  405. package/crates/team-agent/src/redaction.rs +0 -259
  406. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  407. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  408. package/crates/team-agent/src/state/identity.rs +0 -914
  409. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  410. package/crates/team-agent/src/state/mod.rs +0 -74
  411. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  412. package/crates/team-agent/src/state/ownership.rs +0 -563
  413. package/crates/team-agent/src/state/paths.rs +0 -395
  414. package/crates/team-agent/src/state/persist.rs +0 -3811
  415. package/crates/team-agent/src/state/projection.rs +0 -1508
  416. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  417. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  418. package/crates/team-agent/src/state/repository.rs +0 -866
  419. package/crates/team-agent/src/state/selector.rs +0 -160
  420. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  421. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
  422. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  423. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  424. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  425. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  426. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4103
  427. package/crates/team-agent/src/tmux_backend.rs +0 -4492
  428. package/crates/team-agent/src/topology.rs +0 -537
  429. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  430. package/crates/team-agent/src/transport/native_input.rs +0 -491
  431. package/crates/team-agent/src/transport/test_support.rs +0 -743
  432. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  433. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  434. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  435. package/crates/team-agent/src/transport.rs +0 -1655
  436. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,3811 +0,0 @@
1
- //!
2
- //! state.json 持久化(bug-084 韧性;真相源 `state.py:save_runtime_state` + `_self_heal_runtime_state`
3
- //! + `runtime.py:_runtime_lock`)。
4
- //!
5
- //! 流程(逐条对齐 bug_084_085_contract.md):
6
- //! 1. 入参 deep-equal `_RUNTIME_STATE_CACHE[path]` → 取锁/os.replace **之前**返回。
7
- //! 2. `_runtime_lock(workspace, "state-save", timeout=2.0)` 串行化(flock;state-save 不发锁事件)。
8
- //! 3. 原子 `tmp -> rename(tmp, state.json)`;payload = `json.dumps(indent=2, ensure_ascii=False)`(无尾换行)。
9
- //! 4. EACCES/EPERM/EBUSY/PermissionError → 有界退避重试 delays=[0.05,0.2,0.5](4 次尝试);
10
- //! ENOSPC 等不重试,直接 raise。
11
- //! 5. 重试耗尽且仍 retryable → self-heal:写 heal-tmp → rename(原 state→backup) → rename(heal-tmp→state);
12
- //! **绝不 in-place truncate**。self-heal 也失败 → 还原 backup(若已建)+ 原 state 仍可见 + raise。
13
- //! 6. 事件:save_retry(每次重试)/ self_healed(成功)/ save_failed(最终失败)/ self_heal_restore_failed。
14
- //! 7. MUST-NOT-13:全程零 provider/network 调用。
15
- //!
16
- //! **已知字节边界(同 event_log,实测 state 不出现;state-rich.json 3471B 字节对拍 PASS)**:
17
- //! `<1e-4` 指数浮点 / `>2^53` 大整数经 serde_json 会漂移;state 字段实测为小整数/字符串/bool/嵌套。
18
- //!
19
- //! **load 迁移(本 slice 接入)**:`load_runtime_state` 现复刻 Python 全链——
20
- //! `normalize_agent_session_state`(SESSION_STATE_FIELDS 补 None)→ `_migrate_state_identity`
21
- //! (`identity::migrate_state_identity`,补 leader_session_uuid)→ `_migrate_active_team_key`
22
- //! (seed active 指针);任一改动 → `save_runtime_state` 回写。不存在且命中缓存 → 返回缓存 deepcopy。
23
-
24
- use std::collections::{BTreeSet, HashMap};
25
- use std::io;
26
- use std::path::{Path, PathBuf};
27
- use std::sync::atomic::{AtomicU64, Ordering};
28
- use std::sync::{LazyLock, Mutex};
29
- use std::time::{Duration, Instant};
30
-
31
- use serde_json::{json, Value};
32
-
33
- use crate::event_log::EventLog;
34
- use crate::model::paths::runtime_dir;
35
- use crate::state::identity::{migrate_state_identity, SystemEnv};
36
- use crate::state::json_truthy;
37
- use crate::state::projection::{team_state_key, CURRENT_TEAM_ALIAS};
38
- use crate::state::StateError;
39
-
40
- /// `state.py:26-29`:agent session-state 归一字段(setdefault None)。
41
- const SESSION_STATE_FIELDS: [&str; 6] = [
42
- "session_id",
43
- "rollout_path",
44
- "captured_at",
45
- "captured_via",
46
- "attribution_confidence",
47
- "spawn_cwd",
48
- ];
49
- const LIVE_TOPOLOGY_FIELDS: [&str; 5] =
50
- ["pane_id", "pane_pid", "window", "spawned_at", "spawn_epoch"];
51
- const ROSTER_STUB_ALLOWLIST: [&str; 17] = [
52
- "agent_id",
53
- "provider",
54
- "auth_mode",
55
- "role",
56
- "model",
57
- "model_source",
58
- "profile",
59
- "_profile_dir",
60
- "dynamic_role_file",
61
- "role_source_ownership",
62
- "effort",
63
- "forked_from",
64
- "managed_mcp_config",
65
- "claude_config_dir",
66
- "claude_projects_root",
67
- "profile_launch",
68
- "explicit_stop",
69
- ];
70
-
71
- /// `state.py:_RUNTIME_STATE_CACHE`:进程级 path→state 缓存(deep-equal 早返回)。
72
- static RUNTIME_STATE_CACHE: LazyLock<Mutex<HashMap<PathBuf, Value>>> =
73
- LazyLock::new(|| Mutex::new(HashMap::new()));
74
- static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
75
-
76
- ///
77
- /// `state.py:41`。
78
- pub fn runtime_state_path(workspace: &Path) -> PathBuf {
79
- runtime_dir(workspace).join("state.json")
80
- }
81
-
82
- fn cache_equals(path: &Path, state: &Value) -> bool {
83
- RUNTIME_STATE_CACHE
84
- .lock()
85
- .is_ok_and(|c| c.get(path) == Some(state))
86
- }
87
- fn cache_set(path: &Path, state: &Value) {
88
- if let Ok(mut c) = RUNTIME_STATE_CACHE.lock() {
89
- c.insert(path.to_path_buf(), state.clone());
90
- }
91
- }
92
- /// `_RUNTIME_STATE_CACHE.get(...)` → `copy.deepcopy(cached)`(clone = deepcopy)。
93
- fn cache_get(path: &Path) -> Option<Value> {
94
- RUNTIME_STATE_CACHE
95
- .lock()
96
- .ok()
97
- .and_then(|c| c.get(path).cloned())
98
- }
99
-
100
- fn unique_tmp(path: &Path, suffix: &str) -> PathBuf {
101
- let name = path
102
- .file_name()
103
- .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
104
- let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
105
- path.with_file_name(format!("{name}.{}.{seq}.{suffix}", std::process::id()))
106
- }
107
-
108
- // 故障注入(测试):**per-call-index 谓词**。FAULT_PLAN[i] = 第 i 次 atomic_replace 的 errno
109
- // (0=成功)。这是对抗检查的 critical 修复:递减计数器无法表达 self-heal restore 分支需要的
110
- // 非连续 succeed/fail 序列(loop 失败、path→backup 成功、heal→path 失败、restore 成功/失败),
111
- // 故崩溃安全不变量「原 state 经 backup 还原」原先根本不可测。
112
- #[cfg(test)]
113
- thread_local! {
114
- static FAULT_PLAN: std::cell::RefCell<Vec<i32>> = const { std::cell::RefCell::new(Vec::new()) };
115
- static FAULT_IDX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
116
- }
117
-
118
- fn atomic_replace(from: &Path, to: &Path) -> io::Result<()> {
119
- #[cfg(test)]
120
- {
121
- let idx = FAULT_IDX.with(|c| {
122
- let i = c.get();
123
- c.set(i + 1);
124
- i
125
- });
126
- let errno = FAULT_PLAN.with(|p| p.borrow().get(idx).copied().unwrap_or(0));
127
- if errno != 0 {
128
- return Err(io::Error::from_raw_os_error(errno));
129
- }
130
- }
131
- std::fs::rename(from, to)
132
- }
133
-
134
- /// `_retryable_replace_error`:PermissionError 或 errno ∈ {EACCES, EPERM, EBUSY}。
135
- fn retryable_replace_error(e: &io::Error) -> bool {
136
- if let Some(errno) = e.raw_os_error() {
137
- return errno == libc::EACCES || errno == libc::EPERM || errno == libc::EBUSY;
138
- }
139
- e.kind() == io::ErrorKind::PermissionDenied
140
- }
141
-
142
- fn errno_name(errno: Option<i32>) -> Option<&'static str> {
143
- match errno {
144
- Some(e) if e == libc::EACCES => Some("EACCES"),
145
- Some(e) if e == libc::EPERM => Some("EPERM"),
146
- Some(e) if e == libc::EBUSY => Some("EBUSY"),
147
- Some(e) if e == libc::ENOSPC => Some("ENOSPC"),
148
- _ => None,
149
- }
150
- }
151
-
152
- /// `runtime.py:_runtime_lock` 的 flock 版(RAII;Drop 释放)。state-save 不发锁事件。
153
- ///
154
- /// 0.5.x Windows portability Batch 2: migrated to
155
- /// `crate::platform::file_lock::{try_lock_once_nonblocking, unlock}` so
156
- /// the same polling loop + timeout + `StateError::Locked(name)` shape
157
- /// works on both Unix (`flock`) and Windows (`LockFileEx`) — 1:1
158
- /// semantic mapping. The Batch 0 non-Unix `not_yet_implemented`
159
- /// fallback is now removed (CR C-2 fallback burn-down; grep guard
160
- /// `platform_fallback_burndown_batch0.rs` flipped in this batch).
161
- pub(crate) struct RuntimeLock {
162
- #[allow(dead_code)]
163
- file: std::fs::File,
164
- }
165
-
166
- impl RuntimeLock {
167
- fn acquire(workspace: &Path, name: &str, timeout: f64) -> Result<Self, StateError> {
168
- let lock_path = runtime_dir(workspace).join(format!("{name}.lock"));
169
- if let Some(parent) = lock_path.parent() {
170
- std::fs::create_dir_all(parent)?;
171
- }
172
- let file = std::fs::OpenOptions::new()
173
- .create(true)
174
- .read(true)
175
- .write(true)
176
- .truncate(false)
177
- .open(&lock_path)?;
178
- let start = Instant::now();
179
- loop {
180
- match crate::platform::file_lock::try_lock_once_nonblocking(&file) {
181
- Ok(true) => return Ok(Self { file }),
182
- Ok(false) => {
183
- if start.elapsed().as_secs_f64() >= timeout {
184
- return Err(StateError::Locked(name.to_string()));
185
- }
186
- std::thread::sleep(Duration::from_millis(50));
187
- }
188
- Err(e) => {
189
- // Byte-preserving: a real I/O error surfaces as a
190
- // `StateError::Io` (via `From<io::Error>`), same as
191
- // the current inline code would if `file.open()`
192
- // failed. The lock-would-block case took the
193
- // Ok(false) arm above.
194
- return Err(StateError::from(e));
195
- }
196
- }
197
- }
198
- }
199
- }
200
-
201
- impl Drop for RuntimeLock {
202
- fn drop(&mut self) {
203
- // Best-effort unlock. OS releases on handle close if this fails.
204
- let _ = crate::platform::file_lock::unlock(&self.file);
205
- }
206
- }
207
-
208
- pub(crate) fn acquire_result_collection_lock(
209
- run_workspace: &Path,
210
- ) -> Result<RuntimeLock, StateError> {
211
- RuntimeLock::acquire(run_workspace, "result-collection", 2.0)
212
- }
213
-
214
- #[cfg(test)]
215
- pub(crate) fn acquire_state_save_lock(
216
- workspace: &Path,
217
- timeout: f64,
218
- ) -> Result<RuntimeLock, StateError> {
219
- RuntimeLock::acquire(workspace, "state-save", timeout)
220
- }
221
-
222
- ///
223
- /// `save_runtime_state`(bug-084)。`state` 是 state.json 的内存 Value(插入序保留)。
224
- /// 注:Python 在此还调 `_migrate_state_identity`(identity slice 落地后接入;本 slice 不改 state 内容)。
225
- pub fn save_runtime_state(workspace: &Path, state: &Value) -> Result<(), StateError> {
226
- save_runtime_state_with_merge_options(
227
- workspace,
228
- state,
229
- &[],
230
- None,
231
- &[],
232
- None,
233
- &[],
234
- None,
235
- None,
236
- false,
237
- )
238
- }
239
-
240
- pub(crate) fn save_runtime_state_with_receiver_authority(
241
- workspace: &Path,
242
- state: &Value,
243
- receiver_team_key: &str,
244
- exact_owner_seed_to_clear: Option<&Value>,
245
- ) -> Result<(), StateError> {
246
- save_runtime_state_with_merge_options(
247
- workspace,
248
- state,
249
- &[],
250
- None,
251
- &[],
252
- None,
253
- &[],
254
- Some(receiver_team_key),
255
- exact_owner_seed_to_clear,
256
- false,
257
- )
258
- }
259
-
260
- pub(crate) fn save_runtime_state_reapplying_after_conflict<F>(
261
- workspace: &Path,
262
- state: &Value,
263
- reapply: F,
264
- ) -> Result<(), StateError>
265
- where
266
- F: FnOnce(&mut Value),
267
- {
268
- match save_runtime_state(workspace, state) {
269
- Ok(()) => Ok(()),
270
- Err(StateError::SaveConflict(_)) => {
271
- let mut latest = load_runtime_state(workspace)?;
272
- reapply(&mut latest);
273
- save_runtime_state(workspace, &latest)
274
- }
275
- Err(error) => Err(error),
276
- }
277
- }
278
-
279
- pub(crate) fn save_runtime_state_with_lifecycle_topology_authority(
280
- workspace: &Path,
281
- state: &Value,
282
- topology_team_key: &str,
283
- agent_ids: &[&str],
284
- ) -> Result<(), StateError> {
285
- save_runtime_state_with_merge_options(
286
- workspace,
287
- state,
288
- &[],
289
- None,
290
- &[],
291
- Some(topology_team_key),
292
- agent_ids,
293
- None,
294
- None,
295
- false,
296
- )
297
- }
298
-
299
- pub(crate) fn save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
300
- workspace: &Path,
301
- state: &Value,
302
- skip_capture_backfill_team_key: &str,
303
- skip_capture_backfill_agent_ids: &[&str],
304
- topology_agent_ids: &[&str],
305
- ) -> Result<(), StateError> {
306
- save_runtime_state_with_merge_options(
307
- workspace,
308
- state,
309
- &[],
310
- Some(skip_capture_backfill_team_key),
311
- skip_capture_backfill_agent_ids,
312
- Some(skip_capture_backfill_team_key),
313
- topology_agent_ids,
314
- None,
315
- None,
316
- false,
317
- )
318
- }
319
-
320
- pub(crate) fn save_runtime_state_with_deleted_agents(
321
- workspace: &Path,
322
- state: &Value,
323
- deleted_agent_ids: &[&str],
324
- ) -> Result<(), StateError> {
325
- save_runtime_state_with_merge_options(
326
- workspace,
327
- state,
328
- deleted_agent_ids,
329
- None,
330
- &[],
331
- None,
332
- &[],
333
- None,
334
- None,
335
- true,
336
- )
337
- }
338
-
339
- pub(crate) fn save_runtime_state_with_team_tombstoned_agents(
340
- workspace: &Path,
341
- state: &Value,
342
- tombstoned_team_key: &str,
343
- tombstoned_agent_ids: &[&str],
344
- ) -> Result<(), StateError> {
345
- save_runtime_state_with_merge_options(
346
- workspace,
347
- state,
348
- &[],
349
- Some(tombstoned_team_key),
350
- tombstoned_agent_ids,
351
- None,
352
- &[],
353
- None,
354
- None,
355
- false,
356
- )
357
- }
358
-
359
- pub(crate) fn save_runtime_state_with_team_tombstone_lifecycle_topology_authority(
360
- workspace: &Path,
361
- state: &Value,
362
- tombstoned_team_key: &str,
363
- agent_ids: &[&str],
364
- ) -> Result<(), StateError> {
365
- save_runtime_state_with_merge_options(
366
- workspace,
367
- state,
368
- &[],
369
- Some(tombstoned_team_key),
370
- agent_ids,
371
- Some(tombstoned_team_key),
372
- agent_ids,
373
- None,
374
- None,
375
- false,
376
- )
377
- }
378
-
379
- fn save_runtime_state_with_merge_options(
380
- workspace: &Path,
381
- state: &Value,
382
- deleted_agent_ids: &[&str],
383
- skip_capture_backfill_team_key: Option<&str>,
384
- skip_capture_backfill_agent_ids: &[&str],
385
- topology_update_team_key: Option<&str>,
386
- topology_update_agent_ids: &[&str],
387
- receiver_update_team_key: Option<&str>,
388
- exact_owner_seed_to_clear: Option<&Value>,
389
- preserve_latest_fork_targets: bool,
390
- ) -> Result<(), StateError> {
391
- persist_runtime_state_with_merge_options_and_expected(
392
- workspace,
393
- state,
394
- deleted_agent_ids,
395
- skip_capture_backfill_team_key,
396
- skip_capture_backfill_agent_ids,
397
- topology_update_team_key,
398
- topology_update_agent_ids,
399
- receiver_update_team_key,
400
- exact_owner_seed_to_clear,
401
- None,
402
- None,
403
- None,
404
- preserve_latest_fork_targets,
405
- )
406
- }
407
-
408
- pub(crate) fn save_runtime_state_with_receiver_authority_and_expected(
409
- workspace: &Path,
410
- state: &Value,
411
- receiver_team_key: &str,
412
- expected_owner: &Value,
413
- expected_receiver: &Value,
414
- ) -> Result<(), StateError> {
415
- persist_runtime_state_with_merge_options_and_expected(
416
- workspace,
417
- state,
418
- &[],
419
- None,
420
- &[],
421
- None,
422
- &[],
423
- Some(receiver_team_key),
424
- None,
425
- Some((expected_owner, expected_receiver)),
426
- None,
427
- None,
428
- false,
429
- )
430
- }
431
-
432
- pub(crate) fn save_runtime_state_with_exact_owner_receiver_cleanup(
433
- workspace: &Path,
434
- state: &Value,
435
- team_key: &str,
436
- expected_owner: &Value,
437
- expected_receiver: &Value,
438
- ) -> Result<(), StateError> {
439
- persist_runtime_state_with_merge_options_and_expected(
440
- workspace,
441
- state,
442
- &[],
443
- None,
444
- &[],
445
- None,
446
- &[],
447
- Some(team_key),
448
- None,
449
- None,
450
- Some((team_key, expected_owner, expected_receiver)),
451
- None,
452
- false,
453
- )
454
- }
455
-
456
- pub(crate) fn save_runtime_state_with_exact_owner_receiver_restore(
457
- workspace: &Path,
458
- state: &Value,
459
- team_key: &str,
460
- expected_owner: &Value,
461
- expected_receiver: &Value,
462
- previous_owner: &Value,
463
- previous_receiver: &Value,
464
- ) -> Result<(), StateError> {
465
- persist_runtime_state_with_merge_options_and_expected(
466
- workspace,
467
- state,
468
- &[],
469
- None,
470
- &[],
471
- None,
472
- &[],
473
- Some(team_key),
474
- None,
475
- None,
476
- None,
477
- Some((
478
- team_key,
479
- expected_owner,
480
- expected_receiver,
481
- previous_owner,
482
- previous_receiver,
483
- )),
484
- false,
485
- )
486
- }
487
-
488
- fn persist_runtime_state_with_merge_options_and_expected(
489
- workspace: &Path,
490
- state: &Value,
491
- deleted_agent_ids: &[&str],
492
- skip_capture_backfill_team_key: Option<&str>,
493
- skip_capture_backfill_agent_ids: &[&str],
494
- topology_update_team_key: Option<&str>,
495
- topology_update_agent_ids: &[&str],
496
- receiver_update_team_key: Option<&str>,
497
- exact_owner_seed_to_clear: Option<&Value>,
498
- expected_owner_receiver: Option<(&Value, &Value)>,
499
- exact_owner_receiver_to_clear: Option<(&str, &Value, &Value)>,
500
- exact_owner_receiver_to_restore: Option<(&str, &Value, &Value, &Value, &Value)>,
501
- preserve_latest_fork_targets: bool,
502
- ) -> Result<(), StateError> {
503
- let path = runtime_state_path(workspace);
504
- // Python `state.py:497`:先对入参 state 跑 `_migrate_state_identity`(就地填缺失 leader uuid)。
505
- // 我们 `&Value` 不可变 → 克隆后迁移,后续比较/写入/缓存/self-heal 全走 `migrated`。
506
- // 该步**不**包 try/except → 错误 propagate(对齐 Python)。
507
- let mut migrated = state.clone();
508
- migrate_state_identity(&mut migrated, &SystemEnv, workspace)?;
509
- // Stage 3 save-output canonical-aware strip (architect direction
510
- // 2026-06-24, .team/artifacts/stage3-save-strip-fix.md): when the
511
- // state carries a canonical `teams.<active>.team_owner` record, drop
512
- // the legacy top-level `team_owner / leader_receiver / owner_epoch`
513
- // before any cache comparison. The pre-fix order ran a `cache_equals`
514
- // check against the RAW (pre-strip) state at the function entry — if
515
- // disk and cache were already in the dual-source (post-restart /
516
- // post-shutdown) shape, the early return would skip the cleanup
517
- // entirely. Moving migrate+strip ahead of every cache_equals makes
518
- // the canonical-only shape the cache invariant for new writes.
519
- crate::state::ownership::strip_top_level_ownership_if_canonical_present(&mut migrated);
520
- // Exact-seed cleanup must observe lock-held disk, not a pre-lock cache or
521
- // byte-equality hit. A matching in-memory document would otherwise no-op
522
- // and leave the seed, or skip copying a concurrent owner.
523
- let skip_pre_lock_fast_path = super::abnormal_watch::needs_compaction(&migrated)
524
- || exact_owner_seed_to_clear.is_some()
525
- || expected_owner_receiver.is_some()
526
- || exact_owner_receiver_to_clear.is_some()
527
- || exact_owner_receiver_to_restore.is_some();
528
- if !skip_pre_lock_fast_path && cache_equals(&path, &migrated) {
529
- return Ok(());
530
- }
531
- // 与磁盘已有内容「迁移后」相同 → 更新缓存返回(避免无谓重写)。字节对拍 Python:对 `existing` 先
532
- // `normalize_agent_session_state` + `_migrate_state_identity` 再比(读/迁移失败 try/except: pass →
533
- // 落写路径)。**修对抗 P1**:此前比较 raw `existing` 漏了这两步,会把「磁盘已是迁移等价形」的 legacy
534
- // 文件误判为不同而 spurious 重写,破坏 load+save 字节恒等。
535
- if !skip_pre_lock_fast_path && path.exists() {
536
- if let Ok(text) = std::fs::read_to_string(&path) {
537
- if let Ok(mut existing) = serde_json::from_str::<Value>(&text) {
538
- normalize_agent_session_state(&mut existing);
539
- let _ = migrate_state_identity(&mut existing, &SystemEnv, workspace);
540
- // Stage 3 save-output strip applied to `existing` too so
541
- // the equality comparison is between two canonical-only
542
- // shapes. Without this, a pre-fix dual-source disk state
543
- // would never match the post-fix canonical-only `migrated`
544
- // and would force a spurious rewrite on every save.
545
- crate::state::ownership::strip_top_level_ownership_if_canonical_present(
546
- &mut existing,
547
- );
548
- if existing == migrated {
549
- cache_set(&path, &migrated);
550
- return Ok(());
551
- }
552
- }
553
- }
554
- }
555
-
556
- let _lock = RuntimeLock::acquire(workspace, "state-save", 2.0)?;
557
- if let Some(parent) = path.parent() {
558
- std::fs::create_dir_all(parent)?;
559
- }
560
- let latest = read_latest_state_under_lock(workspace, &path);
561
- if let Some((expected_owner, expected_receiver)) = expected_owner_receiver {
562
- let expected_matches = latest.as_ref().is_some_and(|latest| {
563
- latest_team_owner_receiver(latest, receiver_update_team_key)
564
- .is_some_and(|(owner, receiver)| {
565
- owner == expected_owner && receiver == expected_receiver
566
- })
567
- });
568
- if !expected_matches {
569
- return Err(StateError::SaveConflict(
570
- "fresh caller owner/receiver changed before commit".to_string(),
571
- ));
572
- }
573
- }
574
- if let Some(latest) = latest.as_ref() {
575
- let deleted = deleted_agent_ids
576
- .iter()
577
- .copied()
578
- .filter(|id| !id.is_empty())
579
- .map(str::to_string)
580
- .collect::<BTreeSet<_>>();
581
- let skip_capture_backfill = skip_capture_backfill_agent_ids
582
- .iter()
583
- .copied()
584
- .filter(|id| !id.is_empty())
585
- .map(str::to_string)
586
- .collect::<BTreeSet<_>>();
587
- let topology_updates = topology_update_team_key
588
- .into_iter()
589
- .flat_map(|team_key| {
590
- topology_update_agent_ids
591
- .iter()
592
- .copied()
593
- .filter(|id| !id.is_empty())
594
- .map(move |agent_id| (team_key.to_string(), agent_id.to_string()))
595
- })
596
- .collect::<BTreeSet<_>>();
597
- let receiver_updates = receiver_update_team_key
598
- .into_iter()
599
- .filter(|team_key| !team_key.is_empty())
600
- .map(str::to_string)
601
- .collect::<BTreeSet<_>>();
602
- apply_persist_merge_contract_with_fork_target_preservation(
603
- &mut migrated,
604
- latest,
605
- &deleted,
606
- skip_capture_backfill_team_key,
607
- &skip_capture_backfill,
608
- &topology_updates,
609
- &receiver_updates,
610
- receiver_update_team_key.zip(exact_owner_seed_to_clear),
611
- exact_owner_receiver_to_clear,
612
- exact_owner_receiver_to_restore,
613
- preserve_latest_fork_targets,
614
- )?;
615
- }
616
- super::abnormal_watch::compact_after_merge(&mut migrated, latest.as_ref(), deleted_agent_ids);
617
- // Stage 3 save-output strip second pass (defence-in-depth): after the
618
- // `preserve_latest_roster_entries` lock-held merge, a future addition
619
- // to the preserve path could re-introduce root owner fields from the
620
- // on-disk latest. Re-strip here so the serialized payload is always
621
- // canonical-only when a canonical teams.<key>.team_owner is present.
622
- crate::state::ownership::strip_top_level_ownership_if_canonical_present(&mut migrated);
623
- write_state_under_lock(workspace, &path, &migrated)
624
- }
625
-
626
- /// Apply a bounded writer to disk under state-save, without a cache shortcut.
627
- pub(super) fn update_runtime_state(
628
- workspace: &Path,
629
- update: impl FnOnce(&Value) -> Result<Value, StateError>,
630
- ) -> Result<Value, StateError> {
631
- update_runtime_state_with_lifecycle_target(workspace, None, update)
632
- }
633
-
634
- /// Keep bounded StartAgent's exact team/seat authority inside the same state-save
635
- /// transaction. Ordinary deltas retain every existing stale-writer guard.
636
- pub(super) fn update_runtime_state_with_lifecycle_target(
637
- workspace: &Path,
638
- target: Option<(&str, &str)>,
639
- update: impl FnOnce(&Value) -> Result<Value, StateError>,
640
- ) -> Result<Value, StateError> {
641
- let path = runtime_state_path(workspace);
642
- let _lock = RuntimeLock::acquire(workspace, "state-save", 2.0)?;
643
- // Malformed/unreadable state is an error, never an empty store.
644
- let mut latest = match std::fs::read_to_string(&path) {
645
- Ok(text) => serde_json::from_str(&text)?,
646
- Err(error) if error.kind() == io::ErrorKind::NotFound => json!({}),
647
- Err(error) => return Err(error.into()),
648
- };
649
- normalize_agent_session_state(&mut latest);
650
- migrate_state_identity(&mut latest, &SystemEnv, workspace)?;
651
- let _ = migrate_active_team_key(&mut latest);
652
- let mut committed = update(&latest)?;
653
- let topology_updates = target.into_iter()
654
- .map(|(team, agent)| (team.to_owned(), agent.to_owned())).collect();
655
- apply_persist_merge_contract(
656
- &mut committed, &latest, &BTreeSet::new(), None, &BTreeSet::new(),
657
- &topology_updates, &BTreeSet::new(), None, None, None,
658
- )?;
659
- migrate_state_identity(&mut committed, &SystemEnv, workspace)?;
660
- crate::state::ownership::strip_top_level_ownership_if_canonical_present(&mut committed);
661
- if committed == latest {
662
- cache_set(&path, &committed);
663
- return Ok(committed);
664
- }
665
- write_state_under_lock(workspace, &path, &committed)?;
666
- Ok(committed)
667
- }
668
-
669
- /// Reuse ordinary roster, topology, ownership, capture and endpoint guards.
670
- pub(super) fn merge_ordinary_state(incoming: &mut Value, latest: &Value) -> Result<(), StateError> {
671
- apply_persist_merge_contract(
672
- incoming, latest, &BTreeSet::new(), None, &BTreeSet::new(),
673
- &BTreeSet::new(), &BTreeSet::new(), None, None, None,
674
- )
675
- }
676
-
677
- fn write_state_under_lock(workspace: &Path, path: &Path, migrated: &Value) -> Result<(), StateError> {
678
- // Shared retry/self-heal/atomic replacement path; caller owns state-save.
679
- let payload = serde_json::to_string_pretty(migrated)?;
680
- let delays = [0.05_f64, 0.2, 0.5];
681
-
682
- for attempt in 0..=delays.len() {
683
- let tmp = unique_tmp(&path, "tmp");
684
- let result: io::Result<()> = (|| {
685
- std::fs::write(&tmp, payload.as_bytes())?;
686
- atomic_replace(&tmp, &path)
687
- })();
688
- let _ = std::fs::remove_file(&tmp); // finally: unlink missing_ok
689
- match result {
690
- Ok(()) => {
691
- cache_set(&path, &migrated);
692
- return Ok(());
693
- }
694
- Err(e) => {
695
- let retryable = retryable_replace_error(&e);
696
- if !retryable || attempt >= delays.len() {
697
- if retryable {
698
- return self_heal(workspace, &path, &payload, &migrated, attempt + 1, &e);
699
- }
700
- return Err(StateError::Io(e));
701
- }
702
- let _ = EventLog::new(workspace).write(
703
- "runtime.state.save_retry",
704
- json!({
705
- "attempt": attempt + 1,
706
- "errno": e.raw_os_error(),
707
- "errno_name": errno_name(e.raw_os_error()),
708
- "error": e.to_string(),
709
- }),
710
- );
711
- std::thread::sleep(Duration::from_secs_f64(delays[attempt]));
712
- }
713
- }
714
- }
715
- Err(StateError::SaveFailed(
716
- "retry loop exhausted without return".to_string(),
717
- ))
718
- }
719
-
720
- fn read_latest_state_under_lock(workspace: &Path, path: &Path) -> Option<Value> {
721
- let text = std::fs::read_to_string(path).ok()?;
722
- let mut latest = serde_json::from_str::<Value>(&text).ok()?;
723
- normalize_agent_session_state(&mut latest);
724
- let _ = migrate_state_identity(&mut latest, &SystemEnv, workspace);
725
- let _ = migrate_active_team_key(&mut latest);
726
- Some(latest)
727
- }
728
-
729
- fn apply_persist_merge_contract(
730
- incoming: &mut Value,
731
- latest: &Value,
732
- deleted_agent_ids: &BTreeSet<String>,
733
- skip_capture_backfill_team_key: Option<&str>,
734
- skip_capture_backfill_agent_ids: &BTreeSet<String>,
735
- topology_updates: &BTreeSet<(String, String)>,
736
- receiver_updates: &BTreeSet<String>,
737
- exact_owner_seed_to_clear: Option<(&str, &Value)>,
738
- exact_owner_receiver_to_clear: Option<(&str, &Value, &Value)>,
739
- exact_owner_receiver_to_restore: Option<(&str, &Value, &Value, &Value, &Value)>,
740
- ) -> Result<(), StateError> {
741
- apply_persist_merge_contract_with_fork_target_preservation(
742
- incoming,
743
- latest,
744
- deleted_agent_ids,
745
- skip_capture_backfill_team_key,
746
- skip_capture_backfill_agent_ids,
747
- topology_updates,
748
- receiver_updates,
749
- exact_owner_seed_to_clear,
750
- exact_owner_receiver_to_clear,
751
- exact_owner_receiver_to_restore,
752
- false,
753
- )
754
- }
755
-
756
- fn apply_persist_merge_contract_with_fork_target_preservation(
757
- incoming: &mut Value,
758
- latest: &Value,
759
- deleted_agent_ids: &BTreeSet<String>,
760
- skip_capture_backfill_team_key: Option<&str>,
761
- skip_capture_backfill_agent_ids: &BTreeSet<String>,
762
- topology_updates: &BTreeSet<(String, String)>,
763
- receiver_updates: &BTreeSet<String>,
764
- exact_owner_seed_to_clear: Option<(&str, &Value)>,
765
- exact_owner_receiver_to_clear: Option<(&str, &Value, &Value)>,
766
- exact_owner_receiver_to_restore: Option<(&str, &Value, &Value, &Value, &Value)>,
767
- preserve_latest_fork_targets: bool,
768
- ) -> Result<(), StateError> {
769
- // A0/R1: the projection gate only guards the TOP-LEVEL passes (top-level agents and
770
- // the top-level<->active-team cross projections depend on which team is active); the
771
- // per-team `teams.<k>.agents` merge below is team-key self-identifying and must run
772
- // even when another process flipped session_name/active_team_key between this
773
- // writer's load and save.
774
- let projection_matches = same_runtime_projection(incoming, latest);
775
- let top_level_team = incoming
776
- .get("active_team_key")
777
- .and_then(Value::as_str)
778
- .filter(|key| !key.is_empty())
779
- .map(str::to_string)
780
- .or_else(|| Some(team_state_key(incoming)))
781
- .or_else(|| Some(team_state_key(latest)));
782
- let skip_top_level_capture_backfill =
783
- should_skip_capture_backfill(top_level_team.as_deref(), skip_capture_backfill_team_key);
784
- if projection_matches {
785
- let topology_update_agent_ids =
786
- topology_updates_for_team(topology_updates, top_level_team.as_deref());
787
- preserve_latest_retired_agents(incoming, latest, &topology_update_agent_ids)?;
788
- // 0.5.26 (§7.3): top-level projection uses the incoming root state's
789
- // implicit "alive" shape (top-level agents are always the active team).
790
- // Passing `None` for team lifecycle keeps historical behavior when the
791
- // active team is not lifecycle-marked.
792
- merge_agent_projection(
793
- "agents",
794
- incoming.get_mut("agents"),
795
- latest.get("agents"),
796
- deleted_agent_ids,
797
- skip_top_level_capture_backfill,
798
- skip_capture_backfill_agent_ids,
799
- &topology_update_agent_ids,
800
- None,
801
- preserve_latest_fork_targets,
802
- )?;
803
- // Stage 3c (identity-boundary unified plan, architect direction
804
- // 2026-06-23): top-level owner copy-back removed. Pre-3c this
805
- // copied legacy `state.{team_owner, leader_receiver, owner_epoch}`
806
- // from disk's latest back into the incoming save — the persist-side
807
- // mirror of the projection promote that 3b removed. With Stage 3a's
808
- // write_owner funneling all owner mutations and 3b's projection
809
- // cleanup, top-level owner truth is no longer authoritative; the
810
- // teams.<key> entry-scoped preservation at :370 remains so legacy
811
- // teams.<key>.team_owner entries still survive a save that omits
812
- // them.
813
-
814
- // 0.5.x Windows portability Batch 7 F6 (leader msg_700a016675d0):
815
- // preserve `state.transport.shim` across saves. The coordinator
816
- // writes this block when it spawns `windows-shim.exe` during
817
- // quick-start (see `coordinator::conpty_shim::finalize`).
818
- // Downstream saves inside the same quick-start (leader-persist,
819
- // worker-persist) construct their `incoming` state from an
820
- // in-memory copy that predates the shim-spawn, so without this
821
- // preserve step the shim block is silently dropped. That
822
- // clobber broke Batch 6 CHECK 6 (`shutdown` couldn't route to
823
- // the shim pid because `state.transport.shim.pid` was gone).
824
- preserve_transport_shim(incoming, latest);
825
- preserve_latest_endpoint_convergence_fields(incoming, latest);
826
- }
827
-
828
- let latest_teams = latest.get("teams").and_then(Value::as_object);
829
- let Some(incoming_teams) = incoming.get_mut("teams").and_then(Value::as_object_mut) else {
830
- return Ok(());
831
- };
832
- if let Some(latest_teams) = latest_teams {
833
- for (team, latest_entry) in latest_teams {
834
- let Some(incoming_entry) = incoming_teams.get_mut(team) else {
835
- continue;
836
- };
837
- // Intentional semantic split with
838
- // `projection::resolve_runtime_team_scope`: that selector checks
839
- // alive/terminal state, but this lock-held merge cannot depend on
840
- // the mutable alive view. A change to either CURRENT_TEAM_ALIAS
841
- // mapping must evaluate the other. The legacy physical alias gets
842
- // active-team authority; every real sibling remains self-scoped.
843
- let authority_team = if team == CURRENT_TEAM_ALIAS {
844
- top_level_team.as_deref()
845
- } else {
846
- Some(team.as_str())
847
- };
848
- let topology_update_agent_ids =
849
- topology_updates_for_team(topology_updates, authority_team);
850
- let receiver_update_authoritative =
851
- authority_team.is_some_and(|team_key| receiver_updates.contains(team_key));
852
- let projection = format!("teams.{team}.agents");
853
- // 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.3):
854
- // decide the containing team's aliveness from BOTH sides — a shutdown
855
- // that stamped the incoming as non-alive would otherwise leak the
856
- // stale latest into the conflict path. `false` on either side kills
857
- // the live-topology protection so a dead sibling's stale pane can't
858
- // block a live sibling's write.
859
- let team_alive = Some(
860
- crate::state::projection::team_is_alive_candidate(latest_entry)
861
- && incoming_entry
862
- .as_object()
863
- .map(|_| crate::state::projection::team_is_alive_candidate(incoming_entry))
864
- .unwrap_or(true),
865
- );
866
- preserve_latest_retired_agents(
867
- incoming_entry,
868
- latest_entry,
869
- &topology_update_agent_ids,
870
- )?;
871
- merge_agent_projection(
872
- &projection,
873
- incoming_entry.get_mut("agents"),
874
- latest_entry.get("agents"),
875
- deleted_agent_ids,
876
- should_skip_capture_backfill(Some(team), skip_capture_backfill_team_key),
877
- skip_capture_backfill_agent_ids,
878
- &topology_update_agent_ids,
879
- team_alive,
880
- preserve_latest_fork_targets,
881
- )?;
882
- preserve_latest_ownership_fields(
883
- incoming_entry,
884
- latest_entry,
885
- receiver_update_authoritative,
886
- );
887
- if let Some((clear_team, seed)) = exact_owner_seed_to_clear {
888
- if team == clear_team {
889
- apply_lock_held_exact_owner_cleanup(incoming_entry, latest_entry, seed);
890
- }
891
- }
892
- if let Some((clear_team, seed, expected_receiver)) = exact_owner_receiver_to_clear {
893
- if team == clear_team {
894
- apply_lock_held_exact_owner_receiver_cleanup(
895
- incoming_entry,
896
- latest_entry,
897
- seed,
898
- Some(expected_receiver),
899
- );
900
- }
901
- }
902
- if let Some((
903
- restore_team,
904
- expected_owner,
905
- expected_receiver,
906
- previous_owner,
907
- previous_receiver,
908
- )) = exact_owner_receiver_to_restore
909
- {
910
- if team == restore_team {
911
- apply_lock_held_exact_owner_receiver_restore(
912
- incoming_entry,
913
- latest_entry,
914
- expected_owner,
915
- expected_receiver,
916
- previous_owner,
917
- previous_receiver,
918
- );
919
- }
920
- }
921
- preserve_latest_endpoint_convergence_fields(incoming_entry, latest_entry);
922
- }
923
- }
924
- Ok(())
925
- }
926
-
927
- fn topology_updates_for_team(
928
- topology_updates: &BTreeSet<(String, String)>,
929
- team_key: Option<&str>,
930
- ) -> BTreeSet<String> {
931
- topology_updates
932
- .iter()
933
- .filter(|(authority_team, _)| Some(authority_team.as_str()) == team_key)
934
- .map(|(_, agent_id)| agent_id.clone())
935
- .collect()
936
- }
937
-
938
- fn preserve_latest_retired_agents(
939
- incoming: &mut Value,
940
- latest: &Value,
941
- topology_update_agent_ids: &BTreeSet<String>,
942
- ) -> Result<(), StateError> {
943
- // A persisted retirement is lifecycle authority, so an ordinary stale
944
- // writer (notably a coordinator tick captured before remove-agent) cannot
945
- // resurrect its old roster row. Explicit lifecycle topology writers are
946
- // the only override: AddAgent uses that existing authority to consume the
947
- // tombstone, while remove itself supplies the newer tombstone as incoming.
948
- let retired = latest
949
- .get("agent_lifecycle")
950
- .and_then(Value::as_object)
951
- .into_iter()
952
- .flat_map(|entries| entries.iter())
953
- .filter(|(agent_id, entry)| {
954
- !topology_update_agent_ids.contains(*agent_id)
955
- && entry.get("state").and_then(Value::as_str) == Some("retired")
956
- })
957
- .map(|(agent_id, entry)| (agent_id.clone(), entry.clone()))
958
- .collect::<Vec<_>>();
959
- if retired.is_empty() {
960
- return Ok(());
961
- }
962
- let Some(incoming) = incoming.as_object_mut() else {
963
- return Err(StateError::SaveFailed(
964
- "incoming runtime projection is not an object".to_string(),
965
- ));
966
- };
967
- if let Some(agents) = incoming.get_mut("agents").and_then(Value::as_object_mut) {
968
- for (agent_id, _) in &retired {
969
- agents.remove(agent_id);
970
- }
971
- }
972
- let lifecycle = incoming
973
- .entry("agent_lifecycle".to_string())
974
- .or_insert_with(|| serde_json::json!({}));
975
- let Some(lifecycle) = lifecycle.as_object_mut() else {
976
- return Err(StateError::SaveFailed(
977
- "incoming agent_lifecycle is not an object".to_string(),
978
- ));
979
- };
980
- for (agent_id, entry) in retired {
981
- lifecycle.insert(agent_id, entry);
982
- }
983
- Ok(())
984
- }
985
-
986
- /// 0.5.x Windows portability Batch 7 F6: copy `latest.transport.shim`
987
- /// into `incoming` if the incoming save omitted it. The coordinator's
988
- /// `conpty_shim::finalize` writes `state.transport.shim = {pid,
989
- /// pipe_name, pipe_ready}` after Hello succeeds. If a subsequent save
990
- /// in the same quick-start starts from a stale in-memory `Value` that
991
- /// predates the finalize, this preserve step keeps the on-disk shim
992
- /// block alive.
993
- ///
994
- /// Only runs when the top-level projection matches (same active team
995
- /// key + same session name) — no risk of leaking a shim block into
996
- /// an unrelated projection.
997
- ///
998
- /// Windows-relevant behavior; on Unix `transport.shim` is never
999
- /// written, so this fn is a no-op (both branches see `None`).
1000
- fn preserve_transport_shim(incoming: &mut Value, latest: &Value) {
1001
- // The shim block only matters when `latest` has one AND
1002
- // `incoming` doesn't (or `incoming.transport` doesn't exist).
1003
- let Some(latest_shim) = latest.get("transport").and_then(|t| t.get("shim")).cloned() else {
1004
- return;
1005
- };
1006
- let Some(incoming_obj) = incoming.as_object_mut() else {
1007
- return;
1008
- };
1009
- let transport = incoming_obj
1010
- .entry("transport".to_string())
1011
- .or_insert_with(|| serde_json::json!({}));
1012
- let Some(transport_obj) = transport.as_object_mut() else {
1013
- return;
1014
- };
1015
- // If the incoming already has a shim block, respect it (the
1016
- // caller has authoritative newer state — e.g. shim was rotated).
1017
- if transport_obj.contains_key("shim") {
1018
- return;
1019
- }
1020
- transport_obj.insert("shim".to_string(), latest_shim);
1021
- }
1022
-
1023
- fn should_skip_capture_backfill(
1024
- current_team_key: Option<&str>,
1025
- skip_team_key: Option<&str>,
1026
- ) -> bool {
1027
- match skip_team_key {
1028
- Some(skip_team_key) => current_team_key == Some(skip_team_key),
1029
- None => true,
1030
- }
1031
- }
1032
-
1033
- fn preserve_latest_ownership_fields(
1034
- incoming: &mut Value,
1035
- latest: &Value,
1036
- receiver_update_authoritative: bool,
1037
- ) {
1038
- if !latest_has_preferable_ownership(incoming, latest, receiver_update_authoritative) {
1039
- return;
1040
- }
1041
- let Some(incoming_obj) = incoming.as_object_mut() else {
1042
- return;
1043
- };
1044
- for key in ["leader_receiver", "team_owner", "owner_epoch"] {
1045
- if let Some(value) = latest.get(key).filter(|value| json_truthy(value)) {
1046
- incoming_obj.insert(key.to_string(), value.clone());
1047
- }
1048
- }
1049
- }
1050
-
1051
- fn apply_lock_held_exact_owner_cleanup(incoming: &mut Value, latest: &Value, seed: &Value) {
1052
- apply_lock_held_exact_owner_receiver_cleanup(incoming, latest, seed, None);
1053
- }
1054
-
1055
- fn apply_lock_held_exact_owner_receiver_cleanup(
1056
- incoming: &mut Value,
1057
- latest: &Value,
1058
- seed: &Value,
1059
- expected_receiver: Option<&Value>,
1060
- ) {
1061
- // Compare the lock-held disk owner and, when supplied, receiver to the
1062
- // attempt-local grant. A same-owner receiver update is a concurrent
1063
- // winner and must survive cleanup just like a different owner/epoch.
1064
- let latest_owner = latest.get("team_owner");
1065
- let receiver_matches = expected_receiver.is_none_or(|expected| {
1066
- latest.get("leader_receiver") == Some(expected)
1067
- });
1068
- let Some(incoming_obj) = incoming.as_object_mut() else {
1069
- return;
1070
- };
1071
- if latest_owner == Some(seed) && receiver_matches {
1072
- incoming_obj.insert("team_owner".to_string(), Value::Null);
1073
- incoming_obj.insert("leader_receiver".to_string(), Value::Null);
1074
- if let Some(epoch) = latest
1075
- .get("owner_epoch")
1076
- .cloned()
1077
- .or_else(|| latest_owner.and_then(|owner| owner.get("owner_epoch")).cloned())
1078
- {
1079
- incoming_obj.insert("owner_epoch".to_string(), epoch);
1080
- }
1081
- return;
1082
- }
1083
- for key in ["team_owner", "leader_receiver", "owner_epoch"] {
1084
- match latest.get(key) {
1085
- Some(value) => {
1086
- incoming_obj.insert(key.to_string(), value.clone());
1087
- }
1088
- None => {
1089
- incoming_obj.remove(key);
1090
- }
1091
- }
1092
- }
1093
- }
1094
-
1095
- fn apply_lock_held_exact_owner_receiver_restore(
1096
- incoming: &mut Value,
1097
- latest: &Value,
1098
- expected_owner: &Value,
1099
- expected_receiver: &Value,
1100
- previous_owner: &Value,
1101
- previous_receiver: &Value,
1102
- ) {
1103
- let latest_owner = latest.get("team_owner");
1104
- let latest_receiver = latest.get("leader_receiver");
1105
- let Some(incoming_obj) = incoming.as_object_mut() else {
1106
- return;
1107
- };
1108
- if latest_owner == Some(expected_owner) && latest_receiver == Some(expected_receiver) {
1109
- incoming_obj.insert("team_owner".to_string(), previous_owner.clone());
1110
- incoming_obj.insert("leader_receiver".to_string(), previous_receiver.clone());
1111
- if let Some(epoch) = previous_owner
1112
- .get("owner_epoch")
1113
- .cloned()
1114
- .or_else(|| latest.get("owner_epoch").cloned())
1115
- {
1116
- incoming_obj.insert("owner_epoch".to_string(), epoch);
1117
- }
1118
- return;
1119
- }
1120
- for key in ["team_owner", "leader_receiver", "owner_epoch"] {
1121
- match latest.get(key) {
1122
- Some(value) => {
1123
- incoming_obj.insert(key.to_string(), value.clone());
1124
- }
1125
- None => {
1126
- incoming_obj.remove(key);
1127
- }
1128
- }
1129
- }
1130
- }
1131
-
1132
- fn preserve_latest_endpoint_convergence_fields(incoming: &mut Value, latest: &Value) {
1133
- if !latest_has_preferable_endpoint_convergence(incoming, latest) {
1134
- return;
1135
- }
1136
- let Some(incoming_obj) = incoming.as_object_mut() else {
1137
- return;
1138
- };
1139
- for key in [
1140
- "tmux_endpoint",
1141
- "tmux_socket",
1142
- "tmux_socket_source",
1143
- "topology_convergence",
1144
- ] {
1145
- if let Some(value) = latest.get(key).filter(|value| json_truthy(value)) {
1146
- incoming_obj.insert(key.to_string(), value.clone());
1147
- }
1148
- }
1149
- }
1150
-
1151
- fn latest_has_preferable_endpoint_convergence(incoming: &Value, latest: &Value) -> bool {
1152
- if latest
1153
- .get("topology_convergence")
1154
- .and_then(|marker| marker.get("status"))
1155
- .and_then(Value::as_str)
1156
- != Some("converged")
1157
- {
1158
- return false;
1159
- }
1160
- let latest_epoch =
1161
- endpoint_convergence_epoch(latest).unwrap_or_else(|| ownership_epoch(latest));
1162
- let incoming_epoch =
1163
- endpoint_convergence_epoch(incoming).unwrap_or_else(|| ownership_epoch(incoming));
1164
- if latest_epoch < incoming_epoch {
1165
- return false;
1166
- }
1167
- !incoming.get("topology_convergence").is_some_and(|marker| {
1168
- marker.get("status").and_then(Value::as_str) == Some("converged")
1169
- && marker
1170
- .get("owner_epoch")
1171
- .and_then(Value::as_u64)
1172
- .is_some_and(|epoch| epoch >= latest_epoch)
1173
- })
1174
- }
1175
-
1176
- fn endpoint_convergence_epoch(state: &Value) -> Option<u64> {
1177
- state
1178
- .get("topology_convergence")
1179
- .and_then(|marker| marker.get("owner_epoch"))
1180
- .and_then(Value::as_u64)
1181
- }
1182
-
1183
- fn latest_has_preferable_ownership(
1184
- incoming: &Value,
1185
- latest: &Value,
1186
- receiver_update_authoritative: bool,
1187
- ) -> bool {
1188
- let latest_epoch = ownership_epoch(latest);
1189
- let incoming_epoch = ownership_epoch(incoming);
1190
- if latest_epoch > incoming_epoch {
1191
- return true;
1192
- }
1193
- latest_epoch == incoming_epoch
1194
- && !receiver_update_authoritative
1195
- && (ownership_attached(latest) || !ownership_attached(incoming))
1196
- }
1197
-
1198
- fn latest_team_owner_receiver<'a>(
1199
- latest: &'a Value,
1200
- team_key: Option<&str>,
1201
- ) -> Option<(&'a Value, &'a Value)> {
1202
- let entry = if let Some(team_key) = team_key {
1203
- latest
1204
- .get("teams")
1205
- .and_then(Value::as_object)
1206
- .and_then(|teams| teams.get(team_key))?
1207
- } else {
1208
- latest
1209
- };
1210
- Some((entry.get("team_owner")?, entry.get("leader_receiver")?))
1211
- }
1212
-
1213
- fn ownership_epoch(state: &Value) -> u64 {
1214
- state
1215
- .get("owner_epoch")
1216
- .and_then(Value::as_u64)
1217
- .or_else(|| {
1218
- state
1219
- .get("team_owner")
1220
- .and_then(|owner| owner.get("owner_epoch"))
1221
- .and_then(Value::as_u64)
1222
- })
1223
- .or_else(|| {
1224
- state
1225
- .get("leader_receiver")
1226
- .and_then(|receiver| receiver.get("owner_epoch"))
1227
- .and_then(Value::as_u64)
1228
- })
1229
- .unwrap_or(0)
1230
- }
1231
-
1232
- fn ownership_attached(state: &Value) -> bool {
1233
- ["leader_receiver", "team_owner"].into_iter().any(|key| {
1234
- state
1235
- .get(key)
1236
- .and_then(|value| value.get("pane_id"))
1237
- .and_then(Value::as_str)
1238
- .is_some_and(|pane| !pane.is_empty() && pane != "__team_agent_unbound__")
1239
- })
1240
- }
1241
-
1242
- #[allow(clippy::too_many_arguments)]
1243
- fn merge_agent_projection(
1244
- projection: &str,
1245
- incoming_agents: Option<&mut Value>,
1246
- latest_agents: Option<&Value>,
1247
- deleted_agent_ids: &BTreeSet<String>,
1248
- skip_capture_backfill: bool,
1249
- skip_capture_backfill_agent_ids: &BTreeSet<String>,
1250
- topology_update_agent_ids: &BTreeSet<String>,
1251
- // 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.3):
1252
- // whether the containing team is a live protection target.
1253
- // - `None`: top-level projection — historical behavior, protect on truthy topology.
1254
- // - `Some(true)`: per-team merge for a canonical-alive team — protect.
1255
- // - `Some(false)`: per-team merge for a shutdown/legacy-stopped team —
1256
- // the merge must NOT protect stale topology so a live sibling's write
1257
- // can go through.
1258
- team_alive: Option<bool>,
1259
- preserve_latest_fork_targets: bool,
1260
- ) -> Result<(), StateError> {
1261
- let Some(incoming_agents) = incoming_agents else {
1262
- return Ok(());
1263
- };
1264
- let Some(incoming_map) = incoming_agents.as_object_mut() else {
1265
- return Ok(());
1266
- };
1267
- let Some(latest_map) = latest_agents.and_then(Value::as_object) else {
1268
- return Ok(());
1269
- };
1270
- for (agent_id, latest_agent) in latest_map {
1271
- if deleted_agent_ids.contains(agent_id) {
1272
- continue;
1273
- }
1274
- let tombstoned_for_projection =
1275
- skip_capture_backfill && skip_capture_backfill_agent_ids.contains(agent_id);
1276
- let fork_target = preserve_latest_fork_targets
1277
- && latest_agent
1278
- .get("forked_from")
1279
- .and_then(Value::as_str)
1280
- .is_some_and(|source| !source.is_empty());
1281
- match incoming_map.entry(agent_id.clone()) {
1282
- serde_json::map::Entry::Vacant(slot) => {
1283
- // Omission by an ordinary/stale writer cannot retire a stopped
1284
- // seat or discard its resume metadata. Explicit RemoveAgent
1285
- // has already been admitted through deleted_agent_ids above.
1286
- if crate::state::projection::agent_explicit_stop(latest_agent) {
1287
- slot.insert(latest_agent.clone());
1288
- continue;
1289
- }
1290
- if fork_target {
1291
- slot.insert(latest_agent.clone());
1292
- continue;
1293
- }
1294
- if topology_update_agent_ids.contains(agent_id) {
1295
- continue;
1296
- }
1297
- if !tombstoned_for_projection
1298
- && latest_has_protected_live_topology(latest_agent, team_alive)
1299
- {
1300
- // A lifecycle-authoritative writer may have loaded its whole
1301
- // projection before this peer finalized. Preserve the complete
1302
- // latest peer row rather than treating that untouched omission
1303
- // as an intentional delete. Ordinary saves (with no topology
1304
- // authority) retain the conflict so omission cannot clobber a
1305
- // live row.
1306
- if !topology_update_agent_ids.is_empty() {
1307
- slot.insert(latest_agent.clone());
1308
- continue;
1309
- }
1310
- return Err(save_conflict(
1311
- projection,
1312
- agent_id,
1313
- live_topology_fields(latest_agent),
1314
- ));
1315
- }
1316
- if let Some(stub) = roster_stub(latest_agent) {
1317
- slot.insert(stub);
1318
- }
1319
- }
1320
- serde_json::map::Entry::Occupied(mut existing) => {
1321
- if !topology_update_agent_ids.contains(agent_id) {
1322
- if crate::state::projection::agent_explicit_stop(latest_agent) {
1323
- *existing.get_mut() = latest_agent.clone();
1324
- continue;
1325
- }
1326
- if let Some(marker) = latest_agent.get("explicit_stop") {
1327
- if let Some(row) = existing.get_mut().as_object_mut() {
1328
- row.insert("explicit_stop".into(), marker.clone());
1329
- }
1330
- }
1331
- }
1332
- if !tombstoned_for_projection && !topology_update_agent_ids.contains(agent_id) {
1333
- let fields = topology_conflict_fields(existing.get(), latest_agent, team_alive);
1334
- if !fields.is_empty() {
1335
- if fork_target {
1336
- preserve_latest_topology(existing.get_mut(), latest_agent);
1337
- } else if !topology_update_agent_ids.is_empty()
1338
- && lifecycle_peer_snapshot_is_stale(existing.get(), latest_agent)
1339
- {
1340
- // A lifecycle writer may have loaded a complete
1341
- // peer row before that peer finalized. Its own
1342
- // topology authority is limited to the IDs it
1343
- // explicitly reports; preserve the latest peer
1344
- // row instead of surfacing a stale self-conflict.
1345
- preserve_latest_topology(existing.get_mut(), latest_agent);
1346
- } else if lifecycle_placeholder(existing.get()) {
1347
- preserve_latest_topology(existing.get_mut(), latest_agent);
1348
- } else {
1349
- return Err(save_conflict(projection, agent_id, fields));
1350
- }
1351
- }
1352
- }
1353
- if !skip_capture_backfill || !skip_capture_backfill_agent_ids.contains(agent_id) {
1354
- backfill_capture_fields(existing.get_mut(), latest_agent);
1355
- }
1356
- }
1357
- }
1358
- }
1359
- Ok(())
1360
- }
1361
-
1362
- fn lifecycle_placeholder(agent: &Value) -> bool {
1363
- matches!(
1364
- agent.get("status").and_then(Value::as_str),
1365
- Some("reserved" | "starting")
1366
- )
1367
- }
1368
-
1369
- fn lifecycle_peer_snapshot_is_stale(incoming: &Value, latest: &Value) -> bool {
1370
- // A save that omitted a not-yet-spawned peer can carry roster_stub's
1371
- // metadata-only row into a later save. It has neither status nor epoch;
1372
- // it must not conflict with the peer that has since started.
1373
- if incoming.get("status").is_none_or(Value::is_null)
1374
- && live_topology_fields(incoming).is_empty()
1375
- && latest.get("status").and_then(Value::as_str) == Some("running")
1376
- {
1377
- return true;
1378
- }
1379
- // A concurrent clone/restart can have promoted its peer to `running`
1380
- // while its capture tuple is still pending. That row is still a
1381
- // lifecycle snapshot, not a completed topology observation; preserving
1382
- // the latest peer avoids making the concurrent writer lose on a pane
1383
- // binding it never owned. A completed row remains epoch-ordered below,
1384
- // so a newer/equal completed topology still conflicts.
1385
- if incoming
1386
- .get("_pending_session_id")
1387
- .and_then(Value::as_str)
1388
- .is_some_and(|session| !session.is_empty())
1389
- {
1390
- return true;
1391
- }
1392
- let Some(incoming_epoch) = incoming.get("spawn_epoch").and_then(Value::as_u64) else {
1393
- return false;
1394
- };
1395
- let Some(latest_epoch) = latest.get("spawn_epoch").and_then(Value::as_u64) else {
1396
- return false;
1397
- };
1398
- incoming_epoch < latest_epoch
1399
- }
1400
-
1401
- fn preserve_latest_topology(incoming: &mut Value, latest: &Value) {
1402
- let Some(incoming) = incoming.as_object_mut() else {
1403
- return;
1404
- };
1405
- // A stale add/clone writer can carry a placeholder row (`starting`) after
1406
- // a peer has completed its spawn. Preserve the completed lifecycle and
1407
- // capture tuple together with topology; otherwise a later peer save can
1408
- // regress the finalized row back to `starting` while returning success.
1409
- if latest.get("status").and_then(Value::as_str) == Some("running") {
1410
- // The finalized row is authoritative as a whole. Copying a hand-picked
1411
- // field list can leave stale capture/metadata keys from the placeholder
1412
- // and is not equivalent to preserving the peer that already finalized.
1413
- *incoming = latest.as_object().cloned().unwrap_or_default();
1414
- return;
1415
- }
1416
- for field in LIVE_TOPOLOGY_FIELDS {
1417
- if let Some(value) = latest.get(field).filter(|value| json_truthy(value)) {
1418
- incoming.insert(field.to_string(), value.clone());
1419
- }
1420
- }
1421
- }
1422
-
1423
- fn save_conflict(projection: &str, agent_id: &str, fields: Vec<&'static str>) -> StateError {
1424
- StateError::SaveConflict(format!(
1425
- "agent_id={agent_id} projection={projection} conflicting_fields={}",
1426
- fields.join(",")
1427
- ))
1428
- }
1429
-
1430
- /// 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.3):
1431
- /// 谓词收敛。原 `latest_has_live_topology` 只看 topology 字段真值,现改为:
1432
- /// - 若上层告知 `team_alive=Some(false)` → 死队,永不 protect;
1433
- /// - 若 latest 的 agent.status 是终态(stopped/dead/…)→ 永不 protect;
1434
- /// - 否则维持原判据(topology 字段真值 → protect)。
1435
- ///
1436
- /// 保守设计:top-level 传 `None` 时行为与 0.5.25 前完全一致(仅看 topology
1437
- /// 真值),避免影响 F0-1/F0-2/E6 已通契约。
1438
- fn latest_has_protected_live_topology(agent: &Value, team_alive: Option<bool>) -> bool {
1439
- if team_alive == Some(false) {
1440
- return false;
1441
- }
1442
- if let Some(status) = agent.get("status").and_then(Value::as_str) {
1443
- if crate::state::projection::agent_status_is_terminal(status) {
1444
- return false;
1445
- }
1446
- }
1447
- LIVE_TOPOLOGY_FIELDS
1448
- .iter()
1449
- .any(|field| agent.get(field).is_some_and(json_truthy))
1450
- }
1451
-
1452
- fn live_topology_fields(agent: &Value) -> Vec<&'static str> {
1453
- LIVE_TOPOLOGY_FIELDS
1454
- .iter()
1455
- .copied()
1456
- .filter(|field| agent.get(*field).is_some_and(json_truthy))
1457
- .collect()
1458
- }
1459
-
1460
- fn topology_conflict_fields(
1461
- incoming_agent: &Value,
1462
- latest_agent: &Value,
1463
- team_alive: Option<bool>,
1464
- ) -> Vec<&'static str> {
1465
- // 0.5.26 (§7.3): 若被守卫的 team 已死 / agent 处终态,不再报 topology
1466
- // 冲突,允许活队 sibling write 通过。
1467
- if !latest_has_protected_live_topology(latest_agent, team_alive) {
1468
- return Vec::new();
1469
- }
1470
- let latest_live = live_topology_fields(latest_agent);
1471
- if latest_live.is_empty() {
1472
- return Vec::new();
1473
- }
1474
- latest_live
1475
- .into_iter()
1476
- .filter(|field| incoming_agent.get(*field) != latest_agent.get(*field))
1477
- .collect()
1478
- }
1479
-
1480
- fn roster_stub(latest_agent: &Value) -> Option<Value> {
1481
- let latest = latest_agent.as_object()?;
1482
- let mut stub = serde_json::Map::new();
1483
- for field in ROSTER_STUB_ALLOWLIST {
1484
- if let Some(value) = latest.get(field).filter(|value| !value.is_null()) {
1485
- stub.insert(field.to_string(), value.clone());
1486
- }
1487
- }
1488
- (!stub.is_empty()).then(|| Value::Object(stub))
1489
- }
1490
-
1491
- /// 0.4.6 tuple-atomic backfill (restart-persist-capture-contract-audit.md):
1492
- /// the authoritative session tuple is `session_id + rollout_path +
1493
- /// captured_at + captured_via`. `attribution_confidence` is metadata on
1494
- /// that tuple. Persist may preserve an already-complete tuple across stale
1495
- /// saves, but it must NEVER:
1496
- /// * synthesise a partial tuple (e.g. copy `session_id` while the other
1497
- /// three are absent — this caused bug-045 by resurrecting an
1498
- /// intentionally cleared session id);
1499
- /// * mix tuple fields across two different session_ids (one writer's
1500
- /// `session_id` glued to another writer's `rollout_path`);
1501
- /// * create non-null session truth where none existed.
1502
- ///
1503
- /// Rules:
1504
- /// 1. If LATEST has a complete tuple AND INCOMING has the same `session_id`
1505
- /// (or null), backfill the full tuple together — concurrent capture
1506
- /// protection (A0/R2).
1507
- /// 2. If LATEST has a complete tuple AND INCOMING has a DIFFERENT non-null
1508
- /// `session_id`, copy nothing (incoming is a different worker session
1509
- /// identity; the latest tuple belongs to the previous identity).
1510
- /// 3. If LATEST tuple is INCOMPLETE (any of the 4 fields null), copy
1511
- /// nothing for the tuple. An incomplete latest tuple is not
1512
- /// authoritative truth, so persist cannot use it as backfill source.
1513
- /// 4. `attribution_confidence` rides with the tuple (copied iff tuple
1514
- /// backfill fires).
1515
- fn backfill_capture_fields(incoming_agent: &mut Value, latest_agent: &Value) {
1516
- const TUPLE_FIELDS: [&str; 4] = ["session_id", "rollout_path", "captured_at", "captured_via"];
1517
- let Some(incoming_row) = incoming_agent.as_object_mut() else {
1518
- return;
1519
- };
1520
- // Rule 3: latest tuple must be COMPLETE to be a backfill source.
1521
- let latest_complete = TUPLE_FIELDS
1522
- .iter()
1523
- .all(|field| latest_agent.get(field).is_some_and(|v| !v.is_null()));
1524
- if !latest_complete {
1525
- return;
1526
- }
1527
- // S1-CAPTURE-001 (0.4.8) Rule 5: a fresh restart marker (`_pending_session_id`
1528
- // present on incoming) signals the worker just respawned and the prior
1529
- // tuple was intentionally cleared. The capture scanner is the only path
1530
- // permitted to promote `_pending_session_id` into the authoritative tuple
1531
- // after it confirms backing. Persist-side backfill MUST NOT revive the
1532
- // latest tuple in this state — doing so resurrects the previous worker's
1533
- // session/rollout pair and delivered tokens land in the OLD transcript
1534
- // (the leader/unassigned mis-attribution surfaced in S1-CAPTURE-001 gate
1535
- // evidence). Refuse backfill regardless of whether incoming session_id
1536
- // is null vs latest's value: the pending marker is authoritative intent.
1537
- let incoming_pending = incoming_row
1538
- .get("_pending_session_id")
1539
- .and_then(Value::as_str)
1540
- .filter(|s| !s.is_empty());
1541
- if incoming_pending.is_some() {
1542
- return;
1543
- }
1544
- // Rule 2: incoming carries a DIFFERENT non-null session_id → do not mix.
1545
- let incoming_session = incoming_row.get("session_id").and_then(Value::as_str);
1546
- let latest_session = latest_agent.get("session_id").and_then(Value::as_str);
1547
- if let Some(inc) = incoming_session {
1548
- if Some(inc) != latest_session {
1549
- return;
1550
- }
1551
- }
1552
- // Rule 1 + 4: copy the full tuple together (only fields incoming has as
1553
- // null/missing) plus attribution_confidence.
1554
- for field in TUPLE_FIELDS
1555
- .iter()
1556
- .copied()
1557
- .chain(std::iter::once("attribution_confidence"))
1558
- {
1559
- if incoming_row.get(field).is_none_or(Value::is_null) {
1560
- if let Some(value) = latest_agent.get(field).filter(|value| !value.is_null()) {
1561
- incoming_row.insert(field.to_string(), value.clone());
1562
- }
1563
- }
1564
- }
1565
- }
1566
-
1567
- fn same_runtime_projection(left: &Value, right: &Value) -> bool {
1568
- let left_session = left.get("session_name").and_then(Value::as_str);
1569
- let right_session = right.get("session_name").and_then(Value::as_str);
1570
- if left_session.is_some() && right_session.is_some() && left_session != right_session {
1571
- return false;
1572
- }
1573
- let left_team = active_team_key(left);
1574
- let right_team = active_team_key(right);
1575
- if left_team.is_some() && right_team.is_some() && left_team != right_team {
1576
- return false;
1577
- }
1578
- true
1579
- }
1580
-
1581
- fn active_team_key(state: &Value) -> Option<String> {
1582
- state
1583
- .get("active_team_key")
1584
- .and_then(Value::as_str)
1585
- .filter(|team| !team.is_empty() && *team != "current")
1586
- .map(str::to_string)
1587
- }
1588
-
1589
- /// `_self_heal_runtime_state`:重建 inode(heal-tmp + backup-rename),绝不 in-place truncate。
1590
- fn self_heal(
1591
- workspace: &Path,
1592
- path: &Path,
1593
- payload: &str,
1594
- state: &Value,
1595
- attempts_used: usize,
1596
- original_exc: &io::Error,
1597
- ) -> Result<(), StateError> {
1598
- let event_log = EventLog::new(workspace);
1599
- let heal_tmp = unique_tmp(path, "heal.tmp");
1600
- let name = path
1601
- .file_name()
1602
- .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
1603
- let backup = path.with_file_name(format!("{name}.bak.{}", std::process::id()));
1604
- let mut backup_created = false;
1605
-
1606
- let outcome: io::Result<()> = (|| {
1607
- std::fs::write(&heal_tmp, payload.as_bytes())?;
1608
- match atomic_replace(path, &backup) {
1609
- Ok(()) => backup_created = true,
1610
- Err(e) if e.kind() == io::ErrorKind::NotFound => {} // 原 state 不存在 → 无需备份
1611
- Err(e) => return Err(e),
1612
- }
1613
- atomic_replace(&heal_tmp, path)
1614
- })();
1615
- let _ = std::fs::remove_file(&heal_tmp); // finally
1616
-
1617
- match outcome {
1618
- Ok(()) => {
1619
- cache_set(path, state);
1620
- let _ = event_log.write(
1621
- "runtime.state.self_healed",
1622
- json!({
1623
- "inode_rebuilt": true,
1624
- "attempts_used": attempts_used,
1625
- "replace_retries": attempts_used.saturating_sub(1),
1626
- }),
1627
- );
1628
- Ok(())
1629
- }
1630
- Err(e) => {
1631
- if backup_created {
1632
- if let Err(restore) = atomic_replace(&backup, path) {
1633
- let _ = event_log.write(
1634
- "runtime.state.self_heal_restore_failed",
1635
- json!({"error": restore.to_string()}),
1636
- );
1637
- }
1638
- }
1639
- let _ = event_log.write(
1640
- "runtime.state.save_failed",
1641
- json!({
1642
- "phase": "save_runtime_state",
1643
- "final_errno": e.raw_os_error().or_else(|| original_exc.raw_os_error()),
1644
- "error": e.to_string(),
1645
- "retries_used": attempts_used.saturating_sub(1),
1646
- }),
1647
- );
1648
- Err(StateError::SaveFailed(e.to_string()))
1649
- }
1650
- }
1651
- }
1652
-
1653
- ///
1654
- /// `load_runtime_state`(本 slice 最小:读+parse+缓存;normalize/migration 待 identity slice)。
1655
- /// `normalize_agent_session_state`(`state.py:45`):为每个 agent dict 的 SESSION_STATE_FIELDS
1656
- /// setdefault None(缺则末尾插)。
1657
- fn normalize_agent_session_state(state: &mut Value) {
1658
- let Some(agents) = state.get_mut("agents").and_then(Value::as_object_mut) else {
1659
- return;
1660
- };
1661
- for agent_state in agents.values_mut() {
1662
- if let Some(obj) = agent_state.as_object_mut() {
1663
- for field in SESSION_STATE_FIELDS {
1664
- obj.entry(field.to_string()).or_insert(Value::Null);
1665
- }
1666
- }
1667
- }
1668
- }
1669
-
1670
- ///
1671
- /// `_migrate_active_team_key`(`state.py:73`,0.2.6 Family B C6):legacy state 缺 active_team_key
1672
- /// 时 seed 一次。返回是否有改动。
1673
- ///
1674
- /// 注:Python `seed if seed in teams or not teams else seed` 两支均为 `seed`(死三元),
1675
- /// 此处直接 `= seed`,与可观测行为一致。
1676
- fn migrate_active_team_key(state: &mut Value) -> bool {
1677
- if state
1678
- .as_object()
1679
- .is_some_and(|o| o.contains_key("active_team_key"))
1680
- {
1681
- return false;
1682
- }
1683
- let teams_is_dict = state.get("teams").is_some_and(Value::is_object);
1684
- let teams_len = state
1685
- .get("teams")
1686
- .and_then(Value::as_object)
1687
- .map_or(0, serde_json::Map::len);
1688
- if state.get("session_name").is_some_and(json_truthy) {
1689
- let seed = team_state_key(state);
1690
- if let Some(o) = state.as_object_mut() {
1691
- o.insert("active_team_key".to_string(), Value::String(seed));
1692
- }
1693
- return true;
1694
- }
1695
- if teams_is_dict && teams_len == 1 {
1696
- let first = state
1697
- .get("teams")
1698
- .and_then(Value::as_object)
1699
- .and_then(|t| t.keys().next().cloned());
1700
- if let (Some(k), Some(o)) = (first, state.as_object_mut()) {
1701
- o.insert("active_team_key".to_string(), Value::String(k));
1702
- }
1703
- return true;
1704
- }
1705
- if let Some(o) = state.as_object_mut() {
1706
- o.insert("active_team_key".to_string(), Value::Null);
1707
- }
1708
- true
1709
- }
1710
-
1711
- ///
1712
- /// RM-039-STAT-001 second-round compat normalizer (architect verdict
1713
- /// 2026-06-22). When `active_team_key` names an existing `teams` entry
1714
- /// but root `team_key` is missing, set root `team_key = active_team_key`
1715
- /// (and mirror it into `teams[active_team_key].team_key` for callers
1716
- /// that read the team-scoped slot). This keeps the cascade in
1717
- /// `state::projection::team_state_key` honest: the first branch
1718
- /// (`state.team_key`) now matches what `active_team_key` says, so
1719
- /// coordinator tick's `save_team_scoped_state` writes activity to the
1720
- /// SAME teams entry the status selector later reads.
1721
- ///
1722
- /// Narrow on purpose:
1723
- /// * Returns `false` (no-op) when root `team_key` already exists,
1724
- /// even if it disagrees with `active_team_key`. Conflict cases
1725
- /// stay observable; we don't silently rewrite.
1726
- /// * Returns `false` when `active_team_key` is null/empty.
1727
- /// * Returns `false` when `teams[active_team_key]` does not exist.
1728
- /// * Does NOT touch any other field (no generic deep merge).
1729
- ///
1730
- /// Returns `true` if state was mutated and the caller should persist.
1731
- fn migrate_team_key_to_match_active_team(state: &mut Value) -> bool {
1732
- let Some(obj) = state.as_object() else {
1733
- return false;
1734
- };
1735
- let already_has_root = obj
1736
- .get("team_key")
1737
- .and_then(Value::as_str)
1738
- .is_some_and(|s| !s.is_empty());
1739
- if already_has_root {
1740
- return false;
1741
- }
1742
- let active = match obj.get("active_team_key").and_then(Value::as_str) {
1743
- Some(s) if !s.is_empty() => s.to_string(),
1744
- _ => return false,
1745
- };
1746
- let teams_has_active = obj
1747
- .get("teams")
1748
- .and_then(Value::as_object)
1749
- .is_some_and(|teams| teams.contains_key(&active));
1750
- if !teams_has_active {
1751
- return false;
1752
- }
1753
- let Some(obj_mut) = state.as_object_mut() else {
1754
- return false;
1755
- };
1756
- obj_mut.insert("team_key".to_string(), Value::String(active.clone()));
1757
- // Mirror inside teams[active] so any code reading the team-scoped
1758
- // slot sees the same canonical key. Skip if the entry isn't an
1759
- // object (defensive — should always be).
1760
- if let Some(team_entry) = obj_mut
1761
- .get_mut("teams")
1762
- .and_then(Value::as_object_mut)
1763
- .and_then(|teams| teams.get_mut(&active))
1764
- .and_then(Value::as_object_mut)
1765
- {
1766
- let needs_team_key = team_entry
1767
- .get("team_key")
1768
- .and_then(Value::as_str)
1769
- .map(|s| s != active)
1770
- .unwrap_or(true);
1771
- if needs_team_key {
1772
- team_entry.insert("team_key".to_string(), Value::String(active));
1773
- }
1774
- }
1775
- true
1776
- }
1777
-
1778
- pub fn load_runtime_state(workspace: &Path) -> Result<Value, StateError> {
1779
- let path = runtime_state_path(workspace);
1780
- if !path.exists() {
1781
- if let Some(cached) = cache_get(&path) {
1782
- return Ok(cached);
1783
- }
1784
- return Ok(
1785
- json!({"agents": {}, "tasks": [], "session_name": null, "active_team_key": null}),
1786
- );
1787
- }
1788
- let text = std::fs::read_to_string(&path)?;
1789
- let mut state: Value = serde_json::from_str(&text)?;
1790
- normalize_agent_session_state(&mut state);
1791
- let mut changed = migrate_state_identity(&mut state, &SystemEnv, workspace)?;
1792
- if migrate_active_team_key(&mut state) {
1793
- changed = true;
1794
- }
1795
- // RM-039-STAT-001 second-round compat (architect verdict 2026-06-22):
1796
- // for states written before the launch-side `team_key` fix landed,
1797
- // promote `active_team_key` into root `team_key` so coordinator tick
1798
- // and status selector agree on which `teams` entry to read/write.
1799
- if migrate_team_key_to_match_active_team(&mut state) {
1800
- changed = true;
1801
- }
1802
- if changed {
1803
- save_runtime_state(workspace, &state)?;
1804
- }
1805
- cache_set(&path, &state);
1806
- Ok(state)
1807
- }
1808
-
1809
- pub(crate) fn load_runtime_state_without_migrations(workspace: &Path) -> Result<Value, StateError> {
1810
- let path = runtime_state_path(workspace);
1811
- if !path.exists() {
1812
- return Ok(
1813
- json!({"agents": {}, "tasks": [], "session_name": null, "active_team_key": null}),
1814
- );
1815
- }
1816
- let text = std::fs::read_to_string(&path)?;
1817
- let mut state: Value = serde_json::from_str(&text)?;
1818
- normalize_agent_session_state(&mut state);
1819
- Ok(state)
1820
- }
1821
-
1822
- /// Run a read-only callback while holding the canonical `state-save` lock.
1823
- /// Unlike `load_runtime_state`, this helper performs no migration, cache
1824
- /// update, or write. A missing state file is represented as `None` so callers
1825
- /// can conservatively retain derived indexes during workspace unavailability.
1826
- pub(crate) fn with_runtime_state_lock_without_migrations<T>(
1827
- workspace: &Path,
1828
- callback: impl FnOnce(Option<Value>) -> T,
1829
- ) -> Result<T, StateError> {
1830
- let path = runtime_state_path(workspace);
1831
- if !path.exists() {
1832
- return Ok(callback(None));
1833
- }
1834
- let _lock = RuntimeLock::acquire(workspace, "state-save", 2.0)?;
1835
- let state = match std::fs::read_to_string(&path) {
1836
- Ok(text) => Some(serde_json::from_str::<Value>(&text)?),
1837
- Err(error) if error.kind() == io::ErrorKind::NotFound => None,
1838
- Err(error) => return Err(error.into()),
1839
- };
1840
- Ok(callback(state))
1841
- }
1842
-
1843
- pub(crate) fn save_runtime_state_without_migrations(
1844
- workspace: &Path,
1845
- state: &Value,
1846
- ) -> Result<(), StateError> {
1847
- let path = runtime_state_path(workspace);
1848
- // Raw writers share the canonical lock so readers/pruners cannot race
1849
- // a restore write through a parallel lock namespace.
1850
- let _lock = RuntimeLock::acquire(workspace, "state-save", 2.0)?;
1851
- if let Some(parent) = path.parent() {
1852
- std::fs::create_dir_all(parent)?;
1853
- }
1854
- let payload = serde_json::to_string_pretty(state)?;
1855
- std::fs::write(&path, payload.as_bytes())?;
1856
- cache_set(&path, state);
1857
- Ok(())
1858
- }
1859
-
1860
- #[cfg(test)]
1861
- mod tests {
1862
- #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
1863
- use super::*;
1864
- use std::sync::atomic::AtomicU32;
1865
-
1866
- static SEQ: AtomicU32 = AtomicU32::new(0);
1867
- fn temp_ws() -> PathBuf {
1868
- let n = SEQ.fetch_add(1, Ordering::Relaxed);
1869
- let ws = std::env::temp_dir().join(format!("ta_rs_state_{}_{}", std::process::id(), n));
1870
- std::fs::create_dir_all(&ws).unwrap();
1871
- ws
1872
- }
1873
- fn read_events(ws: &Path) -> Vec<Value> {
1874
- EventLog::new(ws).tail(50).unwrap()
1875
- }
1876
- fn count_event(ws: &Path, name: &str) -> usize {
1877
- read_events(ws)
1878
- .iter()
1879
- .filter(|e| e["event"] == json!(name))
1880
- .count()
1881
- }
1882
- // per-call-index 故障计划:plan[i] = 第 i 次 atomic_replace 的 errno(0=成功)。
1883
- fn set_fault_plan(plan: &[i32]) {
1884
- FAULT_PLAN.with(|p| *p.borrow_mut() = plan.to_vec());
1885
- FAULT_IDX.with(|c| c.set(0));
1886
- }
1887
- fn clear_fault() {
1888
- set_fault_plan(&[]);
1889
- }
1890
- fn get_event(ws: &Path, name: &str) -> Value {
1891
- read_events(ws)
1892
- .into_iter()
1893
- .find(|e| e["event"] == json!(name))
1894
- .unwrap_or(Value::Null)
1895
- }
1896
- fn read_state(ws: &Path) -> Value {
1897
- serde_json::from_str(&std::fs::read_to_string(runtime_state_path(ws)).unwrap()).unwrap()
1898
- }
1899
- fn write_state(ws: &Path, state: &Value) {
1900
- std::fs::create_dir_all(runtime_dir(ws)).unwrap();
1901
- std::fs::write(
1902
- runtime_state_path(ws),
1903
- serde_json::to_string_pretty(state).unwrap(),
1904
- )
1905
- .unwrap();
1906
- }
1907
- fn bak_files(ws: &Path) -> Vec<PathBuf> {
1908
- let dir = runtime_dir(ws);
1909
- std::fs::read_dir(&dir)
1910
- .map(|rd| {
1911
- rd.filter_map(std::result::Result::ok)
1912
- .map(|e| e.path())
1913
- .filter(|p| {
1914
- p.file_name()
1915
- .is_some_and(|n| n.to_string_lossy().contains(".bak."))
1916
- })
1917
- .collect()
1918
- })
1919
- .unwrap_or_default()
1920
- }
1921
-
1922
- // 字节对拍:state-rich.json 经 to_string_pretty 字节 == Python json.dumps(indent=2, ensure_ascii=False)。
1923
- #[test]
1924
- fn state_json_byte_parity_with_python_indent2() {
1925
- let fixture = include_str!(concat!(
1926
- env!("CARGO_MANIFEST_DIR"),
1927
- "/../../snapshot/fixtures/bug_084_state_resilience/state-rich.json"
1928
- ));
1929
- let canonical = include_str!("testdata/state-rich.canonical.json");
1930
- let v: Value = serde_json::from_str(fixture).unwrap();
1931
- assert_eq!(
1932
- serde_json::to_string_pretty(&v).unwrap(),
1933
- canonical,
1934
- "state.json 序列化未字节对齐 Python indent=2"
1935
- );
1936
- }
1937
-
1938
- #[test]
1939
- fn save_writes_atomically_and_caches() {
1940
- let ws = temp_ws();
1941
- let state =
1942
- json!({"session_name":"t","agents":{"a":{"agent_id":"a"}},"active_team_key":"t"});
1943
- save_runtime_state(&ws, &state).unwrap();
1944
- let on_disk = std::fs::read_to_string(runtime_state_path(&ws)).unwrap();
1945
- assert_eq!(on_disk, serde_json::to_string_pretty(&state).unwrap());
1946
- assert!(!on_disk.ends_with('\n'), "无尾换行(对齐 json.dumps)");
1947
- // deep-equal 缓存早返回:再 save 相同 state 不应改文件 mtime 行为(此处验返回 Ok 且无错)。
1948
- save_runtime_state(&ws, &state).unwrap();
1949
- }
1950
-
1951
- #[test]
1952
- fn deep_equal_cache_early_returns() {
1953
- let ws = temp_ws();
1954
- let state = json!({"x":1});
1955
- save_runtime_state(&ws, &state).unwrap();
1956
- // 删掉文件;若缓存早返回生效,save 相同 state 不会重建文件。
1957
- std::fs::remove_file(runtime_state_path(&ws)).unwrap();
1958
- save_runtime_state(&ws, &state).unwrap();
1959
- assert!(
1960
- !runtime_state_path(&ws).exists(),
1961
- "deep-equal 命中缓存 → 未重写(文件仍不存在)"
1962
- );
1963
- }
1964
-
1965
- // bug-084 核心:EACCES 重试 3 次(有界退避)→ self-heal 成功 + 事件**字段精确**。
1966
- #[test]
1967
- fn retryable_eacces_retries_then_self_heals() {
1968
- let ws = temp_ws();
1969
- save_runtime_state(&ws, &json!({"v":1})).unwrap(); // 原 state(供 self-heal backup-rename)
1970
- let s2 = json!({"v":2});
1971
- set_fault_plan(&[libc::EACCES, libc::EACCES, libc::EACCES, libc::EACCES]); // loop 4 失败,heal 的 2 次 replace 成功
1972
- save_runtime_state(&ws, &s2).unwrap();
1973
- clear_fault();
1974
- assert_eq!(read_state(&ws), s2, "inode 重建,文件为 s2");
1975
- // 事件序列 + 字段精确。
1976
- let retries: Vec<_> = read_events(&ws)
1977
- .into_iter()
1978
- .filter(|e| e["event"] == json!("runtime.state.save_retry"))
1979
- .collect();
1980
- assert_eq!(retries.len(), 3, "3 次重试");
1981
- assert_eq!(retries[0]["attempt"], json!(1));
1982
- assert_eq!(retries[0]["errno_name"], json!("EACCES"));
1983
- assert_eq!(retries[2]["attempt"], json!(3));
1984
- let healed = get_event(&ws, "runtime.state.self_healed");
1985
- assert_eq!(healed["inode_rebuilt"], json!(true));
1986
- assert_eq!(healed["attempts_used"], json!(4));
1987
- assert_eq!(healed["replace_retries"], json!(3));
1988
- }
1989
-
1990
- // EPERM / EBUSY 也是 retryable(不只 EACCES)。
1991
- #[test]
1992
- fn eperm_and_ebusy_are_retryable() {
1993
- for (errno, name) in [(libc::EPERM, "EPERM"), (libc::EBUSY, "EBUSY")] {
1994
- let ws = temp_ws();
1995
- save_runtime_state(&ws, &json!({"v":1})).unwrap();
1996
- set_fault_plan(&[errno, errno, errno, errno]);
1997
- save_runtime_state(&ws, &json!({"v":2})).unwrap();
1998
- clear_fault();
1999
- assert_eq!(read_state(&ws), json!({"v":2}));
2000
- assert_eq!(count_event(&ws, "runtime.state.self_healed"), 1);
2001
- assert_eq!(
2002
- get_event(&ws, "runtime.state.save_retry")["errno_name"],
2003
- json!(name)
2004
- );
2005
- }
2006
- }
2007
-
2008
- // 非 retryable(ENOSPC)→ 不重试、不 self-heal,直接 Err。
2009
- #[test]
2010
- fn non_retryable_enospc_raises_without_self_heal() {
2011
- let ws = temp_ws();
2012
- set_fault_plan(&[libc::ENOSPC]);
2013
- let r = save_runtime_state(&ws, &json!({"v":9}));
2014
- clear_fault();
2015
- assert!(matches!(r, Err(StateError::Io(_))), "ENOSPC 直接 raise");
2016
- assert_eq!(count_event(&ws, "runtime.state.self_healed"), 0);
2017
- assert_eq!(count_event(&ws, "runtime.state.save_retry"), 0);
2018
- }
2019
-
2020
- // 重试边界:恰 3 次重试,第 4 次(attempt 3)成功 → 无 self-heal。钉死 0..=delays.len() 的 off-by-one。
2021
- #[test]
2022
- fn retry_boundary_exactly_three_then_succeeds() {
2023
- let ws = temp_ws();
2024
- set_fault_plan(&[libc::EACCES, libc::EACCES, libc::EACCES]); // 前 3 失败,第 4 次成功
2025
- save_runtime_state(&ws, &json!({"v":7})).unwrap();
2026
- clear_fault();
2027
- assert_eq!(read_state(&ws), json!({"v":7}));
2028
- assert_eq!(count_event(&ws, "runtime.state.save_retry"), 3);
2029
- assert_eq!(
2030
- count_event(&ws, "runtime.state.self_healed"),
2031
- 0,
2032
- "未触发 self-heal"
2033
- );
2034
- }
2035
-
2036
- // 崩溃安全不变量①:self-heal 中途失败但 restore 成功 → 原 state 复位 + 0 restore_failed + 1 save_failed。
2037
- // (per-index 注入器解锁:loop4 失败、path→backup 成功、heal→path 失败、restore 成功。)
2038
- #[test]
2039
- fn self_heal_restore_success_recovers_original() {
2040
- let ws = temp_ws();
2041
- let original = json!({"keep":"original"});
2042
- save_runtime_state(&ws, &original).unwrap();
2043
- let e = libc::EACCES;
2044
- set_fault_plan(&[e, e, e, e, 0, e, 0]); // idx4=path→backup ok, idx5=heal→path fail, idx6=restore ok
2045
- let r = save_runtime_state(&ws, &json!({"keep":"new"}));
2046
- clear_fault();
2047
- assert!(matches!(r, Err(StateError::SaveFailed(_))));
2048
- assert_eq!(
2049
- read_state(&ws),
2050
- original,
2051
- "restore 成功:原 state 复位到 state.json"
2052
- );
2053
- assert_eq!(
2054
- count_event(&ws, "runtime.state.self_heal_restore_failed"),
2055
- 0
2056
- );
2057
- let failed = get_event(&ws, "runtime.state.save_failed");
2058
- assert_eq!(failed["phase"], json!("save_runtime_state"));
2059
- assert_eq!(failed["retries_used"], json!(3));
2060
- }
2061
-
2062
- // 崩溃安全不变量②:self-heal 失败且 restore 也失败 → 原 state 在 .bak 里完好可恢复 + restore_failed 事件。
2063
- #[test]
2064
- fn self_heal_restore_failed_leaves_original_in_backup() {
2065
- let ws = temp_ws();
2066
- let original = json!({"keep":"original"});
2067
- save_runtime_state(&ws, &original).unwrap();
2068
- let e = libc::EACCES;
2069
- set_fault_plan(&[e, e, e, e, 0, e, e]); // idx4=backup ok, idx5=heal fail, idx6=restore fail
2070
- let r = save_runtime_state(&ws, &json!({"keep":"new"}));
2071
- clear_fault();
2072
- assert!(matches!(r, Err(StateError::SaveFailed(_))));
2073
- assert_eq!(
2074
- count_event(&ws, "runtime.state.self_heal_restore_failed"),
2075
- 1
2076
- );
2077
- assert_eq!(count_event(&ws, "runtime.state.save_failed"), 1);
2078
- // state.json 已被 rename 到 backup(restore 失败),原 state 在 .bak 里完好(绝不丢失)。
2079
- let baks = bak_files(&ws);
2080
- assert_eq!(baks.len(), 1, "应有一个 .bak 存原 state");
2081
- let v: Value = serde_json::from_str(&std::fs::read_to_string(&baks[0]).unwrap()).unwrap();
2082
- assert_eq!(v, original, "原 state 经 backup 可恢复");
2083
- }
2084
-
2085
- // backup FileNotFound 分支:无前置 state.json → path→backup 当 NotFound 吞,heal 仍成功,无 .bak。
2086
- #[test]
2087
- fn self_heal_with_no_prior_state_swallows_backup_notfound() {
2088
- let ws = temp_ws();
2089
- let e = libc::EACCES;
2090
- set_fault_plan(&[e, e, e, e]); // 仅 loop 失败;heal 的 path→backup(真 NotFound,未注入)+ heal→path 成功
2091
- save_runtime_state(&ws, &json!({"fresh":true})).unwrap();
2092
- clear_fault();
2093
- assert_eq!(read_state(&ws), json!({"fresh":true}));
2094
- assert_eq!(count_event(&ws, "runtime.state.self_healed"), 1);
2095
- assert!(bak_files(&ws).is_empty(), "原 state 不存在 → 不应产生 .bak");
2096
- }
2097
-
2098
- // non-ASCII 字节透传(ensure_ascii=False):中文/emoji 字面写入,不转 \\uXXXX。
2099
- #[test]
2100
- fn non_ascii_values_pass_through_literally() {
2101
- let ws = temp_ws();
2102
- save_runtime_state(&ws, &json!({"objective":"héllo🦀 世界","x":1})).unwrap();
2103
- let bytes = std::fs::read_to_string(runtime_state_path(&ws)).unwrap();
2104
- assert!(bytes.contains("héllo🦀 世界"), "非 ASCII 应字面保留");
2105
- assert!(!bytes.contains("\\u"), "不应 ascii-escape");
2106
- }
2107
-
2108
- // deep-equal 命中必须在**取锁之前**返回:持锁时对相同 state 再 save 应立即 Ok(不撞锁 timeout)。
2109
- #[test]
2110
- fn deep_equal_save_returns_before_lock() {
2111
- let ws = temp_ws();
2112
- let state = json!({"v":1});
2113
- save_runtime_state(&ws, &state).unwrap(); // 填充缓存
2114
- let _held = RuntimeLock::acquire(&ws, "state-save", 2.0).unwrap(); // 占锁
2115
- // 若 deep-equal 不早返回,会去抢已被占的锁 → 2s timeout → Locked。Ok 即证早返回。
2116
- assert!(
2117
- save_runtime_state(&ws, &state).is_ok(),
2118
- "deep-equal 应在取锁前返回"
2119
- );
2120
- }
2121
-
2122
- // 并发全流程 save(非仅 lock acquire):多线程存不同 state → 全 Ok + 最终文件合法 JSON + 无 tmp 残留。
2123
- #[test]
2124
- fn concurrent_full_flow_saves_serialize_without_corruption() {
2125
- let ws = temp_ws();
2126
- std::fs::create_dir_all(runtime_dir(&ws)).unwrap();
2127
- let handles: Vec<_> = (0..6)
2128
- .map(|t| {
2129
- let w = ws.clone();
2130
- std::thread::spawn(move || save_runtime_state(&w, &json!({ "t": t })))
2131
- })
2132
- .collect();
2133
- for h in handles {
2134
- h.join().unwrap().unwrap(); // 每个线程 save 都 Ok
2135
- }
2136
- let v = read_state(&ws); // 最终文件是合法 JSON(某个线程的 state)
2137
- assert!(v["t"].is_number());
2138
- let residue: Vec<_> = std::fs::read_dir(runtime_dir(&ws))
2139
- .unwrap()
2140
- .filter_map(std::result::Result::ok)
2141
- .filter(|e| {
2142
- let n = e.file_name().to_string_lossy().into_owned();
2143
- n.ends_with(".tmp") || n.contains(".heal.")
2144
- })
2145
- .collect();
2146
- assert!(residue.is_empty(), "无 tmp/heal 残留:{residue:?}");
2147
- }
2148
-
2149
- // 锁串行化:持锁时第二个 acquire 在 timeout 内拿不到 → Locked。
2150
- #[test]
2151
- fn runtime_lock_serializes() {
2152
- let ws = temp_ws();
2153
- std::fs::create_dir_all(runtime_dir(&ws)).unwrap();
2154
- let held = RuntimeLock::acquire(&ws, "state-save", 2.0).unwrap();
2155
- // 另一线程在短 timeout 内尝试 → 应 Locked(flock 进程内/跨 fd 互斥)。
2156
- let ws2 = ws.clone();
2157
- let r = std::thread::spawn(move || RuntimeLock::acquire(&ws2, "state-save", 0.2))
2158
- .join()
2159
- .unwrap();
2160
- assert!(
2161
- matches!(r, Err(StateError::Locked(_))),
2162
- "持锁时第二者应 Locked"
2163
- );
2164
- drop(held);
2165
- }
2166
-
2167
- // ---- load 迁移(state.py:45/73/55)----
2168
-
2169
- #[test]
2170
- fn normalize_agent_session_state_fills_fields_in_order() {
2171
- let mut state = json!({"agents": {"w1": {"session_id": "keep"}}});
2172
- normalize_agent_session_state(&mut state);
2173
- let expected = json!({"agents": {"w1": {
2174
- "session_id": "keep", "rollout_path": null, "captured_at": null,
2175
- "captured_via": null, "attribution_confidence": null, "spawn_cwd": null,
2176
- }}});
2177
- assert_eq!(
2178
- serde_json::to_string(&state).unwrap(),
2179
- serde_json::to_string(&expected).unwrap()
2180
- );
2181
- }
2182
-
2183
- #[test]
2184
- fn migrate_active_team_key_branches() {
2185
- // session_name 存在 → seed = team_state_key。
2186
- let mut m1 = json!({"session_name": "s", "team_dir": "/w/.team/tk", "teams": {}});
2187
- assert!(migrate_active_team_key(&mut m1));
2188
- assert_eq!(m1["active_team_key"], json!("tk"));
2189
- // 单 team → 取唯一 key。
2190
- let mut m2 = json!({"teams": {"only": {}}});
2191
- assert!(migrate_active_team_key(&mut m2));
2192
- assert_eq!(m2["active_team_key"], json!("only"));
2193
- // 多 team 无 session → None。
2194
- let mut m3 = json!({"teams": {"a": {}, "b": {}}});
2195
- assert!(migrate_active_team_key(&mut m3));
2196
- assert_eq!(m3["active_team_key"], json!(null));
2197
- // 已有 active_team_key → 不迁移。
2198
- let mut m4 = json!({"active_team_key": "x"});
2199
- assert!(!migrate_active_team_key(&mut m4));
2200
- }
2201
-
2202
- #[test]
2203
- fn load_runtime_state_missing_returns_default() {
2204
- let ws = temp_ws();
2205
- let s = load_runtime_state(&ws).unwrap();
2206
- assert_eq!(
2207
- s,
2208
- json!({"agents": {}, "tasks": [], "session_name": null, "active_team_key": null})
2209
- );
2210
- }
2211
-
2212
- #[test]
2213
- fn load_runtime_state_migrates_and_persists() {
2214
- // legacy state:有 session_name、无 active_team_key、agent 缺 session 字段、team_owner 缺 uuid。
2215
- let ws = temp_ws();
2216
- std::fs::create_dir_all(runtime_dir(&ws)).unwrap();
2217
- let legacy = json!({
2218
- "session_name": "sess",
2219
- "team_dir": "/w/.team/tk",
2220
- "agents": {"w1": {"agent_id": "w1"}},
2221
- "team_owner": {"pane_id": "%1", "machine_fingerprint": "fp"},
2222
- });
2223
- std::fs::write(
2224
- runtime_state_path(&ws),
2225
- serde_json::to_string(&legacy).unwrap(),
2226
- )
2227
- .unwrap();
2228
- let s = load_runtime_state(&ws).unwrap();
2229
- // active_team_key seed = team_state_key = "tk"。
2230
- assert_eq!(s["active_team_key"], json!("tk"));
2231
- // agent session 字段补 None。
2232
- assert_eq!(s["agents"]["w1"]["spawn_cwd"], json!(null));
2233
- // team_owner 补 leader_session_uuid。
2234
- assert_eq!(
2235
- s["team_owner"]["leader_session_uuid"]
2236
- .as_str()
2237
- .unwrap()
2238
- .len(),
2239
- 32
2240
- );
2241
- // 迁移已回写磁盘(再 load 不再变;active_team_key 已在)。
2242
- let on_disk = read_state(&ws);
2243
- assert_eq!(on_disk["active_team_key"], json!("tk"));
2244
- assert_eq!(
2245
- on_disk["team_owner"]["leader_session_uuid"],
2246
- s["team_owner"]["leader_session_uuid"]
2247
- );
2248
- }
2249
-
2250
- // 对抗 P1:legacy 文件**已有 active_team_key** 但缺 leader_session_uuid。load 内存补 uuid,
2251
- // 但 save 对 on-disk existing 同样 normalize+migrate 后发现等价 → **不重写**,磁盘字节恒等。
2252
- // (此前 save 比 raw existing 漏了这两步 → spurious 重写成 pretty 形,破坏 load+save 字节恒等。)
2253
- #[test]
2254
- fn load_does_not_rewrite_already_migrated_equivalent_legacy() {
2255
- let ws = temp_ws();
2256
- std::fs::create_dir_all(runtime_dir(&ws)).unwrap();
2257
- let legacy = r#"{"active_team_key": "preset", "session_name": "sess", "team_owner": {"pane_id": "%1"}}"#;
2258
- std::fs::write(runtime_state_path(&ws), legacy).unwrap();
2259
- let before = std::fs::read_to_string(runtime_state_path(&ws)).unwrap();
2260
- let loaded = load_runtime_state(&ws).unwrap();
2261
- // 内存态补了 uuid(证明确实需要迁移)。
2262
- assert_eq!(
2263
- loaded["team_owner"]["leader_session_uuid"]
2264
- .as_str()
2265
- .unwrap()
2266
- .len(),
2267
- 32
2268
- );
2269
- // 但磁盘未被重写(字节恒等)。
2270
- let after = std::fs::read_to_string(runtime_state_path(&ws)).unwrap();
2271
- assert_eq!(
2272
- after, before,
2273
- "已是迁移等价形的 legacy 文件不得 spurious 重写"
2274
- );
2275
- }
2276
-
2277
- // Phase C: persist no longer repairs stale topology by cloning missing rows.
2278
- // A stale non-lifecycle save that would remove a live row must surface a
2279
- // typed conflict and leave disk unchanged.
2280
- #[test]
2281
- fn stale_snapshot_cannot_overwrite_new_topology() {
2282
- let ws = temp_ws();
2283
- let latest = json!({
2284
- "session_name": "team-a",
2285
- "active_team_key": "team-a",
2286
- "agents": {
2287
- "w1": {
2288
- "status": "running",
2289
- "provider": "codex",
2290
- "agent_id": "w1",
2291
- "window": "w1-new",
2292
- "pane_id": "%2",
2293
- "pane_pid": 222,
2294
- "spawned_at": "2026-06-01T00:00:00Z",
2295
- "spawn_epoch": 2
2296
- }
2297
- },
2298
- });
2299
- write_state(&ws, &latest);
2300
- let incoming = json!({
2301
- "session_name": "team-a",
2302
- "active_team_key": "team-a",
2303
- "agents": {
2304
- "w1": {
2305
- "status": "running",
2306
- "provider": "codex",
2307
- "agent_id": "w1",
2308
- "window": "w1-old",
2309
- "pane_id": "%1",
2310
- "pane_pid": 111,
2311
- "spawned_at": "2026-05-31T00:00:00Z",
2312
- "spawn_epoch": 1
2313
- }
2314
- },
2315
- });
2316
- let err = save_runtime_state(&ws, &incoming).expect_err("stale topology must conflict");
2317
- assert!(matches!(err, StateError::SaveConflict(_)));
2318
- let message = err.to_string();
2319
- assert!(message.contains("agent_id=w1"), "message={message}");
2320
- assert!(message.contains("projection=agents"), "message={message}");
2321
- assert!(message.contains("pane_id"), "message={message}");
2322
- assert_eq!(
2323
- read_state(&ws),
2324
- latest,
2325
- "conflict must leave disk unchanged"
2326
- );
2327
- }
2328
-
2329
- #[test]
2330
- fn vacant_roster_preserve_cannot_resurrect_live_topology() {
2331
- let ws = temp_ws();
2332
- let latest = json!({
2333
- "session_name": "team-a",
2334
- "active_team_key": "team-a",
2335
- "agents": {
2336
- "w1": {"status": "running", "provider": "codex", "agent_id": "w1"},
2337
- "joiner": {
2338
- "status": "running",
2339
- "provider": "codex",
2340
- "agent_id": "joiner",
2341
- "window": "joiner",
2342
- "pane_id": "%9",
2343
- "spawned_at": "2026-06-01T00:00:00Z",
2344
- "spawn_epoch": 1
2345
- }
2346
- },
2347
- });
2348
- write_state(&ws, &latest);
2349
- let incoming = json!({
2350
- "session_name": "team-a",
2351
- "active_team_key": "team-a",
2352
- "agents": { "w1": {"status": "running", "provider": "codex", "agent_id": "w1"} },
2353
- });
2354
- let err = save_runtime_state(&ws, &incoming).expect_err("missing live row must conflict");
2355
- assert!(matches!(err, StateError::SaveConflict(_)));
2356
- assert!(err.to_string().contains("agent_id=joiner"));
2357
- }
2358
-
2359
- #[test]
2360
- fn vacant_non_live_roster_preserve_is_allow_list_only() {
2361
- let ws = temp_ws();
2362
- write_state(
2363
- &ws,
2364
- &json!({
2365
- "session_name": "team-a",
2366
- "active_team_key": "team-a",
2367
- "agents": {
2368
- "typed": {
2369
- "agent_id": "typed",
2370
- "provider": "codex",
2371
- "role": "Developer",
2372
- "model": "gpt-5.5",
2373
- "status": "running",
2374
- "spawn_cwd": "/tmp/old",
2375
- "session_id": "old-session",
2376
- "rollout_path": "/tmp/old.jsonl"
2377
- }
2378
- },
2379
- }),
2380
- );
2381
- let incoming = json!({
2382
- "session_name": "team-a",
2383
- "active_team_key": "team-a",
2384
- "agents": {},
2385
- });
2386
- save_runtime_state(&ws, &incoming).unwrap();
2387
- let saved = read_state(&ws);
2388
- let typed = saved.pointer("/agents/typed").expect("typed stub");
2389
- assert_eq!(typed.get("provider").and_then(Value::as_str), Some("codex"));
2390
- assert_eq!(typed.get("role").and_then(Value::as_str), Some("Developer"));
2391
- assert_eq!(typed.get("model").and_then(Value::as_str), Some("gpt-5.5"));
2392
- for forbidden in ["status", "spawn_cwd", "session_id", "rollout_path"] {
2393
- assert!(
2394
- typed.get(forbidden).is_none(),
2395
- "typed roster stub must not copy {forbidden}; typed={typed}"
2396
- );
2397
- }
2398
- }
2399
-
2400
- #[test]
2401
- fn reapplying_after_conflict_retries_without_losing_delta() {
2402
- let ws = temp_ws();
2403
- write_state(
2404
- &ws,
2405
- &json!({
2406
- "session_name": "team-a",
2407
- "active_team_key": "team-a",
2408
- "agents": {
2409
- "w1": {
2410
- "agent_id": "w1",
2411
- "provider": "codex",
2412
- "window": "w1-new",
2413
- "pane_id": "%2",
2414
- "pane_pid": 222,
2415
- "spawn_epoch": 2
2416
- }
2417
- },
2418
- "delivery": {}
2419
- }),
2420
- );
2421
- let stale_with_delta = json!({
2422
- "session_name": "team-a",
2423
- "active_team_key": "team-a",
2424
- "agents": {
2425
- "w1": {
2426
- "agent_id": "w1",
2427
- "provider": "codex",
2428
- "window": "w1-old",
2429
- "pane_id": "%1",
2430
- "pane_pid": 111,
2431
- "spawn_epoch": 1
2432
- }
2433
- },
2434
- "delivery": {"msg-1": {"status": "delivered"}}
2435
- });
2436
- let mut reapplied = false;
2437
- save_runtime_state_reapplying_after_conflict(&ws, &stale_with_delta, |latest| {
2438
- reapplied = true;
2439
- latest.as_object_mut().unwrap().insert(
2440
- "delivery".to_string(),
2441
- json!({"msg-1": {"status": "delivered"}}),
2442
- );
2443
- })
2444
- .unwrap();
2445
-
2446
- let saved = read_state(&ws);
2447
- assert!(reapplied, "SaveConflict path must reload and reapply once");
2448
- assert_eq!(saved.pointer("/agents/w1/pane_id"), Some(&json!("%2")));
2449
- assert_eq!(saved.pointer("/agents/w1/window"), Some(&json!("w1-new")));
2450
- assert_eq!(
2451
- saved.pointer("/delivery/msg-1/status"),
2452
- Some(&json!("delivered")),
2453
- "non-topology delta must survive retry; saved={saved}"
2454
- );
2455
- }
2456
-
2457
- #[test]
2458
- fn deleted_ids_stay_dead_even_when_latest_has_live_topology() {
2459
- let ws = temp_ws();
2460
- write_state(
2461
- &ws,
2462
- &json!({
2463
- "session_name": "team-a",
2464
- "active_team_key": "team-a",
2465
- "agents": {
2466
- "gone": {
2467
- "status": "running",
2468
- "provider": "codex",
2469
- "agent_id": "gone",
2470
- "window": "gone",
2471
- "pane_id": "%7",
2472
- "spawn_epoch": 1
2473
- },
2474
- },
2475
- }),
2476
- );
2477
- let incoming = json!({
2478
- "session_name": "team-a",
2479
- "active_team_key": "team-a",
2480
- "agents": {},
2481
- });
2482
- save_runtime_state_with_deleted_agents(&ws, &incoming, &["gone"]).unwrap();
2483
- let saved = read_state(&ws);
2484
- assert!(
2485
- saved.pointer("/agents/gone").is_none(),
2486
- "deleted_agent_ids 豁免:被 remove 的 `gone` 不得被 preserve 复活;saved={saved}"
2487
- );
2488
- }
2489
-
2490
- #[test]
2491
- fn stopped_intent_and_resume_metadata_survive_stale_writers_until_targeted_start() {
2492
- let ws = temp_ws();
2493
- let held = json!({"agent_id":"held","provider":"codex","status":"stopped","explicit_stop":true,
2494
- "session_id":"same-session","rollout_path":"/controlled/rollout","captured_at":"2026-10-12T00:00:00Z",
2495
- "captured_via":"native","generation":7});
2496
- let mut latest = json!({"session_name":"team-a","active_team_key":"team-a","agents":{"held":held},
2497
- "teams":{"team-a":{"session_name":"team-a","agents":{"held":held}}}});
2498
- normalize_agent_session_state(&mut latest);
2499
- for omit in [false, true] {
2500
- write_state(&ws, &latest);
2501
- let before = read_state(&ws);
2502
- let held_root = before.pointer("/agents/held").unwrap().clone();
2503
- let held_team = before.pointer("/teams/team-a/agents/held").unwrap().clone();
2504
- let rows = if omit { json!({}) } else { json!({"held":{"agent_id":"held","provider":"codex","status":"running","explicit_stop":false,"session_id":"stale"}}) };
2505
- let stale = json!({"session_name":"team-a","active_team_key":"team-a","agents":rows,
2506
- "teams":{"team-a":{"session_name":"team-a","agents":rows}},"delivery":{"message":"observed"}});
2507
- save_runtime_state(&ws, &stale).unwrap();
2508
- let saved = read_state(&ws);
2509
- assert_eq!(saved.pointer("/agents/held"), Some(&held_root));
2510
- assert_eq!(saved.pointer("/teams/team-a/agents/held"), Some(&held_team));
2511
- assert_eq!(saved.pointer("/delivery/message"), Some(&json!("observed")));
2512
- }
2513
- let mut started = latest;
2514
- for pointer in ["/agents/held", "/teams/team-a/agents/held"] {
2515
- let row = started.pointer_mut(pointer).unwrap();
2516
- row["status"] = json!("running");
2517
- row["explicit_stop"] = json!(false);
2518
- }
2519
- save_runtime_state_with_lifecycle_topology_authority(&ws, &started, "team-a", &["held"]).unwrap();
2520
- let saved = read_state(&ws);
2521
- assert_eq!(saved.pointer("/agents/held/explicit_stop"), Some(&json!(false)));
2522
- assert_eq!(saved.pointer("/agents/held/session_id"), Some(&json!("same-session")));
2523
- assert_eq!(saved.pointer("/teams/team-a/agents/held/explicit_stop"), Some(&json!(false)));
2524
- }
2525
-
2526
- #[test]
2527
- fn lifecycle_topology_authority_only_applies_to_target_agent() {
2528
- let ws = temp_ws();
2529
- let latest = json!({
2530
- "session_name": "team-a",
2531
- "active_team_key": "team-a",
2532
- "agents": {
2533
- "target": {"agent_id": "target", "provider": "codex", "window": "target", "pane_id": "%1", "spawn_epoch": 1},
2534
- "other": {"agent_id": "other", "provider": "codex", "window": "other", "pane_id": "%2", "spawn_epoch": 1}
2535
- },
2536
- });
2537
- write_state(&ws, &latest);
2538
- let incoming = json!({
2539
- "session_name": "team-a",
2540
- "active_team_key": "team-a",
2541
- "agents": {
2542
- "target": {"agent_id": "target", "provider": "codex", "status": "stopped"},
2543
- "other": {"agent_id": "other", "provider": "codex", "window": "old-other", "pane_id": "%old", "spawn_epoch": 1}
2544
- },
2545
- });
2546
- let err = save_runtime_state_with_lifecycle_topology_authority(
2547
- &ws,
2548
- &incoming,
2549
- "team-a",
2550
- &["target"],
2551
- )
2552
- .expect_err("authorized target must not hide other agent conflict");
2553
- assert!(matches!(err, StateError::SaveConflict(_)));
2554
- assert!(err.to_string().contains("agent_id=other"));
2555
- }
2556
-
2557
- #[test]
2558
- fn lifecycle_topology_authority_can_clear_target_topology() {
2559
- let ws = temp_ws();
2560
- write_state(
2561
- &ws,
2562
- &json!({
2563
- "session_name": "team-a",
2564
- "active_team_key": "team-a",
2565
- "agents": {
2566
- "target": {"agent_id": "target", "provider": "codex", "window": "target", "pane_id": "%1", "spawn_epoch": 1}
2567
- },
2568
- }),
2569
- );
2570
- let incoming = json!({
2571
- "session_name": "team-a",
2572
- "active_team_key": "team-a",
2573
- "agents": {
2574
- "target": {"agent_id": "target", "provider": "codex", "status": "stopped"}
2575
- },
2576
- });
2577
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["target"])
2578
- .unwrap();
2579
- let target = read_state(&ws).pointer("/agents/target").cloned().unwrap();
2580
- assert!(
2581
- target.get("pane_id").is_none(),
2582
- "target topology was intentionally cleared: {target}"
2583
- );
2584
- assert!(
2585
- target.get("window").is_none(),
2586
- "target window was intentionally cleared: {target}"
2587
- );
2588
- }
2589
-
2590
- #[test]
2591
- fn lifecycle_authority_preserves_stale_omitted_finalized_peer() {
2592
- let latest_state = || {
2593
- json!({
2594
- "session_name": "team-a",
2595
- "active_team_key": "team-a",
2596
- "agents": {
2597
- "f1": {
2598
- "agent_id": "f1",
2599
- "provider": "codex",
2600
- "role": "Developer",
2601
- "model": "gpt-5.5",
2602
- "status": "running",
2603
- "session_id": "session-f1",
2604
- "rollout_path": "/tmp/f1.jsonl",
2605
- "captured_at": "2026-08-28T00:00:00Z",
2606
- "captured_via": "contract-fixture",
2607
- "attribution_confidence": "high",
2608
- "capture_state": "complete",
2609
- "spawn_cwd": "/tmp/f1",
2610
- "owner_team_id": "team-a",
2611
- "pane_id": "%1",
2612
- "pane_pid": 101,
2613
- "window": "f1",
2614
- "spawned_at": "2026-08-28T00:00:01Z",
2615
- "spawn_epoch": 1
2616
- }
2617
- }
2618
- })
2619
- };
2620
- let f2 = json!({
2621
- "agent_id": "f2",
2622
- "provider": "codex",
2623
- "role": "Developer",
2624
- "model": "gpt-5.5",
2625
- "status": "running",
2626
- "session_id": "session-f2",
2627
- "rollout_path": "/tmp/f2.jsonl",
2628
- "captured_at": "2026-08-28T00:00:02Z",
2629
- "captured_via": "contract-fixture",
2630
- "attribution_confidence": "high",
2631
- "capture_state": "complete",
2632
- "spawn_cwd": "/tmp/f2",
2633
- "owner_team_id": "team-a",
2634
- "pane_id": "%2",
2635
- "pane_pid": 102,
2636
- "window": "f2",
2637
- "spawned_at": "2026-08-28T00:00:03Z",
2638
- "spawn_epoch": 1
2639
- });
2640
-
2641
- // A stale f2 finalization omitted the peer that finalized after its
2642
- // snapshot. Lifecycle authority preserves f1 byte-for-byte and writes f2.
2643
- let ws = temp_ws();
2644
- let latest = latest_state();
2645
- write_state(&ws, &latest);
2646
- let incoming = json!({
2647
- "session_name": "team-a",
2648
- "active_team_key": "team-a",
2649
- "agents": {"f2": f2.clone()}
2650
- });
2651
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["f2"])
2652
- .unwrap();
2653
- let saved = read_state(&ws);
2654
- assert_eq!(saved["agents"]["f1"], latest["agents"]["f1"]);
2655
- assert_eq!(saved["agents"]["f2"], f2);
2656
-
2657
- // Captured R4 f1/f2 shape: the writer includes a stale, already
2658
- // running f1 snapshot while finalizing f2. Lifecycle authority must
2659
- // preserve f1 byte-for-byte rather than report SaveConflict for its
2660
- // five topology fields.
2661
- let ws = temp_ws();
2662
- let latest = latest_state();
2663
- write_state(&ws, &latest);
2664
- let incoming = json!({
2665
- "session_name": "team-a",
2666
- "active_team_key": "team-a",
2667
- "agents": {
2668
- "f1": {
2669
- "agent_id": "f1",
2670
- "provider": "codex",
2671
- "status": "running",
2672
- "session_id": "session-f1",
2673
- "rollout_path": "/tmp/f1.jsonl",
2674
- "captured_at": "2026-08-28T00:00:00Z",
2675
- "captured_via": "contract-fixture",
2676
- "attribution_confidence": "high",
2677
- "capture_state": "complete",
2678
- "spawn_cwd": "/tmp/f1",
2679
- "owner_team_id": "team-a",
2680
- "pane_id": "%stale",
2681
- "pane_pid": 999,
2682
- "window": "f1-stale",
2683
- "spawned_at": "2026-08-27T23:59:59Z",
2684
- "spawn_epoch": 0
2685
- },
2686
- "f2": f2.clone()
2687
- }
2688
- });
2689
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["f2"])
2690
- .unwrap();
2691
- let saved = read_state(&ws);
2692
- assert_eq!(saved["agents"]["f1"], latest["agents"]["f1"]);
2693
- assert_eq!(saved["agents"]["f2"], f2);
2694
-
2695
- // The same omission without lifecycle authority remains a conflict.
2696
- let ws = temp_ws();
2697
- let latest = latest_state();
2698
- write_state(&ws, &latest);
2699
- let incoming = json!({
2700
- "session_name": "team-a",
2701
- "active_team_key": "team-a",
2702
- "agents": {"f2": f2.clone()}
2703
- });
2704
- assert!(matches!(
2705
- save_runtime_state(&ws, &incoming),
2706
- Err(StateError::SaveConflict(_))
2707
- ));
2708
- assert_eq!(read_state(&ws), latest);
2709
-
2710
- // Explicit deletion remains authoritative and must not be resurrected.
2711
- let ws = temp_ws();
2712
- let latest = latest_state();
2713
- write_state(&ws, &latest);
2714
- let incoming = json!({
2715
- "session_name": "team-a",
2716
- "active_team_key": "team-a",
2717
- "agents": {"f2": f2}
2718
- });
2719
- save_runtime_state_with_deleted_agents(&ws, &incoming, &["f1"]).unwrap();
2720
- let saved = read_state(&ws);
2721
- assert!(saved["agents"].get("f1").is_none());
2722
- assert!(saved["agents"].get("f2").is_some());
2723
- }
2724
-
2725
- #[test]
2726
- fn lifecycle_authority_preserves_peer_that_started_after_roster_stub_snapshot() {
2727
- let ws = temp_ws();
2728
- write_state(
2729
- &ws,
2730
- &json!({
2731
- "session_name": "team-a",
2732
- "active_team_key": "team-a",
2733
- "agents": {"f1": {"provider": "claude", "status": "starting"}}
2734
- }),
2735
- );
2736
- // f2 loaded before f1's reservation. Persist carries the still-unspawned
2737
- // f1 forward as an actual roster stub, not a fabricated test shape.
2738
- let incoming = json!({
2739
- "session_name": "team-a",
2740
- "active_team_key": "team-a",
2741
- "agents": {"f2": {"provider": "claude", "status": "starting"}}
2742
- });
2743
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["f2"])
2744
- .unwrap();
2745
- let mut stale = read_state(&ws);
2746
- assert!(stale["agents"]["f1"].get("status").is_none());
2747
- assert!(live_topology_fields(&stale["agents"]["f1"]).is_empty());
2748
-
2749
- // f1 starts after f2 takes its snapshot; capture is not complete yet.
2750
- let mut started = stale.clone();
2751
- started["agents"]["f1"] = json!({
2752
- "provider": "claude",
2753
- "status": "running",
2754
- "pane_id": "%1",
2755
- "pane_pid": 101,
2756
- "window": "f1",
2757
- "spawned_at": "2026-10-11T05:55:20Z",
2758
- "spawn_epoch": 1,
2759
- "_pending_session_id": "session-f1"
2760
- });
2761
- normalize_agent_session_state(&mut started);
2762
- save_runtime_state_with_lifecycle_topology_authority(&ws, &started, "team-a", &["f1"])
2763
- .unwrap();
2764
- let latest = read_state(&ws);
2765
- stale["agents"]["f2"] = json!({
2766
- "provider": "claude",
2767
- "status": "running",
2768
- "pane_id": "%2",
2769
- "pane_pid": 102,
2770
- "window": "f2",
2771
- "spawned_at": "2026-10-11T05:55:21Z",
2772
- "spawn_epoch": 1,
2773
- "_pending_session_id": "session-f2"
2774
- });
2775
-
2776
- // Ordinary writers still cannot overwrite the live peer from a stub.
2777
- assert!(matches!(
2778
- save_runtime_state(&ws, &stale),
2779
- Err(StateError::SaveConflict(_))
2780
- ));
2781
- assert_eq!(read_state(&ws), latest);
2782
- save_runtime_state_with_lifecycle_topology_authority(&ws, &stale, "team-a", &["f2"])
2783
- .unwrap();
2784
- let saved = read_state(&ws);
2785
- assert_eq!(saved["agents"]["f1"], latest["agents"]["f1"]);
2786
- assert_eq!(saved["agents"]["f2"], stale["agents"]["f2"]);
2787
- }
2788
-
2789
- #[test]
2790
- fn lifecycle_authority_preserves_complete_latest_row_for_starting_peer() {
2791
- let ws = temp_ws();
2792
- let latest = json!({
2793
- "session_name": "team-a",
2794
- "active_team_key": "team-a",
2795
- "agents": {
2796
- "f1": {
2797
- "agent_id": "f1",
2798
- "provider": "codex",
2799
- "status": "running",
2800
- "session_id": "session-f1",
2801
- "rollout_path": "/tmp/f1.jsonl",
2802
- "captured_at": "2026-08-28T00:00:00Z",
2803
- "captured_via": "contract-fixture",
2804
- "attribution_confidence": "high",
2805
- "capture_state": "complete",
2806
- "spawn_cwd": "/tmp/f1",
2807
- "owner_team_id": "team-a",
2808
- "pane_id": "%1",
2809
- "pane_pid": 101,
2810
- "window": "f1",
2811
- "spawned_at": "2026-08-28T00:00:01Z",
2812
- "spawn_epoch": 1
2813
- }
2814
- }
2815
- });
2816
- write_state(&ws, &latest);
2817
- let incoming = json!({
2818
- "session_name": "team-a",
2819
- "active_team_key": "team-a",
2820
- "agents": {
2821
- "f1": {
2822
- "agent_id": "f1",
2823
- "provider": "codex",
2824
- "status": "starting",
2825
- "stale_metadata": "must-not-survive"
2826
- },
2827
- "f2": {"agent_id": "f2", "status": "starting"}
2828
- }
2829
- });
2830
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["f2"])
2831
- .unwrap();
2832
- assert_eq!(read_state(&ws)["agents"]["f1"], latest["agents"]["f1"]);
2833
- }
2834
-
2835
- #[test]
2836
- fn lifecycle_authority_still_conflicts_on_different_completed_topology() {
2837
- let ws = temp_ws();
2838
- let latest = json!({
2839
- "session_name": "team-a",
2840
- "active_team_key": "team-a",
2841
- "agents": {
2842
- "f1": {
2843
- "agent_id": "f1",
2844
- "status": "running",
2845
- "pane_id": "%1",
2846
- "pane_pid": 101,
2847
- "window": "f1",
2848
- "spawned_at": "2026-08-28T00:00:01Z",
2849
- "spawn_epoch": 1
2850
- }
2851
- }
2852
- });
2853
- write_state(&ws, &latest);
2854
- let incoming = json!({
2855
- "session_name": "team-a",
2856
- "active_team_key": "team-a",
2857
- "agents": {
2858
- "f1": {
2859
- "agent_id": "f1",
2860
- "status": "running",
2861
- "pane_id": "%9",
2862
- "pane_pid": 109,
2863
- "window": "f1-new",
2864
- "spawned_at": "2026-08-28T00:00:09Z",
2865
- "spawn_epoch": 9
2866
- },
2867
- "f2": {"agent_id": "f2", "status": "running"}
2868
- }
2869
- });
2870
- let err =
2871
- save_runtime_state_with_lifecycle_topology_authority(&ws, &incoming, "team-a", &["f2"])
2872
- .expect_err("two completed topologies for f1 must conflict");
2873
- assert!(matches!(err, StateError::SaveConflict(_)));
2874
- assert!(err.to_string().contains("agent_id=f1"));
2875
- }
2876
-
2877
- #[test]
2878
- fn owner_epoch_preserve_is_explicit_and_bounded_to_team_entry() {
2879
- let ws = temp_ws();
2880
- write_state(
2881
- &ws,
2882
- &json!({
2883
- "session_name": "team-a",
2884
- "active_team_key": "team-a",
2885
- "teams": {
2886
- "team-a": {
2887
- "agents": {},
2888
- "team_owner": {"pane_id": "%7", "owner_epoch": 7},
2889
- "leader_receiver": {"pane_id": "%7", "owner_epoch": 7},
2890
- "owner_epoch": 7
2891
- }
2892
- }
2893
- }),
2894
- );
2895
- let incoming = json!({
2896
- "session_name": "team-a",
2897
- "active_team_key": "team-a",
2898
- "teams": {
2899
- "team-a": {
2900
- "agents": {},
2901
- "team_owner": {"pane_id": "%3", "owner_epoch": 3},
2902
- "leader_receiver": {"pane_id": "%3", "owner_epoch": 3},
2903
- "owner_epoch": 3
2904
- }
2905
- }
2906
- });
2907
- save_runtime_state(&ws, &incoming).unwrap();
2908
- let saved = read_state(&ws);
2909
- assert_eq!(
2910
- saved
2911
- .pointer("/teams/team-a/owner_epoch")
2912
- .and_then(Value::as_u64),
2913
- Some(7)
2914
- );
2915
- assert_eq!(
2916
- saved
2917
- .pointer("/teams/team-a/team_owner/pane_id")
2918
- .and_then(Value::as_str),
2919
- Some("%7")
2920
- );
2921
- assert!(
2922
- saved.get("team_owner").is_none(),
2923
- "top-level owner must not be recreated: {saved}"
2924
- );
2925
- assert!(
2926
- saved.get("owner_epoch").is_none(),
2927
- "top-level owner_epoch must not be recreated: {saved}"
2928
- );
2929
- }
2930
-
2931
- // 0.5.x Windows portability Batch 7 F6 (leader msg_700a016675d0):
2932
- // `state.transport.shim` must survive a downstream save whose
2933
- // `incoming` was constructed from a stale in-memory Value.
2934
- #[test]
2935
- fn transport_shim_block_is_preserved_across_merge() {
2936
- let ws = temp_ws();
2937
- // Disk state has the shim block (coordinator wrote it after
2938
- // Hello succeeded).
2939
- write_state(
2940
- &ws,
2941
- &json!({
2942
- "session_name": "team-a",
2943
- "active_team_key": "team-a",
2944
- "agents": {},
2945
- "transport": {
2946
- "kind": "conpty",
2947
- "shim": { "pid": 4242, "pipe_name": r"\\.\pipe\team-agent-conpty-abc-team-a", "pipe_ready": true }
2948
- }
2949
- }),
2950
- );
2951
- // Incoming save (leader-persist or worker-persist) doesn't
2952
- // know about the shim block.
2953
- let incoming = json!({
2954
- "session_name": "team-a",
2955
- "active_team_key": "team-a",
2956
- "agents": {},
2957
- "transport": {
2958
- "kind": "conpty"
2959
- }
2960
- });
2961
- save_runtime_state(&ws, &incoming).unwrap();
2962
- let saved = read_state(&ws);
2963
- // Shim block must survive the merge.
2964
- assert_eq!(
2965
- saved.pointer("/transport/shim/pid").and_then(Value::as_u64),
2966
- Some(4242),
2967
- "shim.pid must be preserved: {saved}"
2968
- );
2969
- assert_eq!(
2970
- saved
2971
- .pointer("/transport/shim/pipe_name")
2972
- .and_then(Value::as_str),
2973
- Some(r"\\.\pipe\team-agent-conpty-abc-team-a"),
2974
- );
2975
- assert_eq!(
2976
- saved
2977
- .pointer("/transport/shim/pipe_ready")
2978
- .and_then(Value::as_bool),
2979
- Some(true),
2980
- );
2981
- // And the incoming's `transport.kind` still wins.
2982
- assert_eq!(
2983
- saved.pointer("/transport/kind").and_then(Value::as_str),
2984
- Some("conpty"),
2985
- );
2986
- }
2987
-
2988
- #[test]
2989
- fn transport_shim_incoming_authoritative_overrides_latest() {
2990
- // If the caller has a NEWER shim block (e.g. rotation), it
2991
- // wins — preserve_transport_shim only fills in the gap.
2992
- let ws = temp_ws();
2993
- write_state(
2994
- &ws,
2995
- &json!({
2996
- "session_name": "team-a",
2997
- "active_team_key": "team-a",
2998
- "agents": {},
2999
- "transport": {
3000
- "kind": "conpty",
3001
- "shim": { "pid": 1000, "pipe_name": "old", "pipe_ready": true }
3002
- }
3003
- }),
3004
- );
3005
- let incoming = json!({
3006
- "session_name": "team-a",
3007
- "active_team_key": "team-a",
3008
- "agents": {},
3009
- "transport": {
3010
- "kind": "conpty",
3011
- "shim": { "pid": 9999, "pipe_name": "new", "pipe_ready": true }
3012
- }
3013
- });
3014
- save_runtime_state(&ws, &incoming).unwrap();
3015
- let saved = read_state(&ws);
3016
- assert_eq!(
3017
- saved.pointer("/transport/shim/pid").and_then(Value::as_u64),
3018
- Some(9999),
3019
- "incoming shim block must win when both sides have one"
3020
- );
3021
- assert_eq!(
3022
- saved
3023
- .pointer("/transport/shim/pipe_name")
3024
- .and_then(Value::as_str),
3025
- Some("new"),
3026
- );
3027
- }
3028
-
3029
- #[test]
3030
- fn transport_shim_no_leak_when_latest_lacks_block() {
3031
- // If disk has no shim block, save must not synthesize one.
3032
- let ws = temp_ws();
3033
- write_state(
3034
- &ws,
3035
- &json!({
3036
- "session_name": "team-a",
3037
- "active_team_key": "team-a",
3038
- "agents": {},
3039
- "transport": {"kind": "tmux"}
3040
- }),
3041
- );
3042
- let incoming = json!({
3043
- "session_name": "team-a",
3044
- "active_team_key": "team-a",
3045
- "agents": {},
3046
- "transport": {"kind": "tmux"}
3047
- });
3048
- save_runtime_state(&ws, &incoming).unwrap();
3049
- let saved = read_state(&ws);
3050
- assert!(
3051
- saved.pointer("/transport/shim").is_none(),
3052
- "shim must not appear when neither side had one: {saved}"
3053
- );
3054
- }
3055
-
3056
- #[test]
3057
- fn projection_paths_do_not_cross_backfill_topology() {
3058
- let ws = temp_ws();
3059
- write_state(
3060
- &ws,
3061
- &json!({
3062
- "session_name": "team-a",
3063
- "active_team_key": "team-a",
3064
- "agents": {
3065
- "top-only": {"agent_id": "top-only", "provider": "codex", "window": "top-only", "pane_id": "%1", "spawn_epoch": 1}
3066
- },
3067
- "teams": {
3068
- "team-a": {
3069
- "agents": {
3070
- "team-only": {"agent_id": "team-only", "provider": "codex", "window": "team-only", "pane_id": "%2", "spawn_epoch": 1}
3071
- }
3072
- }
3073
- }
3074
- }),
3075
- );
3076
- let incoming = json!({
3077
- "session_name": "team-a",
3078
- "active_team_key": "team-a",
3079
- "agents": {
3080
- "top-only": {"agent_id": "top-only", "provider": "codex", "window": "top-only", "pane_id": "%1", "spawn_epoch": 1}
3081
- },
3082
- "teams": {
3083
- "team-a": {
3084
- "agents": {
3085
- "team-only": {"agent_id": "team-only", "provider": "codex", "window": "team-only", "pane_id": "%2", "spawn_epoch": 1}
3086
- }
3087
- }
3088
- }
3089
- });
3090
- save_runtime_state(&ws, &incoming).unwrap();
3091
- let saved = read_state(&ws);
3092
- assert!(
3093
- saved.pointer("/agents/team-only").is_none(),
3094
- "teams.<key> topology must not cross-fill top-level agents; saved={saved}"
3095
- );
3096
- assert!(
3097
- saved.pointer("/teams/team-a/agents/top-only").is_none(),
3098
- "top-level topology must not cross-fill teams.<key>.agents; saved={saved}"
3099
- );
3100
- }
3101
-
3102
- /// RM-039-STAT-001 second-round regression (architect verdict
3103
- /// 2026-06-22): `migrate_team_key_to_match_active_team` must
3104
- /// promote `team_key = active_team_key` when root `team_key` is
3105
- /// missing AND `teams[active_team_key]` exists, and mirror it into
3106
- /// the team-scoped slot. Coordinator tick then writes to the same
3107
- /// teams entry that status selector reads.
3108
- #[test]
3109
- fn migrate_team_key_to_match_active_team_promotes_when_missing() {
3110
- let mut state = json!({
3111
- "active_team_key": "rm039-status-working-891",
3112
- "session_name": "team-rm039-status-working",
3113
- "team_dir": "./.team/current",
3114
- "teams": {
3115
- "rm039-status-working-891": {
3116
- "active_team_key": "rm039-status-working-891",
3117
- "session_name": "team-rm039-status-working",
3118
- "agents": {}
3119
- }
3120
- }
3121
- });
3122
- let changed = migrate_team_key_to_match_active_team(&mut state);
3123
- assert!(changed, "state must be mutated when team_key is missing");
3124
- assert_eq!(
3125
- state.get("team_key").and_then(Value::as_str),
3126
- Some("rm039-status-working-891"),
3127
- "root team_key must equal active_team_key after migration"
3128
- );
3129
- // mirrored into the team-scoped entry
3130
- assert_eq!(
3131
- state
3132
- .pointer("/teams/rm039-status-working-891/team_key")
3133
- .and_then(Value::as_str),
3134
- Some("rm039-status-working-891"),
3135
- "teams[active].team_key must be set as part of the migration"
3136
- );
3137
- // team_state_key cascade now agrees with active_team_key.
3138
- assert_eq!(
3139
- crate::state::projection::team_state_key(&state),
3140
- "rm039-status-working-891",
3141
- "team_state_key first branch must hit `state.team_key` and \
3142
- return the canonical key"
3143
- );
3144
- }
3145
-
3146
- /// Conflict cases stay observable: if `team_key` already exists,
3147
- /// the migrator does NOT silently overwrite it, even when it
3148
- /// disagrees with `active_team_key`. The user/team can resolve.
3149
- #[test]
3150
- fn migrate_team_key_to_match_active_team_is_noop_when_team_key_present() {
3151
- let mut state = json!({
3152
- "team_key": "explicit-key",
3153
- "active_team_key": "different-active",
3154
- "teams": {
3155
- "different-active": {"agents": {}},
3156
- "explicit-key": {"agents": {}}
3157
- }
3158
- });
3159
- let changed = migrate_team_key_to_match_active_team(&mut state);
3160
- assert!(!changed, "existing team_key must NOT be overwritten");
3161
- assert_eq!(
3162
- state.get("team_key").and_then(Value::as_str),
3163
- Some("explicit-key")
3164
- );
3165
- }
3166
-
3167
- /// Narrow: only promote when teams[active_team_key] actually exists.
3168
- /// Otherwise we'd be claiming a key for a non-existent team slot.
3169
- #[test]
3170
- fn migrate_team_key_to_match_active_team_is_noop_when_active_team_entry_missing() {
3171
- let mut state = json!({
3172
- "active_team_key": "missing-team",
3173
- "teams": {
3174
- "other": {"agents": {}}
3175
- }
3176
- });
3177
- let changed = migrate_team_key_to_match_active_team(&mut state);
3178
- assert!(
3179
- !changed,
3180
- "no migration when teams[active_team_key] does not exist"
3181
- );
3182
- assert!(state.get("team_key").is_none());
3183
- }
3184
-
3185
- /// Null / empty active_team_key is not actionable.
3186
- #[test]
3187
- fn migrate_team_key_to_match_active_team_is_noop_when_active_team_key_absent() {
3188
- for active in [json!(null), json!(""), json!(serde_json::Value::Null)] {
3189
- let mut state = json!({
3190
- "active_team_key": active,
3191
- "teams": {}
3192
- });
3193
- assert!(
3194
- !migrate_team_key_to_match_active_team(&mut state),
3195
- "no migration when active_team_key is null/empty"
3196
- );
3197
- }
3198
- }
3199
-
3200
- /// RM-039-STAT-001 second-round end-to-end at the persistence layer
3201
- /// (architect verdict 2026-06-22): loading a state file in the dirty
3202
- /// shape (active_team_key disagrees with team_dir basename, root
3203
- /// team_key absent) must persist the canonical `team_key` so the
3204
- /// next `save_team_scoped_state` writes the team-scoped slot at
3205
- /// `teams[active_team_key]`, not at `teams[team_dir_basename]`.
3206
- /// This is the bridging contract that decides whether coordinator
3207
- /// tick's activity write lands where the status selector later reads.
3208
- #[test]
3209
- fn load_runtime_state_pins_team_key_from_active_team_key_on_dirty_shape() {
3210
- let ws = temp_ws();
3211
- let active = "rm039-status-working-891";
3212
- let raw = json!({
3213
- "session_name": "team-rm039-status-working",
3214
- "team_dir": "./.team/current",
3215
- "active_team_key": active,
3216
- // intentionally NO root "team_key" — the dirty shape.
3217
- "agents": {
3218
- "coder": {"status": "running", "first_send_at": "2026-01-01T00:00:00Z"}
3219
- },
3220
- "teams": {
3221
- "current": {
3222
- "active_team_key": active,
3223
- "agents": {"coder": {"status": "running"}}
3224
- },
3225
- active: {
3226
- "active_team_key": active,
3227
- "agents": {"coder": {"status": "running"}}
3228
- }
3229
- }
3230
- });
3231
- let runtime_dir = ws.join(".team").join("runtime");
3232
- std::fs::create_dir_all(&runtime_dir).unwrap();
3233
- std::fs::write(
3234
- runtime_dir.join("state.json"),
3235
- serde_json::to_vec_pretty(&raw).unwrap(),
3236
- )
3237
- .unwrap();
3238
- // temp_ws() returns a unique path per call, so the cache
3239
- // (keyed by path) does not collide with previous tests.
3240
-
3241
- let loaded = load_runtime_state(&ws).expect("loaded state");
3242
- assert_eq!(
3243
- loaded.get("team_key").and_then(Value::as_str),
3244
- Some(active),
3245
- "load_runtime_state must promote team_key=active_team_key on the dirty shape"
3246
- );
3247
- // team_state_key now cascades to state.team_key, returning the
3248
- // canonical key instead of the team_dir basename.
3249
- assert_eq!(
3250
- crate::state::projection::team_state_key(&loaded),
3251
- active,
3252
- "team_state_key must return the canonical key after migration"
3253
- );
3254
-
3255
- // Re-read from disk (not cache) to confirm the migration was persisted.
3256
- let on_disk: Value =
3257
- serde_json::from_str(&std::fs::read_to_string(runtime_dir.join("state.json")).unwrap())
3258
- .unwrap();
3259
- assert_eq!(
3260
- on_disk.get("team_key").and_then(Value::as_str),
3261
- Some(active),
3262
- "migration must be persisted to disk so subsequent processes see it"
3263
- );
3264
- }
3265
-
3266
- /// 0.4.6 tuple-atomic contract test #1 (audit §Required Tests, line 264):
3267
- /// latest has `session_id` only (PARTIAL TUPLE), incoming has null
3268
- /// tuple → no backfill. This is bug-045's core failure mode: persist
3269
- /// must not resurrect a scalar session_id when the latest row's tuple
3270
- /// is incomplete.
3271
- #[test]
3272
- fn backfill_capture_skips_when_latest_tuple_is_partial() {
3273
- let mut incoming = json!({
3274
- "session_id": Value::Null,
3275
- "rollout_path": Value::Null,
3276
- "captured_at": Value::Null,
3277
- "captured_via": Value::Null,
3278
- });
3279
- let latest = json!({
3280
- "session_id": "partial-only-uuid",
3281
- "rollout_path": Value::Null,
3282
- "captured_at": Value::Null,
3283
- "captured_via": Value::Null,
3284
- });
3285
- backfill_capture_fields(&mut incoming, &latest);
3286
- assert_eq!(
3287
- incoming.get("session_id"),
3288
- Some(&Value::Null),
3289
- "0.4.6: partial latest tuple must NOT backfill session_id; got {incoming}"
3290
- );
3291
- }
3292
-
3293
- /// 0.4.6 tuple-atomic contract test #2 (audit, line 265):
3294
- /// latest has complete tuple, incoming has null tuple → all 4 fields
3295
- /// backfilled together. This is the concurrent-capture protection
3296
- /// (A0/R2) that must still work after the tuple-atomic rewrite.
3297
- #[test]
3298
- fn backfill_capture_atomically_copies_complete_tuple() {
3299
- let mut incoming = json!({
3300
- "session_id": Value::Null,
3301
- "rollout_path": Value::Null,
3302
- "captured_at": Value::Null,
3303
- "captured_via": Value::Null,
3304
- });
3305
- let latest = json!({
3306
- "session_id": "real-uuid",
3307
- "rollout_path": "/tmp/real.jsonl",
3308
- "captured_at": "2026-06-25T10:00:00+00:00",
3309
- "captured_via": "session.captured",
3310
- "attribution_confidence": "high",
3311
- });
3312
- backfill_capture_fields(&mut incoming, &latest);
3313
- assert_eq!(
3314
- incoming.get("session_id").and_then(Value::as_str),
3315
- Some("real-uuid")
3316
- );
3317
- assert_eq!(
3318
- incoming.get("rollout_path").and_then(Value::as_str),
3319
- Some("/tmp/real.jsonl")
3320
- );
3321
- assert_eq!(
3322
- incoming.get("captured_at").and_then(Value::as_str),
3323
- Some("2026-06-25T10:00:00+00:00")
3324
- );
3325
- assert_eq!(
3326
- incoming.get("captured_via").and_then(Value::as_str),
3327
- Some("session.captured")
3328
- );
3329
- assert_eq!(
3330
- incoming
3331
- .get("attribution_confidence")
3332
- .and_then(Value::as_str),
3333
- Some("high"),
3334
- "attribution_confidence rides with the tuple"
3335
- );
3336
- }
3337
-
3338
- /// 0.4.6 tuple-atomic contract test #3 (audit, line 266):
3339
- /// latest has complete tuple for one session_id, incoming has non-null
3340
- /// DIFFERENT session_id → no mixed tuple. Prevents one writer's
3341
- /// session_id getting glued to another writer's rollout_path/captured_at.
3342
- #[test]
3343
- fn backfill_capture_refuses_mixing_different_session_ids() {
3344
- let mut incoming = json!({
3345
- "session_id": "incoming-different-uuid",
3346
- "rollout_path": Value::Null,
3347
- "captured_at": Value::Null,
3348
- "captured_via": Value::Null,
3349
- });
3350
- let latest = json!({
3351
- "session_id": "latest-uuid",
3352
- "rollout_path": "/tmp/latest.jsonl",
3353
- "captured_at": "2026-06-25T10:00:00+00:00",
3354
- "captured_via": "session.captured",
3355
- });
3356
- backfill_capture_fields(&mut incoming, &latest);
3357
- // session_id stays as incoming (not overwritten).
3358
- assert_eq!(
3359
- incoming.get("session_id").and_then(Value::as_str),
3360
- Some("incoming-different-uuid"),
3361
- "0.4.6: incoming session_id must not be overwritten by a different latest"
3362
- );
3363
- // Sibling fields stay null (no cross-session mixing).
3364
- assert_eq!(
3365
- incoming.get("rollout_path"),
3366
- Some(&Value::Null),
3367
- "0.4.6: must not copy latest rollout_path onto a different session_id"
3368
- );
3369
- }
3370
-
3371
- /// 0.4.6 tuple-atomic contract test #4 (audit, line 267):
3372
- /// `normalize_agent_session_state` may only insert null defaults — it
3373
- /// must never create non-null session truth.
3374
- #[test]
3375
- fn normalize_agent_session_state_only_inserts_null_defaults() {
3376
- let mut state = json!({
3377
- "agents": {
3378
- "alpha": {}
3379
- }
3380
- });
3381
- normalize_agent_session_state(&mut state);
3382
- let alpha = state.pointer("/agents/alpha").expect("alpha");
3383
- for field in [
3384
- "session_id",
3385
- "rollout_path",
3386
- "captured_at",
3387
- "captured_via",
3388
- "attribution_confidence",
3389
- "spawn_cwd",
3390
- ] {
3391
- assert_eq!(
3392
- alpha.get(field),
3393
- Some(&Value::Null),
3394
- "normalize must insert null for {field}; got {alpha}"
3395
- );
3396
- }
3397
- }
3398
-
3399
- /// Bug 045 end-to-end persist regression: poisoned latest (session_id
3400
- /// but no captured_at/captured_via) cannot resurrect a cleared incoming
3401
- /// row through a real save → reload cycle.
3402
- #[test]
3403
- fn poisoned_partial_latest_does_not_resurrect_on_save_reload() {
3404
- let ws = temp_ws();
3405
- // Seed disk with the exact bug-045 poisoned shape: session_id set,
3406
- // no captured_at / captured_via / rollout_path.
3407
- let poisoned = json!({
3408
- "session_name": "team-bug045-poisoned",
3409
- "team_key": "teamP",
3410
- "agents": {
3411
- "alpha": {
3412
- "status": "stopped",
3413
- "provider": "claude",
3414
- "session_id": "stale-poisoned-uuid",
3415
- "rollout_path": Value::Null,
3416
- "captured_at": Value::Null,
3417
- "captured_via": Value::Null
3418
- }
3419
- }
3420
- });
3421
- save_runtime_state(&ws, &poisoned).unwrap();
3422
-
3423
- // Restart-fresh writes a cleared row.
3424
- let cleared = json!({
3425
- "session_name": "team-bug045-poisoned",
3426
- "team_key": "teamP",
3427
- "agents": {
3428
- "alpha": {
3429
- "status": "running",
3430
- "provider": "claude",
3431
- "session_id": Value::Null,
3432
- "rollout_path": Value::Null,
3433
- "captured_at": Value::Null,
3434
- "captured_via": Value::Null
3435
- }
3436
- }
3437
- });
3438
- save_runtime_state(&ws, &cleared).unwrap();
3439
-
3440
- let on_disk = read_state(&ws);
3441
- let alpha = on_disk.pointer("/agents/alpha").expect("alpha");
3442
- assert_eq!(
3443
- alpha.get("session_id"),
3444
- Some(&Value::Null),
3445
- "0.4.6: partial poisoned latest must not resurrect cleared session_id; got {alpha}"
3446
- );
3447
- }
3448
-
3449
- fn ownership_projection(session: &str, tty: &str) -> Value {
3450
- let entry = json!({
3451
- "session_name": "team-authority-merge",
3452
- "owner_epoch": 10,
3453
- "team_owner": {"status": "attached", "owner_epoch": 10, "pane_id": "%7"},
3454
- "leader_receiver": {
3455
- "status": "attached",
3456
- "owner_epoch": 10,
3457
- "pane_id": "%7",
3458
- "session_name": session,
3459
- "pane_tty": tty
3460
- }
3461
- });
3462
- let mut state = json!({
3463
- "session_name": "team-authority-merge",
3464
- "active_team_key": "team-authority-merge",
3465
- "teams": {
3466
- "team-authority-merge": entry.clone(),
3467
- "sibling": entry.clone()
3468
- }
3469
- });
3470
- state["teams"][CURRENT_TEAM_ALIAS] = entry;
3471
- state
3472
- }
3473
-
3474
- #[test]
3475
- fn equal_epoch_ordinary_writer_preserves_latest_receiver_observation() {
3476
- let mut incoming = ownership_projection("stale-session", "/dev/stale");
3477
- let latest = ownership_projection("refreshed-session", "/dev/refreshed");
3478
- apply_persist_merge_contract(
3479
- &mut incoming,
3480
- &latest,
3481
- &BTreeSet::new(),
3482
- None,
3483
- &BTreeSet::new(),
3484
- &BTreeSet::new(),
3485
- &BTreeSet::new(),
3486
- None,
3487
- None,
3488
- None,
3489
- )
3490
- .unwrap();
3491
-
3492
- assert_eq!(
3493
- incoming.pointer("/teams/team-authority-merge/leader_receiver/session_name"),
3494
- Some(&json!("refreshed-session"))
3495
- );
3496
- assert_eq!(
3497
- incoming.pointer("/teams/team-authority-merge/leader_receiver/pane_tty"),
3498
- Some(&json!("/dev/refreshed"))
3499
- );
3500
- assert_eq!(
3501
- incoming["teams"][CURRENT_TEAM_ALIAS]["leader_receiver"]["session_name"],
3502
- json!("refreshed-session")
3503
- );
3504
- assert_eq!(
3505
- incoming["teams"]["sibling"]["leader_receiver"]["session_name"],
3506
- json!("refreshed-session")
3507
- );
3508
- }
3509
-
3510
- #[test]
3511
- fn equal_epoch_receiver_authority_keeps_incoming_refresh() {
3512
- let mut incoming = ownership_projection("refreshed-session", "/dev/refreshed");
3513
- let latest = ownership_projection("stale-session", "/dev/stale");
3514
- let receiver_updates = BTreeSet::from(["team-authority-merge".to_string()]);
3515
- apply_persist_merge_contract(
3516
- &mut incoming,
3517
- &latest,
3518
- &BTreeSet::new(),
3519
- None,
3520
- &BTreeSet::new(),
3521
- &BTreeSet::new(),
3522
- &receiver_updates,
3523
- None,
3524
- None,
3525
- None,
3526
- )
3527
- .unwrap();
3528
-
3529
- assert_eq!(
3530
- incoming.pointer("/teams/team-authority-merge/leader_receiver/session_name"),
3531
- Some(&json!("refreshed-session"))
3532
- );
3533
- assert_eq!(
3534
- incoming.pointer("/teams/team-authority-merge/leader_receiver/pane_tty"),
3535
- Some(&json!("/dev/refreshed"))
3536
- );
3537
- assert_eq!(
3538
- incoming["teams"][CURRENT_TEAM_ALIAS]["leader_receiver"]["session_name"],
3539
- json!("refreshed-session"),
3540
- "current alias must inherit the active team's receiver authority"
3541
- );
3542
- assert_eq!(
3543
- incoming["teams"]["sibling"]["leader_receiver"]["session_name"],
3544
- json!("stale-session"),
3545
- "team-scoped receiver authority must not overwrite a sibling's latest tuple"
3546
- );
3547
- }
3548
-
3549
- fn seed_owner(epoch: u64) -> Value {
3550
- json!({
3551
- "pane_id": "%42",
3552
- "provider": "pi",
3553
- "leader_session_uuid": "uuid-seed",
3554
- "owner_epoch": epoch,
3555
- "claimed_via": "quick-start"
3556
- })
3557
- }
3558
-
3559
- fn seed_receiver(epoch: u64) -> Value {
3560
- json!({
3561
- "mode": "direct_tmux",
3562
- "status": "attached",
3563
- "pane_id": "%42",
3564
- "provider": "pi",
3565
- "leader_session_uuid": "uuid-seed",
3566
- "owner_epoch": epoch
3567
- })
3568
- }
3569
-
3570
- fn takeover_owner(epoch: u64) -> Value {
3571
- json!({
3572
- "pane_id": "%99",
3573
- "provider": "codex",
3574
- "leader_session_uuid": "uuid-other",
3575
- "owner_epoch": epoch,
3576
- "claimed_via": "claim-leader"
3577
- })
3578
- }
3579
-
3580
- fn takeover_receiver(epoch: u64) -> Value {
3581
- json!({
3582
- "mode": "direct_tmux",
3583
- "status": "attached",
3584
- "pane_id": "%99",
3585
- "provider": "codex",
3586
- "leader_session_uuid": "uuid-other",
3587
- "owner_epoch": epoch,
3588
- "tmux_socket": "/tmp/other"
3589
- })
3590
- }
3591
-
3592
- fn team_state_with_binding(ws: &Path, owner: Value, receiver: Value, epoch: u64) -> Value {
3593
- json!({
3594
- "workspace": ws.display().to_string(),
3595
- "active_team_key": "fresh",
3596
- "team_key": "fresh",
3597
- "session_name": "team-fresh",
3598
- "agents": {"sol": {"status": "running"}},
3599
- "teams": {
3600
- "fresh": {
3601
- "team_key": "fresh",
3602
- "session_name": "team-fresh",
3603
- "agents": {"sol": {"status": "running"}},
3604
- "team_owner": owner,
3605
- "leader_receiver": receiver,
3606
- "owner_epoch": epoch
3607
- }
3608
- }
3609
- })
3610
- }
3611
-
3612
- fn tombstone_incoming(ws: &Path, epoch: u64) -> Value {
3613
- let mut incoming = team_state_with_binding(
3614
- ws,
3615
- seed_owner(epoch),
3616
- seed_receiver(epoch),
3617
- epoch,
3618
- );
3619
- incoming["teams"]["fresh"]["team_owner"] = Value::Null;
3620
- incoming["teams"]["fresh"]["leader_receiver"] = Value::Null;
3621
- incoming
3622
- }
3623
-
3624
- fn assert_fresh_binding(persisted: &Value, owner: &Value, receiver: &Value, epoch: u64) {
3625
- assert_eq!(&persisted["teams"]["fresh"]["team_owner"], owner);
3626
- assert_eq!(&persisted["teams"]["fresh"]["leader_receiver"], receiver);
3627
- assert_eq!(persisted["teams"]["fresh"]["owner_epoch"], json!(epoch));
3628
- }
3629
-
3630
- fn persisted_fresh_owner(ws: &Path) -> Value {
3631
- load_runtime_state(ws).unwrap()["teams"]["fresh"]["team_owner"].clone()
3632
- }
3633
-
3634
- #[test]
3635
- fn exact_seed_cleanup_ignores_pre_lock_cache_and_equality_fast_path() {
3636
- let ws = temp_ws();
3637
- save_runtime_state(
3638
- &ws,
3639
- &team_state_with_binding(&ws, seed_owner(1), seed_receiver(1), 1),
3640
- )
3641
- .unwrap();
3642
- let incoming = load_runtime_state(&ws).unwrap();
3643
- let seed = persisted_fresh_owner(&ws);
3644
- save_runtime_state_with_receiver_authority(&ws, &incoming, "fresh", Some(&seed)).unwrap();
3645
- let persisted = load_runtime_state(&ws).unwrap();
3646
- assert!(
3647
- persisted
3648
- .pointer("/teams/fresh/team_owner")
3649
- .is_some_and(Value::is_null),
3650
- "cache/equality hit must not skip exact-seed cleanup; got {}",
3651
- persisted["teams"]["fresh"]["team_owner"]
3652
- );
3653
- assert_eq!(persisted["teams"]["fresh"]["owner_epoch"], json!(1));
3654
- }
3655
-
3656
- #[test]
3657
- fn lock_held_exact_seed_cleanup_clears_matching_owner_without_epoch_bump() {
3658
- let ws = temp_ws();
3659
- save_runtime_state(
3660
- &ws,
3661
- &team_state_with_binding(&ws, seed_owner(1), seed_receiver(1), 1),
3662
- )
3663
- .unwrap();
3664
- let seed = persisted_fresh_owner(&ws);
3665
- save_runtime_state_with_receiver_authority(
3666
- &ws,
3667
- &tombstone_incoming(&ws, 1),
3668
- "fresh",
3669
- Some(&seed),
3670
- )
3671
- .unwrap();
3672
- let persisted = load_runtime_state(&ws).unwrap();
3673
- assert!(
3674
- persisted
3675
- .pointer("/teams/fresh/team_owner")
3676
- .is_some_and(Value::is_null),
3677
- "exact seed must be cleared; got {}",
3678
- persisted["teams"]["fresh"]["team_owner"]
3679
- );
3680
- assert!(
3681
- persisted
3682
- .pointer("/teams/fresh/leader_receiver")
3683
- .is_some_and(Value::is_null)
3684
- );
3685
- assert_eq!(
3686
- persisted["teams"]["fresh"]["owner_epoch"],
3687
- json!(1),
3688
- "cleanup must not bump epoch past a same-epoch concurrent owner"
3689
- );
3690
- }
3691
-
3692
- #[test]
3693
- fn lock_held_exact_seed_cleanup_preserves_equal_epoch_concurrent_binding() {
3694
- let ws = temp_ws();
3695
- save_runtime_state(
3696
- &ws,
3697
- &team_state_with_binding(&ws, seed_owner(1), seed_receiver(1), 1),
3698
- )
3699
- .unwrap();
3700
- let seed = persisted_fresh_owner(&ws);
3701
- save_runtime_state_with_receiver_authority(
3702
- &ws,
3703
- &team_state_with_binding(&ws, takeover_owner(1), takeover_receiver(1), 1),
3704
- "fresh",
3705
- None,
3706
- )
3707
- .unwrap();
3708
- let expected = load_runtime_state(&ws).unwrap();
3709
- assert_fresh_binding(&expected, &takeover_owner(1), &takeover_receiver(1), 1);
3710
- save_runtime_state_with_receiver_authority(
3711
- &ws,
3712
- &tombstone_incoming(&ws, 1),
3713
- "fresh",
3714
- Some(&seed),
3715
- )
3716
- .unwrap();
3717
- assert_fresh_binding(
3718
- &load_runtime_state(&ws).unwrap(),
3719
- &expected["teams"]["fresh"]["team_owner"],
3720
- &expected["teams"]["fresh"]["leader_receiver"],
3721
- 1,
3722
- );
3723
- }
3724
-
3725
- #[test]
3726
- fn lock_held_exact_seed_receiver_cleanup_preserves_same_owner_receiver_update() {
3727
- let ws = temp_ws();
3728
- save_runtime_state(
3729
- &ws,
3730
- &team_state_with_binding(&ws, seed_owner(1), seed_receiver(1), 1),
3731
- )
3732
- .unwrap();
3733
- let seed = persisted_fresh_owner(&ws);
3734
- let seeded_receiver = load_runtime_state(&ws).unwrap()["teams"]["fresh"]
3735
- ["leader_receiver"]
3736
- .clone();
3737
- let mut winner = team_state_with_binding(&ws, seed_owner(1), takeover_receiver(1), 1);
3738
- winner["teams"]["fresh"]["team_owner"] = seed.clone();
3739
- save_runtime_state_with_receiver_authority(&ws, &winner, "fresh", None).unwrap();
3740
- save_runtime_state_with_exact_owner_receiver_cleanup(
3741
- &ws,
3742
- &tombstone_incoming(&ws, 1),
3743
- "fresh",
3744
- &seed,
3745
- &seeded_receiver,
3746
- )
3747
- .unwrap();
3748
- assert_fresh_binding(
3749
- &load_runtime_state(&ws).unwrap(),
3750
- &seed,
3751
- &takeover_receiver(1),
3752
- 1,
3753
- );
3754
- }
3755
-
3756
- #[test]
3757
- fn lock_held_exact_seed_cleanup_preserves_epoch2_takeover_binding() {
3758
- let ws = temp_ws();
3759
- save_runtime_state(
3760
- &ws,
3761
- &team_state_with_binding(&ws, seed_owner(1), seed_receiver(1), 1),
3762
- )
3763
- .unwrap();
3764
- let seed = persisted_fresh_owner(&ws);
3765
- save_runtime_state(
3766
- &ws,
3767
- &team_state_with_binding(&ws, takeover_owner(2), takeover_receiver(2), 2),
3768
- )
3769
- .unwrap();
3770
- let expected = load_runtime_state(&ws).unwrap();
3771
- save_runtime_state_with_receiver_authority(
3772
- &ws,
3773
- &tombstone_incoming(&ws, 1),
3774
- "fresh",
3775
- Some(&seed),
3776
- )
3777
- .unwrap();
3778
- assert_fresh_binding(
3779
- &load_runtime_state(&ws).unwrap(),
3780
- &expected["teams"]["fresh"]["team_owner"],
3781
- &expected["teams"]["fresh"]["leader_receiver"],
3782
- 2,
3783
- );
3784
- }
3785
-
3786
- #[test]
3787
- fn state_save_lock_serializes_raw_writer_and_prune_reader() {
3788
- let ws = temp_ws();
3789
- save_runtime_state(&ws, &json!({"teams": {"fresh": {}}})).unwrap();
3790
- let lock = RuntimeLock::acquire(&ws, "state-save", 2.0).unwrap();
3791
-
3792
- let writer_ws = ws.clone();
3793
- let writer = std::thread::spawn(move || {
3794
- save_runtime_state_without_migrations(&writer_ws, &json!({"teams": {"fresh": {}}}))
3795
- });
3796
- std::thread::sleep(Duration::from_millis(100));
3797
- assert!(!writer.is_finished(), "raw writer must share state-save lock");
3798
- drop(lock);
3799
- writer.join().unwrap().unwrap();
3800
-
3801
- let lock = RuntimeLock::acquire(&ws, "state-save", 2.0).unwrap();
3802
- let reader_ws = ws.clone();
3803
- let reader = std::thread::spawn(move || {
3804
- with_runtime_state_lock_without_migrations(&reader_ws, |state| state.is_some())
3805
- });
3806
- std::thread::sleep(Duration::from_millis(100));
3807
- assert!(!reader.is_finished(), "prune reader must use state-save lock");
3808
- drop(lock);
3809
- assert!(reader.join().unwrap().unwrap());
3810
- }
3811
- }