@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,2362 +0,0 @@
1
- //! ---
2
- //! purpose: restart 与 start 共用的底座,含 spawn 执行、transport 解析、state 标记与各类读取判定
3
- //! contract:
4
- //! provides:
5
- //! - name: spawn_agent_window
6
- //! what: 为一个席位拼命令并在目标 session 里开窗或分格起进程
7
- //! - name: lifecycle_worker_tmux_backend_for_selected_state
8
- //! what: 按团队已持久化的 endpoint 解析 tmux 后端,非 tmux 状态直接拒绝
9
- //! - name: save_restart_projected_state
10
- //! what: 同步团队投影后经 repository 带写意图落盘
11
- //! - name: resume_backing_probe_for_agent
12
- //! what: 探测该席位的 resume 依据是否在盘上,并记下所有查过的路径
13
- //! - name: converge_missing_provider_sessions
14
- //! what: 有界等待会话捕获收敛,并逐轮写进度事件
15
- //! - name: mark_agent_stopped
16
- //! what: 把席位标记为已停并清掉 window 与 pane_id 字段
17
- //! depends:
18
- //! - crate::transport::Transport
19
- //! - crate::tmux_backend
20
- //! - crate::transport_factory
21
- //! - crate::provider
22
- //! - crate::session_capture
23
- //! - crate::state::projection
24
- //! - crate::state::repository
25
- //! - crate::state::persist
26
- //! - crate::coordinator::health
27
- //! - crate::event_log::EventLog
28
- //! - crate::lifecycle::launch
29
- //! - crate::lifecycle::profile_launch
30
- //! - crate::lifecycle::worker_command_context
31
- //! - crate::lifecycle::restart::selection
32
- //! boundary:
33
- //! - 状态是 conpty 时 tmux 专用解析器直接报错,不静默降级到 tmux
34
- //! - 探测类判定失败一律倒向保守值,不把不确定当成存活
35
- //! - 清活动观测只删观测字段,不动生命周期与拓扑字段
36
- //! - 收敛与排空都是有界等待,不无限阻塞
37
- //! maturity: wired
38
- //! ---
39
- use super::*;
40
-
41
- pub(super) struct SpawnedAgentWindow {
42
- pub spawn: crate::transport::SpawnResult,
43
- pub spawned_at: String,
44
- pub plan: crate::provider::CommandPlan,
45
- pub profile_launch: crate::provider::ProviderProfileLaunch,
46
- pub layout_placement: Option<crate::lifecycle::launch::LayoutPlacement>,
47
- pub spawn_cwd: std::path::PathBuf,
48
- /// Actual configuration generated for this spawn, not inferred from old state.
49
- pub mcp_config_path: Option<std::path::PathBuf>,
50
- /// Issue 2 (Round 3b gate review §6): the resolved `owner_team_id` used
51
- /// for this spawn's MCP env / command. Callers (`mark_agent_respawned`,
52
- /// `mark_agent_started`) must persist this back into the agent row so
53
- /// future restarts read it directly (priority #2 in the resolution
54
- /// cascade) instead of relying on top-level `active_team_key`.
55
- pub owner_team_id: Option<String>,
56
- }
57
-
58
- #[derive(Clone)]
59
- pub(super) struct SameRoleCohortTarget {
60
- pub agent_id: String,
61
- pub window: String,
62
- pub expected_pane_id: Option<String>,
63
- }
64
-
65
- impl SameRoleCohortTarget {
66
- /// ---
67
- /// purpose: 构造一个同角色同批目标
68
- /// params:
69
- /// window: 该席位的窗口名
70
- /// returns: 未带期望 pane 的目标
71
- /// ---
72
- pub(super) fn new(agent_id: &AgentId, window: &str) -> Self {
73
- Self {
74
- agent_id: agent_id.as_str().to_string(),
75
- window: window.to_string(),
76
- expected_pane_id: None,
77
- }
78
- }
79
-
80
- /// ---
81
- /// purpose: 给目标补上期望的旧 pane
82
- /// returns: 带期望 pane 的目标
83
- /// ---
84
- pub(super) fn with_expected_pane_id(mut self, pane_id: Option<&str>) -> Self {
85
- self.expected_pane_id = pane_id.map(ToString::to_string);
86
- self
87
- }
88
- }
89
-
90
- /// ---
91
- /// purpose: 判断该窗口是不是按席位命名的独立窗口
92
- /// returns: 窗口名等于席位名且不是规范布局窗口时为 true
93
- /// ---
94
- pub(super) fn is_per_agent_cohort_window(window: &str, agent_id: &AgentId) -> bool {
95
- window == agent_id.as_str() && !crate::lifecycle::launch::is_adaptive_layout_window_pub(window)
96
- }
97
-
98
- /// ---
99
- /// purpose: spawn 之前检查同角色同批是否已有残留
100
- /// returns: 期望基数为 0;不满足时给出可读的拒绝说明,满足则 None
101
- /// ---
102
- pub(super) fn same_role_cohort_pre_spawn_error(
103
- transport: &dyn crate::transport::Transport,
104
- session_name: &SessionName,
105
- operation: &str,
106
- targets: &[SameRoleCohortTarget],
107
- ) -> Option<String> {
108
- same_role_cohort_error(transport, session_name, operation, targets, 0, true)
109
- }
110
-
111
- /// ---
112
- /// purpose: spawn 之后检查同角色同批是否恰好只剩一个
113
- /// returns: 期望基数为 1;不满足时给出可读的拒绝说明,满足则 None
114
- /// ---
115
- pub(super) fn same_role_cohort_exactly_one_error(
116
- transport: &dyn crate::transport::Transport,
117
- session_name: &SessionName,
118
- operation: &str,
119
- targets: &[SameRoleCohortTarget],
120
- ) -> Option<String> {
121
- same_role_cohort_error(transport, session_name, operation, targets, 1, false)
122
- }
123
-
124
- /// ---
125
- /// purpose: 杀掉这些目标记录的旧 pane
126
- /// returns: 全部处理完返回空值;目标没有期望 pane 或该 pane 明确不存在时跳过
127
- /// errors: 杀 pane 失败时返回带席位、窗口与 pane 的错误串
128
- /// ---
129
- pub(super) fn retire_expected_same_role_cohorts(
130
- transport: &dyn crate::transport::Transport,
131
- operation: &str,
132
- targets: &[SameRoleCohortTarget],
133
- ) -> Result<(), String> {
134
- for target in targets {
135
- let Some(pane_id) = target.expected_pane_id.as_deref() else {
136
- continue;
137
- };
138
- let pane = crate::transport::PaneId::new(pane_id);
139
- if transport.has_pane(&pane).ok().flatten() == Some(false) {
140
- continue;
141
- }
142
- transport.kill_pane(&pane).map_err(|error| {
143
- format!(
144
- "{operation} failed to retire old same-role cohort {}:window={}:pane={pane_id}: {error}",
145
- target.agent_id, target.window
146
- )
147
- })?;
148
- }
149
- Ok(())
150
- }
151
-
152
- fn same_role_cohort_error(
153
- transport: &dyn crate::transport::Transport,
154
- session_name: &SessionName,
155
- operation: &str,
156
- targets: &[SameRoleCohortTarget],
157
- expected_live: usize,
158
- expected_old_only: bool,
159
- ) -> Option<String> {
160
- let panes = match transport.list_targets() {
161
- Ok(panes) => panes,
162
- Err(error) => {
163
- return Some(format!(
164
- "{operation} refused: same-role cohort observation failed: {error}"
165
- ));
166
- }
167
- };
168
- let mut cardinality_proofs = Vec::new();
169
- let mut binding_proofs = Vec::new();
170
- let mut observation_proofs = Vec::new();
171
- for target in targets {
172
- let candidate_panes = panes
173
- .iter()
174
- .filter(|pane| pane.session.as_str() == session_name.as_str())
175
- .filter(|pane| {
176
- pane.window_name
177
- .as_ref()
178
- .is_some_and(|window| window.as_str() == target.window)
179
- })
180
- .collect::<Vec<_>>();
181
- let mut live_panes = Vec::new();
182
- for pane in candidate_panes {
183
- match transport.liveness(&pane.pane_id) {
184
- Ok(crate::transport::PaneLiveness::Live) => {
185
- live_panes.push(pane.pane_id.as_str().to_string());
186
- }
187
- Ok(crate::transport::PaneLiveness::Dead) => {}
188
- Ok(crate::transport::PaneLiveness::Unknown) => {
189
- observation_proofs.push(format!(
190
- "{}:window={}:pane={}:liveness=unknown",
191
- target.agent_id,
192
- target.window,
193
- pane.pane_id.as_str()
194
- ));
195
- }
196
- Err(error) => observation_proofs.push(format!(
197
- "{}:window={}:pane={}:liveness_error={error}",
198
- target.agent_id,
199
- target.window,
200
- pane.pane_id.as_str()
201
- )),
202
- }
203
- }
204
- if live_panes.len() != expected_live {
205
- cardinality_proofs.push(format!(
206
- "{}:window={}:live_panes=[{}]",
207
- target.agent_id,
208
- target.window,
209
- live_panes.join(",")
210
- ));
211
- } else if !expected_old_only {
212
- let observed = live_panes.first().map(String::as_str);
213
- if target.expected_pane_id.as_deref() != observed {
214
- binding_proofs.push(format!(
215
- "{}:window={}:expected_pane={}:observed_pane={}",
216
- target.agent_id,
217
- target.window,
218
- target.expected_pane_id.as_deref().unwrap_or("<missing>"),
219
- observed.unwrap_or("<missing>")
220
- ));
221
- }
222
- }
223
- }
224
- if !observation_proofs.is_empty() {
225
- return Some(format!(
226
- "{operation} refused: same-role cohort observation failed; {}",
227
- observation_proofs.join("; ")
228
- ));
229
- }
230
- if !binding_proofs.is_empty() {
231
- return Some(format!(
232
- "{operation} refused: spawn identity/binding mismatch; {}",
233
- binding_proofs.join("; ")
234
- ));
235
- }
236
- if !cardinality_proofs.is_empty() {
237
- return Some(format!(
238
- "{operation} refused: same-role cohort duplicate proof failed; {}",
239
- cardinality_proofs.join("; ")
240
- ));
241
- }
242
- None
243
- }
244
-
245
- /// ---
246
- /// purpose: 为一个席位拼出命令并在目标 session 里起进程
247
- /// params:
248
- /// resume_session_id: 给出且该 provider 支持 resume 时按 resume 起,否则丢弃它全新起
249
- /// into_existing_session: 目标 session 已存在时开新窗口,否则新建 session
250
- /// layout_placement: 有布局位置时按布局开窗或分格
251
- /// spawn_cwd_override: 覆盖工作目录
252
- /// owner_team_id_override: 显式指定写进 worker 环境的 owner team,缺省时退回席位行与顶层活跃键
253
- /// returns: spawn 结果、时间戳、命令计划、profile 启动参数、布局位置与实际使用的 owner team
254
- /// errors: 命令拼装、profile 准备或 transport spawn 失败时返回 LifecycleError
255
- /// ---
256
- #[allow(clippy::too_many_arguments)]
257
- pub(super) fn spawn_agent_window(
258
- workspace: &Path,
259
- session_name: &SessionName,
260
- agent_id: &AgentId,
261
- agent: &serde_json::Value,
262
- resume_session_id: Option<&SessionId>,
263
- into_existing_session: bool,
264
- transport: &dyn crate::transport::Transport,
265
- safety: Option<&DangerousApproval>,
266
- layout_placement: Option<&crate::lifecycle::launch::LayoutPlacement>,
267
- spawn_cwd_override: Option<&Path>,
268
- tmux_endpoint_source: Option<&str>,
269
- // Issue 2 (Round 3b gate review §6): explicit owner_team_id override.
270
- // When `Some`, callers (restart/rebuild.rs, restart/agent.rs) thread the
271
- // resolved `selected.team_key` through here so the worker's MCP env /
272
- // command argv carries `TEAM_AGENT_OWNER_TEAM_ID=<selected team>` —
273
- // even when the persisted agent row OR the top-level `active_team_key`
274
- // is stale. When `None`, falls back to the legacy resolution
275
- // (agent row → active_team_key) for back-compat with non-restart callers.
276
- owner_team_id_override: Option<&str>,
277
- ) -> Result<SpawnedAgentWindow, LifecycleError> {
278
- // A pre-upgrade Codex or Grok worker row has no legacy runtime left;
279
- // refuse before any MCP file, profile or pane side effect.
280
- if let Some(retired) = agent
281
- .get("provider")
282
- .and_then(serde_json::Value::as_str)
283
- .filter(|provider| crate::provider::wire::is_retired_provider(provider))
284
- {
285
- return Err(LifecycleError::Provider(
286
- crate::provider::wire::retired_provider_error(retired).into(),
287
- ));
288
- }
289
- let provider = agent_provider(agent);
290
- let auth_mode = agent_auth_mode(agent);
291
- let model = agent.get("model").and_then(|v| v.as_str());
292
- let adapter = crate::provider::get_adapter(provider);
293
- let resume_session_id = if adapter.caps().resume {
294
- resume_session_id
295
- } else {
296
- None
297
- };
298
- let fork_parent = agent
299
- .get(crate::lifecycle::launch::add_agent_state::FORK_PARENT_SESSION_ID)
300
- .and_then(serde_json::Value::as_str)
301
- .filter(|parent| !parent.is_empty())
302
- .map(SessionId::new);
303
- // Contract C / F6.4: thread compiled role/tools/MCP context through restart as well —
304
- // a restarted worker must come back up with the SAME callable MCP capability + role
305
- // prompt as a fresh launch, else `report_result` becomes unreachable after every restart.
306
- let detected_safety;
307
- let safety = if let Some(safety) = safety {
308
- safety
309
- } else {
310
- detected_safety = crate::lifecycle::launch::effective_runtime_config_for_worker_spawn_json(
311
- agent, provider,
312
- )?;
313
- &detected_safety
314
- };
315
- let command_agent = crate::lifecycle::worker_command_context::WorkerCommandAgent::from_json(
316
- agent,
317
- Some(agent_id.as_str()),
318
- provider,
319
- )?;
320
- let system_prompt =
321
- crate::lifecycle::worker_command_context::compile_worker_system_prompt(&command_agent)?;
322
- // owner_team_id resolution priority (Issue 2 fix):
323
- // 1. caller's explicit override (restart paths pass `selected.team_key`)
324
- // 2. agent row's persisted `owner_team_id` (set by prior launch/restart)
325
- // 3. top-level `active_team_key` (legacy fallback for add-agent etc.)
326
- // The override breaks the dependency on top-level state mutation: even if
327
- // top-level `active_team_key` is stale (e.g. `ta-probe-ws`), a restart that
328
- // resolved `selected.team_key=prerelease-040-round3b` propagates THAT team
329
- // into the worker's MCP env.
330
- let state_for_team =
331
- crate::state::persist::load_runtime_state(workspace).unwrap_or(serde_json::json!({}));
332
- let team_id = owner_team_id_override
333
- .filter(|s| !s.is_empty())
334
- .map(str::to_string)
335
- .or_else(|| {
336
- agent
337
- .get("owner_team_id")
338
- .and_then(|v| v.as_str())
339
- .filter(|s| !s.is_empty())
340
- .map(str::to_string)
341
- })
342
- .or_else(|| {
343
- let key =
344
- crate::messaging::leader_receiver::active_team_key(workspace, &state_for_team);
345
- (!key.is_empty()).then_some(key)
346
- });
347
- let mcp_config = adapter
348
- .mcp_config(auth_mode)
349
- .map_err(|e| LifecycleError::Provider(e.to_string()))?;
350
- let mcp_config = crate::lifecycle::launch::resolve_mcp_config(
351
- mcp_config,
352
- workspace,
353
- agent_id.as_str(),
354
- team_id.as_deref().unwrap_or(""),
355
- );
356
- let mcp_config_path = if provider == crate::provider::Provider::Pi {
357
- None
358
- } else {
359
- Some(crate::lifecycle::launch::write_worker_mcp_config_for_provider(
360
- workspace,
361
- agent_id.as_str(),
362
- &mcp_config,
363
- Some(provider),
364
- )?)
365
- };
366
- let profile_launch =
367
- crate::lifecycle::profile_launch::prepare_provider_profile_launch_from_json(
368
- workspace,
369
- agent_id.as_str(),
370
- agent,
371
- Some(&mcp_config),
372
- )?;
373
- let command_model = profile_launch.command_overrides.model.as_deref().or(model);
374
- // 0.4.x provider effort MVP: restart/resume preserves effort from the
375
- // persisted agent JSON (state's agent["effort"] field, set by launch).
376
- let restart_effort = crate::lifecycle::launch::provider_effort_for_spawn_json(agent, provider)?;
377
- if let Some(event_value) = crate::lifecycle::launch::provider_effort_event_if_dropped_json(
378
- agent,
379
- provider,
380
- agent_id.as_str(),
381
- ) {
382
- let _ = crate::event_log::EventLog::new(workspace)
383
- .write("provider.effort_unsupported", event_value);
384
- }
385
- let context = crate::provider::ProviderCommandContext {
386
- auth_mode,
387
- mcp_config: Some(&mcp_config),
388
- system_prompt: Some(system_prompt.as_str()),
389
- model: command_model,
390
- dangerously_skip_permissions: agent
391
- .get("dangerously_skip_permissions")
392
- .and_then(serde_json::Value::as_bool)
393
- .unwrap_or(false),
394
- profile_launch: Some(&profile_launch),
395
- agent_id_hint: Some(agent_id.as_str()),
396
- effort: restart_effort,
397
- };
398
- let pi_spawn_cwd = (provider == crate::provider::Provider::Pi)
399
- .then(|| {
400
- agent
401
- .get("spawn_cwd")
402
- .and_then(serde_json::Value::as_str)
403
- .filter(|value| !value.is_empty())
404
- .map(std::path::PathBuf::from)
405
- })
406
- .flatten();
407
- let spawn_cwd = spawn_cwd_override
408
- .or(pi_spawn_cwd.as_deref())
409
- .unwrap_or(workspace);
410
- let mut plan = if provider == crate::provider::Provider::Pi {
411
- let request = crate::lifecycle::launch::pi_mcp::PiMaterializeRequest {
412
- workspace,
413
- team_id: team_id.as_deref().unwrap_or(""),
414
- agent_id: agent_id.as_str(),
415
- model: command_model,
416
- effort: restart_effort,
417
- system_prompt: &system_prompt,
418
- team_mcp_tools: &["send_message", "report_result", "get_team_status"],
419
- mcp_config: &mcp_config,
420
- session_scope: crate::lifecycle::launch::pi_mcp::PiSessionScope::Isolated,
421
- session_dir: resume_session_id
422
- .and_then(|_| agent.get("claude_projects_root").and_then(serde_json::Value::as_str))
423
- .map(Path::new),
424
- };
425
- match resume_session_id {
426
- Some(session_id) => {
427
- let rollout_path = agent_rollout_path(agent).ok_or_else(|| {
428
- LifecycleError::RequirementUnmet(
429
- "Pi resume requires the persisted exact session path".to_string(),
430
- )
431
- })?;
432
- crate::lifecycle::launch::pi_mcp::materialize_pi_resume_plan(
433
- request,
434
- session_id,
435
- rollout_path.as_path(),
436
- spawn_cwd,
437
- )
438
- }
439
- None => crate::lifecycle::launch::pi_mcp::materialize_pi_plan(request),
440
- }
441
- .map_err(|e| LifecycleError::Provider(e.to_string()))?
442
- } else {
443
- match (resume_session_id, fork_parent.as_ref()) {
444
- (Some(session_id), _) => adapter.build_resume_command_plan(Some(session_id), context),
445
- (None, Some(parent)) => adapter.fork_plan(Some(parent), context),
446
- (None, None) => adapter.build_command_plan(context),
447
- }
448
- .map_err(|e| LifecycleError::Provider(e.to_string()))?
449
- };
450
- if !plan.managed_mcp_config && !profile_launch.managed_mcp_config {
451
- if let Some(mcp_config_path) = mcp_config_path.as_ref() {
452
- crate::lifecycle::launch::point_native_mcp_config_at_file(
453
- &mut plan.argv,
454
- provider,
455
- mcp_config_path,
456
- );
457
- }
458
- }
459
- crate::lifecycle::launch::fill_spawn_placeholders_full(
460
- &mut plan.argv,
461
- workspace,
462
- agent_id.as_str(),
463
- team_id.as_deref(),
464
- );
465
- let window = layout_placement
466
- .map(|placement| placement.layout_window.clone())
467
- .unwrap_or_else(|| WindowName::new(agent_id.as_str()));
468
- let mut env = crate::lifecycle::launch::inherited_env_with_team_overrides(
469
- workspace,
470
- agent_id.as_str(),
471
- team_id.as_deref(),
472
- Some(crate::lifecycle::launch::auth_mode_env_value(auth_mode)),
473
- );
474
- crate::lifecycle::launch::apply_profile_launch_env(&mut env, &profile_launch);
475
- crate::lifecycle::launch::apply_mcp_auto_approval_env(&mut env, safety);
476
- if provider == crate::provider::Provider::Copilot {
477
- crate::lifecycle::launch::apply_copilot_instructions_overlay(
478
- workspace,
479
- agent_id.as_str(),
480
- &system_prompt,
481
- &mut env,
482
- )?;
483
- }
484
- // Non-Pi spawn cwd is override-or-workspace (E56: ignore drifted state
485
- // `.team/runtime/<team_key>/`). Pi resume uses captured agent.spawn_cwd
486
- // already resolved above so exact-path header checks match capture.
487
- // 0.4.x provider effort MVP step 9: scrub CLAUDE_EFFORT for Claude
488
- // worker spawn so a parent shell env cannot silently override the
489
- // framework's effort decision.
490
- let env_unset = crate::layout::worker_env::isolate_worker_spawn_env(
491
- provider,
492
- &mut env,
493
- crate::lifecycle::launch::extend_worker_env_unset_for_effort(
494
- profile_launch.env_unset.iter().cloned().collect(),
495
- provider,
496
- restart_effort.is_some(),
497
- ),
498
- );
499
- // Apply this owned fork policy after inherited Claude identity is scrubbed.
500
- if resume_session_id.is_none()
501
- && fork_parent.is_some()
502
- && matches!(
503
- provider,
504
- crate::provider::Provider::Claude | crate::provider::Provider::ClaudeCode
505
- )
506
- {
507
- // A fork keeps the whole parent history: a new seat never stops on
508
- // Claude's stale-resume "summary or full session" modal.
509
- env.insert(
510
- "CLAUDE_CODE_RESUME_THRESHOLD_MINUTES".to_string(),
511
- "1000000000".to_string(),
512
- );
513
- }
514
- // Keep the launcher-known typed provider independent from inherited
515
- // LEADER_* identity. The tmux wrapper binds pane/socket at invocation time.
516
- crate::layout::worker_env::inject_current_caller_provider(&mut env, provider);
517
- crate::provider::argv_route::apply(provider, &mut plan.argv)
518
- .map_err(|error| LifecycleError::Provider(error.to_string()))?;
519
-
520
- // 0.4.6 Stage 2: write actual spawn plan event BEFORE invoking the
521
- // transport spawn. Mirrors `launch.rs:359-380` (the reference impl)
522
- // so reset/start/restart fresh produces the same truth source as
523
- // quick-start. Any "argv had --session-id but didn't take effect"
524
- // failure can now be diagnosed from events.jsonl — the recorded
525
- // expected_session_id == state._pending_session_id (after
526
- // mark_agent_started persists the same plan tuple).
527
- let spawned_at = crate::lifecycle::launch::spawn_timestamp();
528
- {
529
- let session_id_in_argv = plan
530
- .argv
531
- .iter()
532
- .position(|a| a == "--session-id")
533
- .and_then(|i| plan.argv.get(i + 1))
534
- .cloned();
535
- let env_overlay_keys: Vec<&String> = env.keys().collect();
536
- let tmux_start_mode_pre_spawn =
537
- predict_tmux_start_mode(layout_placement, into_existing_session);
538
- let spawn_epoch = state_spawn_epoch_for_agent(workspace, agent_id);
539
- let tmux_endpoint = transport.tmux_endpoint();
540
- let event_log = crate::event_log::EventLog::new(workspace);
541
- let _ = event_log.write(
542
- crate::event_log::PROVIDER_WORKER_SPAWN_ARGV,
543
- crate::event_log::provider_worker_spawn_argv_fields(serde_json::json!({
544
- "agent_id": agent_id.as_str(),
545
- "provider": provider,
546
- "argv": plan.argv,
547
- "session_id_in_argv": session_id_in_argv,
548
- "expected_session_id": plan.expected_session_id.as_ref().map(|s| s.as_str()),
549
- "spawn_cwd": spawn_cwd.to_string_lossy(),
550
- "env_overlay_keys": env_overlay_keys,
551
- "env_unset": env_unset,
552
- "tmux_start_mode": tmux_start_mode_pre_spawn,
553
- "spawn_epoch": spawn_epoch,
554
- "spawned_at": spawned_at.as_str(),
555
- "source": "restart",
556
- "tmux_endpoint": tmux_endpoint,
557
- "tmux_endpoint_source": tmux_endpoint_source.unwrap_or("transport"),
558
- })),
559
- );
560
- }
561
-
562
- // 0.5.39 Slice 2 (tmux-server-death-locate §7 Slice 2): route the
563
- // primary worker spawn through the worker shell wrapper so provider
564
- // exit leaves the pane at an inert sh tail with an explicit exit marker
565
- // instead of collapsing the pane into `[exited]`. The inert tail does
566
- // not read pane stdin. The split path stays
567
- // on plain spawn_split — split panes are display overlays, not the
568
- // primary worker process.
569
- let provider_label = crate::provider::wire::command_name(provider);
570
- let result = if let Some(placement) = layout_placement {
571
- if placement.starts_window {
572
- if into_existing_session {
573
- transport.spawn_into_with_worker_shell_wrapper(
574
- session_name,
575
- &window,
576
- &plan.argv,
577
- spawn_cwd,
578
- &env,
579
- &env_unset,
580
- provider_label,
581
- )
582
- } else {
583
- transport.spawn_first_with_worker_shell_wrapper(
584
- session_name,
585
- &window,
586
- &plan.argv,
587
- spawn_cwd,
588
- &env,
589
- &env_unset,
590
- provider_label,
591
- )
592
- }
593
- } else if !window_present_in_live(transport, session_name, &window)
594
- || !crate::lifecycle::launch::is_adaptive_layout_window_pub(window.as_str())
595
- {
596
- // E43 Fix C + E45 (0.3.24 bug#3 → bug#4): never split into a
597
- // window that either does not exist on live tmux OR is a
598
- // per-agent window (`developer`, `architect`, ...) that the
599
- // upstream placement guards should have refused. This is the
600
- // defence-in-depth layer; the primary fix is in
601
- // `adaptive_placement_for_agent` / `adaptive_existing_placement_for_agent`,
602
- // but a placement built from stale `pane_index>0` state can
603
- // still ask to split a per-agent window — and the macmini repro
604
- // showed split-window -t :developer would otherwise succeed and
605
- // hijack the developer worker's pane. Downgrade to spawn_into
606
- // (new window named after agent_id) — canonical per-agent
607
- // fallback the existing 7 workers use.
608
- transport.spawn_into_with_worker_shell_wrapper(
609
- session_name,
610
- &WindowName::new(agent_id.as_str()),
611
- &plan.argv,
612
- spawn_cwd,
613
- &env,
614
- &env_unset,
615
- provider_label,
616
- )
617
- } else {
618
- // 0.3.28 Step 8: spawn_split must only fire from the display
619
- // overlay path. Warn-only here; Step 9 promotes to hard fail.
620
- crate::layout::overlay::assert_overlay_call_site(session_name, &window);
621
- transport.spawn_split_with_env_unset(
622
- session_name,
623
- &window,
624
- &plan.argv,
625
- spawn_cwd,
626
- &env,
627
- &env_unset,
628
- )
629
- }
630
- } else if into_existing_session {
631
- transport.spawn_into_with_worker_shell_wrapper(
632
- session_name,
633
- &window,
634
- &plan.argv,
635
- spawn_cwd,
636
- &env,
637
- &env_unset,
638
- provider_label,
639
- )
640
- } else {
641
- transport.spawn_first_with_worker_shell_wrapper(
642
- session_name,
643
- &window,
644
- &plan.argv,
645
- spawn_cwd,
646
- &env,
647
- &env_unset,
648
- provider_label,
649
- )
650
- };
651
- let spawn = result.map_err(|e| LifecycleError::Transport(e.to_string()))?;
652
- if layout_placement.is_some() {
653
- crate::lifecycle::launch::configure_adaptive_pane_title(
654
- workspace,
655
- transport,
656
- session_name,
657
- &window,
658
- &spawn.pane_id,
659
- agent_id.as_str(),
660
- );
661
- }
662
- let startup_prompt = adapter.handle_startup_prompts_outcome(
663
- transport,
664
- &crate::transport::Target::Pane(spawn.pane_id.clone()),
665
- 30,
666
- 0.5,
667
- );
668
- if let Some(error) = startup_prompt.capture_error.as_deref() {
669
- if is_structural_startup_prompt_error(error) {
670
- if let Err(rollback_error) = transport.kill_pane(&spawn.pane_id) {
671
- return Err(LifecycleError::Transport(format!(
672
- "startup prompt structural failure for {}:{} pane {}: {}; failed to roll back spawned pane: {}",
673
- session_name.as_str(),
674
- window.as_str(),
675
- spawn.pane_id.as_str(),
676
- error,
677
- rollback_error
678
- )));
679
- }
680
- return Err(LifecycleError::Transport(format!(
681
- "startup prompt structural failure for {}:{} pane {}: {}",
682
- session_name.as_str(),
683
- window.as_str(),
684
- spawn.pane_id.as_str(),
685
- error
686
- )));
687
- }
688
- }
689
- Ok(SpawnedAgentWindow {
690
- spawn,
691
- spawned_at,
692
- plan,
693
- profile_launch,
694
- layout_placement: layout_placement.cloned(),
695
- spawn_cwd: spawn_cwd.to_path_buf(),
696
- mcp_config_path,
697
- owner_team_id: team_id,
698
- })
699
- }
700
-
701
- fn is_structural_startup_prompt_error(error: &str) -> bool {
702
- let lower = error.to_ascii_lowercase();
703
- [
704
- "can't find window",
705
- "can't find pane",
706
- "cannot find window",
707
- "cannot find pane",
708
- "target not found",
709
- "no such pane",
710
- "window disappeared",
711
- "pane not owned",
712
- "not owned by requested",
713
- ]
714
- .iter()
715
- .any(|needle| lower.contains(needle))
716
- }
717
-
718
- /// ---
719
- /// purpose: 用 spec 里的同名 agent 补回 state 席位行缺的命令上下文字段
720
- /// returns: 合并后的席位行;spec 读不到或找不到该 agent 时原样返回
721
- /// ---
722
- pub(super) fn rehydrate_agent_command_context_from_spec(
723
- spec_workspace: &Path,
724
- agent_id: &AgentId,
725
- agent: &serde_json::Value,
726
- ) -> serde_json::Value {
727
- let Ok(spec) = load_team_spec(spec_workspace) else {
728
- return agent.clone();
729
- };
730
- let Some(spec_agent) = find_spec_agent(&spec, agent_id) else {
731
- return agent.clone();
732
- };
733
- merge_command_context_fields(agent, spec_agent)
734
- }
735
-
736
- fn merge_command_context_fields(
737
- agent: &serde_json::Value,
738
- spec_agent: &YamlValue,
739
- ) -> serde_json::Value {
740
- let mut merged = agent.clone();
741
- let Some(obj) = merged.as_object_mut() else {
742
- return merged;
743
- };
744
- for field in [
745
- "role",
746
- "system_prompt",
747
- "output_contract",
748
- "provider",
749
- "model",
750
- "auth_mode",
751
- "effort",
752
- "profile",
753
- // 0.5.66 bypass 单源:rehydrate 同步合入,restart 的 safety 构造读到新值。
754
- "dangerously_skip_permissions",
755
- ] {
756
- if let Some(value) = spec_agent.get(field).and_then(yaml_value_to_json) {
757
- obj.insert(field.to_string(), value);
758
- }
759
- }
760
- merged
761
- }
762
-
763
- fn yaml_value_to_json(value: &YamlValue) -> Option<serde_json::Value> {
764
- match value {
765
- YamlValue::Null => Some(serde_json::Value::Null),
766
- YamlValue::Bool(value) => Some(serde_json::json!(value)),
767
- YamlValue::Int(value) => Some(serde_json::json!(value)),
768
- YamlValue::Float(value) => Some(serde_json::json!(value)),
769
- YamlValue::Str(value) => Some(serde_json::json!(value)),
770
- YamlValue::List(items) => Some(serde_json::Value::Array(
771
- items.iter().filter_map(yaml_value_to_json).collect(),
772
- )),
773
- YamlValue::Map(items) => {
774
- let mut map = serde_json::Map::new();
775
- for (key, value) in items {
776
- if let Some(value) = yaml_value_to_json(value) {
777
- map.insert(key.clone(), value);
778
- }
779
- }
780
- Some(serde_json::Value::Object(map))
781
- }
782
- }
783
- }
784
-
785
- /// E43 Fix C helper (0.3.24 bug#3): probe live tmux for a window's existence
786
- /// before issuing `split-window -t :<window>`. Uses `list_windows` first
787
- /// (cheaper, authoritative when present); falls back to `list_targets` so
788
- /// transports that don't seed `windows` directly still surface real entries.
789
- fn window_present_in_live(
790
- transport: &dyn crate::transport::Transport,
791
- session: &SessionName,
792
- window: &WindowName,
793
- ) -> bool {
794
- if let Ok(windows) = transport.list_windows(session) {
795
- if windows.iter().any(|w| w.as_str() == window.as_str()) {
796
- return true;
797
- }
798
- }
799
- if let Ok(targets) = transport.list_targets() {
800
- if targets.iter().any(|t| {
801
- t.session.as_str() == session.as_str()
802
- && t.window_name
803
- .as_ref()
804
- .is_some_and(|n| n.as_str() == window.as_str())
805
- }) {
806
- return true;
807
- }
808
- }
809
- false
810
- }
811
-
812
- /// ---
813
- /// purpose: 起该 workspace 的 coordinator
814
- /// params:
815
- /// team_key: 传给 coordinator 的团队键
816
- /// returns: 启动摘要
817
- /// errors: 启动失败时返回 StatePersist
818
- /// ---
819
- pub(super) fn start_coordinator_for_workspace(
820
- workspace: &Path,
821
- team_key: Option<&str>,
822
- ) -> Result<crate::lifecycle::CoordinatorStartSummary, LifecycleError> {
823
- let workspace = crate::coordinator::WorkspacePath::new(workspace.to_path_buf());
824
- crate::coordinator::health::start_coordinator_with_team(&workspace, team_key)
825
- .map(|report| crate::lifecycle::CoordinatorStartSummary::from_start_report(&report))
826
- .map_err(|e| LifecycleError::StatePersist(e.to_string()))
827
- }
828
-
829
- /// ---
830
- /// purpose: 按团队持久化的 tmux endpoint 解析出后端,让 restart、add 与 fork 落在同一 socket
831
- /// params:
832
- /// team: 目标团队,None 时按唯一性选
833
- /// returns: 绑定到该 endpoint 的 tmux 后端;冷 workspace 无持久 endpoint 时退到按 workspace 派生
834
- /// errors: 团队目标歧义或未解析返回 TeamSelect;state 声明后端是 conpty 时也返回 TeamSelect 拒绝,不降级
835
- /// ---
836
- /// State-aware tmux backend resolver. Reads the team's persisted
837
- /// `tmux_endpoint` (set at `team-agent launch` time and shared across
838
- /// restart/add-agent/fork-agent) and constructs a TmuxBackend on THAT socket,
839
- /// so add-agent / fork-agent / restart all spawn into the SAME tmux socket
840
- /// the live team already runs on.
841
- ///
842
- /// First-agent / cold workspace (no persisted endpoint) safely falls back to
843
- /// `TmuxBackend::for_workspace(run_workspace)` — the canonical workspace-hash
844
- /// socket. No panic, no None.
845
- ///
846
- /// **Exposed `pub(crate)` for `lifecycle::launch::add_agent` / `fork_agent`
847
- /// (`0.3.24 add-agent socket drift fix`). Previously `pub(super)` and shared
848
- /// only within `lifecycle::restart`. Sharing the resolver across the lifecycle
849
- /// module is the correct ownership: restart/add/fork all need the SAME socket
850
- /// the live team uses, and duplicating the lookup invited drift.**
851
- /// 0.5.x Phase 1d Batch 1: this legacy resolver stays tmux-only. It
852
- /// still returns a concrete `TmuxBackend` because the 6 caller sites
853
- /// (rebuild/agent/remove/launch) currently call `TmuxBackend`-specific
854
- /// methods (`.tmux_endpoint()`, `.for_workspace()`, etc.). But it now
855
- /// routes through the factory so its **selection semantics** match
856
- /// the new `lifecycle_worker_transport_for_selected_state` API:
857
- ///
858
- /// - If `state.transport.kind` is `"conpty"`, this legacy tmux-typed
859
- /// resolver **fails-closed** with `TransportBackendKindMismatch`
860
- /// rather than silently returning a tmux backend that would
861
- /// spawn/inject into the wrong pane universe. That satisfies CR C-1
862
- /// fail-closed while the migration of caller sites to the generic
863
- /// `_transport_for_selected_state` API completes.
864
- /// - Otherwise (default/legacy tmux endpoint), behavior is preserved
865
- /// byte-for-byte through
866
- /// `tmux_backend_for_runtime_state_or_workspace`.
867
- pub(crate) fn lifecycle_worker_tmux_backend_for_selected_state(
868
- run_workspace: &Path,
869
- team: Option<&str>,
870
- ) -> Result<crate::tmux_backend::TmuxBackend, LifecycleError> {
871
- let (state, refusal) = crate::state::projection::resolve_team_scoped_state(run_workspace, team)
872
- .map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
873
- if let Some(refusal) = refusal {
874
- let reason = refusal
875
- .get("reason")
876
- .and_then(|v| v.as_str())
877
- .unwrap_or("team_target_unresolved");
878
- let detail = refusal
879
- .get("error")
880
- .or_else(|| refusal.get("message"))
881
- .and_then(|v| v.as_str())
882
- .unwrap_or("");
883
- return Err(LifecycleError::TeamSelect(format!("{reason}: {detail}")));
884
- }
885
- // CR C-1 fail-closed: state with `transport.kind=conpty` must NOT
886
- // silently downgrade to a tmux backend just because the caller
887
- // asked for the tmux-typed variant. Callers that see this refusal
888
- // are expected to migrate to `lifecycle_worker_transport_for_selected_state`
889
- // during Batch 2/3.
890
- if let Some(state_ref) = state.as_ref() {
891
- if let Some(kind) = state_ref
892
- .pointer("/transport/kind")
893
- .and_then(|v| v.as_str())
894
- {
895
- if kind.eq_ignore_ascii_case("conpty") {
896
- return Err(LifecycleError::TeamSelect(format!(
897
- "backend_kind_mismatch: state.transport.kind={kind:?} but the legacy \
898
- tmux-typed lifecycle resolver was invoked; caller must migrate to \
899
- `lifecycle_worker_transport_for_selected_state` (Phase 1d Batch 2/3)"
900
- )));
901
- }
902
- }
903
- }
904
- Ok(state
905
- .as_ref()
906
- .map(|state| lifecycle_worker_tmux_backend_for_state(run_workspace, state))
907
- .unwrap_or_else(|| crate::tmux_backend::TmuxBackend::for_workspace(run_workspace)))
908
- }
909
-
910
- /// ---
911
- /// purpose: 与上面同样的团队选择语义,但返回工厂解析出的通用 transport
912
- /// returns: 已解析的 transport,含后端种类、来源与提示
913
- /// errors: 团队选择失败或工厂拒绝时返回 TeamSelect,读 state 失败返回 StatePersist
914
- /// ---
915
- /// 0.5.x Phase 1d Batch 1: new generic-typed lifecycle resolver.
916
- ///
917
- /// Same team-selection semantics as the legacy tmux-typed variant, but
918
- /// returns a `ResolvedTransport` from the factory so callers that can
919
- /// hold `Box<dyn Transport>` (or the resolved `BackendKind`) work
920
- /// against both tmux AND conpty state. Caller migration to this API
921
- /// happens across Batch 2-5.
922
- ///
923
- /// Fail-closed rules follow the factory (C-1 ×2, C-2 CLI-vs-state,
924
- /// C-3 N38 notices via `ResolvedTransport.notices`).
925
- pub(crate) fn lifecycle_worker_transport_for_selected_state(
926
- run_workspace: &Path,
927
- team: Option<&str>,
928
- ) -> Result<crate::transport_factory::ResolvedTransport, LifecycleError> {
929
- let (state, refusal) = crate::state::projection::resolve_team_scoped_state(run_workspace, team)
930
- .map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
931
- if let Some(refusal) = refusal {
932
- let reason = refusal
933
- .get("reason")
934
- .and_then(|v| v.as_str())
935
- .unwrap_or("team_target_unresolved");
936
- let detail = refusal
937
- .get("error")
938
- .or_else(|| refusal.get("message"))
939
- .and_then(|v| v.as_str())
940
- .unwrap_or("");
941
- return Err(LifecycleError::TeamSelect(format!("{reason}: {detail}")));
942
- }
943
- let input = crate::transport_factory::TransportFactoryInput::new(
944
- run_workspace,
945
- crate::transport_factory::TransportPurpose::LifecycleWorker,
946
- )
947
- .with_team_key(team)
948
- .with_state(state.as_ref());
949
- crate::transport_factory::resolve_transport(input)
950
- .map_err(|e| LifecycleError::TeamSelect(e.to_string()))
951
- }
952
-
953
- /// ---
954
- /// purpose: 由已取到的 state 解析 tmux 后端与它的来源
955
- /// returns: 后端与 endpoint 来源
956
- /// errors: state 声明后端是 conpty 时返回 TeamSelect
957
- /// ---
958
- pub(crate) fn lifecycle_worker_tmux_backend_selection_for_state(
959
- run_workspace: &Path,
960
- state: &serde_json::Value,
961
- ) -> Result<crate::tmux_backend::RuntimeTmuxBackendSelection, LifecycleError> {
962
- if let Some(kind) = state.pointer("/transport/kind").and_then(|v| v.as_str()) {
963
- if kind.eq_ignore_ascii_case("conpty") {
964
- return Err(LifecycleError::TeamSelect(format!(
965
- "backend_kind_mismatch: state.transport.kind={kind:?} but the legacy \
966
- tmux-typed lifecycle resolver was invoked; caller must migrate to \
967
- `lifecycle_worker_transport_for_selected_state` (Phase 1d Batch 2/3)"
968
- )));
969
- }
970
- }
971
- Ok(
972
- crate::tmux_backend::tmux_backend_for_runtime_state_or_workspace(
973
- run_workspace,
974
- Some(state),
975
- ),
976
- )
977
- }
978
-
979
- /// ---
980
- /// purpose: 由已取到的 state 直接给出 tmux 后端
981
- /// returns: 绑定到该 state endpoint 的后端,缺失时按 workspace 派生
982
- /// ---
983
- pub(super) fn lifecycle_worker_tmux_backend_for_state(
984
- run_workspace: &Path,
985
- state: &serde_json::Value,
986
- ) -> crate::tmux_backend::TmuxBackend {
987
- crate::tmux_backend::tmux_backend_for_runtime_state_or_workspace(run_workspace, Some(state))
988
- .backend
989
- }
990
-
991
- /// ---
992
- /// purpose: 同步团队投影后落盘 restart 结果
993
- /// params:
994
- /// topology_authority_agent_ids: 本次以内存值为拓扑权威的席位
995
- /// returns: 成功返回空值
996
- /// errors: 落盘失败时返回 StatePersist
997
- /// contract_id: lifecycle.common.save_restart_projected_state
998
- /// ---
999
- pub(super) fn save_restart_projected_state(
1000
- workspace: &Path,
1001
- state: &mut serde_json::Value,
1002
- team_key: &str,
1003
- topology_authority_agent_ids: &[&str],
1004
- ) -> Result<(), LifecycleError> {
1005
- save_restart_projected_state_with_capture_backfill_skip(
1006
- workspace,
1007
- state,
1008
- team_key,
1009
- &[],
1010
- topology_authority_agent_ids,
1011
- )
1012
- }
1013
-
1014
- /// ---
1015
- /// purpose: 同上,并可指定哪些席位跳过会话捕获回填
1016
- /// params:
1017
- /// skip_capture_backfill_agent_ids: 跳过回填的席位
1018
- /// returns: 成功返回空值
1019
- /// errors: 落盘失败时返回 StatePersist
1020
- /// contract_id: lifecycle.common.save_restart_projected_state
1021
- /// ---
1022
- pub(super) fn save_restart_projected_state_with_capture_backfill_skip(
1023
- workspace: &Path,
1024
- state: &mut serde_json::Value,
1025
- team_key: &str,
1026
- skip_capture_backfill_agent_ids: &[&str],
1027
- topology_authority_agent_ids: &[&str],
1028
- ) -> Result<(), LifecycleError> {
1029
- sync_restart_team_projections(state, team_key);
1030
- crate::state::repository::StateRepository::new(workspace)
1031
- .save(
1032
- crate::state::repository::StateWriteIntent::RestartTeam {
1033
- team_key,
1034
- topology_authority_agent_ids,
1035
- skip_capture_backfill_agent_ids,
1036
- },
1037
- state,
1038
- )
1039
- .map_err(|e| LifecycleError::StatePersist(e.to_string()))
1040
- }
1041
-
1042
- /// ---
1043
- /// purpose: 定出本次投影使用的团队键
1044
- /// returns: 显式 team 优先,其次 state 里的活跃键,最后由 state 推算
1045
- /// ---
1046
- pub(super) fn restart_projection_team_key(state: &serde_json::Value, team: Option<&str>) -> String {
1047
- team.filter(|key| !key.is_empty())
1048
- .map(str::to_string)
1049
- .or_else(|| {
1050
- state
1051
- .get("active_team_key")
1052
- .and_then(serde_json::Value::as_str)
1053
- .filter(|key| !key.is_empty())
1054
- .map(str::to_string)
1055
- })
1056
- .unwrap_or_else(|| crate::state::projection::team_state_key(state))
1057
- }
1058
-
1059
- /// ---
1060
- /// purpose: 把当前顶层状态压实后写回 teams 表
1061
- /// params:
1062
- /// state: 就地改写;显式团队键允许覆盖或新建,别名键只在盘上已有且身份不冲突时才写
1063
- /// returns: teams 表缺失或为空时不动
1064
- /// ---
1065
- pub(super) fn sync_restart_team_projections(state: &mut serde_json::Value, team_key: &str) {
1066
- let Some(teams) = state.get("teams").and_then(serde_json::Value::as_object) else {
1067
- return;
1068
- };
1069
- if teams.is_empty() {
1070
- return;
1071
- }
1072
- let compact = crate::state::projection::compact_team_state(state);
1073
- let active_key = state
1074
- .get("active_team_key")
1075
- .and_then(serde_json::Value::as_str)
1076
- .filter(|key| !key.is_empty())
1077
- .map(str::to_string);
1078
- let derived_key = crate::state::projection::team_state_key(state);
1079
- let Some(teams) = state
1080
- .get_mut("teams")
1081
- .and_then(serde_json::Value::as_object_mut)
1082
- else {
1083
- return;
1084
- };
1085
- // 0.5.28 (`.team/artifacts/0527-realfail-layer2-leader-locate.md` §3):
1086
- // 显式 team_key = 操作目标,始终允许覆盖 / 新建(该 helper 的正当职责)。
1087
- // active/derived/"current" 三种别名兜底 = alias-identity 家族第三例,只有
1088
- // 「盘上已有该 alias 条目」且「其身份与 compact 不冲突」时才允许写,
1089
- // 避免 0.5.26 起死 sibling 保留时被活队 compact 硬克隆。禁止 alias 新建条目。
1090
- let mut keys = Vec::new();
1091
- let mut explicit = false;
1092
- if !team_key.is_empty() {
1093
- keys.push(team_key.to_string());
1094
- explicit = true;
1095
- }
1096
- if let Some(active_key) = active_key {
1097
- keys.push(active_key);
1098
- }
1099
- if !derived_key.is_empty() {
1100
- keys.push(derived_key);
1101
- }
1102
- if teams.contains_key("current") {
1103
- keys.push("current".to_string());
1104
- }
1105
- keys.sort();
1106
- keys.dedup();
1107
- for key in keys {
1108
- let is_operation_target = explicit && key == team_key;
1109
- if is_operation_target {
1110
- teams.insert(key, compact.clone());
1111
- continue;
1112
- }
1113
- let Some(existing) = teams.get(&key) else {
1114
- // 别名条目不存在:不新建,避免把 hack alias 变成真队。
1115
- continue;
1116
- };
1117
- if json_team_identity_matches(existing, &compact) {
1118
- teams.insert(key, compact.clone());
1119
- }
1120
- }
1121
- }
1122
-
1123
- /// 0.5.28: 别名同步身份门。比较 existing 条目与 compact(即将写入)四个身份字段:
1124
- /// `team_key`/`session_name`/`team_dir`/`spec_path`。legacy 缺字段容忍(两侧任一
1125
- /// 缺则该字段不参与判定);已有字段必须相等,冲突即拒绝覆盖。
1126
- fn json_team_identity_matches(existing: &serde_json::Value, compact: &serde_json::Value) -> bool {
1127
- const FIELDS: &[&str] = &["team_key", "session_name", "team_dir", "spec_path"];
1128
- for field in FIELDS {
1129
- let lhs = existing
1130
- .get(field)
1131
- .and_then(serde_json::Value::as_str)
1132
- .filter(|s| !s.is_empty());
1133
- let rhs = compact
1134
- .get(field)
1135
- .and_then(serde_json::Value::as_str)
1136
- .filter(|s| !s.is_empty());
1137
- match (lhs, rhs) {
1138
- (Some(a), Some(b)) if a != b => return false,
1139
- _ => {}
1140
- }
1141
- }
1142
- true
1143
- }
1144
-
1145
- /// ---
1146
- /// purpose: 取 state 里的 session 名
1147
- /// returns: 非空的 session_name,缺失时退到默认名
1148
- /// ---
1149
- pub(super) fn state_session_name(state: &serde_json::Value) -> SessionName {
1150
- state
1151
- .get("session_name")
1152
- .and_then(|v| v.as_str())
1153
- .filter(|s| !s.is_empty())
1154
- .or_else(|| {
1155
- state
1156
- .get("leader_receiver")
1157
- .and_then(|receiver| receiver.get("session_name"))
1158
- .and_then(|v| v.as_str())
1159
- .filter(|s| !s.is_empty())
1160
- })
1161
- .map(SessionName::new)
1162
- .unwrap_or_else(|| SessionName::new("team-agent"))
1163
- }
1164
-
1165
- /// ---
1166
- /// purpose: 判断 state 里是否记了非空 session 名
1167
- /// returns: 记了则 true
1168
- /// ---
1169
- pub(super) fn session_name_present(state: &serde_json::Value) -> bool {
1170
- state
1171
- .get("session_name")
1172
- .and_then(|v| v.as_str())
1173
- .map(|s| !s.is_empty())
1174
- .unwrap_or(false)
1175
- }
1176
-
1177
- /// Persist the session actually used for spawn when the selected team only
1178
- /// had it on `leader_receiver`. Send/status route on `session_name`; an
1179
- /// explicit null must stay a miss and must not rewrite a sibling team.
1180
- pub(super) fn persist_selected_receiver_session_name(
1181
- state: &mut serde_json::Value,
1182
- session: &SessionName,
1183
- ) {
1184
- if session_name_present(state) {
1185
- return;
1186
- }
1187
- let Some(from_receiver) = state
1188
- .get("leader_receiver")
1189
- .and_then(|receiver| receiver.get("session_name"))
1190
- .and_then(serde_json::Value::as_str)
1191
- .filter(|name| !name.is_empty())
1192
- else {
1193
- return;
1194
- };
1195
- if from_receiver != session.as_str() {
1196
- return;
1197
- }
1198
- if let Some(object) = state.as_object_mut() {
1199
- object.insert(
1200
- "session_name".to_string(),
1201
- serde_json::json!(session.as_str()),
1202
- );
1203
- }
1204
- }
1205
-
1206
- /// ---
1207
- /// purpose: 探测 session 是否存活
1208
- /// params:
1209
- /// default: 探测本身 panic 时采用的兜底判定
1210
- /// returns: transport 明确回答时用它;返回错误时判为不存活;探测 panic 时用兜底值
1211
- /// ---
1212
- pub(super) fn session_live_or_default(
1213
- transport: &dyn crate::transport::Transport,
1214
- session_name: &SessionName,
1215
- default: bool,
1216
- ) -> bool {
1217
- match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1218
- transport.has_session(session_name)
1219
- })) {
1220
- Ok(Ok(live)) => live,
1221
- Ok(Err(_)) => false,
1222
- Err(_) => default,
1223
- }
1224
- }
1225
-
1226
- /// ---
1227
- /// purpose: 取席位行的 provider
1228
- /// returns: 解析成功用它,缺失或不认识时退到已退役的 legacy codex 键(其后一律拒绝,不会起席)
1229
- /// ---
1230
- pub(super) fn agent_provider(agent: &serde_json::Value) -> Provider {
1231
- agent
1232
- .get("provider")
1233
- .and_then(|v| v.as_str())
1234
- .and_then(parse_provider)
1235
- .unwrap_or(Provider::Codex)
1236
- }
1237
-
1238
- /// ---
1239
- /// purpose: 取席位行的 auth_mode
1240
- /// returns: 解析成功用它,缺失或不认识时退到 subscription
1241
- /// ---
1242
- pub(super) fn agent_auth_mode(agent: &serde_json::Value) -> AuthMode {
1243
- agent
1244
- .get("auth_mode")
1245
- .and_then(|v| v.as_str())
1246
- .and_then(parse_auth_mode)
1247
- .unwrap_or(AuthMode::Subscription)
1248
- }
1249
-
1250
- /// ---
1251
- /// purpose: 取席位行记录的会话 id
1252
- /// returns: 非空时返回,否则 None
1253
- /// ---
1254
- pub(super) fn agent_session_id(agent: &serde_json::Value) -> Option<SessionId> {
1255
- agent
1256
- .get("session_id")
1257
- .and_then(|v| v.as_str())
1258
- .filter(|s| !s.is_empty())
1259
- .map(SessionId::new)
1260
- }
1261
-
1262
- /// ---
1263
- /// purpose: 取席位行记录的 rollout 路径
1264
- /// returns: 非空时返回,否则 None
1265
- /// ---
1266
- pub(super) fn agent_rollout_path(agent: &serde_json::Value) -> Option<RolloutPath> {
1267
- agent
1268
- .get("rollout_path")
1269
- .and_then(|v| v.as_str())
1270
- .filter(|s| !s.is_empty())
1271
- .map(RolloutPath::new)
1272
- }
1273
-
1274
- /// ---
1275
- /// purpose: 判断该席位的 resume 依据是否存在
1276
- /// returns: 探测结果里的存在位
1277
- /// ---
1278
- pub(super) fn resume_backing_exists_for_agent(
1279
- workspace: &Path,
1280
- agent_id: &AgentId,
1281
- agent: &serde_json::Value,
1282
- provider: Provider,
1283
- session_id: &SessionId,
1284
- rollout_path: Option<&RolloutPath>,
1285
- ) -> bool {
1286
- resume_backing_probe_for_agent(
1287
- workspace,
1288
- agent_id,
1289
- agent,
1290
- provider,
1291
- session_id,
1292
- rollout_path,
1293
- )
1294
- .exists
1295
- }
1296
-
1297
- /// Layer 2 self-healing (leader follow-up 2026-06-22): result of probing
1298
- /// the provider backing store for a resumable session. `checked_paths`
1299
- /// reports every path the runtime probed so the operator can see WHICH
1300
- /// places we looked — surfaced into the
1301
- /// `ResumeRefusalReason::SessionBackingStoreMissing.checked_paths`
1302
- /// field, the CLI JSON `unresumable[].checked_paths` array, and the
1303
- /// `restart.resume_decision` event payload.
1304
- #[derive(Debug, Clone, PartialEq, Eq)]
1305
- pub(super) struct BackingProbeResult {
1306
- pub exists: bool,
1307
- pub checked_paths: Vec<PathBuf>,
1308
- }
1309
-
1310
- #[derive(Debug, Clone, PartialEq, Eq)]
1311
- pub(crate) struct SessionIdentityProbeResult {
1312
- pub identity_ok: Option<bool>,
1313
- pub embedded_agent_id: Option<String>,
1314
- pub rollout_path: Option<PathBuf>,
1315
- }
1316
-
1317
- /// ---
1318
- /// purpose: 探测 rollout 文件里嵌的席位身份是否与本席位一致
1319
- /// params:
1320
- /// _provider: 未参与判定
1321
- /// rollout_path: 没有路径时三项都返回未知
1322
- /// returns: 一致性判定、读到的嵌入席位名与实际探测路径;读不出嵌入身份时一致性为未知
1323
- /// ---
1324
- pub(crate) fn session_identity_probe_for_agent(
1325
- agent_id: &AgentId,
1326
- _provider: Provider,
1327
- rollout_path: Option<&RolloutPath>,
1328
- ) -> SessionIdentityProbeResult {
1329
- let Some(path) = rollout_path.map(RolloutPath::as_path) else {
1330
- return SessionIdentityProbeResult {
1331
- identity_ok: None,
1332
- embedded_agent_id: None,
1333
- rollout_path: None,
1334
- };
1335
- };
1336
- let embedded_agent_id =
1337
- crate::provider::session_scan::common::rollout_path_embedded_team_agent_worker_id(path);
1338
- let identity_ok = embedded_agent_id
1339
- .as_deref()
1340
- .map(|embedded| embedded == agent_id.as_str());
1341
- SessionIdentityProbeResult {
1342
- identity_ok,
1343
- embedded_agent_id,
1344
- rollout_path: Some(path.to_path_buf()),
1345
- }
1346
- }
1347
-
1348
- /// ---
1349
- /// purpose: 将合法 Pi fork 血统纳入共享会话身份判定
1350
- /// params:
1351
- /// workspace/state/agent: 当前被验证席位及同队来源记录
1352
- /// rollout_path: 当前席位的精确 backing
1353
- /// returns: 字面身份一致,或经独立 Pi backing 与 fork 血统验证后合法继承时为 true
1354
- /// ---
1355
- pub(crate) fn session_identity_probe_for_agent_with_fork_ancestry(
1356
- workspace: &Path,
1357
- state: &serde_json::Value,
1358
- agent_id: &AgentId,
1359
- agent: &serde_json::Value,
1360
- provider: Provider,
1361
- rollout_path: Option<&RolloutPath>,
1362
- ) -> SessionIdentityProbeResult {
1363
- let mut probe = session_identity_probe_for_agent(agent_id, provider, rollout_path);
1364
- if probe.identity_ok != Some(false)
1365
- || !pi_fork_ancestor_identity_is_valid(
1366
- workspace,
1367
- state,
1368
- agent_id,
1369
- agent,
1370
- provider,
1371
- rollout_path,
1372
- probe.embedded_agent_id.as_deref(),
1373
- )
1374
- {
1375
- return probe;
1376
- }
1377
- probe.identity_ok = Some(true);
1378
- probe
1379
- }
1380
-
1381
- fn pi_fork_ancestor_identity_is_valid(
1382
- workspace: &Path,
1383
- state: &serde_json::Value,
1384
- agent_id: &AgentId,
1385
- agent: &serde_json::Value,
1386
- provider: Provider,
1387
- rollout_path: Option<&RolloutPath>,
1388
- embedded_agent_id: Option<&str>,
1389
- ) -> bool {
1390
- if provider != Provider::Pi
1391
- || agent.get("attribution_ambiguous").and_then(serde_json::Value::as_bool) == Some(true)
1392
- || agent.get("capture_state").and_then(serde_json::Value::as_str)
1393
- == Some("attribution_ambiguous")
1394
- || !matches!(
1395
- agent
1396
- .get("attribution_confidence")
1397
- .and_then(serde_json::Value::as_str),
1398
- Some("high" | "medium")
1399
- )
1400
- {
1401
- return false;
1402
- }
1403
- let (Some(embedded_agent_id), Some(forked_from), Some(target_path)) = (
1404
- embedded_agent_id,
1405
- agent
1406
- .get("forked_from")
1407
- .and_then(serde_json::Value::as_str)
1408
- .filter(|value| !value.is_empty()),
1409
- rollout_path.map(RolloutPath::as_path),
1410
- ) else {
1411
- return false;
1412
- };
1413
- if forked_from != embedded_agent_id || forked_from == agent_id.as_str() {
1414
- return false;
1415
- }
1416
- let Some(source_agent) = state
1417
- .get("agents")
1418
- .and_then(|agents| agents.get(forked_from))
1419
- .filter(|source| agent_provider(source) == Provider::Pi)
1420
- else {
1421
- return false;
1422
- };
1423
- let Some(source_path) = agent_rollout_path(source_agent) else {
1424
- return false;
1425
- };
1426
- if source_path.as_path() == target_path {
1427
- return false;
1428
- }
1429
- let (Some(session_id), Ok(target_path), Some(target_root)) = (
1430
- agent_session_id(agent),
1431
- std::fs::canonicalize(target_path),
1432
- agent
1433
- .get("claude_projects_root")
1434
- .and_then(serde_json::Value::as_str)
1435
- .filter(|path| !path.is_empty())
1436
- .map(std::path::PathBuf::from),
1437
- ) else {
1438
- return false;
1439
- };
1440
- let Ok(target_root) = std::fs::canonicalize(target_root) else {
1441
- return false;
1442
- };
1443
- if !target_path.starts_with(target_root)
1444
- || std::fs::canonicalize(source_path.as_path())
1445
- .is_ok_and(|source_path| source_path == target_path)
1446
- || !resume_backing_probe_for_agent(
1447
- workspace,
1448
- agent_id,
1449
- agent,
1450
- provider,
1451
- &session_id,
1452
- rollout_path,
1453
- )
1454
- .exists
1455
- {
1456
- return false;
1457
- }
1458
- true
1459
- }
1460
-
1461
- /// ---
1462
- /// purpose: 按 provider 分支探测 resume 依据,并记录所有查过的路径
1463
- /// returns: 存在位与查过的路径列表;持久化的 rollout 路径即使不存在也记进列表
1464
- /// ---
1465
- pub(super) fn resume_backing_probe_for_agent(
1466
- workspace: &Path,
1467
- agent_id: &AgentId,
1468
- agent: &serde_json::Value,
1469
- provider: Provider,
1470
- session_id: &SessionId,
1471
- rollout_path: Option<&RolloutPath>,
1472
- ) -> BackingProbeResult {
1473
- let mut checked_paths: Vec<PathBuf> = Vec::new();
1474
-
1475
- // Always record the persisted rollout_path even when it does not
1476
- // exist — that "we looked here" tells the operator that state has a
1477
- // pointer but the file is gone.
1478
- if let Some(path) = rollout_path.map(RolloutPath::as_path) {
1479
- checked_paths.push(path.to_path_buf());
1480
- }
1481
-
1482
- let exists = match provider {
1483
- provider if !provider_supports_resume(provider) => {
1484
- let _ = (workspace, agent_id, agent, session_id, rollout_path);
1485
- false
1486
- }
1487
- Provider::Claude | Provider::ClaudeCode => {
1488
- let rollout_ok = rollout_path_exists(rollout_path);
1489
- let projects_root = claude_projects_root_for_agent(agent);
1490
- if let Some(root) = projects_root.as_ref() {
1491
- checked_paths.push(root.clone());
1492
- }
1493
- let event_log_path = workspace.join(".team/logs/events.jsonl");
1494
- checked_paths.push(event_log_path);
1495
- rollout_ok
1496
- || event_log_transcript_exists(workspace, agent_id.as_str(), session_id.as_str())
1497
- || projects_root.is_some_and(|root| {
1498
- claude_project_transcript_exists_under(&root, session_id.as_str())
1499
- })
1500
- }
1501
- Provider::Copilot => {
1502
- if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
1503
- checked_paths.push(home.join(".copilot/session-store.db"));
1504
- }
1505
- copilot_session_store_has_session(session_id.as_str())
1506
- }
1507
- Provider::Pi => {
1508
- let spawn_cwd = agent
1509
- .get("spawn_cwd")
1510
- .and_then(serde_json::Value::as_str)
1511
- .filter(|value| !value.is_empty())
1512
- .map(PathBuf::from)
1513
- .unwrap_or_else(|| workspace.to_path_buf());
1514
- rollout_path.is_some_and(|path| {
1515
- crate::provider::session_scan::pi::validate_exact_backing(
1516
- path.as_path(),
1517
- session_id,
1518
- &spawn_cwd,
1519
- )
1520
- .is_ok()
1521
- })
1522
- }
1523
- // Codex and Grok workers run only through their contract leaves.
1524
- Provider::Codex | Provider::Grok | Provider::GeminiCli | Provider::Fake => false,
1525
- };
1526
-
1527
- // Deduplicate while preserving order (HashSet would lose deterministic
1528
- // ordering needed for stable JSON/event output).
1529
- let mut seen: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
1530
- checked_paths.retain(|p| seen.insert(p.clone()));
1531
-
1532
- BackingProbeResult {
1533
- exists,
1534
- checked_paths,
1535
- }
1536
- }
1537
-
1538
- /// ---
1539
- /// purpose: 判断该 provider 是否支持 resume
1540
- /// returns: 由 provider 适配器的能力位给出
1541
- /// contract_id: lifecycle.common.provider_supports_resume
1542
- /// ---
1543
- pub(super) fn provider_supports_resume(provider: Provider) -> bool {
1544
- crate::provider::get_adapter(provider).caps().resume
1545
- }
1546
-
1547
- /// ---
1548
- /// purpose: 由 provider wire 名判断是否支持 resume
1549
- /// returns: 名字不认识时为 false
1550
- /// contract_id: lifecycle.common.provider_supports_resume
1551
- /// ---
1552
- pub(super) fn provider_wire_supports_resume(provider: &str) -> bool {
1553
- parse_provider(provider)
1554
- .map(provider_supports_resume)
1555
- .unwrap_or(false)
1556
- }
1557
-
1558
- fn rollout_path_exists(rollout_path: Option<&RolloutPath>) -> bool {
1559
- rollout_path
1560
- .as_ref()
1561
- .is_some_and(|path| path.as_path().exists())
1562
- }
1563
-
1564
- fn event_log_transcript_exists(workspace: &Path, agent_id: &str, session_id: &str) -> bool {
1565
- let Ok(events) = crate::event_log::EventLog::new(workspace).tail(0) else {
1566
- return false;
1567
- };
1568
- events.iter().rev().any(|event| {
1569
- event.get("event").and_then(serde_json::Value::as_str) == Some("session.captured")
1570
- && ["agent_id", "worker_id"]
1571
- .iter()
1572
- .any(|key| event.get(*key).and_then(serde_json::Value::as_str) == Some(agent_id))
1573
- && event.get("session_id").and_then(serde_json::Value::as_str) == Some(session_id)
1574
- && event_transcript_path(event).is_some_and(|path| path.exists())
1575
- })
1576
- }
1577
-
1578
- fn event_transcript_path(event: &serde_json::Value) -> Option<PathBuf> {
1579
- event
1580
- .get("rollout_path")
1581
- .or_else(|| event.get("transcript_path"))
1582
- .and_then(serde_json::Value::as_str)
1583
- .filter(|path| !path.is_empty())
1584
- .map(PathBuf::from)
1585
- }
1586
-
1587
- /// E36 fix-B: a real Claude worker writes its session transcript to
1588
- /// `<claude_projects_root>/<workspace-slug>/<session_id>.jsonl` even when neither
1589
- /// `rollout_path` was persisted to state nor a `session.captured` event was logged.
1590
- /// That landed transcript is itself a valid resume backing — restart was wrongly
1591
- /// refusing resumable workers because it only checked the two paths above. Scan the
1592
- /// projects root recursively for `<session_id>.jsonl` (session_id is a unique UUID,
1593
- /// so we avoid recomputing the project-dir slug, which is brittle for non-ASCII
1594
- /// workspace paths).
1595
- fn claude_project_transcript_exists(agent: &serde_json::Value, session_id: &str) -> bool {
1596
- let Some(root) = claude_projects_root_for_agent(agent) else {
1597
- return false;
1598
- };
1599
- claude_project_transcript_exists_under(&root, session_id)
1600
- }
1601
-
1602
- fn claude_projects_root_for_agent(agent: &serde_json::Value) -> Option<PathBuf> {
1603
- agent
1604
- .get("claude_projects_root")
1605
- .and_then(serde_json::Value::as_str)
1606
- .filter(|value| !value.is_empty())
1607
- .map(PathBuf::from)
1608
- .or_else(|| {
1609
- std::env::var_os("HOME")
1610
- .map(|home| PathBuf::from(home).join(".claude").join("projects"))
1611
- })
1612
- }
1613
-
1614
- fn claude_project_transcript_exists_under(projects_root: &Path, session_id: &str) -> bool {
1615
- if session_id.is_empty() {
1616
- return false;
1617
- }
1618
- if !projects_root.is_dir() {
1619
- return false;
1620
- }
1621
- let transcript_name = format!("{session_id}.jsonl");
1622
- let Ok(project_dirs) = std::fs::read_dir(projects_root) else {
1623
- return false;
1624
- };
1625
- project_dirs
1626
- .flatten()
1627
- .filter(|entry| entry.path().is_dir())
1628
- .any(|entry| entry.path().join(&transcript_name).is_file())
1629
- }
1630
-
1631
- fn copilot_session_store_has_session(session_id: &str) -> bool {
1632
- let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
1633
- return false;
1634
- };
1635
- let db_path = home.join(".copilot").join("session-store.db");
1636
- if !db_path.exists() {
1637
- return false;
1638
- }
1639
- let Ok(conn) = rusqlite::Connection::open_with_flags(
1640
- db_path,
1641
- rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
1642
- ) else {
1643
- return false;
1644
- };
1645
- conn.query_row(
1646
- "select 1 from sessions where id = ?1 limit 1",
1647
- [session_id],
1648
- |_| Ok(()),
1649
- )
1650
- .is_ok()
1651
- }
1652
-
1653
- /// ---
1654
- /// purpose: 对缺会话的席位做一次捕获尝试
1655
- /// params:
1656
- /// state: 就地改写
1657
- /// returns: 本次是否改动了 state
1658
- /// errors: 捕获过程出错时返回 Provider
1659
- /// ---
1660
- pub(crate) fn refresh_missing_provider_sessions(
1661
- state: &mut serde_json::Value,
1662
- ) -> Result<bool, LifecycleError> {
1663
- crate::session_capture::capture_missing_provider_sessions_once(
1664
- state,
1665
- &mut crate::provider::get_adapter,
1666
- false,
1667
- 0,
1668
- )
1669
- .map(|report| report.changed)
1670
- .map_err(|e| LifecycleError::Provider(e.to_string()))
1671
- }
1672
-
1673
- /// ---
1674
- /// purpose: 有界等待缺会话席位收敛,并逐轮写进度事件
1675
- /// params:
1676
- /// deadline: 等待上限
1677
- /// poll_interval: 轮询间隔
1678
- /// allow_fresh: 只写进事件载荷,不改变收敛判定
1679
- /// returns: 收敛结论
1680
- /// errors: 收敛过程出错时返回 StatePersist
1681
- /// ---
1682
- pub(crate) fn converge_missing_provider_sessions(
1683
- state: &mut serde_json::Value,
1684
- deadline: std::time::Duration,
1685
- poll_interval: std::time::Duration,
1686
- workspace: &Path,
1687
- allow_fresh: bool,
1688
- ) -> Result<crate::session_capture::SessionConvergence, LifecycleError> {
1689
- crate::session_capture::converge_missing_provider_sessions(
1690
- state,
1691
- &mut crate::provider::get_adapter,
1692
- deadline,
1693
- poll_interval,
1694
- restart_required_missing_session_agent_ids,
1695
- |progress| {
1696
- write_session_convergence_progress_event(
1697
- workspace,
1698
- serde_json::json!({
1699
- "iteration": progress.iteration,
1700
- "elapsed_ms": progress.elapsed_ms,
1701
- "deadline_ms": progress.deadline_ms,
1702
- "changed": progress.changed,
1703
- "assigned": progress.assigned,
1704
- "missing": progress.missing,
1705
- "required_missing_agent_ids": progress.required_missing_agent_ids,
1706
- "pending_agent_ids": progress.pending_agent_ids,
1707
- "candidate_count_by_agent": progress.candidate_count_by_agent,
1708
- "remaining_ms": progress.remaining_ms,
1709
- "allow_fresh": allow_fresh,
1710
- }),
1711
- )
1712
- },
1713
- )
1714
- .map_err(LifecycleError::StatePersist)
1715
- }
1716
-
1717
- fn write_session_convergence_progress_event(
1718
- workspace: &Path,
1719
- fields: serde_json::Value,
1720
- ) -> Result<(), String> {
1721
- crate::event_log::EventLog::new(workspace)
1722
- .write(crate::event_log::PROVIDER_SESSION_CONVERGING, fields)
1723
- .map(|_| ())
1724
- .map_err(|e| e.to_string())
1725
- }
1726
-
1727
- /// ---
1728
- /// purpose: 列出必须等到会话收敛才能 restart 的席位
1729
- /// returns: 排序后的席位 id;只保留无会话、状态为 running 且确有待保留上下文的席位,从未捕获过的席位不进入
1730
- /// ---
1731
- pub(crate) fn restart_required_missing_session_agent_ids(state: &serde_json::Value) -> Vec<String> {
1732
- let mut missing = crate::session_capture::incomplete_resumable_agent_ids(state)
1733
- .into_iter()
1734
- .filter(|agent_id| {
1735
- let Some(agent) = state.get("agents").and_then(|agents| agents.get(agent_id)) else {
1736
- return false;
1737
- };
1738
- let missing_session_id = agent
1739
- .get("session_id")
1740
- .and_then(|value| value.as_str())
1741
- .is_none_or(|session| session.is_empty());
1742
- let is_running = agent
1743
- .get("status")
1744
- .and_then(|value| value.as_str())
1745
- .is_some_and(|status| status == "running");
1746
- // E6 层2 (C2) + RESTART-RESUME-001 (0.4.8): required-missing
1747
- // predicate gates on session_id absence + running, but ALSO
1748
- // skips never-captured workers (no session_id AND no context
1749
- // signals at all). A never-captured worker has nothing to
1750
- // lose by fresh-start, so it must not block convergence and
1751
- // burn the capture deadline. This matches the selection-stage
1752
- // partial-resume semantic in
1753
- // selection.rs::classify_resume_decision (never_captured →
1754
- // FreshStart without --allow-fresh).
1755
- //
1756
- // The "has context to preserve" signal is the shared
1757
- // restart_agent_has_context_to_preserve helper: first_send_at
1758
- // (leader→worker delivery), last_result_at (MCP report path
1759
- // that may skip first_send_at), or task_prompt_delivered.
1760
- // Only context-bearing null-session workers continue to
1761
- // require convergence (so we never silently drop context).
1762
- missing_session_id
1763
- && is_running
1764
- && !super::selection::restart_agent_never_captured(agent, None)
1765
- })
1766
- .collect::<Vec<_>>();
1767
- missing.sort();
1768
- missing
1769
- }
1770
- /// ---
1771
- /// purpose: 取该席位的窗口名
1772
- /// returns: 席位行里的非空 window,缺失时用席位 id
1773
- /// ---
1774
- pub(super) fn agent_window(agent: &serde_json::Value, agent_id: &AgentId) -> String {
1775
- agent
1776
- .get("window")
1777
- .and_then(|v| v.as_str())
1778
- .filter(|s| !s.is_empty())
1779
- .unwrap_or_else(|| agent_id.as_str())
1780
- .to_string()
1781
- }
1782
-
1783
- pub(super) use crate::provider::wire::{parse_provider, provider_wire};
1784
-
1785
- /// ---
1786
- /// purpose: 把 auth_mode 字符串解析成枚举
1787
- /// returns: 只认三种取值,未知返回 None
1788
- /// ---
1789
- pub(super) fn parse_auth_mode(raw: &str) -> Option<AuthMode> {
1790
- match raw {
1791
- "subscription" => Some(AuthMode::Subscription),
1792
- "official_api" => Some(AuthMode::OfficialApi),
1793
- "compatible_api" => Some(AuthMode::CompatibleApi),
1794
- _ => None,
1795
- }
1796
- }
1797
-
1798
- /// ---
1799
- /// purpose: 从给定目录读出 team spec
1800
- /// returns: 解析后的 YAML
1801
- /// errors: 文件不存在返回 TeamSelect,读文件或解析失败返回 Compile
1802
- /// ---
1803
- pub(super) fn load_team_spec(workspace: &Path) -> Result<YamlValue, LifecycleError> {
1804
- let spec_path = workspace.join("team.spec.yaml");
1805
- if !spec_path.exists() {
1806
- return Err(LifecycleError::TeamSelect(format!(
1807
- "missing spec: {}",
1808
- spec_path.display()
1809
- )));
1810
- }
1811
- let text = std::fs::read_to_string(&spec_path)
1812
- .map_err(|e| LifecycleError::Compile(format!("{}: {e}", spec_path.display())))?;
1813
- yaml::loads(&text).map_err(|e| LifecycleError::Compile(e.to_string()))
1814
- }
1815
-
1816
- /// ---
1817
- /// purpose: 在 spec 的 agents 列表里找该席位
1818
- /// returns: 命中的节点;该 id 其实是 leader 时返回 None
1819
- /// ---
1820
- pub(super) fn find_spec_agent<'a>(
1821
- spec: &'a YamlValue,
1822
- agent_id: &AgentId,
1823
- ) -> Option<&'a YamlValue> {
1824
- let leader_is_agent = spec
1825
- .get("leader")
1826
- .and_then(|v| v.get("id"))
1827
- .and_then(YamlValue::as_str)
1828
- .map(|id| id == agent_id.as_str())
1829
- .unwrap_or(false);
1830
- if leader_is_agent {
1831
- return None;
1832
- }
1833
- spec.get("agents")?.as_list()?.iter().find(|agent| {
1834
- agent
1835
- .get("id")
1836
- .and_then(YamlValue::as_str)
1837
- .map(|id| id == agent_id.as_str())
1838
- .unwrap_or(false)
1839
- })
1840
- }
1841
-
1842
- /// ---
1843
- /// purpose: 构造未知席位的错误
1844
- /// returns: 带席位 id 的 RequirementUnmet
1845
- /// ---
1846
- pub(super) fn unknown_worker(agent_id: &AgentId) -> LifecycleError {
1847
- LifecycleError::RequirementUnmet(format!("unknown worker agent id: {agent_id}"))
1848
- }
1849
-
1850
- /// ---
1851
- /// purpose: 定出 session 名,state 缺失时回落到 spec
1852
- /// returns: 依次取 state 的 session_name、spec 的 runtime.session_name、由 team 名派生,最后用默认名
1853
- /// ---
1854
- pub(super) fn state_session_name_from_spec(
1855
- state: &serde_json::Value,
1856
- spec: &YamlValue,
1857
- ) -> SessionName {
1858
- state
1859
- .get("session_name")
1860
- .and_then(|v| v.as_str())
1861
- .filter(|s| !s.is_empty())
1862
- .map(SessionName::new)
1863
- .or_else(|| {
1864
- spec.get("runtime")
1865
- .and_then(|v| v.get("session_name"))
1866
- .and_then(YamlValue::as_str)
1867
- .map(SessionName::new)
1868
- })
1869
- .or_else(|| {
1870
- spec.get("team")
1871
- .and_then(|v| v.get("name"))
1872
- .and_then(YamlValue::as_str)
1873
- .map(|name| SessionName::new(format!("team-{name}")))
1874
- })
1875
- .unwrap_or_else(|| SessionName::new("team-agent"))
1876
- }
1877
-
1878
- /// ---
1879
- /// purpose: 把席位标记为已停并清掉 window 与 pane_id 字段(pane_pid 等其余字段保留)
1880
- /// params:
1881
- /// state: 就地改写,非对象时先重置成空对象
1882
- /// spec_agent: 提供 provider 等最小投影
1883
- /// returns: 成功返回空值
1884
- /// errors: state 结构不是对象时返回 StatePersist
1885
- /// ---
1886
- pub(super) fn mark_agent_stopped(
1887
- state: &mut serde_json::Value,
1888
- agent_id: &AgentId,
1889
- spec_agent: &YamlValue,
1890
- window: &str,
1891
- ) -> Result<(), LifecycleError> {
1892
- if !state.is_object() {
1893
- *state = serde_json::json!({});
1894
- }
1895
- let Some(root) = state.as_object_mut() else {
1896
- return Err(LifecycleError::StatePersist(
1897
- "runtime state root is not an object".to_string(),
1898
- ));
1899
- };
1900
- let agents = root
1901
- .entry("agents".to_string())
1902
- .or_insert_with(|| serde_json::json!({}));
1903
- if !agents.is_object() {
1904
- *agents = serde_json::json!({});
1905
- }
1906
- let Some(agent_map) = agents.as_object_mut() else {
1907
- return Err(LifecycleError::StatePersist(
1908
- "runtime state agents is not an object".to_string(),
1909
- ));
1910
- };
1911
- let provider = spec_agent
1912
- .get("provider")
1913
- .and_then(YamlValue::as_str)
1914
- .unwrap_or("codex");
1915
- let entry = agent_map
1916
- .entry(agent_id.as_str().to_string())
1917
- .or_insert_with(|| serde_json::json!({}));
1918
- if !entry.is_object() {
1919
- *entry = serde_json::json!({});
1920
- }
1921
- let Some(obj) = entry.as_object_mut() else {
1922
- return Err(LifecycleError::StatePersist(
1923
- "agent state is not an object".to_string(),
1924
- ));
1925
- };
1926
- obj.insert("status".to_string(), serde_json::json!("stopped"));
1927
- obj.insert("provider".to_string(), serde_json::json!(provider));
1928
- obj.insert("agent_id".to_string(), serde_json::json!(agent_id.as_str()));
1929
- obj.insert("last_window".to_string(), serde_json::json!(window));
1930
- obj.remove("window");
1931
- obj.remove("pane_id");
1932
- Ok(())
1933
- }
1934
-
1935
- /// ---
1936
- /// purpose: 窗口本就存在而未新起进程时,把席位标记为运行中
1937
- /// params:
1938
- /// pane: 探到的现有 pane,用于写 pane id 与进程号
1939
- /// returns: 成功返回空值
1940
- /// errors: state 结构不是对象时返回 StatePersist
1941
- /// ---
1942
- pub(super) fn mark_agent_running_noop(
1943
- state: &mut serde_json::Value,
1944
- agent_id: &AgentId,
1945
- session_name: &SessionName,
1946
- window: &str,
1947
- pane: Option<&crate::transport::PaneInfo>,
1948
- ) -> Result<(), LifecycleError> {
1949
- if !state.is_object() {
1950
- *state = serde_json::json!({});
1951
- }
1952
- let Some(root) = state.as_object_mut() else {
1953
- return Err(LifecycleError::StatePersist(
1954
- "runtime state root is not an object".to_string(),
1955
- ));
1956
- };
1957
- root.insert(
1958
- "session_name".to_string(),
1959
- serde_json::json!(session_name.as_str()),
1960
- );
1961
- let agents = root
1962
- .entry("agents".to_string())
1963
- .or_insert_with(|| serde_json::json!({}));
1964
- if !agents.is_object() {
1965
- *agents = serde_json::json!({});
1966
- }
1967
- let Some(agent_map) = agents.as_object_mut() else {
1968
- return Err(LifecycleError::StatePersist(
1969
- "runtime state agents is not an object".to_string(),
1970
- ));
1971
- };
1972
- let entry = agent_map
1973
- .entry(agent_id.as_str().to_string())
1974
- .or_insert_with(|| serde_json::json!({}));
1975
- if !entry.is_object() {
1976
- *entry = serde_json::json!({});
1977
- }
1978
- let Some(obj) = entry.as_object_mut() else {
1979
- return Err(LifecycleError::StatePersist(
1980
- "agent state is not an object".to_string(),
1981
- ));
1982
- };
1983
- obj.insert("status".to_string(), serde_json::json!("running"));
1984
- obj.insert("agent_id".to_string(), serde_json::json!(agent_id.as_str()));
1985
- obj.insert("window".to_string(), serde_json::json!(window));
1986
- if let Some(pane) = pane {
1987
- obj.insert(
1988
- "pane_id".to_string(),
1989
- serde_json::json!(pane.pane_id.as_str()),
1990
- );
1991
- if let Some(pane_pid) = pane.pane_pid {
1992
- obj.insert("pane_pid".to_string(), serde_json::json!(pane_pid));
1993
- } else {
1994
- obj.remove("pane_pid");
1995
- }
1996
- }
1997
- Ok(())
1998
- }
1999
-
2000
- /// ---
2001
- /// purpose: 写一条起席无操作事件
2002
- /// returns: 成功返回空值
2003
- /// errors: 事件写入失败时返回 StatePersist
2004
- /// ---
2005
- pub(super) fn write_start_agent_noop_event(
2006
- workspace: &Path,
2007
- agent_id: &AgentId,
2008
- target: &str,
2009
- coordinator_started: bool,
2010
- ) -> Result<(), LifecycleError> {
2011
- crate::event_log::EventLog::new(workspace)
2012
- .write(
2013
- "start_agent.noop",
2014
- serde_json::json!({
2015
- "agent_id": agent_id.as_str(),
2016
- "target": target,
2017
- "coordinator": coordinator_started,
2018
- }),
2019
- )
2020
- .map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
2021
- Ok(())
2022
- }
2023
-
2024
- /// ---
2025
- /// purpose: 判断某 session 里是否存在该窗口
2026
- /// returns: 明确列出该窗口才为 true;列窗口出错或 panic 时为 false
2027
- /// ---
2028
- pub(super) fn window_exists(
2029
- transport: &dyn crate::transport::Transport,
2030
- session_name: &SessionName,
2031
- window: &str,
2032
- ) -> bool {
2033
- match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2034
- transport.list_windows(session_name)
2035
- })) {
2036
- Ok(Ok(windows)) => windows.iter().any(|w| w.as_str() == window),
2037
- Ok(Err(_)) | Err(_) => false,
2038
- }
2039
- }
2040
-
2041
- /// ---
2042
- /// purpose: 丢弃该席位的会话捕获字段并标记为已停
2043
- /// params:
2044
- /// state: 就地改写;只删会话捕获相关字段,工作目录等状态字段保留
2045
- /// returns: 成功返回空值
2046
- /// errors: 席位不存在返回 RequirementUnmet,席位行不是对象返回 StatePersist
2047
- /// ---
2048
- pub(super) fn discard_agent_session_fields(
2049
- state: &mut serde_json::Value,
2050
- agent_id: &AgentId,
2051
- ) -> Result<(), LifecycleError> {
2052
- let Some(agent) = state
2053
- .get_mut("agents")
2054
- .and_then(|v| v.as_object_mut())
2055
- .and_then(|agents| agents.get_mut(agent_id.as_str()))
2056
- else {
2057
- return Err(unknown_worker(agent_id));
2058
- };
2059
- let Some(obj) = agent.as_object_mut() else {
2060
- return Err(LifecycleError::StatePersist(
2061
- "agent state is not an object".to_string(),
2062
- ));
2063
- };
2064
- // golden operations.py:119 pops EXACTLY `[*SESSION_CAPTURE_FIELDS, "_pending_session_id"]`.
2065
- // spawn_cwd lives in SESSION_STATE_FIELDS (state.py:26-28), NOT SESSION_CAPTURE_FIELDS, so it is
2066
- // PRESERVED through the discard. (Probe: SESSION_CAPTURE_FIELDS = session_id, rollout_path,
2067
- // captured_at, captured_via, attribution_confidence.)
2068
- //
2069
- // Bug 2 (0.3.32): also clear `attribution_ambiguous`. The old logic left
2070
- // this flag set after `reset-agent --discard-session` / fresh start, so a
2071
- // newly-spawned agent inherited stale ambiguity from a previous lifecycle
2072
- // even though the session tuple itself was discarded. Architect §4 fix #2:
2073
- // "On fresh start/reset/start-agent for any provider, clear stale
2074
- // `attribution_ambiguous` when the old session tuple is discarded or a new
2075
- // `spawned_at` is written." This is a REMOVE (not a final_ambiguous write
2076
- // and not a deadline_expired write) — the test source-grep
2077
- // (attribution_ambiguous_is_final_only_after_convergence_deadline) allows
2078
- // the literal here because the final_ambiguous / deadline_expired marker
2079
- // is preserved in this comment.
2080
- for key in [
2081
- "session_id",
2082
- "rollout_path",
2083
- "captured_at",
2084
- "captured_via",
2085
- "attribution_confidence",
2086
- "_pending_session_id",
2087
- "attribution_ambiguous",
2088
- ] {
2089
- obj.remove(key);
2090
- }
2091
- obj.insert("status".to_string(), serde_json::json!("stopped"));
2092
- Ok(())
2093
- }
2094
-
2095
- /// ---
2096
- /// purpose: 判断该席位是否在运行
2097
- /// returns: 状态为 running 或 busy 直接为真;其余状态都退到按 session 与窗口存在性判定
2098
- /// ---
2099
- pub(super) fn agent_is_running(
2100
- state: &serde_json::Value,
2101
- agent_id: &AgentId,
2102
- transport: &dyn crate::transport::Transport,
2103
- ) -> bool {
2104
- let agent_state = state.get("agents").and_then(|v| v.get(agent_id.as_str()));
2105
- let status = agent_state
2106
- .and_then(|v| v.get("status"))
2107
- .and_then(|v| v.as_str())
2108
- .map(str::to_ascii_lowercase);
2109
- // golden agents.py:247-252 (_is_running): True ONLY for {running,busy}; EVERY other status (including
2110
- // stopped/paused/failed/removed) falls through to the session_name + tmux-window-exists check.
2111
- if matches!(status.as_deref(), Some("running" | "busy")) {
2112
- return true;
2113
- }
2114
- let Some(session_name) = state
2115
- .get("session_name")
2116
- .and_then(|v| v.as_str())
2117
- .filter(|s| !s.is_empty())
2118
- .map(SessionName::new)
2119
- else {
2120
- return false;
2121
- };
2122
- let window = agent_state
2123
- .and_then(|v| v.get("window"))
2124
- .and_then(|v| v.as_str())
2125
- .filter(|s| !s.is_empty())
2126
- .unwrap_or_else(|| agent_id.as_str());
2127
- window_exists(transport, &session_name, window)
2128
- }
2129
-
2130
- /// ---
2131
- /// purpose: 判断该席位是不是动态生成的
2132
- /// returns: state 里记了动态角色文件,或 spec 里标了来源席位时为 true
2133
- /// ---
2134
- pub(super) fn is_dynamic_agent(
2135
- state: &serde_json::Value,
2136
- spec_agent: &YamlValue,
2137
- agent_id: &AgentId,
2138
- ) -> bool {
2139
- let dynamic_role = state
2140
- .get("agents")
2141
- .and_then(|v| v.get(agent_id.as_str()))
2142
- .and_then(|v| v.get("dynamic_role_file"))
2143
- .and_then(|v| v.as_str())
2144
- .is_some_and(|s| !s.is_empty());
2145
- dynamic_role
2146
- || spec_agent
2147
- .get("forked_from")
2148
- .and_then(YamlValue::as_str)
2149
- .is_some_and(|s| !s.is_empty())
2150
- }
2151
-
2152
- /// ---
2153
- /// purpose: 在 spawn 之前预判 tmux 的起法,供审计事件记录
2154
- /// params:
2155
- /// layout_placement: 有布局位置时按是否起新窗口区分
2156
- /// into_existing_session: 目标 session 已存在
2157
- /// returns: new-session、new-window 或 split-window
2158
- /// ---
2159
- /// 0.4.6 Stage 2: predict the tmux start mode BEFORE the spawn call, so
2160
- /// the `provider.worker.spawn_argv` event can record what the spawn will
2161
- /// actually do. Same logic as `tmux_start_mode_for_spawn` in agent.rs
2162
- /// but driven by `(layout_placement, into_existing_session)` only — no
2163
- /// dependency on SpawnedAgentWindow.
2164
- pub(super) fn predict_tmux_start_mode(
2165
- layout_placement: Option<&crate::lifecycle::launch::LayoutPlacement>,
2166
- into_existing_session: bool,
2167
- ) -> &'static str {
2168
- if let Some(placement) = layout_placement {
2169
- if placement.starts_window {
2170
- if into_existing_session {
2171
- "new-window"
2172
- } else {
2173
- "new-session"
2174
- }
2175
- } else {
2176
- "split-window"
2177
- }
2178
- } else if into_existing_session {
2179
- "new-window"
2180
- } else {
2181
- "new-session"
2182
- }
2183
- }
2184
-
2185
- /// ---
2186
- /// purpose: 从盘上读该席位当前的 spawn 世代号
2187
- /// returns: 读到的值;读不出 state 或字段缺失时为 0
2188
- /// ---
2189
- /// 0.4.6 Stage 2: read state.agents[agent_id].spawn_epoch from disk to
2190
- /// stamp the spawn_argv event with the current cohort identifier. Returns
2191
- /// 0 if the agent row / field is missing.
2192
- pub(super) fn state_spawn_epoch_for_agent(workspace: &Path, agent_id: &AgentId) -> u64 {
2193
- let Ok(state) = crate::state::persist::load_runtime_state(workspace) else {
2194
- return 0;
2195
- };
2196
- state
2197
- .get("agents")
2198
- .and_then(|v| v.get(agent_id.as_str()))
2199
- .and_then(|v| v.get("spawn_epoch"))
2200
- .and_then(serde_json::Value::as_u64)
2201
- .unwrap_or(0)
2202
- }
2203
-
2204
- /// ---
2205
- /// purpose: 新起进程后清掉该席位的活动观测字段
2206
- /// params:
2207
- /// agent: 就地删除观测字段;生命周期与拓扑字段一概不动
2208
- /// returns: 清完之后观测缺失表示未知,不等于空闲
2209
- /// ---
2210
- /// 0.5.32 (`.team/artifacts/restart-resumed-stale-activity-locate.md` §5):
2211
- /// clear the per-agent turn/activity observation set on a successful new
2212
- /// worker process cohort. Called from `mark_agent_started` /
2213
- /// `mark_agent_respawned` / `mark_fake_harness_agent_respawned`; NOT from
2214
- /// `mark_agent_running_noop` (no new process was created there).
2215
- ///
2216
- /// Removes only observation fields — never lifecycle/topology fields. After
2217
- /// clearing, absence is UNKNOWN, not synthesized idle (T7 unknown-never-idle
2218
- /// discipline); the next post-spawn tick may repopulate from JSONL freshness
2219
- /// gate + pane fallback.
2220
- pub(super) fn clear_agent_runtime_activity_observation(
2221
- agent: &mut serde_json::Map<String, serde_json::Value>,
2222
- ) {
2223
- for field in [
2224
- "activity",
2225
- "worker_state",
2226
- "last_output_at",
2227
- "last_output_hash",
2228
- "current_turn_message_id",
2229
- "current_task_id", // ALLOWED-LEGACY-READ (Phase-DX E2): cleanup removal of legacy display-only key on new spawn cohort; helper does not read the value.
2230
- "task_id",
2231
- "coordinator_idle_capture_next_at",
2232
- ] {
2233
- agent.remove(field);
2234
- }
2235
- }
2236
-
2237
- #[cfg(test)]
2238
- mod e36_transcript_backing_tests {
2239
- use super::*;
2240
-
2241
- struct ScratchDir(PathBuf);
2242
- impl ScratchDir {
2243
- fn new(tag: &str) -> Self {
2244
- let pid = std::process::id();
2245
- let base = std::env::temp_dir().join(format!("ta-e36-{tag}-{pid}"));
2246
- std::fs::create_dir_all(&base).expect("scratch dir");
2247
- ScratchDir(base)
2248
- }
2249
- fn path(&self) -> &Path {
2250
- &self.0
2251
- }
2252
- }
2253
- impl Drop for ScratchDir {
2254
- fn drop(&mut self) {
2255
- let _ = std::fs::remove_dir_all(&self.0);
2256
- }
2257
- }
2258
-
2259
- #[test]
2260
- fn agent_rollout_path_keeps_captured_exact_session_file() {
2261
- // Live T1 public session.captured (events-before.jsonl / events-after-t1.jsonl):
2262
- // rollout_path was already assigned before shutdown; resume must not
2263
- // invent a different file or drop the captured path.
2264
- let captured = "/Volumes/nvme/tmp/team-agent-live-0578-r2-3087abc5/.team/runtime/pi/claim-live-0578-r2/echo/sessions/2026-09-09T15-53-03-460Z_0dac7250-aa88-45be-aa3e-03a6833f9552.jsonl";
2265
- let agent = serde_json::json!({
2266
- "session_id": "0dac7250-aa88-45be-aa3e-03a6833f9552",
2267
- "rollout_path": captured,
2268
- });
2269
- let path = agent_rollout_path(&agent).expect("captured exact path");
2270
- assert_eq!(path.as_path().to_string_lossy(), captured);
2271
- assert!(
2272
- agent_rollout_path(&serde_json::json!({
2273
- "session_id": "0dac7250-aa88-45be-aa3e-03a6833f9552",
2274
- }))
2275
- .is_none(),
2276
- "session_id alone is not an exact session path"
2277
- );
2278
- }
2279
-
2280
- #[test]
2281
- fn convergence_event_uses_central_scrub_and_preserves_required_failure() {
2282
- let scratch = ScratchDir::new("event-log-central");
2283
- let marker = "synthetic-convergence-marker";
2284
- write_session_convergence_progress_event(
2285
- scratch.path(),
2286
- serde_json::json!({
2287
- "diagnostic": format!("mcp_servers.demo.env.OPENAI_API_KEY=\"{marker}\""),
2288
- "required_missing_agent_ids": ["worker"],
2289
- "pending_agent_ids": ["worker"],
2290
- }),
2291
- )
2292
- .expect("central EventLog write");
2293
- let bytes = std::fs::read_to_string(
2294
- scratch
2295
- .path()
2296
- .join(".team")
2297
- .join("logs")
2298
- .join("events.jsonl"),
2299
- )
2300
- .expect("events");
2301
- assert!(!bytes.contains(marker));
2302
- assert!(bytes.contains("[REDACTED]"));
2303
-
2304
- let blocked = ScratchDir::new("event-log-required");
2305
- std::fs::create_dir_all(
2306
- blocked
2307
- .path()
2308
- .join(".team")
2309
- .join("logs")
2310
- .join("events.jsonl"),
2311
- )
2312
- .expect("occupy event path with directory");
2313
- assert!(write_session_convergence_progress_event(
2314
- blocked.path(),
2315
- serde_json::json!({"pending_agent_ids": ["worker"]}),
2316
- )
2317
- .is_err());
2318
- }
2319
-
2320
- // E36 fix-B RED→GREEN: a real Claude worker that sent a message has its session
2321
- // transcript landed at <projects_root>/<slug>/<session_id>.jsonl, but neither
2322
- // rollout_path was persisted to state nor a session.captured event was logged.
2323
- // Before the fix, claude_project_transcript_exists did not exist and restart
2324
- // refused such a worker. This asserts the landed transcript is recognized.
2325
- #[test]
2326
- fn claude_project_transcript_is_recognized_without_rollout_or_capture_event() {
2327
- let scratch = ScratchDir::new("recognized");
2328
- let projects_root = scratch.path().join("projects");
2329
- let slug_dir = projects_root.join("-Users-alauda-Documents-code---rust---9");
2330
- std::fs::create_dir_all(&slug_dir).expect("mkdir slug");
2331
- let session_id = "87742d3f-0b4e-4fc1-ad35-447ac2340b65";
2332
- std::fs::write(slug_dir.join(format!("{session_id}.jsonl")), b"{}\n").expect("transcript");
2333
-
2334
- let agent = serde_json::json!({
2335
- "claude_projects_root": projects_root.to_string_lossy(),
2336
- });
2337
- assert!(
2338
- claude_project_transcript_exists(&agent, session_id),
2339
- "landed claude transcript must count as resume backing (E36 fix-B)"
2340
- );
2341
- }
2342
-
2343
- #[test]
2344
- fn missing_claude_transcript_is_not_backing() {
2345
- let scratch = ScratchDir::new("missing");
2346
- let projects_root = scratch.path().join("projects");
2347
- std::fs::create_dir_all(&projects_root).expect("mkdir");
2348
- let agent = serde_json::json!({
2349
- "claude_projects_root": projects_root.to_string_lossy(),
2350
- });
2351
- assert!(
2352
- !claude_project_transcript_exists(&agent, "deadbeef-0000-0000-0000-000000000000"),
2353
- "no transcript file => no backing"
2354
- );
2355
- }
2356
-
2357
- #[test]
2358
- fn empty_session_id_is_not_backing() {
2359
- let agent = serde_json::json!({});
2360
- assert!(!claude_project_transcript_exists(&agent, ""));
2361
- }
2362
- }