@team-agent/installer 0.5.127 → 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 (421) hide show
  1. package/README.md +15 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +41 -26
  5. package/skills/team-agent/command-coverage.json +170 -184
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +66 -32
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +66 -32
  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 -1298
  15. package/crates/team-agent/src/cli/arguments.rs +0 -401
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1675
  18. package/crates/team-agent/src/cli/emit.rs +0 -2898
  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 -1189
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -821
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -691
  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 -6528
  29. package/crates/team-agent/src/cli/models.rs +0 -449
  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/send/coordinator.rs +0 -164
  34. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  35. package/crates/team-agent/src/cli/send/persist.rs +0 -192
  36. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  37. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  38. package/crates/team-agent/src/cli/send.rs +0 -201
  39. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  40. package/crates/team-agent/src/cli/spec.rs +0 -159
  41. package/crates/team-agent/src/cli/status.rs +0 -280
  42. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  43. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  44. package/crates/team-agent/src/cli/status_port/brief.rs +0 -2043
  45. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  46. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  47. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  48. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  49. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  50. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  51. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  52. package/crates/team-agent/src/cli/status_port.rs +0 -92
  53. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  54. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  55. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  56. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -372
  57. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  58. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  59. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  60. package/crates/team-agent/src/cli/tests/named_address.rs +0 -760
  61. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  62. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -481
  63. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  64. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  65. package/crates/team-agent/src/cli/tests/status_send.rs +0 -1091
  66. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  67. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  68. package/crates/team-agent/src/cli/triage.rs +0 -234
  69. package/crates/team-agent/src/cli/types.rs +0 -591
  70. package/crates/team-agent/src/codex_app_server.rs +0 -546
  71. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  72. package/crates/team-agent/src/compiler/tests.rs +0 -842
  73. package/crates/team-agent/src/compiler.rs +0 -691
  74. package/crates/team-agent/src/conpty/backend.rs +0 -829
  75. package/crates/team-agent/src/conpty/mod.rs +0 -33
  76. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1610
  77. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  78. package/crates/team-agent/src/contract_runtime/config.rs +0 -354
  79. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -56
  80. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -438
  81. package/crates/team-agent/src/contract_runtime/fork.rs +0 -368
  82. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  83. package/crates/team-agent/src/contract_runtime/framework.rs +0 -350
  84. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -399
  85. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  86. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  87. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  88. package/crates/team-agent/src/contract_runtime/registry.rs +0 -589
  89. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  90. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  91. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  92. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  93. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  94. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  95. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  96. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  97. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  98. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  99. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  101. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  102. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  104. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  105. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  106. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -338
  107. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  108. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  109. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  110. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -461
  111. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  112. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  113. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  114. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  115. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  116. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  117. package/crates/team-agent/src/coordinator/tick.rs +0 -3112
  118. package/crates/team-agent/src/coordinator/types.rs +0 -540
  119. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  120. package/crates/team-agent/src/db/message_store.rs +0 -1585
  121. package/crates/team-agent/src/db/migration.rs +0 -984
  122. package/crates/team-agent/src/db/mod.rs +0 -26
  123. package/crates/team-agent/src/db/schema.rs +0 -663
  124. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  125. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  126. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  127. package/crates/team-agent/src/event_log.rs +0 -502
  128. package/crates/team-agent/src/fake_worker.rs +0 -303
  129. package/crates/team-agent/src/kill_audit.rs +0 -106
  130. package/crates/team-agent/src/layout/manager.rs +0 -248
  131. package/crates/team-agent/src/layout/mod.rs +0 -36
  132. package/crates/team-agent/src/layout/overlay.rs +0 -134
  133. package/crates/team-agent/src/layout/placement.rs +0 -52
  134. package/crates/team-agent/src/layout/recovery.rs +0 -106
  135. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  136. package/crates/team-agent/src/layout/sessions.rs +0 -294
  137. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  138. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  139. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  140. package/crates/team-agent/src/leader/helpers.rs +0 -178
  141. package/crates/team-agent/src/leader/incident.rs +0 -6
  142. package/crates/team-agent/src/leader/lease.rs +0 -3356
  143. package/crates/team-agent/src/leader/mod.rs +0 -104
  144. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  145. package/crates/team-agent/src/leader/prompt.rs +0 -905
  146. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  147. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  148. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  149. package/crates/team-agent/src/leader/registry.rs +0 -883
  150. package/crates/team-agent/src/leader/start.rs +0 -4500
  151. package/crates/team-agent/src/leader/takeover.rs +0 -65
  152. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  153. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  154. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  155. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  156. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  157. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  158. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  159. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  160. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  161. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  162. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -267
  163. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  164. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  165. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  166. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  167. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  168. package/crates/team-agent/src/leader/types.rs +0 -534
  169. package/crates/team-agent/src/lib.rs +0 -145
  170. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  171. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -848
  172. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -393
  173. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  174. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -178
  175. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -82
  176. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -63
  177. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  178. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  179. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  180. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -152
  181. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  182. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -629
  183. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -226
  184. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  185. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5176
  186. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  187. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  188. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  189. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -450
  190. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  191. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  192. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  193. package/crates/team-agent/src/lifecycle/launch.rs +0 -534
  194. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  195. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  196. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  197. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -757
  198. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  199. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2198
  200. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2052
  201. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  202. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  203. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  204. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  205. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  206. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  207. package/crates/team-agent/src/lifecycle/restart.rs +0 -223
  208. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1205
  209. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  210. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  211. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  212. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  213. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  214. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -135
  215. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1415
  216. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  217. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -396
  218. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -418
  219. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2039
  220. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1298
  221. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  222. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  223. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  224. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -71
  225. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  226. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  227. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -472
  228. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  229. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  230. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  231. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3981
  232. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  233. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  234. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  235. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  236. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  237. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  238. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -152
  239. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -182
  240. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -374
  241. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -546
  242. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -31
  243. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -528
  244. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -134
  245. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -333
  246. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  247. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  248. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  249. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  250. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  251. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  252. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  253. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  254. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  255. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  256. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  257. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  258. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -90
  259. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  260. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  261. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  262. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  263. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  264. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  265. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  266. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -996
  267. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -827
  268. package/crates/team-agent/src/lifecycle/tests.rs +0 -102
  269. package/crates/team-agent/src/lifecycle/types.rs +0 -861
  270. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -370
  271. package/crates/team-agent/src/main.rs +0 -52
  272. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  273. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  274. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  275. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  276. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  277. package/crates/team-agent/src/mcp_server/readiness.rs +0 -546
  278. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -369
  279. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  280. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  281. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -168
  282. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -388
  283. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -343
  284. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  285. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  286. package/crates/team-agent/src/mcp_server/tools.rs +0 -1015
  287. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  288. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  289. package/crates/team-agent/src/messaging/activity.rs +0 -461
  290. package/crates/team-agent/src/messaging/address.rs +0 -87
  291. package/crates/team-agent/src/messaging/delivery.rs +0 -3785
  292. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  293. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  294. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  295. package/crates/team-agent/src/messaging/helpers.rs +0 -354
  296. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  297. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  298. package/crates/team-agent/src/messaging/mod.rs +0 -166
  299. package/crates/team-agent/src/messaging/persist.rs +0 -377
  300. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  301. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  302. package/crates/team-agent/src/messaging/results.rs +0 -1415
  303. package/crates/team-agent/src/messaging/scheduler.rs +0 -217
  304. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  305. package/crates/team-agent/src/messaging/send.rs +0 -981
  306. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  307. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -551
  308. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  309. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  310. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  311. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  312. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  313. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3655
  314. package/crates/team-agent/src/messaging/tests/spine.rs +0 -837
  315. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  316. package/crates/team-agent/src/messaging/trust.rs +0 -215
  317. package/crates/team-agent/src/messaging/types.rs +0 -471
  318. package/crates/team-agent/src/messaging/wait.rs +0 -366
  319. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  320. package/crates/team-agent/src/model/enums.rs +0 -356
  321. package/crates/team-agent/src/model/errors.rs +0 -18
  322. package/crates/team-agent/src/model/ids.rs +0 -165
  323. package/crates/team-agent/src/model/mod.rs +0 -29
  324. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  325. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  326. package/crates/team-agent/src/model/paths.rs +0 -257
  327. package/crates/team-agent/src/model/routing.rs +0 -387
  328. package/crates/team-agent/src/model/spec.rs +0 -1184
  329. package/crates/team-agent/src/model/task_graph.rs +0 -321
  330. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  331. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  332. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  333. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  334. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  335. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  336. package/crates/team-agent/src/model/yaml.rs +0 -802
  337. package/crates/team-agent/src/os_probe.rs +0 -280
  338. package/crates/team-agent/src/packaging/install.rs +0 -219
  339. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  340. package/crates/team-agent/src/packaging/mod.rs +0 -91
  341. package/crates/team-agent/src/packaging/repair.rs +0 -33
  342. package/crates/team-agent/src/packaging/tests.rs +0 -822
  343. package/crates/team-agent/src/packaging/types.rs +0 -417
  344. package/crates/team-agent/src/platform/argv.rs +0 -331
  345. package/crates/team-agent/src/platform/errors.rs +0 -104
  346. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  347. package/crates/team-agent/src/platform/mod.rs +0 -5
  348. package/crates/team-agent/src/platform/process.rs +0 -545
  349. package/crates/team-agent/src/provider/adapter.rs +0 -898
  350. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  351. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  352. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  353. package/crates/team-agent/src/provider/adapters/mod.rs +0 -28
  354. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  355. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  356. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  357. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  358. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  359. package/crates/team-agent/src/provider/classify.rs +0 -773
  360. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  361. package/crates/team-agent/src/provider/faults.rs +0 -165
  362. package/crates/team-agent/src/provider/helpers.rs +0 -52
  363. package/crates/team-agent/src/provider/mod.rs +0 -78
  364. package/crates/team-agent/src/provider/model_catalog.rs +0 -722
  365. package/crates/team-agent/src/provider/session/capture.rs +0 -2631
  366. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -168
  367. package/crates/team-agent/src/provider/session/context_fork.rs +0 -264
  368. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  369. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  370. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  371. package/crates/team-agent/src/provider/session_scan/common.rs +0 -618
  372. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  373. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -152
  374. package/crates/team-agent/src/provider/session_scan.rs +0 -61
  375. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  376. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  377. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  378. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  379. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  380. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  381. package/crates/team-agent/src/provider/tests/adapter.rs +0 -354
  382. package/crates/team-agent/src/provider/tests/classify.rs +0 -201
  383. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -26
  384. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  385. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  386. package/crates/team-agent/src/provider/tests/idle.rs +0 -140
  387. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  388. package/crates/team-agent/src/provider/tests.rs +0 -32
  389. package/crates/team-agent/src/provider/types.rs +0 -529
  390. package/crates/team-agent/src/provider/wire.rs +0 -406
  391. package/crates/team-agent/src/redaction.rs +0 -259
  392. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  393. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  394. package/crates/team-agent/src/state/identity.rs +0 -914
  395. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  396. package/crates/team-agent/src/state/mod.rs +0 -74
  397. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  398. package/crates/team-agent/src/state/ownership.rs +0 -563
  399. package/crates/team-agent/src/state/paths.rs +0 -395
  400. package/crates/team-agent/src/state/persist.rs +0 -3811
  401. package/crates/team-agent/src/state/projection.rs +0 -1508
  402. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  403. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  404. package/crates/team-agent/src/state/repository.rs +0 -866
  405. package/crates/team-agent/src/state/selector.rs +0 -160
  406. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  407. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  408. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  409. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  410. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  411. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4254
  412. package/crates/team-agent/src/tmux_backend.rs +0 -4527
  413. package/crates/team-agent/src/topology.rs +0 -537
  414. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  415. package/crates/team-agent/src/transport/native_input.rs +0 -491
  416. package/crates/team-agent/src/transport/test_support.rs +0 -743
  417. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  418. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  419. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  420. package/crates/team-agent/src/transport.rs +0 -1655
  421. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,1508 +0,0 @@
1
- //!
2
- //! projection:team 选择 / top-level 派生视图(真相源 `state.py`,0.2.6 Family B C6-C8)。
3
- //!
4
- //! `state.teams` 是唯一候选源(`status == "alive"`);顶层 `session_name`/`team_dir`/`agents`/`tasks`
5
- //! 是「当前 team」的**派生视图**,不算独立候选。选 team 用时把 `teams[key]` 投影回扁平 dict
6
- //! (`_project_top_level_view`),并保留 `team_owner`/`leader_receiver`/`coordinator` 等辅助态。
7
- //!
8
- //! 纯函数操作 `serde_json::Value`;`select_runtime_state`/`resolve_team_scoped_state` 经
9
- //! `persist::load_runtime_state` 读盘。键序对齐 Python dict(preserve_order):`setdefault`→
10
- //! 「缺则末尾插」,`d[k]=v`→「在则原位更新,缺则末尾插」(serde_json::Map = IndexMap)。
11
- //! §10:无 unwrap/expect/panic(全程 owned `Map`,非 object 优雅退化为空 object)。
12
-
13
- use std::path::Path;
14
-
15
- use serde_json::{json, Map, Value};
16
-
17
- use super::StateError;
18
- use crate::state::persist::{
19
- load_runtime_state, load_runtime_state_without_migrations,
20
- save_runtime_state_with_deleted_agents,
21
- save_runtime_state_with_lifecycle_topology_authority,
22
- save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip,
23
- save_runtime_state_with_team_tombstone_lifecycle_topology_authority,
24
- save_runtime_state_with_team_tombstoned_agents,
25
- };
26
-
27
- pub(crate) const CURRENT_TEAM_ALIAS: &str = "current";
28
-
29
- /// Physical tmux session birth identity, independent of later worker spawns.
30
- /// Legacy launches did not persist it: freeze their fallback BEFORE respawn.
31
- pub fn session_generation(state: &Value) -> Option<&str> {
32
- state.get("generation").and_then(Value::as_str).or_else(|| {
33
- state
34
- .get("agents")
35
- .and_then(Value::as_object)
36
- .and_then(|agents| {
37
- agents.values().find_map(|agent| {
38
- agent.get("spawned_at").and_then(Value::as_str)
39
- })
40
- })
41
- })
42
- }
43
-
44
- ///
45
- /// `team_state_key`(`state.py:93`):从 team_dir(.name)/spec_path(.parent.name)派生 team key,
46
- /// 跳过 `.team`/`runtime`;兜底 `session_name` 或 `"current"`。
47
- pub fn team_state_key(state: &Value) -> String {
48
- if let Some(team_key) = state
49
- .get("team_key")
50
- .and_then(Value::as_str)
51
- .filter(|key| !key.is_empty())
52
- {
53
- return team_key.to_string();
54
- }
55
- for field in ["team_dir", "spec_path"] {
56
- // Python `if not value: continue` —— None/空串 falsy 跳过。
57
- let value = match state.get(field).and_then(Value::as_str) {
58
- Some(v) if !v.is_empty() => v,
59
- _ => continue,
60
- };
61
- let path = Path::new(value);
62
- let key = if field == "team_dir" {
63
- path.file_name()
64
- } else {
65
- path.parent().and_then(Path::file_name)
66
- };
67
- let key = key
68
- .map(|s| s.to_string_lossy().into_owned())
69
- .unwrap_or_default();
70
- if !key.is_empty() && key != ".team" && key != "runtime" {
71
- return key;
72
- }
73
- }
74
- state
75
- .get("session_name")
76
- .and_then(Value::as_str)
77
- .filter(|s| !s.is_empty())
78
- .map_or_else(|| "current".to_string(), str::to_string)
79
- }
80
-
81
- #[derive(Debug, Clone, PartialEq, Eq)]
82
- pub enum OwnerTeamResolution {
83
- Canonical(String),
84
- LegacyAlias {
85
- requested: String,
86
- canonical: String,
87
- },
88
- Unresolved {
89
- requested: String,
90
- },
91
- Ambiguous {
92
- requested: String,
93
- matches: Vec<String>,
94
- },
95
- }
96
-
97
- impl OwnerTeamResolution {
98
- pub fn canonical_key(&self) -> Option<&str> {
99
- match self {
100
- OwnerTeamResolution::Canonical(key)
101
- | OwnerTeamResolution::LegacyAlias { canonical: key, .. } => Some(key),
102
- OwnerTeamResolution::Unresolved { .. } | OwnerTeamResolution::Ambiguous { .. } => None,
103
- }
104
- }
105
- }
106
-
107
- pub fn resolve_owner_team_id(state: &Value, owner_team_id: &str) -> OwnerTeamResolution {
108
- let requested = owner_team_id.trim();
109
- if requested.is_empty() {
110
- return OwnerTeamResolution::Unresolved {
111
- requested: owner_team_id.to_string(),
112
- };
113
- }
114
- let teams = state.get("teams").and_then(Value::as_object);
115
- if teams.is_some_and(|teams| teams.contains_key(requested)) {
116
- return OwnerTeamResolution::Canonical(requested.to_string());
117
- }
118
- if teams.is_none_or(Map::is_empty) {
119
- let active = state
120
- .get("active_team_key")
121
- .and_then(Value::as_str)
122
- .unwrap_or("");
123
- let derived = team_state_key(state);
124
- if active == requested || derived == requested {
125
- return OwnerTeamResolution::Canonical(requested.to_string());
126
- }
127
- if !active.is_empty() {
128
- return OwnerTeamResolution::LegacyAlias {
129
- requested: requested.to_string(),
130
- canonical: active.to_string(),
131
- };
132
- }
133
- if derived != "current" {
134
- return OwnerTeamResolution::LegacyAlias {
135
- requested: requested.to_string(),
136
- canonical: derived,
137
- };
138
- }
139
- return OwnerTeamResolution::Canonical(requested.to_string());
140
- }
141
- let Some(teams) = teams else {
142
- return OwnerTeamResolution::Unresolved {
143
- requested: requested.to_string(),
144
- };
145
- };
146
- let mut matches = Vec::new();
147
- for (key, entry) in teams {
148
- if legacy_owner_team_aliases(entry).any(|alias| alias == requested) {
149
- matches.push(key.clone());
150
- }
151
- }
152
- matches.sort();
153
- matches.dedup();
154
- match matches.len() {
155
- 0 => OwnerTeamResolution::Unresolved {
156
- requested: requested.to_string(),
157
- },
158
- 1 => OwnerTeamResolution::LegacyAlias {
159
- requested: requested.to_string(),
160
- canonical: matches.remove(0),
161
- },
162
- _ => OwnerTeamResolution::Ambiguous {
163
- requested: requested.to_string(),
164
- matches,
165
- },
166
- }
167
- }
168
-
169
- fn legacy_owner_team_aliases(entry: &Value) -> impl Iterator<Item = String> + '_ {
170
- let scalar_paths = [
171
- "/team/name",
172
- "/team/id",
173
- "/name",
174
- "/team_name",
175
- "/team_id",
176
- "/spec_name",
177
- "/legacy_owner_team_id",
178
- "/legacy_team_id",
179
- "/legacy_team_name",
180
- "/legacy_alias",
181
- ];
182
- let list_paths = [
183
- "/legacy_aliases",
184
- "/legacy_team_aliases",
185
- "/legacy_owner_team_ids",
186
- "/aliases",
187
- ];
188
- let scalars = scalar_paths
189
- .into_iter()
190
- .filter_map(|path| entry.pointer(path).and_then(Value::as_str));
191
- let lists = list_paths.into_iter().flat_map(|path| {
192
- entry
193
- .pointer(path)
194
- .and_then(Value::as_array)
195
- .into_iter()
196
- .flatten()
197
- .filter_map(Value::as_str)
198
- });
199
- scalars
200
- .chain(lists)
201
- .filter(|alias| !alias.is_empty())
202
- .map(str::to_string)
203
- }
204
-
205
- ///
206
- /// `compact_team_state`(`state.py:105`):剔除 `teams`(team entry 不嵌套全量 teams),保序。
207
- pub fn compact_team_state(state: &Value) -> Value {
208
- match state.as_object() {
209
- Some(obj) => Value::Object(
210
- obj.iter()
211
- .filter(|(k, _)| k.as_str() != "teams")
212
- .map(|(k, v)| (k.clone(), v.clone()))
213
- .collect(),
214
- ),
215
- None => state.clone(),
216
- }
217
- }
218
-
219
- pub fn state_is_external_leader(state: &Value) -> bool {
220
- state
221
- .get("is_external_leader")
222
- .and_then(Value::as_bool)
223
- .unwrap_or(false)
224
- }
225
-
226
- pub fn state_is_managed_leader(state: &Value) -> bool {
227
- !state_is_external_leader(state)
228
- }
229
-
230
- ///
231
- /// `merge_workspace_team_state`(`state.py:111`):把新启动的 team 并入既有 workspace state。
232
- pub fn merge_workspace_team_state(existing: &Value, launched: &Value) -> Value {
233
- let launched_key = team_state_key(launched);
234
- // existing 无 session_name → 直接以 launched 为基,seed teams。
235
- if !truthy_str(existing.get("session_name")) {
236
- let mut merged = to_object(launched);
237
- let mut teams = take_object(merged.get("teams"));
238
- teams.insert(launched_key, compact_team_state(launched));
239
- merged.insert("teams".to_string(), Value::Object(teams));
240
- return Value::Object(merged);
241
- }
242
- let existing_key = team_state_key(existing);
243
- if existing_key == launched_key {
244
- // 同 key → launched 为基,teams 取 existing 历史 + launched。
245
- let mut merged = to_object(launched);
246
- let mut teams = take_object(existing.get("teams"));
247
- teams.insert(launched_key, compact_team_state(launched));
248
- merged.insert("teams".to_string(), Value::Object(teams));
249
- return Value::Object(merged);
250
- }
251
- // 异 key → existing 为基,两个 team 都进 teams(existing 仅在缺时 seed)。
252
- let mut merged = to_object(existing);
253
- let mut teams = take_object(merged.get("teams"));
254
- teams
255
- .entry(existing_key)
256
- .or_insert_with(|| compact_team_state(existing));
257
- teams.insert(launched_key, compact_team_state(launched));
258
- merged.insert("teams".to_string(), Value::Object(teams));
259
- Value::Object(merged)
260
- }
261
-
262
- ///
263
- /// `team_state_candidates`(`state.py:131`):唯一候选源 = `state.teams` 中
264
- /// `status=="alive"`(大小写不敏感;缺 status/空 视为 alive,但 0.5.26 起
265
- /// legacy shutdown 残留「无 status + 全体 agents 处于终态」不再算 alive)。
266
- /// 保留 teams 插入序。
267
- ///
268
- /// 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.1):
269
- /// shutdown 只标 agent stopped 不动 team status,retained state 让 selector
270
- /// 把死队当活队,进而卡活队写入的 SaveConflict。谓词收敛到
271
- /// [`team_is_alive_candidate`],这里只做遍历。
272
- pub fn team_state_candidates(state: &Value) -> Map<String, Value> {
273
- let mut out = Map::new();
274
- let teams = match state.get("teams") {
275
- Some(Value::Object(m)) => m,
276
- _ => return out,
277
- };
278
- for (key, value) in teams {
279
- if !team_is_alive_candidate(value) {
280
- continue;
281
- }
282
- out.insert(key.clone(), value.clone());
283
- }
284
- out
285
- }
286
-
287
- ///
288
- /// 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.1): 唯一 alive
289
- /// 谓词。规则:
290
- /// - 非 object → 排除;
291
- /// - `archived_at` 非空 → 排除;
292
- /// - 显式 `status` → 只有 case-insensitive `alive` 才算活;
293
- /// - `status` 缺失/空 + `agents` 有条目且全体处于终态 → legacy shutdown
294
- /// residue,排除;
295
- /// - `status` 缺失/空 + 无 agent 或至少一个非终态 agent → 保持兼容 alive。
296
- pub(crate) fn team_is_alive_candidate(team: &Value) -> bool {
297
- if !team.is_object() {
298
- return false;
299
- }
300
- if team.get("archived_at").is_some_and(|v| !v.is_null()) {
301
- return false;
302
- }
303
- let status_raw = team
304
- .get("status")
305
- .and_then(Value::as_str)
306
- .filter(|s| !s.is_empty());
307
- if let Some(status) = status_raw {
308
- return status.eq_ignore_ascii_case("alive");
309
- }
310
- if !team
311
- .get("agents")
312
- .and_then(Value::as_object)
313
- .is_some_and(|agents| !agents.is_empty())
314
- && team_has_live_leader_binding(team)
315
- {
316
- return false;
317
- }
318
- if all_present_agents_terminal(team) && !team_has_live_leader_binding(team) {
319
- return false;
320
- }
321
- true
322
- }
323
-
324
- /// 0.5.26: legacy team 缺 `status` 时,若挂着 `leader_receiver`/`team_owner`
325
- /// 视为仍活的绑定面(0515 endpoint-convergence 家族:worker stopped 但 receiver
326
- /// attached,restart 预检要能看到 leader_receiver 以派 `leader_receiver_socket_mismatch`)。
327
- fn team_has_live_leader_binding(team: &Value) -> bool {
328
- let is_non_null_object = |key: &str| {
329
- team.get(key)
330
- .filter(|v| !v.is_null())
331
- .and_then(Value::as_object)
332
- .is_some_and(|m| !m.is_empty())
333
- };
334
- is_non_null_object("leader_receiver") || is_non_null_object("team_owner")
335
- }
336
-
337
- fn team_has_attached_leader_receiver(team: &Value) -> bool {
338
- let Some(receiver) = team.get("leader_receiver").and_then(Value::as_object) else {
339
- return false;
340
- };
341
- receiver
342
- .get("status")
343
- .and_then(Value::as_str)
344
- .is_some_and(|status| status.eq_ignore_ascii_case("attached"))
345
- && receiver
346
- .get("pane_id")
347
- .and_then(Value::as_str)
348
- .is_some_and(|pane| !pane.is_empty())
349
- }
350
-
351
- fn all_present_agents_terminal(team: &Value) -> bool {
352
- let Some(agents) = team.get("agents").and_then(Value::as_object) else {
353
- return false;
354
- };
355
- if agents.is_empty() {
356
- return false;
357
- }
358
- agents.values().all(|agent| {
359
- agent
360
- .get("status")
361
- .and_then(Value::as_str)
362
- .is_some_and(agent_status_is_terminal)
363
- })
364
- }
365
-
366
- /// Team restart never consumes an explicit stop or legacy stopped row.
367
- /// A malformed persisted marker is held closed, not coerced to false.
368
- pub(crate) fn agent_stopped_for_restart(agent: &Value) -> bool {
369
- agent.get("status").and_then(Value::as_str)
370
- .is_some_and(|status| status.eq_ignore_ascii_case("stopped"))
371
- || agent_explicit_stop(agent)
372
- }
373
-
374
- /// Only an explicit persisted stop freezes metadata against ordinary writers.
375
- /// Historical stopped rows still follow existing roster-pruning semantics.
376
- pub(crate) fn agent_explicit_stop(agent: &Value) -> bool {
377
- !matches!(agent.get("explicit_stop"), None | Some(Value::Bool(false)))
378
- }
379
-
380
- pub(crate) fn agent_status_is_terminal(status: &str) -> bool {
381
- matches!(
382
- status.to_ascii_lowercase().as_str(),
383
- "stopped" | "removed" | "dead" | "terminated" | "failed"
384
- )
385
- }
386
-
387
- ///
388
- /// `format_team_candidates`(`state.py:148`):候选摘要串(key 排序;agents 排序逗号连,空→`-`)。
389
- fn format_team_candidates(team_states: &Map<String, Value>) -> String {
390
- if team_states.is_empty() {
391
- return "No team state was found.".to_string();
392
- }
393
- let mut keys: Vec<&String> = team_states.keys().collect();
394
- keys.sort();
395
- let mut parts = Vec::new();
396
- for key in keys {
397
- let st = &team_states[key];
398
- let mut agent_keys: Vec<&String> = st
399
- .get("agents")
400
- .and_then(Value::as_object)
401
- .map(|a| a.keys().collect())
402
- .unwrap_or_default();
403
- agent_keys.sort();
404
- let agents = if agent_keys.is_empty() {
405
- "-".to_string()
406
- } else {
407
- agent_keys
408
- .iter()
409
- .map(|s| s.as_str())
410
- .collect::<Vec<_>>()
411
- .join(",")
412
- };
413
- let session = st
414
- .get("session_name")
415
- .and_then(Value::as_str)
416
- .filter(|s| !s.is_empty())
417
- .unwrap_or("-");
418
- parts.push(format!("{key} session={session} agents={agents}"));
419
- }
420
- "Candidates: ".to_string() + &parts.join("; ")
421
- }
422
-
423
- /// `_team_entry_from_state`(`state.py:159`):`teams[team_key]` 若为 dict 则返回引用。
424
- fn team_entry_from_state<'a>(state: &'a Value, team_key: &str) -> Option<&'a Value> {
425
- state
426
- .get("teams")
427
- .and_then(Value::as_object)
428
- .and_then(|teams| teams.get(team_key))
429
- .filter(|e| e.is_object())
430
- }
431
-
432
- pub fn read_owner<'a>(state: &'a Value, team_key: Option<&str>) -> Option<&'a Value> {
433
- let owner = match team_key.filter(|team| !team.is_empty()) {
434
- Some(team) => team_entry_from_state(state, team).and_then(|entry| entry.get("team_owner")),
435
- None => state.get("team_owner"),
436
- }?;
437
- let pane_id = owner.get("pane_id").and_then(Value::as_str)?;
438
- if !valid_owner_pane_id(pane_id) {
439
- return None;
440
- }
441
- Some(owner)
442
- }
443
-
444
- fn valid_owner_pane_id(pane_id: &str) -> bool {
445
- let pane_id = pane_id.trim();
446
- if pane_id.is_empty() {
447
- return false;
448
- }
449
- pane_id.starts_with('%') || pane_id.chars().all(|ch| ch.is_ascii_digit())
450
- }
451
-
452
- ///
453
- /// `_project_top_level_view`(`state.py:167`,C8):把 `teams[team_key]` 投影成扁平顶层视图。
454
- pub fn project_top_level_view(state: &Value, team_key: &str) -> Value {
455
- // entry = _team_entry_from_state(...) or {} —— 空 dict 亦走 {} 分支(同内容)。
456
- let entry_obj: Map<String, Value> = team_entry_from_state(state, team_key)
457
- .and_then(Value::as_object)
458
- .cloned()
459
- .unwrap_or_default();
460
- let mut p = entry_obj.clone(); // projection = deepcopy(entry)
461
- // setdefault session_name/team_dir ← entry.get(...)(缺则插,值可为 null)。
462
- // **0.3.24 excision** (U1-A real-machine RED v2): the ff38ab9 root-state
463
- // `or_else` fallback was reverted along with the wave-2 U1-A drift fallback,
464
- // since this projection change had no other consumer. v0.3.25 will re-introduce
465
- // this together with the writer-shape + rediscover-writer fix — see
466
- // `.team/artifacts/u1-a-realmachine-v2-fix-or-excise.md`.
467
- if !p.contains_key("session_name") {
468
- p.insert(
469
- "session_name".to_string(),
470
- entry_obj
471
- .get("session_name")
472
- .cloned()
473
- .unwrap_or(Value::Null),
474
- );
475
- }
476
- if !p.contains_key("team_dir") {
477
- p.insert(
478
- "team_dir".to_string(),
479
- entry_obj.get("team_dir").cloned().unwrap_or(Value::Null),
480
- );
481
- }
482
- // d[k]=v:active_team_key 原位更新或末尾插。
483
- p.insert(
484
- "active_team_key".to_string(),
485
- Value::String(team_key.to_string()),
486
- );
487
- // 保全全量 teams 供消费者看兄弟 team(`state.get("teams") or {}` 的 truthy 语义)。
488
- p.insert("teams".to_string(), py_or_empty_map(state.get("teams")));
489
- let has_team_entries = state
490
- .get("teams")
491
- .and_then(Value::as_object)
492
- .is_some_and(|teams| !teams.is_empty());
493
- // Stage 3b (identity-boundary unified plan, architect direction 2026-06-23):
494
- // remove the top-level owner promote. Pre-3b, when `teams.<key>` lacked
495
- // an owner entry the projection promoted the legacy top-level
496
- // `state.team_owner` into the projected view — that's the
497
- // "copy-back/promotion" the architect §Stage 3 calls out as the
498
- // dual-source bug origin (stale top-level owner could be served to
499
- // callers of a different team's projection). Now only the canonical
500
- // teams.<key> branch promotes; callers needing the legacy top-level
501
- // path must go through `state::ownership::read_owner_for_team` whose
502
- // precedence rule applies the migration-precedence semantics
503
- // explicitly (architect §3: teams > top-level only when
504
- // team_state_key matches).
505
- if let Some(v) = entry_obj.get("team_owner") {
506
- p.insert("team_owner".to_string(), v.clone());
507
- }
508
- if let Some(v) = entry_obj.get("leader_receiver") {
509
- p.insert("leader_receiver".to_string(), v.clone());
510
- }
511
- let _ = has_team_entries; // silence unused warning; kept for clarity.
512
- // coordinator:仅顶层有 key 时 setdefault(投影里没有才插)。
513
- if state
514
- .as_object()
515
- .is_some_and(|o| o.contains_key("coordinator"))
516
- && !p.contains_key("coordinator")
517
- {
518
- let mut coordinator = state["coordinator"].clone();
519
- // Workspace legacy watch facts have no proven owner in this team.
520
- // Preserve other coordinator fields, but never broadcast this cache.
521
- if let Some(coordinator) = coordinator.as_object_mut() {
522
- coordinator.remove("abnormal_exit_watch");
523
- }
524
- p.insert("coordinator".to_string(), coordinator);
525
- }
526
- Value::Object(p)
527
- }
528
-
529
- #[derive(Debug, Clone)]
530
- pub struct TeamScopeResolution {
531
- pub canonical_team_key: String,
532
- pub state: Value,
533
- }
534
-
535
- ///
536
- /// Resolve a requested team selector once, returning both the canonical map key and its
537
- /// projected state. Callers must carry `canonical_team_key` forward rather than deriving team
538
- /// identity again from the projection or the original alias.
539
- pub fn resolve_runtime_team_scope(
540
- workspace: &Path,
541
- team: Option<&str>,
542
- ) -> Result<TeamScopeResolution, StateError> {
543
- resolve_runtime_team_scope_loaded(load_runtime_state(workspace)?, team)
544
- }
545
-
546
- /// Same team selection as [`resolve_runtime_team_scope`], but never migrates or
547
- /// writes runtime state. Status and other read-only CLI surfaces must use this.
548
- pub fn resolve_runtime_team_scope_readonly(
549
- workspace: &Path,
550
- team: Option<&str>,
551
- ) -> Result<TeamScopeResolution, StateError> {
552
- resolve_runtime_team_scope_loaded(load_runtime_state_without_migrations(workspace)?, team)
553
- }
554
-
555
- fn resolve_runtime_team_scope_loaded(
556
- state: Value,
557
- team: Option<&str>,
558
- ) -> Result<TeamScopeResolution, StateError> {
559
- let alive = team_state_candidates(&state);
560
- // Python `if team:` —— 空串 falsy,等同无 team(对抗 P1:此前 Some("") 误入 team 分支,空
561
- // team_dir 匹配致歧义/未找到错误串漂移)。
562
- let team = team.filter(|t| !t.is_empty());
563
- if let Some(team) = team {
564
- // Intentional semantic split with `persist::apply_persist_merge_contract`:
565
- // selector resolution validates the active team against the alive/terminal
566
- // view, while the lock-held merge cannot depend on that mutable view. A
567
- // change to either CURRENT_TEAM_ALIAS mapping must evaluate the other.
568
- let canonical_request = if team.eq_ignore_ascii_case(CURRENT_TEAM_ALIAS) {
569
- let teams = state.get("teams").and_then(Value::as_object);
570
- state
571
- .get("active_team_key")
572
- .and_then(Value::as_str)
573
- .filter(|active| {
574
- alive.contains_key(*active)
575
- || teams.is_none_or(Map::is_empty)
576
- || teams
577
- .and_then(|teams| teams.get(*active))
578
- .is_some_and(team_has_attached_leader_receiver)
579
- })
580
- .map(str::to_string)
581
- .or_else(|| {
582
- teams
583
- .is_none_or(Map::is_empty)
584
- .then(|| team_state_key(&state))
585
- .filter(|derived| derived != "current")
586
- })
587
- .ok_or_else(|| {
588
- StateError::TeamSelect(format!(
589
- "team 'current' not found among alive teams. Use --team <team-key> with an explicit team key to address a terminal team. {}",
590
- format_team_candidates(&alive)
591
- ))
592
- })?
593
- } else {
594
- team.to_string()
595
- };
596
- let team = canonical_request.as_str();
597
- // An exact canonical key is authoritative even when the team is terminal or excluded from
598
- // the default alive-candidate set. Explicit lifecycle operations must still be able to
599
- // address a shutdown team without falling back to the raw root projection.
600
- if state
601
- .get("teams")
602
- .and_then(Value::as_object)
603
- .is_some_and(|teams| teams.contains_key(team))
604
- {
605
- return Ok(TeamScopeResolution {
606
- canonical_team_key: team.to_string(),
607
- state: project_top_level_view(&state, team),
608
- });
609
- }
610
- // 无 alive 但 team 命中 active_team_key / 派生 key → 直接以全量 state 投影。
611
- if alive.is_empty() {
612
- let active = state
613
- .get("active_team_key")
614
- .and_then(Value::as_str)
615
- .unwrap_or("");
616
- if team == active || team == team_state_key(&state) {
617
- let mut projection = state.clone();
618
- match projection.as_object_mut() {
619
- Some(o) => {
620
- o.insert(
621
- "active_team_key".to_string(),
622
- Value::String(team.to_string()),
623
- );
624
- }
625
- None => projection = json!({ "active_team_key": team }),
626
- }
627
- return Ok(TeamScopeResolution {
628
- canonical_team_key: team.to_string(),
629
- state: projection,
630
- });
631
- }
632
- }
633
- let matches: Vec<&String> = alive
634
- .iter()
635
- .filter(|(key, value)| team_selector_matches(team, key, value))
636
- .map(|(k, _)| k)
637
- .collect();
638
- if matches.len() == 1 {
639
- return Ok(TeamScopeResolution {
640
- canonical_team_key: matches[0].clone(),
641
- state: project_top_level_view(&state, matches[0]),
642
- });
643
- }
644
- if matches.len() > 1 {
645
- return Err(StateError::TeamSelect(
646
- "team selector is ambiguous. ".to_string() + &format_team_candidates(&alive),
647
- ));
648
- }
649
- return Err(StateError::TeamSelect(format!(
650
- "team {} not found. {}",
651
- py_repr_str(team),
652
- format_team_candidates(&alive)
653
- )));
654
- }
655
- // 无 team 参数:active 命中 → 投影;唯一 alive → 投影;无 alive → 全量;多 alive → 歧义。
656
- let active = state
657
- .get("active_team_key")
658
- .and_then(Value::as_str)
659
- .filter(|s| !s.is_empty());
660
- if let Some(active) = active {
661
- if alive.contains_key(active) {
662
- return Ok(TeamScopeResolution {
663
- canonical_team_key: active.to_string(),
664
- state: project_top_level_view(&state, active),
665
- });
666
- }
667
- }
668
- if alive.len() == 1 {
669
- let only = alive.keys().next().cloned().unwrap_or_default();
670
- return Ok(TeamScopeResolution {
671
- canonical_team_key: only.clone(),
672
- state: project_top_level_view(&state, &only),
673
- });
674
- }
675
- if alive.is_empty() {
676
- // 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.1):
677
- // 全体被标 shutdown(bare restart 场景),`active_team_key` 若命中
678
- // `state.teams` 则仍投影,让 `project_top_level_view` 用 nested
679
- // `teams[key].agents` 覆盖历史顶层注入(E2E-REST-002 前置)。
680
- if let Some(active_key) = state.get("active_team_key").and_then(Value::as_str) {
681
- if state
682
- .get("teams")
683
- .and_then(Value::as_object)
684
- .is_some_and(|teams| teams.contains_key(active_key))
685
- {
686
- return Ok(TeamScopeResolution {
687
- canonical_team_key: active_key.to_string(),
688
- state: project_top_level_view(&state, active_key),
689
- });
690
- }
691
- }
692
- let canonical_team_key = state
693
- .get("active_team_key")
694
- .and_then(Value::as_str)
695
- .filter(|key| !key.is_empty())
696
- .map(str::to_string)
697
- .unwrap_or_else(|| team_state_key(&state));
698
- return Ok(TeamScopeResolution {
699
- canonical_team_key,
700
- state,
701
- });
702
- }
703
- Err(StateError::TeamSelect(
704
- "multiple teams found in this workspace; pass --team <team> to choose. ".to_string()
705
- + &format_team_candidates(&alive),
706
- ))
707
- }
708
-
709
- ///
710
- /// `select_runtime_state`(`state.py:193`):compatibility projection wrapper.
711
- pub fn select_runtime_state(workspace: &Path, team: Option<&str>) -> Result<Value, StateError> {
712
- resolve_runtime_team_scope(workspace, team).map(|resolved| resolved.state)
713
- }
714
-
715
- fn team_selector_matches(team: &str, key: &str, value: &Value) -> bool {
716
- if team == key {
717
- return true;
718
- }
719
- let session = value
720
- .get("session_name")
721
- .and_then(Value::as_str)
722
- .unwrap_or("");
723
- if team == session {
724
- return true;
725
- }
726
- if let Some(stripped) = session.strip_prefix("team-") {
727
- if team == stripped {
728
- return true;
729
- }
730
- }
731
- let dir = value.get("team_dir").and_then(Value::as_str).unwrap_or("");
732
- if team == dir {
733
- return true;
734
- }
735
- std::path::Path::new(dir)
736
- .file_name()
737
- .and_then(|name| name.to_str())
738
- .is_some_and(|name| team == name)
739
- }
740
-
741
- ///
742
- /// `ambiguous_team_target_result`(`state.py:226`):无显式 team 且多候选 → 拒绝 dict;否则 None。
743
- fn ambiguous_team_target_result(state: &Value) -> Option<Value> {
744
- let alive = team_state_candidates(state);
745
- let active = state
746
- .get("active_team_key")
747
- .and_then(Value::as_str)
748
- .filter(|s| !s.is_empty());
749
- if let Some(active) = active {
750
- if alive.contains_key(active) {
751
- return None;
752
- }
753
- }
754
- if alive.len() <= 1 {
755
- return None;
756
- }
757
- let mut candidates: Vec<&String> = alive.keys().collect();
758
- candidates.sort();
759
- Some(json!({
760
- "ok": false,
761
- "status": "refused",
762
- "reason": "team_target_ambiguous",
763
- "candidates": candidates,
764
- "message": "multiple teams found in this workspace; pass --team <team> to choose. ".to_string()
765
- + &format_team_candidates(&alive),
766
- }))
767
- }
768
-
769
- ///
770
- /// `resolve_team_scoped_state`(`state.py:243`):返回 `(state, refusal)`,二者恰一为 Some。
771
- /// `team=None` 且歧义 → refusal;否则 select,RuntimeError → `team_target_unresolved` refusal。
772
- pub fn resolve_team_scoped_state(
773
- workspace: &Path,
774
- team: Option<&str>,
775
- ) -> Result<(Option<Value>, Option<Value>), StateError> {
776
- if team.is_none() {
777
- let state = load_runtime_state(workspace)?;
778
- if let Some(ambiguous) = ambiguous_team_target_result(&state) {
779
- return Ok((None, Some(ambiguous)));
780
- }
781
- }
782
- match select_runtime_state(workspace, team) {
783
- Ok(state) => Ok((Some(state), None)),
784
- Err(StateError::TeamSelect(msg)) => Ok((
785
- None,
786
- Some(json!({
787
- "ok": false,
788
- "status": "refused",
789
- "reason": "team_target_unresolved",
790
- "team": team,
791
- "error": msg,
792
- })),
793
- )),
794
- Err(e) => Err(e),
795
- }
796
- }
797
-
798
- ///
799
- /// `save_team_scoped_state`(`state.py:594`):把 team-scoped(投影后)state 写回 workspace,**保全**
800
- /// 多 team workspace 里其他 team 的持久态。单 team(磁盘无 `teams` 且 primary key == target)退化为
801
- /// 纯 `save_runtime_state`(字节等价);多 team 时把本 team 落到 `teams[target_key]=compact(...)`,顶层
802
- /// 视图按 golden 的 `existing_primary_key` 逻辑择 incoming/existing。§10:无 unwrap/panic。
803
- pub fn save_team_scoped_state(workspace: &Path, team_state: &Value) -> Result<(), StateError> {
804
- save_team_scoped_state_with_deleted_agents(workspace, team_state, &[])
805
- }
806
-
807
- /// Materialize a bounded Team update from the lock-held workspace. Siblings
808
- /// come only from latest; retain the existing primary/legacy projection rules.
809
- pub(super) fn merge_committed_team(existing: &Value, team_state: &Value, target_key: &str) -> Value {
810
- let mut primary = existing.get("session_name").and_then(Value::as_str)
811
- .filter(|name| !name.is_empty()).map(|_| team_state_key(existing));
812
- if primary.as_deref().is_some_and(|key| key != target_key)
813
- && existing.get("session_name") == team_state.get("session_name")
814
- {
815
- primary = Some(target_key.to_string());
816
- }
817
- let mut teams = take_object(existing.get("teams"));
818
- if teams.is_empty() && primary.as_deref() == Some(target_key) {
819
- return compact_team_state(team_state);
820
- }
821
- teams.insert(target_key.to_string(), compact_team_state(team_state));
822
- let mut merged = if primary.is_none() || primary.as_deref() == Some(target_key) {
823
- to_object(team_state)
824
- } else {
825
- to_object(existing)
826
- };
827
- merged.insert("teams".to_string(), Value::Object(teams));
828
- Value::Object(merged)
829
- }
830
-
831
- pub(crate) fn save_team_scoped_state_reapplying_after_conflict<F>(
832
- workspace: &Path,
833
- team_state: &Value,
834
- reapply: F,
835
- ) -> Result<(), StateError>
836
- where
837
- F: FnOnce(&mut Value),
838
- {
839
- match save_team_scoped_state(workspace, team_state) {
840
- Ok(()) => Ok(()),
841
- Err(StateError::SaveConflict(_)) => {
842
- let target_key = team_state_key(team_state);
843
- let mut latest = select_runtime_state(workspace, Some(&target_key))?;
844
- reapply(&mut latest);
845
- save_team_scoped_state(workspace, &latest)
846
- }
847
- Err(error) => Err(error),
848
- }
849
- }
850
-
851
- pub(crate) fn save_team_scoped_state_with_deleted_agents(
852
- workspace: &Path,
853
- team_state: &Value,
854
- deleted_agent_ids: &[&str],
855
- ) -> Result<(), StateError> {
856
- save_team_scoped_state_with_merge_exceptions(workspace, team_state, deleted_agent_ids, &[])
857
- }
858
-
859
- pub(crate) fn save_team_scoped_state_with_tombstone_lifecycle_topology_authority(
860
- workspace: &Path,
861
- team_state: &Value,
862
- topology_team_key: &str,
863
- agent_ids: &[&str],
864
- ) -> Result<(), StateError> {
865
- save_team_scoped_state_with_merge_options(
866
- workspace,
867
- team_state,
868
- &[],
869
- agent_ids,
870
- &[],
871
- Some(topology_team_key),
872
- agent_ids,
873
- )
874
- }
875
-
876
- pub(crate) fn save_team_scoped_state_with_lifecycle_topology_authority(
877
- workspace: &Path,
878
- team_state: &Value,
879
- topology_team_key: &str,
880
- agent_ids: &[&str],
881
- ) -> Result<(), StateError> {
882
- save_team_scoped_state_with_merge_options(
883
- workspace,
884
- team_state,
885
- &[],
886
- &[],
887
- &[],
888
- Some(topology_team_key),
889
- agent_ids,
890
- )
891
- }
892
-
893
- pub(crate) fn save_team_scoped_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
894
- workspace: &Path,
895
- team_state: &Value,
896
- topology_team_key: &str,
897
- skip_capture_backfill_agent_ids: &[&str],
898
- topology_agent_ids: &[&str],
899
- ) -> Result<(), StateError> {
900
- save_team_scoped_state_with_merge_options(
901
- workspace,
902
- team_state,
903
- &[],
904
- &[],
905
- skip_capture_backfill_agent_ids,
906
- Some(topology_team_key),
907
- topology_agent_ids,
908
- )
909
- }
910
-
911
- fn save_team_scoped_state_with_merge_exceptions(
912
- workspace: &Path,
913
- team_state: &Value,
914
- deleted_agent_ids: &[&str],
915
- tombstoned_agent_ids: &[&str],
916
- ) -> Result<(), StateError> {
917
- save_team_scoped_state_with_merge_options(
918
- workspace,
919
- team_state,
920
- deleted_agent_ids,
921
- tombstoned_agent_ids,
922
- &[],
923
- None,
924
- &[],
925
- )
926
- }
927
-
928
- fn save_team_scoped_state_with_merge_options(
929
- workspace: &Path,
930
- team_state: &Value,
931
- deleted_agent_ids: &[&str],
932
- tombstoned_agent_ids: &[&str],
933
- skip_capture_backfill_agent_ids: &[&str],
934
- topology_team_key: Option<&str>,
935
- topology_agent_ids: &[&str],
936
- ) -> Result<(), StateError> {
937
- let target_key = team_state_key(team_state);
938
- let existing = load_runtime_state(workspace)?;
939
- // existing_primary_key = team_state_key(existing) if existing.get("session_name") else None
940
- let mut existing_primary_key = if truthy_str(existing.get("session_name")) {
941
- Some(team_state_key(&existing))
942
- } else {
943
- None
944
- };
945
- // 异 key 但顶层 session_name 与 incoming 相同 → 视为同 primary(golden:把 existing_primary_key 拉成 target)。
946
- let same_session = existing
947
- .get("session_name")
948
- .and_then(Value::as_str)
949
- .filter(|s| !s.is_empty())
950
- .is_some_and(|s| {
951
- team_state
952
- .get("session_name")
953
- .and_then(Value::as_str)
954
- .is_some_and(|t| t == s)
955
- });
956
- if existing_primary_key
957
- .as_deref()
958
- .is_some_and(|k| k != target_key)
959
- && same_session
960
- {
961
- existing_primary_key = Some(target_key.clone());
962
- }
963
- let existing_teams = take_object(existing.get("teams"));
964
- // incoming_teams = team_state.get("teams") if isinstance(dict) else None
965
- let incoming_teams = team_state.get("teams").and_then(Value::as_object).cloned();
966
- // not existing_teams and existing_primary_key == target_key → 纯 save(剔 teams)。
967
- if existing_teams.is_empty() && existing_primary_key.as_deref() == Some(target_key.as_str()) {
968
- let merged = compact_team_state(team_state);
969
- if !topology_agent_ids.is_empty() {
970
- if !tombstoned_agent_ids.is_empty() {
971
- return save_runtime_state_with_team_tombstone_lifecycle_topology_authority(
972
- workspace,
973
- &merged,
974
- topology_team_key.unwrap_or(&target_key),
975
- topology_agent_ids,
976
- );
977
- }
978
- if !skip_capture_backfill_agent_ids.is_empty() {
979
- return save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
980
- workspace,
981
- &merged,
982
- topology_team_key.unwrap_or(&target_key),
983
- skip_capture_backfill_agent_ids,
984
- topology_agent_ids,
985
- );
986
- }
987
- return save_runtime_state_with_lifecycle_topology_authority(
988
- workspace,
989
- &merged,
990
- topology_team_key.unwrap_or(&target_key),
991
- topology_agent_ids,
992
- );
993
- }
994
- if !skip_capture_backfill_agent_ids.is_empty() {
995
- return save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
996
- workspace,
997
- &merged,
998
- &target_key,
999
- skip_capture_backfill_agent_ids,
1000
- &[],
1001
- );
1002
- }
1003
- if tombstoned_agent_ids.is_empty() {
1004
- return save_runtime_state_with_deleted_agents(
1005
- workspace,
1006
- &merged,
1007
- deleted_agent_ids,
1008
- );
1009
- }
1010
- return save_runtime_state_with_team_tombstoned_agents(
1011
- workspace,
1012
- &merged,
1013
- &target_key,
1014
- tombstoned_agent_ids,
1015
- );
1016
- }
1017
- // teams = deepcopy(incoming_teams or existing_teams)
1018
- let mut teams = match incoming_teams {
1019
- Some(m) if !m.is_empty() => m,
1020
- _ => existing_teams,
1021
- };
1022
- teams.insert(target_key.clone(), compact_team_state(team_state));
1023
- let mut merged = if existing_primary_key.is_none()
1024
- || existing_primary_key.as_deref() == Some(target_key.as_str())
1025
- {
1026
- to_object(team_state)
1027
- } else {
1028
- to_object(&existing)
1029
- };
1030
- merged.insert("teams".to_string(), Value::Object(teams));
1031
- // if not merged.get("teams"): merged.pop("teams", None) —— teams 为空 dict(falsy)则剔除。
1032
- if merged
1033
- .get("teams")
1034
- .and_then(Value::as_object)
1035
- .is_some_and(Map::is_empty)
1036
- {
1037
- merged.remove("teams");
1038
- }
1039
- if tombstoned_agent_ids.is_empty() {
1040
- if !topology_agent_ids.is_empty() {
1041
- if !skip_capture_backfill_agent_ids.is_empty() {
1042
- save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
1043
- workspace,
1044
- &Value::Object(merged),
1045
- topology_team_key.unwrap_or(&target_key),
1046
- skip_capture_backfill_agent_ids,
1047
- topology_agent_ids,
1048
- )
1049
- } else {
1050
- save_runtime_state_with_lifecycle_topology_authority(
1051
- workspace,
1052
- &Value::Object(merged),
1053
- topology_team_key.unwrap_or(&target_key),
1054
- topology_agent_ids,
1055
- )
1056
- }
1057
- } else if !skip_capture_backfill_agent_ids.is_empty() {
1058
- save_runtime_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
1059
- workspace,
1060
- &Value::Object(merged),
1061
- &target_key,
1062
- skip_capture_backfill_agent_ids,
1063
- &[],
1064
- )
1065
- } else {
1066
- save_runtime_state_with_deleted_agents(
1067
- workspace,
1068
- &Value::Object(merged),
1069
- deleted_agent_ids,
1070
- )
1071
- }
1072
- } else {
1073
- if !topology_agent_ids.is_empty() {
1074
- return save_runtime_state_with_team_tombstone_lifecycle_topology_authority(
1075
- workspace,
1076
- &Value::Object(merged),
1077
- &target_key,
1078
- topology_agent_ids,
1079
- );
1080
- }
1081
- save_runtime_state_with_team_tombstoned_agents(
1082
- workspace,
1083
- &Value::Object(merged),
1084
- &target_key,
1085
- tombstoned_agent_ids,
1086
- )
1087
- }
1088
- }
1089
-
1090
- // ---- helpers ----
1091
-
1092
- /// Python truthiness of a string-or-null value(非空串 → true;null/缺/空串 → false)。
1093
- fn truthy_str(v: Option<&Value>) -> bool {
1094
- v.and_then(Value::as_str).is_some_and(|s| !s.is_empty())
1095
- }
1096
-
1097
- /// Python `x or {}`:`x` truthy 则取 `x`,否则 `{}`。
1098
- fn py_or_empty_map(v: Option<&Value>) -> Value {
1099
- match v {
1100
- Some(x) if super::json_truthy(x) => x.clone(),
1101
- _ => json!({}),
1102
- }
1103
- }
1104
-
1105
- /// `v` 为 object → 克隆其 `Map`;否则空 `Map`(deepcopy(dict) 的优雅退化)。
1106
- fn to_object(v: &Value) -> Map<String, Value> {
1107
- v.as_object().cloned().unwrap_or_default()
1108
- }
1109
-
1110
- /// `v.get(...) or {}` 取 object → 克隆;否则空 `Map`。
1111
- fn take_object(v: Option<&Value>) -> Map<String, Value> {
1112
- v.and_then(Value::as_object).cloned().unwrap_or_default()
1113
- }
1114
-
1115
- /// Python `repr()` of a `str`(与 `model::spec::py_repr_str` 同实现,本地副本免改工作模块)。
1116
- fn py_repr_str(s: &str) -> String {
1117
- let quote = if s.contains('\'') && !s.contains('"') {
1118
- '"'
1119
- } else {
1120
- '\''
1121
- };
1122
- let mut out = String::new();
1123
- out.push(quote);
1124
- for c in s.chars() {
1125
- match c {
1126
- '\\' => out.push_str("\\\\"),
1127
- c if c == quote => {
1128
- out.push('\\');
1129
- out.push(c);
1130
- }
1131
- '\n' => out.push_str("\\n"),
1132
- '\r' => out.push_str("\\r"),
1133
- '\t' => out.push_str("\\t"),
1134
- c => out.push(c),
1135
- }
1136
- }
1137
- out.push(quote);
1138
- out
1139
- }
1140
-
1141
- #[cfg(test)]
1142
- mod tests {
1143
- #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
1144
- use super::*;
1145
- use std::sync::atomic::{AtomicU32, Ordering};
1146
-
1147
- static SEQ: AtomicU32 = AtomicU32::new(0);
1148
-
1149
- /// 比较紧凑序列化(serde_json::to_string 无空格)—— 同时锁值 + 键插入序。
1150
- fn same_repr(a: &Value, b: &Value) {
1151
- assert_eq!(
1152
- serde_json::to_string(a).unwrap(),
1153
- serde_json::to_string(b).unwrap()
1154
- );
1155
- }
1156
-
1157
- fn temp_ws_with_state(state: &Value) -> std::path::PathBuf {
1158
- let n = SEQ.fetch_add(1, Ordering::Relaxed);
1159
- let ws = std::env::temp_dir().join(format!("ta_rs_proj_{}_{}", std::process::id(), n));
1160
- let rt = ws.join(".team").join("runtime");
1161
- std::fs::create_dir_all(&rt).unwrap();
1162
- std::fs::write(rt.join("state.json"), serde_json::to_string(state).unwrap()).unwrap();
1163
- ws
1164
- }
1165
-
1166
- #[test]
1167
- fn restart_stop_marker_is_conservative_without_blocking_crash_states() {
1168
- for row in [
1169
- json!({"status":"stopped"}),
1170
- json!({"status":"stopped","explicit_stop":false}),
1171
- json!({"status":"running","explicit_stop":true}),
1172
- json!({"status":"running","explicit_stop":"false"}),
1173
- ] {
1174
- assert!(agent_stopped_for_restart(&row));
1175
- }
1176
- for status in ["running", "dead", "restart_failed"] {
1177
- assert!(!agent_stopped_for_restart(&json!({"status":status,"explicit_stop":false})));
1178
- }
1179
- }
1180
-
1181
- #[test]
1182
- fn team_state_key_cases() {
1183
- assert_eq!(
1184
- team_state_key(&json!({"team_dir": "/ws/.team/myteam"})),
1185
- "myteam"
1186
- );
1187
- assert_eq!(
1188
- team_state_key(&json!({"team_dir": "/ws/.team/runtime", "session_name": "sess"})),
1189
- "sess"
1190
- );
1191
- assert_eq!(
1192
- team_state_key(&json!({"spec_path": "/ws/.team/alpha/TEAM.md"})),
1193
- "alpha"
1194
- );
1195
- assert_eq!(team_state_key(&json!({"session_name": "sname"})), "sname");
1196
- assert_eq!(team_state_key(&json!({})), "current");
1197
- assert_eq!(team_state_key(&json!({"session_name": ""})), "current");
1198
- }
1199
-
1200
- #[test]
1201
- fn compact_drops_teams_keeps_order() {
1202
- let r = compact_team_state(&json!({"a": 1, "teams": {"x": {}}, "b": 2}));
1203
- same_repr(&r, &json!({"a": 1, "b": 2}));
1204
- }
1205
-
1206
- #[test]
1207
- fn candidates_alive_filter_and_order() {
1208
- // 0.5.26 (`.team/artifacts/stale-team-saveconflict-locate.md` §7.1):
1209
- // 空 bootstrap team(无 agents)在 status 缺失时保 alive 兼容;
1210
- // 但「status 缺失 + 全体 agent stopped」是 legacy shutdown residue,
1211
- // 必须被剔除,防止 shutdown --keep-logs 的死队卡活队写入。
1212
- let s = json!({"teams": {
1213
- "alive1": {"status": "alive", "session_name": "sa"},
1214
- "dead1": {"status": "shutdown"},
1215
- "nostatus": {"session_name": "sn"},
1216
- "ALIVE_CASE": {"status": "ALIVE"},
1217
- "legacy_shutdown_all_stopped": {
1218
- "session_name": "team-supermarket-suite",
1219
- "agents": {"adminweb": {"status": "stopped"}}
1220
- },
1221
- }});
1222
- let cands = team_state_candidates(&s);
1223
- let keys: Vec<&String> = cands.keys().collect();
1224
- assert_eq!(keys, vec!["alive1", "nostatus", "ALIVE_CASE"]);
1225
- }
1226
-
1227
- #[test]
1228
- fn format_candidates_golden() {
1229
- let s = json!({"teams": {
1230
- "alive1": {"status": "alive", "session_name": "sa"},
1231
- "dead1": {"status": "shutdown"},
1232
- "nostatus": {"session_name": "sn"},
1233
- "ALIVE_CASE": {"status": "ALIVE"},
1234
- }});
1235
- assert_eq!(
1236
- format_team_candidates(&team_state_candidates(&s)),
1237
- "Candidates: ALIVE_CASE session=- agents=-; alive1 session=sa agents=-; nostatus session=sn agents=-"
1238
- );
1239
- assert_eq!(
1240
- format_team_candidates(&Map::new()),
1241
- "No team state was found."
1242
- );
1243
- let mut m = Map::new();
1244
- m.insert(
1245
- "k2".to_string(),
1246
- json!({"session_name": "s2", "agents": {"b": {}, "a": {}}}),
1247
- );
1248
- m.insert("k1".to_string(), json!({}));
1249
- assert_eq!(
1250
- format_team_candidates(&m),
1251
- "Candidates: k1 session=- agents=-; k2 session=s2 agents=a,b"
1252
- );
1253
- }
1254
-
1255
- #[test]
1256
- fn project_top_level_view_golden() {
1257
- let s = json!({
1258
- "teams": {"t1": {"session_name": "ses1", "team_dir": "/w/.team/t1", "agents": {"a": {}}, "team_owner": {"pane_id": "%1"}}},
1259
- "team_owner": {"pane_id": "%top"},
1260
- "leader_receiver": {"pane_id": "%lr"},
1261
- "coordinator": {"pid": 99},
1262
- });
1263
- let expected = json!({
1264
- "session_name": "ses1", "team_dir": "/w/.team/t1", "agents": {"a": {}}, "team_owner": {"pane_id": "%1"},
1265
- "active_team_key": "t1",
1266
- "teams": {"t1": {"session_name": "ses1", "team_dir": "/w/.team/t1", "agents": {"a": {}}, "team_owner": {"pane_id": "%1"}}},
1267
- "coordinator": {"pid": 99},
1268
- });
1269
- same_repr(&project_top_level_view(&s, "t1"), &expected);
1270
- }
1271
-
1272
- #[test]
1273
- fn project_top_level_view_does_not_fall_to_toplevel_owner_when_teams_exist() {
1274
- let s =
1275
- json!({"teams": {"t2": {"session_name": "s2"}}, "team_owner": {"pane_id": "%top2"}});
1276
- let expected = json!({
1277
- "session_name": "s2", "team_dir": null, "active_team_key": "t2",
1278
- "teams": {"t2": {"session_name": "s2"}},
1279
- });
1280
- same_repr(&project_top_level_view(&s, "t2"), &expected);
1281
- }
1282
-
1283
- #[test]
1284
- fn merge_three_branches_golden() {
1285
- same_repr(
1286
- &merge_workspace_team_state(
1287
- &json!({}),
1288
- &json!({"team_dir": "/w/.team/t1", "session_name": "s1", "agents": {}}),
1289
- ),
1290
- &json!({"team_dir": "/w/.team/t1", "session_name": "s1", "agents": {},
1291
- "teams": {"t1": {"team_dir": "/w/.team/t1", "session_name": "s1", "agents": {}}}}),
1292
- );
1293
- same_repr(
1294
- &merge_workspace_team_state(
1295
- &json!({"team_dir": "/w/.team/t1", "session_name": "old", "teams": {"t1": {"session_name": "older"}}}),
1296
- &json!({"team_dir": "/w/.team/t1", "session_name": "new"}),
1297
- ),
1298
- &json!({"team_dir": "/w/.team/t1", "session_name": "new",
1299
- "teams": {"t1": {"team_dir": "/w/.team/t1", "session_name": "new"}}}),
1300
- );
1301
- same_repr(
1302
- &merge_workspace_team_state(
1303
- &json!({"team_dir": "/w/.team/t1", "session_name": "s1"}),
1304
- &json!({"team_dir": "/w/.team/t2", "session_name": "s2"}),
1305
- ),
1306
- &json!({"team_dir": "/w/.team/t1", "session_name": "s1",
1307
- "teams": {"t1": {"team_dir": "/w/.team/t1", "session_name": "s1"},
1308
- "t2": {"team_dir": "/w/.team/t2", "session_name": "s2"}}}),
1309
- );
1310
- }
1311
-
1312
- #[test]
1313
- fn select_runtime_state_errors_match_python() {
1314
- let ws = temp_ws_with_state(&json!({"teams": {
1315
- "t1": {"status": "alive", "session_name": "s1"},
1316
- "t2": {"status": "alive", "session_name": "s2"},
1317
- }}));
1318
- let e = select_runtime_state(&ws, Some("missing")).unwrap_err();
1319
- assert_eq!(
1320
- e.to_string(),
1321
- "team 'missing' not found. Candidates: t1 session=s1 agents=-; t2 session=s2 agents=-"
1322
- );
1323
- let e2 = select_runtime_state(&ws, None).unwrap_err();
1324
- assert_eq!(
1325
- e2.to_string(),
1326
- "multiple teams found in this workspace; pass --team <team> to choose. Candidates: t1 session=s1 agents=-; t2 session=s2 agents=-"
1327
- );
1328
-
1329
- let ws2 = temp_ws_with_state(&json!({"teams": {
1330
- "t1": {"status": "alive", "session_name": "dup"},
1331
- "t2": {"status": "alive", "session_name": "dup"},
1332
- }}));
1333
- let e3 = select_runtime_state(&ws2, Some("dup")).unwrap_err();
1334
- assert_eq!(
1335
- e3.to_string(),
1336
- "team selector is ambiguous. Candidates: t1 session=dup agents=-; t2 session=dup agents=-"
1337
- );
1338
- }
1339
-
1340
- #[test]
1341
- fn resolve_runtime_team_scope_current_uses_valid_active_key() {
1342
- let ws = temp_ws_with_state(&json!({
1343
- "active_team_key": "alpha",
1344
- "teams": {
1345
- "alpha": {"status": "alive", "session_name": "team-alpha", "agents": {"worker": {}}},
1346
- "old-team": {"team_owner": {"pane_id": "%9"}}
1347
- }
1348
- }));
1349
- let resolved = resolve_runtime_team_scope(&ws, Some("current")).unwrap();
1350
- assert_eq!(resolved.canonical_team_key, "alpha");
1351
- assert_eq!(
1352
- resolved.state.get("active_team_key").and_then(Value::as_str),
1353
- Some("alpha")
1354
- );
1355
- }
1356
-
1357
- #[test]
1358
- fn resolve_runtime_team_scope_current_accepts_attached_receiver_recovery() {
1359
- let ws = temp_ws_with_state(&json!({
1360
- "active_team_key": "alpha",
1361
- "teams": {
1362
- "alpha": {
1363
- "agents": {},
1364
- "leader_receiver": {"status": "attached", "pane_id": "%9"}
1365
- }
1366
- }
1367
- }));
1368
- let resolved = resolve_runtime_team_scope(&ws, Some("current")).unwrap();
1369
- assert_eq!(resolved.canonical_team_key, "alpha");
1370
- }
1371
-
1372
- #[test]
1373
- fn resolve_runtime_team_scope_current_accepts_shutdown_receiver_recovery() {
1374
- let ws = temp_ws_with_state(&json!({
1375
- "active_team_key": "alpha",
1376
- "teams": {
1377
- "alpha": {
1378
- "status": "shutdown",
1379
- "agents": {"worker": {"status": "stopped"}},
1380
- "leader_receiver": {"status": "attached", "pane_id": "%9"}
1381
- }
1382
- }
1383
- }));
1384
- let resolved = resolve_runtime_team_scope(&ws, Some("current")).unwrap();
1385
- assert_eq!(resolved.canonical_team_key, "alpha");
1386
- }
1387
-
1388
- #[test]
1389
- fn resolve_runtime_team_scope_current_rejects_owner_only_stub() {
1390
- let ws = temp_ws_with_state(&json!({
1391
- "active_team_key": "old-team",
1392
- "teams": {
1393
- "old-team": {"agents": {}, "team_owner": {"pane_id": "%9"}}
1394
- }
1395
- }));
1396
- let error = resolve_runtime_team_scope(&ws, Some("current")).unwrap_err();
1397
- assert!(error.to_string().contains("team 'current' not found"));
1398
- }
1399
-
1400
- #[test]
1401
- fn resolve_runtime_team_scope_current_fails_without_valid_active_key() {
1402
- let ws = temp_ws_with_state(&json!({
1403
- "active_team_key": "missing",
1404
- "teams": {
1405
- "alpha": {"status": "alive", "session_name": "team-alpha", "agents": {"worker": {}}}
1406
- }
1407
- }));
1408
- let error = resolve_runtime_team_scope(&ws, Some("current")).unwrap_err();
1409
- assert!(error.to_string().contains("team 'current' not found"));
1410
- }
1411
-
1412
- #[test]
1413
- fn resolve_runtime_team_scope_current_keeps_legacy_single_team_state() {
1414
- let ws = temp_ws_with_state(&json!({
1415
- "active_team_key": "legacy",
1416
- "team_key": "legacy",
1417
- "session_name": "team-legacy",
1418
- "agents": {"worker": {"status": "running"}}
1419
- }));
1420
- let resolved = resolve_runtime_team_scope(&ws, Some("current")).unwrap();
1421
- assert_eq!(resolved.canonical_team_key, "legacy");
1422
- assert_eq!(resolved.state["active_team_key"], json!("legacy"));
1423
- }
1424
-
1425
- #[test]
1426
- fn resolve_runtime_team_scope_current_rejects_empty_workspace_bootstrap() {
1427
- let ws = temp_ws_with_state(&json!({}));
1428
- let error = resolve_runtime_team_scope(&ws, Some("current")).unwrap_err();
1429
- assert!(error.to_string().contains("team 'current' not found"));
1430
- let saved = load_runtime_state(&ws).unwrap();
1431
- assert_ne!(
1432
- saved.get("active_team_key").and_then(Value::as_str),
1433
- Some("current")
1434
- );
1435
- assert!(!crate::model::paths::runtime_spec_path(&ws, "current").exists());
1436
- }
1437
-
1438
- // 对抗 P1:空串 team 必须走「无 team」分支(Python `if team:` falsy),报「multiple teams」
1439
- // 而非「team selector is ambiguous」(后者是非空 team 多匹配)。
1440
- #[test]
1441
- fn select_runtime_state_empty_team_is_no_team() {
1442
- let ws = temp_ws_with_state(&json!({"teams": {
1443
- "t1": {"status": "alive", "session_name": "s1"},
1444
- "t2": {"status": "alive", "session_name": "s2"},
1445
- }}));
1446
- let empty = select_runtime_state(&ws, Some("")).unwrap_err();
1447
- let none = select_runtime_state(&ws, None).unwrap_err();
1448
- assert_eq!(empty.to_string(), none.to_string());
1449
- assert!(empty
1450
- .to_string()
1451
- .starts_with("multiple teams found in this workspace"));
1452
- }
1453
-
1454
- #[test]
1455
- fn select_runtime_state_team_id_exact_match_beats_session_alias() {
1456
- let ws = temp_ws_with_state(&json!({"teams": {
1457
- "current": {"status": "alive", "session_name": "dup"},
1458
- "dup": {"status": "alive", "session_name": "actual-session"},
1459
- }}));
1460
- let selected = select_runtime_state(&ws, Some("dup")).unwrap();
1461
- assert_eq!(
1462
- selected["active_team_key"],
1463
- json!("dup"),
1464
- "an exact team-id match must not be ambiguous just because another team has the same session alias"
1465
- );
1466
- assert_eq!(selected["session_name"], json!("actual-session"));
1467
- }
1468
-
1469
- #[test]
1470
- fn archived_team_without_alive_status_is_not_a_default_status_candidate() {
1471
- let candidates = team_state_candidates(&json!({"teams": {
1472
- "archived": {"archived_at": "2026-06-04T00:00:00Z", "session_name": "old-session"},
1473
- "current": {"status": "alive", "session_name": "current-session"},
1474
- }}));
1475
- assert_eq!(
1476
- candidates.keys().cloned().collect::<Vec<_>>(),
1477
- vec!["current".to_string()],
1478
- "status should default to the current/live team; archived markers must not be treated as alive"
1479
- );
1480
- }
1481
-
1482
- #[test]
1483
- fn select_runtime_state_single_alive_projects() {
1484
- let ws = temp_ws_with_state(
1485
- &json!({"teams": {"only": {"status": "alive", "session_name": "so"}}}),
1486
- );
1487
- let r = select_runtime_state(&ws, None).unwrap();
1488
- assert_eq!(r["active_team_key"], json!("only"));
1489
- assert_eq!(r["session_name"], json!("so"));
1490
- }
1491
-
1492
- #[test]
1493
- fn resolve_team_scoped_state_ambiguous_refusal() {
1494
- let ws = temp_ws_with_state(&json!({"teams": {
1495
- "t1": {"status": "alive", "session_name": "s1"},
1496
- "t2": {"status": "alive", "session_name": "s2"},
1497
- }}));
1498
- let (state, refusal) = resolve_team_scoped_state(&ws, None).unwrap();
1499
- assert!(state.is_none());
1500
- let refusal = refusal.unwrap();
1501
- assert_eq!(refusal["reason"], json!("team_target_ambiguous"));
1502
- assert_eq!(refusal["candidates"], json!(["t1", "t2"]));
1503
-
1504
- let (state2, refusal2) = resolve_team_scoped_state(&ws, Some("missing")).unwrap();
1505
- assert!(state2.is_none());
1506
- assert_eq!(refusal2.unwrap()["reason"], json!("team_target_unresolved"));
1507
- }
1508
- }