@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,3981 +0,0 @@
1
- #[path = "../../../tests/support/hermetic.rs"]
2
- mod hermetic_guard;
3
-
4
- use super::*;
5
- use crate::tmux_backend::TmuxBackend;
6
- use crate::transport::test_support::OfflineTransport;
7
- use crate::transport::Transport;
8
- use serde_json::json;
9
- use serial_test::serial;
10
-
11
- fn enter_hermetic(tag: &str) -> hermetic_guard::HermeticTestEnv {
12
- let env = hermetic_guard::HermeticTestEnv::enter(tag);
13
- env.scrub_tmux();
14
- env.assert_no_real_tmux();
15
- env
16
- }
17
-
18
- fn launch_source() -> String {
19
- let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/lifecycle");
20
- let mut files = vec![src.join("launch.rs")];
21
- let mut siblings = std::fs::read_dir(src.join("launch"))
22
- .expect("read launch module directory")
23
- .map(|entry| entry.expect("read launch module entry").path())
24
- .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("rs"))
25
- .collect::<Vec<_>>();
26
- siblings.sort();
27
- files.extend(siblings);
28
-
29
- files
30
- .into_iter()
31
- .map(|path| {
32
- format!(
33
- "\n// @source {}\n{}",
34
- path.strip_prefix(&src).unwrap().display(),
35
- std::fs::read_to_string(&path).expect("read launch source")
36
- )
37
- })
38
- .collect()
39
- }
40
-
41
- const QS_TEAM_MD: &str =
42
- "---\nname: quickteam\nobjective: Quick start.\nprovider: codex\n---\n\nQuick-start team.\n";
43
- pub(super) const QS_VALID_ROLE: &str = "---\nname: implementer\nrole: Implementation Engineer\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nImplement bounded tasks.\n";
44
-
45
- /// A REAL team dir `<base>/teamdir/{TEAM.md, agents/implementer.md}` — already in team-dir
46
- /// layout, so quick_start's prepare_quick_start_team returns it as-is and writes the compiled
47
- /// `team.spec.yaml` into it (diagnose/quick_start.py:prepare_quick_start_team, before launch).
48
- pub(super) fn quick_start_team_dir(role_doc: &str) -> PathBuf {
49
- let team = temp_ws().join("teamdir");
50
- std::fs::create_dir_all(team.join("agents")).unwrap();
51
- std::fs::write(team.join("TEAM.md"), QS_TEAM_MD).unwrap();
52
- std::fs::write(team.join("agents").join("implementer.md"), role_doc).unwrap();
53
- team
54
- }
55
-
56
- fn quick_start_team_dir_with_roles(role_docs: &[(&str, &str)]) -> PathBuf {
57
- let team = temp_ws().join("teamdir");
58
- std::fs::create_dir_all(team.join("agents")).unwrap();
59
- std::fs::write(team.join("TEAM.md"), QS_TEAM_MD).unwrap();
60
- for (file, role_doc) in role_docs {
61
- std::fs::write(team.join("agents").join(file), role_doc).unwrap();
62
- }
63
- team
64
- }
65
-
66
- fn role_doc(id: &str) -> String {
67
- provider_role_doc(id, "fake", "fake")
68
- }
69
-
70
- fn provider_role_doc(id: &str, provider: &str, model: &str) -> String {
71
- format!(
72
- "---\nname: {id}\nrole: {id} Worker\nprovider: {provider}\nmodel: {model}\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\n{id} worker.\n"
73
- )
74
- }
75
-
76
- fn layout_pane(
77
- session: &str,
78
- window: &str,
79
- pane: &str,
80
- pane_index: u32,
81
- ) -> crate::transport::PaneInfo {
82
- crate::transport::PaneInfo {
83
- pane_id: crate::transport::PaneId::new(pane),
84
- session: crate::transport::SessionName::new(session),
85
- window_index: None,
86
- window_name: Some(crate::transport::WindowName::new(window)),
87
- pane_index: Some(pane_index),
88
- tty: None,
89
- current_command: Some("team-agent".to_string()),
90
- current_path: None,
91
- active: pane_index == 0,
92
- pane_pid: None,
93
- leader_env: std::collections::BTreeMap::new(),
94
- }
95
- }
96
-
97
- /// E5 spec 迁移:spec 不再落 team_dir,而在 <team_workspace>/.team/runtime/<team_key>/。
98
- /// quick-start 未显式指定 id 时,team_key 来自 compiled TEAM.md name(`quickteam`)。
99
- pub(super) fn quick_start_runtime_spec_path(team: &std::path::Path) -> PathBuf {
100
- let workspace = crate::model::paths::team_workspace(team).unwrap();
101
- crate::model::paths::runtime_spec_path(&workspace, "quickteam")
102
- }
103
-
104
- /// 在 team 自身或其 team_workspace 父下找 .team/runtime/*/team.spec.yaml。run_workspace 解析
105
- /// 可能是 team 或父、team_key 可能因 state 缺省而非 team 名,故扫整个 runtime 目录任一子目录。
106
- /// `team_key` 给定时优先精确命中,否则取扫到的第一个。
107
- pub(super) fn find_runtime_spec(team: &std::path::Path, team_key: &str) -> Option<PathBuf> {
108
- let mut workspaces = vec![team.to_path_buf()];
109
- if let Ok(ws) = crate::model::paths::team_workspace(team) {
110
- workspaces.push(ws);
111
- }
112
- // 精确命中优先。
113
- for ws in &workspaces {
114
- let exact = crate::model::paths::runtime_spec_path(ws, team_key);
115
- if exact.exists() {
116
- return Some(exact);
117
- }
118
- }
119
- // 回退:扫 .team/runtime/*/team.spec.yaml。
120
- for ws in &workspaces {
121
- let runtime = crate::model::paths::runtime_dir(ws);
122
- let Ok(entries) = std::fs::read_dir(&runtime) else {
123
- continue;
124
- };
125
- for entry in entries.flatten() {
126
- let spec = entry.path().join("team.spec.yaml");
127
- if spec.exists() {
128
- return Some(spec);
129
- }
130
- }
131
- }
132
- None
133
- }
134
-
135
- /// A no-owner running workspace: state.json carries session_name + agents but NO team_owner →
136
- /// check_team_owner returns None = allowed (owner_gate.rs:48), so the owner-gated entry points can
137
- /// proceed PAST the owner gate. Also inits the real team.db.
138
- fn unowned_running_ws() -> PathBuf {
139
- let ws = temp_ws();
140
- crate::state::persist::save_runtime_state(
141
- &ws,
142
- &json!({
143
- "session_name": "team-x",
144
- "agents": { "w1": { "provider": "fake", "role": "Worker", "model": "fake", "auth_mode": "subscription" } },
145
- }),
146
- )
147
- .unwrap();
148
- let _ = crate::message_store::MessageStore::open(&ws).unwrap();
149
- ws
150
- }
151
-
152
- // P0 — quick_start over a VALID team dir must COMPILE the real spec (the compiler runs before any
153
- // launch/spawn) → team.spec.yaml is written carrying the agent set, and the result is NOT the
154
- // hardcoded "no role docs found" PreflightBlocked. Golden: quick_start.py → _compile_team_dir_spec
155
- // writes spec_path=team_dir/team.spec.yaml BEFORE launch.
156
- #[test]
157
- #[serial(env)]
158
- fn quick_start_compiles_real_spec_to_team_spec_yaml() {
159
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-compile-spec");
160
- let team = quick_start_team_dir(QS_VALID_ROLE);
161
- seed_healthy_coordinator(&crate::model::paths::team_workspace(&team).unwrap());
162
- let transport = OfflineTransport::new();
163
- let result = quick_start_with_transport(&team, None, true, None, &transport);
164
-
165
- // OBSERVABLE 1 (real compiler ran; spawn-independent): the compiled spec is written.
166
- // E5: spec lands in .team/runtime/<team_key>/ (NOT the user team dir).
167
- let spec_path = quick_start_runtime_spec_path(&team);
168
- assert!(
169
- spec_path.exists(),
170
- "quick_start must compile the team dir and write team.spec.yaml under .team/runtime/<team_key>/ \
171
- (the real compiler runs before launch); the stub returns before compiling. result={result:?}"
172
- );
173
- assert!(
174
- !team.join("team.spec.yaml").exists(),
175
- "E5: spec must NOT be written into the user team dir"
176
- );
177
- let spec_text = std::fs::read_to_string(&spec_path).unwrap_or_default();
178
- assert!(
179
- spec_text.contains("implementer"),
180
- "the compiled team.spec.yaml must carry the role-doc agent 'implementer'"
181
- );
182
-
183
- // OBSERVABLE 2 (report, robust): a VALID dir must never be the hardcoded always-blocked stub.
184
- if let Ok(QuickStartReport::PreflightBlocked { blockers, .. }) = &result {
185
- assert!(
186
- !blockers.iter().any(|b| b.contains("no role docs found")),
187
- "a VALID team dir must never yield the hardcoded 'no role docs found' blocker"
188
- );
189
- }
190
- }
191
-
192
- #[test]
193
- #[serial(env)]
194
- fn quick_start_without_team_id_uses_compiled_team_name_as_canonical_key() {
195
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-canonical-team");
196
- let team = quick_start_team_dir(QS_VALID_ROLE);
197
- let workspace = crate::model::paths::team_workspace(&team).unwrap();
198
- seed_healthy_coordinator(&workspace);
199
- let transport = OfflineTransport::new();
200
-
201
- let result = quick_start_with_transport(&team, None, true, None, &transport);
202
- assert!(result.is_ok(), "quick-start fixture must run: {result:?}");
203
-
204
- let state = crate::state::persist::load_runtime_state(&workspace).unwrap();
205
- assert_eq!(state["active_team_key"], json!("quickteam"));
206
- assert_eq!(state["team_key"], json!("quickteam"));
207
- assert!(state["teams"].get("quickteam").is_some(), "{state}");
208
- assert!(state["teams"].get("teamdir").is_none(), "{state}");
209
- assert!(
210
- crate::model::paths::runtime_spec_path(&workspace, "quickteam").exists(),
211
- "runtime spec must share the canonical key"
212
- );
213
- }
214
-
215
- #[test]
216
- #[serial(env)]
217
- fn existing_runtime_producer_scopes_canonical_team() {
218
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-existing-producer");
219
- let team = quick_start_team_dir(QS_VALID_ROLE);
220
- seed_healthy_coordinator(&crate::model::paths::team_workspace(&team).unwrap());
221
- let transport = OfflineTransport::new();
222
- let first = quick_start_with_transport(&team, Some("from-name"), true, None, &transport)
223
- .expect("first quick-start");
224
- match &first {
225
- QuickStartReport::Ready { team: canonical, .. } => {
226
- assert_eq!(canonical, "from-name", "Ready producer must emit canonical team");
227
- }
228
- other => panic!("first quick-start must be Ready; got {other:?}"),
229
- }
230
- let second = quick_start_with_transport(&team, Some("from-name"), true, None, &transport)
231
- .expect("second quick-start");
232
- match second {
233
- QuickStartReport::ExistingRuntime {
234
- team: canonical,
235
- agent_ids,
236
- ..
237
- } => {
238
- assert_eq!(canonical.as_deref(), Some("from-name"));
239
- assert!(
240
- agent_ids.iter().any(|id| id == "implementer"),
241
- "ExistingRuntime producer agent_ids={agent_ids:?}"
242
- );
243
- }
244
- other => panic!("duplicate quick-start must be ExistingRuntime; got {other:?}"),
245
- }
246
- }
247
-
248
- #[test]
249
- #[serial(env)]
250
- fn existing_runtime_requested_bob_does_not_emit_alice_members_or_attach() {
251
- let team = quick_start_team_dir(QS_VALID_ROLE);
252
- let workspace = crate::model::paths::team_workspace(&team).unwrap();
253
- let state = json!({
254
- "active_team_key": "alice",
255
- "agents": { "alice": { "window": "alice" } },
256
- "session_name": "team-alice",
257
- "tmux_endpoint": "/tmp/shared.sock",
258
- "teams": {
259
- "alice": {
260
- "agents": { "alice": { "window": "alice" } },
261
- "session_name": "team-alice"
262
- },
263
- "bob": {
264
- "agents": { "bob": { "window": "bob" } },
265
- "session_name": "team-bob"
266
- }
267
- }
268
- });
269
- crate::state::persist::save_runtime_state(&workspace, &state).unwrap();
270
- let report = quick_start_with_transport(&team, Some("bob"), true, None, &OfflineTransport::new())
271
- .expect("requested bob existing runtime");
272
- match report {
273
- QuickStartReport::ExistingRuntime {
274
- team: canonical,
275
- agent_ids,
276
- session_name,
277
- attach_commands,
278
- ..
279
- } => {
280
- assert_eq!(canonical.as_deref(), Some("bob"));
281
- assert_eq!(agent_ids, vec!["bob".to_string()]);
282
- assert_eq!(
283
- session_name.as_ref().map(|session| session.as_str()),
284
- Some("team-bob")
285
- );
286
- assert!(
287
- attach_commands.iter().any(|command| command.contains("team-bob")),
288
- "attach must follow bob session; got {attach_commands:?}"
289
- );
290
- assert!(
291
- attach_commands
292
- .iter()
293
- .all(|command| !command.contains("alice") && !command.contains("team-alice")),
294
- "attach must not steer to alice; got {attach_commands:?}"
295
- );
296
- }
297
- other => panic!("expected ExistingRuntime for bob; got {other:?}"),
298
- }
299
- }
300
-
301
- #[test]
302
- #[serial(env)]
303
- fn existing_runtime_empty_top_level_agents_still_emits_bob() {
304
- let team = quick_start_team_dir(QS_VALID_ROLE);
305
- let workspace = crate::model::paths::team_workspace(&team).unwrap();
306
- let state = json!({
307
- "active_team_key": "bob",
308
- "agents": {},
309
- "teams": {
310
- "bob": {
311
- "agents": { "bob": { "window": "bob" } },
312
- "session_name": "team-bob"
313
- }
314
- }
315
- });
316
- crate::state::persist::save_runtime_state(&workspace, &state).unwrap();
317
- let report = quick_start_with_transport(&team, Some("bob"), true, None, &OfflineTransport::new())
318
- .expect("requested bob with empty top-level agents");
319
- match report {
320
- QuickStartReport::ExistingRuntime { agent_ids, .. } => {
321
- assert_eq!(agent_ids, vec!["bob".to_string()]);
322
- }
323
- other => panic!("expected ExistingRuntime; got {other:?}"),
324
- }
325
- }
326
-
327
- #[test]
328
- #[serial(env)]
329
- fn quick_start_teamdir_under_dot_team_uses_project_workspace_for_status_and_collect() {
330
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-dot-team-workspace");
331
- let workspace = temp_ws();
332
- seed_healthy_coordinator(&workspace);
333
- let team = workspace.join(".team").join("current");
334
- std::fs::create_dir_all(team.join("agents")).unwrap();
335
- std::fs::write(team.join("TEAM.md"), QS_TEAM_MD).unwrap();
336
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
337
-
338
- let transport = OfflineTransport::new();
339
- let result = quick_start_with_transport(&team, None, true, None, &transport);
340
- assert!(
341
- matches!(result, Ok(QuickStartReport::Ready { .. })),
342
- "quick-start failed: {result:?}"
343
- );
344
-
345
- let state_path = crate::state::persist::runtime_state_path(&workspace);
346
- assert!(
347
- state_path.exists(),
348
- "quick-start .team/current must persist runtime state under project root"
349
- );
350
- assert!(
351
- !workspace
352
- .join(".team")
353
- .join(".team")
354
- .join("runtime")
355
- .join("state.json")
356
- .exists(),
357
- "quick-start .team/current must not create nested .team/.team runtime state"
358
- );
359
-
360
- for input in [&workspace, &team] {
361
- let selected = crate::state::selector::resolve_active_team(
362
- input,
363
- None,
364
- crate::state::selector::SelectorMode::RuntimeOnly,
365
- )
366
- .expect("status/collect selector should resolve project root");
367
- assert_eq!(
368
- selected.run_workspace,
369
- workspace,
370
- "input={}",
371
- input.display()
372
- );
373
- // E5: selector resolves spec_path to .team/runtime/<canonical team_key>/.
374
- let expected_spec = crate::model::paths::runtime_spec_path(&workspace, "quickteam");
375
- assert_eq!(
376
- selected
377
- .spec_path
378
- .as_deref()
379
- .map(std::fs::canonicalize)
380
- .transpose()
381
- .unwrap(),
382
- Some(std::fs::canonicalize(&expected_spec).unwrap()),
383
- "input={}",
384
- input.display()
385
- );
386
- }
387
-
388
- let status = crate::cli::cmd_status(&crate::cli::StatusArgs {
389
- agent: None,
390
- workspace: team.clone(),
391
- detail: false,
392
- summary: false,
393
- json: true,
394
- team: None,
395
- });
396
- assert!(
397
- status.is_ok(),
398
- "status should normalize teamdir to project-root runtime state: {status:?}"
399
- );
400
-
401
- }
402
-
403
- #[test]
404
- #[serial(env)]
405
- fn quick_start_default_workspace_compiled_spec_uses_project_root() {
406
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-default-workspace");
407
- let workspace = temp_ws();
408
- std::fs::create_dir_all(workspace.join("agents")).unwrap();
409
- std::fs::write(workspace.join("TEAM.md"), QS_TEAM_MD).unwrap();
410
- std::fs::write(
411
- workspace.join("agents").join("implementer.md"),
412
- QS_VALID_ROLE,
413
- )
414
- .unwrap();
415
- seed_healthy_coordinator(&workspace);
416
- let transport = OfflineTransport::new();
417
-
418
- let report = quick_start_with_transport_in_workspace(
419
- &workspace, &workspace, None, true, None, &transport,
420
- )
421
- .expect("quick-start workspace-root team should reach a report");
422
- assert!(
423
- matches!(report, QuickStartReport::Ready { .. }),
424
- "quick-start failed: {report:?}"
425
- );
426
-
427
- let state = crate::state::persist::load_runtime_state(&workspace).unwrap();
428
- let spec_path = state
429
- .get("spec_path")
430
- .and_then(serde_json::Value::as_str)
431
- .map(PathBuf::from)
432
- .expect("quick-start state should carry spec_path");
433
- let spec = crate::model::yaml::loads(&std::fs::read_to_string(spec_path).unwrap()).unwrap();
434
- assert_eq!(
435
- spec.get("team")
436
- .and_then(|team| team.get("workspace"))
437
- .and_then(crate::model::yaml::Value::as_str),
438
- Some(workspace.to_string_lossy().as_ref()),
439
- "compiled team.workspace must be the project root, not its parent"
440
- );
441
- for agent in spec
442
- .get("agents")
443
- .and_then(crate::model::yaml::Value::as_list)
444
- .unwrap()
445
- {
446
- assert_eq!(
447
- agent
448
- .get("working_directory")
449
- .and_then(crate::model::yaml::Value::as_str),
450
- Some(workspace.to_string_lossy().as_ref()),
451
- "compiled agent working_directory must be the project root"
452
- );
453
- }
454
- assert_eq!(
455
- transport.spawn_cwd_records(),
456
- vec![workspace],
457
- "quick-start must spawn workers from the project root"
458
- );
459
- }
460
-
461
- // An omitted role `provider` is the default `pi`, which declares the Pi contract leaf: the
462
- // compiled spec carries the leaf id, so quick-start never produces a legacy `pi` worker row.
463
- #[cfg(unix)]
464
- #[test]
465
- fn quick_start_role_without_provider_compiles_to_the_pi_leaf() {
466
- let team = quick_start_team_dir(
467
- "---\nname: implementer\nrole: Implementation Engineer\nmodel: gpt-5.5\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nImplement bounded tasks.\n",
468
- );
469
- let spec = crate::compiler::compile_team(&team).expect("an omitted provider is the default pi");
470
- let providers = spec
471
- .get("agents")
472
- .and_then(crate::model::yaml::Value::as_list)
473
- .expect("compiled agents")
474
- .iter()
475
- .map(|agent| agent.get("provider").and_then(crate::model::yaml::Value::as_str))
476
- .collect::<Vec<_>>();
477
- assert_eq!(providers, vec![Some("pi_tui")]);
478
- }
479
-
480
- // P0 — launch (dry_run) over a real compiled spec must resolve the REAL route/permission plan
481
- // (no spawn) — NOT the hardcoded RequirementUnmet stub. Golden: launch/core.py dry_run resolves
482
- // routing + permissions without starting any process.
483
- #[test]
484
- fn launch_dry_run_resolves_real_plan_not_stub_error() {
485
- let team = quick_start_team_dir(QS_VALID_ROLE);
486
- let spec = crate::compiler::compile_team(&team).expect("compile the seeded valid team");
487
- let spec_path = team.join("team.spec.yaml");
488
- std::fs::write(&spec_path, crate::model::yaml::dumps(&spec)).unwrap();
489
-
490
- let result = launch(&spec_path, true, true, true);
491
-
492
- match result {
493
- Err(LifecycleError::RequirementUnmet(msg)) if msg.contains("not available") => {
494
- panic!("launch returned the hardcoded stub error; the real dry_run plan was never resolved");
495
- }
496
- Ok(report) => {
497
- assert!(report.dry_run, "dry_run launch must report dry_run=true");
498
- assert!(
499
- !report.routes.is_empty(),
500
- "dry_run launch must resolve a real route plan from the compiled spec"
501
- );
502
- }
503
- // any OTHER Err (a real requirement/transport error) still proves the stub is gone.
504
- Err(_) => {}
505
- }
506
- }
507
-
508
- // P1 — start_agent must PROCEED past the owner gate for a no-owner workspace (check_team_owner →
509
- // None = allowed). The stub hard-returns OwnerRefused unconditionally. Golden: lifecycle/start.py
510
- // runs under the owner gate, then the resume-or-fresh decision. (The resume/fresh PLAN + real
511
- // spawn is the #[ignore] OS boundary — see quick_start_full_ready_real_spawn.)
512
- #[test]
513
- fn start_agent_proceeds_past_owner_gate_for_unowned_workspace() {
514
- let ws = unowned_running_ws();
515
- let transport = OfflineTransport::new();
516
- let result = start_agent_with_transport(
517
- &ws,
518
- &AgentId::new("w1"),
519
- false,
520
- false,
521
- true,
522
- None,
523
- &transport,
524
- );
525
- assert!(
526
- !matches!(result, Err(LifecycleError::OwnerRefused(_))),
527
- "start_agent must reach the real chain for a no-owner workspace, not hard-refuse owner; got {result:?}"
528
- );
529
- }
530
-
531
- // P1 — restart (Route B) must PROCEED past the owner gate for a no-owner workspace. Stub →
532
- // OwnerRefused. Golden: restart/orchestration.py runs the resume-selection under the owner gate.
533
- #[test]
534
- fn restart_proceeds_past_owner_gate_for_unowned_workspace() {
535
- let ws = unowned_running_ws();
536
- let transport = OfflineTransport::new();
537
- let result = restart_with_transport(&ws, true, None, &transport);
538
- assert!(
539
- !matches!(result, Err(LifecycleError::OwnerRefused(_))),
540
- "restart must reach the real Route-B chain for a no-owner workspace; got {result:?}"
541
- );
542
- }
543
-
544
- // P1 — add_agent must PROCEED past the owner gate (no-owner ws) and reach the real recompile chain.
545
- // Stub → OwnerRefused. Golden: lifecycle/operations.py:add_agent recompiles the role doc into the
546
- // spec under the owner gate.
547
- #[test]
548
- fn add_agent_proceeds_past_owner_gate_and_reaches_recompile() {
549
- let ws = unowned_running_ws();
550
- let role = ws.join("w2-role.md");
551
- std::fs::write(
552
- &role,
553
- "---\nname: w2\nrole: Second Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nSecond worker.\n",
554
- )
555
- .unwrap();
556
- let transport = OfflineTransport::new();
557
- let result = add_agent_with_transport(&ws, &AgentId::new("w2"), &role, false, None, &transport);
558
- assert!(
559
- !matches!(result, Err(LifecycleError::OwnerRefused(_))),
560
- "add_agent must reach the real recompile chain for a no-owner workspace; got {result:?}"
561
- );
562
- }
563
-
564
- // P1 — fork_agent must PROCEED past the owner gate (no-owner ws). Stub → OwnerRefused.
565
- // Golden: lifecycle/operations.py:fork_agent native session fork under the owner gate.
566
- #[test]
567
- fn fork_agent_proceeds_past_owner_gate_for_unowned_workspace() {
568
- let ws = unowned_running_ws();
569
- let transport = OfflineTransport::new();
570
- let result = fork_agent_with_transport(
571
- &ws,
572
- &AgentId::new("w1"),
573
- &AgentId::new("w1-fork"),
574
- None,
575
- false,
576
- None,
577
- &transport,
578
- );
579
- assert!(
580
- !matches!(result, Err(LifecycleError::OwnerRefused(_))),
581
- "fork_agent must reach the real native-fork chain for a no-owner workspace; got {result:?}"
582
- );
583
- }
584
-
585
- // REAL-MACHINE boundary (acceptance framework): a full quick_start that actually LAUNCHES workers
586
- // needs a live tmux + provider spawn — db/state seeding + the Ready report happen INSIDE launch()'s
587
- // real spawn. Asserted by the acceptance crate, not here (do NOT fake the spawn).
588
- #[test]
589
- #[ignore = "real-machine: full quick_start Ready needs a live tmux + provider spawn (db/state seeding \
590
- happens inside launch's real spawn). Acceptance-crate boundary, not a unit RED."]
591
- fn quick_start_full_ready_real_spawn() {
592
- let team = quick_start_team_dir(QS_VALID_ROLE);
593
- let report = quick_start(&team, None, true, None).expect("quick_start launches the team");
594
- assert!(
595
- matches!(report, QuickStartReport::Ready { .. }),
596
- "got {report:?}"
597
- );
598
- }
599
-
600
- // ═════════════════════════════════════════════════════════════════════════
601
- // SPINE-WIRING (③ review→fix) RED — lifecycle wiring divergences vs golden v0.2.11
602
- // (diagnose/quick_start.py, launch/core.py + config.py + routing.py, restart/orchestration.py,
603
- // lifecycle/operations.py). /tmp/spine_divergences.md #8/#15, #10, #12, #13, #14.
604
- // ═════════════════════════════════════════════════════════════════════════
605
-
606
- const QS_TEAM_MD_DANGEROUS: &str =
607
- "---\nname: dangerteam\nobjective: Dangerous.\nprovider: codex\ndangerous_auto_approve: true\n---\n\nteam.\n";
608
-
609
- fn quick_start_team_dir_custom(team_md: &str, role_doc: &str) -> PathBuf {
610
- let team = temp_ws().join("teamdir");
611
- std::fs::create_dir_all(team.join("agents")).unwrap();
612
- std::fs::write(team.join("TEAM.md"), team_md).unwrap();
613
- std::fs::write(team.join("agents").join("implementer.md"), role_doc).unwrap();
614
- team
615
- }
616
-
617
- fn compiled_spec_path(team: &std::path::Path) -> PathBuf {
618
- let spec = crate::compiler::compile_team(team).expect("compile team");
619
- let spec_path = team.join("team.spec.yaml");
620
- std::fs::write(&spec_path, crate::model::yaml::dumps(&spec)).unwrap();
621
- spec_path
622
- }
623
-
624
- fn raw_runtime_state(workspace: &std::path::Path) -> (String, serde_json::Value) {
625
- let state_path = crate::model::paths::runtime_dir(workspace).join("state.json");
626
- let raw = std::fs::read_to_string(&state_path)
627
- .unwrap_or_else(|e| panic!("read state.json at {}: {e}", state_path.display()));
628
- let state = serde_json::from_str(&raw).expect("state.json must parse");
629
- (raw, state)
630
- }
631
-
632
- struct EnvVarGuard {
633
- key: &'static str,
634
- previous: Option<String>,
635
- }
636
-
637
- impl EnvVarGuard {
638
- fn set(key: &'static str, value: &str) -> Self {
639
- let previous = std::env::var(key).ok();
640
- unsafe {
641
- std::env::set_var(key, value);
642
- }
643
- Self { key, previous }
644
- }
645
-
646
- fn unset(key: &'static str) -> Self {
647
- let previous = std::env::var(key).ok();
648
- unsafe {
649
- std::env::remove_var(key);
650
- }
651
- Self { key, previous }
652
- }
653
- }
654
-
655
- impl Drop for EnvVarGuard {
656
- fn drop(&mut self) {
657
- unsafe {
658
- if let Some(value) = self.previous.take() {
659
- std::env::set_var(self.key, value);
660
- } else {
661
- std::env::remove_var(self.key);
662
- }
663
- }
664
- }
665
- }
666
-
667
- fn compiled_spec_path_with_paused_agent(team: &std::path::Path) -> PathBuf {
668
- let mut spec = crate::compiler::compile_team(team).expect("compile team");
669
- let crate::model::yaml::Value::Map(root) = &mut spec else {
670
- panic!("compiled spec must be a map");
671
- };
672
- let agents = root
673
- .iter_mut()
674
- .find(|(key, _)| key == "agents")
675
- .and_then(|(_, value)| match value {
676
- crate::model::yaml::Value::List(agents) => Some(agents),
677
- _ => None,
678
- })
679
- .expect("compiled spec must contain agents");
680
- let first = agents
681
- .first_mut()
682
- .expect("compiled spec must contain an agent");
683
- let crate::model::yaml::Value::Map(agent) = first else {
684
- panic!("compiled agent must be a map");
685
- };
686
- agent.push(("paused".to_string(), crate::model::yaml::Value::Bool(true)));
687
- let spec_path = team.join("team.spec.yaml");
688
- std::fs::write(&spec_path, crate::model::yaml::dumps(&spec)).unwrap();
689
- spec_path
690
- }
691
-
692
- fn unowned_running_ws_all_paused() -> PathBuf {
693
- let ws = temp_ws();
694
- crate::state::persist::save_runtime_state(
695
- &ws,
696
- &json!({
697
- "session_name": "team-x",
698
- "agents": { "w1": { "provider": "fake", "role": "Worker", "model": "fake", "auth_mode": "subscription", "status": "paused" } },
699
- }),
700
- )
701
- .unwrap();
702
- let _ = crate::message_store::MessageStore::open(&ws).unwrap();
703
- ws
704
- }
705
-
706
- // #15 — quick_start seeds runtime state under team_workspace(team_dir) (the PARENT), not inside the
707
- // team dir, so restart/status can locate it. Golden quick_start.py:35 team_workspace(team_dir).
708
- #[test]
709
- #[serial(env)]
710
- fn spine_quick_start_seeds_state_under_team_workspace_not_team_dir() {
711
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-spine-workspace");
712
- let team = quick_start_team_dir(QS_VALID_ROLE); // <base>/teamdir
713
- seed_healthy_coordinator(&crate::model::paths::team_workspace(&team).unwrap());
714
- let transport = OfflineTransport::new();
715
- let _ = quick_start_with_transport(&team, None, true, None, &transport);
716
- let workspace = team.parent().unwrap(); // team_workspace(<base>/teamdir) = <base>
717
- let ws_state = crate::model::paths::runtime_dir(workspace).join("state.json");
718
- assert!(
719
- ws_state.exists(),
720
- "quick_start must seed runtime state under team_workspace(team_dir)={} (not inside the team dir)",
721
- workspace.display()
722
- );
723
- }
724
-
725
- // #10 removed — launch dry-run safety was derived from spec.runtime.dangerous_auto_approve.
726
- // 0.5.66 bypass 单源:该字段废弃,safety 改由 per-agent `dangerously_skip_permissions` 派生。
727
-
728
- // #12 — launch dry-run produces one RoutingDecision PER spec.task via route_task, with the real task id
729
- // and the route_task reason taxonomy — not one synthetic 'default_assignee' route. Golden core.py:77-88.
730
- #[test]
731
- fn spine_launch_dry_run_routes_one_per_task_with_route_reason() {
732
- let team = quick_start_team_dir(QS_VALID_ROLE);
733
- let spec_path = compiled_spec_path(&team);
734
- let report = launch(&spec_path, true, true, true).expect("dry_run launch");
735
- // compile_team emits one task 'task_initial' assigned to 'implementer' → reason 'explicit assignee on task'.
736
- let route = report
737
- .routes
738
- .iter()
739
- .find(|r| r.task_id.as_deref() == Some("task_initial"))
740
- .unwrap_or_else(|| panic!("a route for task_initial expected; got {:?}", report.routes));
741
- assert_eq!(
742
- route.reason, "explicit assignee on task",
743
- "the route reason must come from route_task, not the hardcoded 'default_assignee'"
744
- );
745
- assert_eq!(route.selected_agent.as_str(), "implementer");
746
- }
747
-
748
- // #13 — an empty/all-paused restart decision set is NOT an atomic refusal (remove the empty-decisions
749
- // clause); only a non-empty unresumable set (and !allow_fresh) refuses. Golden orchestration.py.
750
- #[test]
751
- fn spine_restart_empty_team_is_not_atomic_refusal() {
752
- let ws = unowned_running_ws_all_paused();
753
- let transport = OfflineTransport::new();
754
- let result = restart_with_transport(&ws, true, None, &transport);
755
- assert!(
756
- !matches!(result, Ok(RestartReport::RefusedResumeAtomicity { .. })),
757
- "an all-paused/empty team must NOT yield an atomic refusal (empty decision set is not a refusal); got {result:?}"
758
- );
759
- }
760
-
761
- // E25 — add_agent duplicate membership is runtime-state based, not role-doc/spec-file based.
762
- #[test]
763
- fn spine_add_agent_rejects_duplicate_agent_id() {
764
- let team = quick_start_team_dir(QS_VALID_ROLE); // team already has agent 'implementer'
765
- crate::state::persist::save_runtime_state(
766
- &team,
767
- &json!({
768
- "session_name": "team-quickteam",
769
- "agents": {
770
- "implementer": {"status": "running", "provider": "fake", "window": "implementer"}
771
- }
772
- }),
773
- )
774
- .unwrap();
775
- let role = team.join("dup-role.md");
776
- std::fs::write(&role, QS_VALID_ROLE).unwrap(); // a role doc named 'implementer' = duplicate
777
- let transport = OfflineTransport::new();
778
- let result = add_agent_with_transport(
779
- &team,
780
- &AgentId::new("implementer"),
781
- &role,
782
- false,
783
- None,
784
- &transport,
785
- );
786
- let text = format!("{result:?}");
787
- assert!(
788
- text.contains("already exists"),
789
- "add_agent must reject an id already present in runtime state; got {text}"
790
- );
791
- }
792
-
793
- // E5 Bug1 — add-agent must NOT copy the external role file into <team_dir>/agents (the
794
- // self-copy O_TRUNC truncation reproduced on real machine), and must still inject the new
795
- // agent into the compiled spec by reading the role file in place.
796
- #[test]
797
- fn e5_add_agent_does_not_copy_role_into_platform_dir_and_injects_into_spec() {
798
- let team = quick_start_team_dir(QS_VALID_ROLE);
799
- seed_canonical_team_identity(&team, "teamdir");
800
- // External role file OUTSIDE team_dir/agents, with recognizable body content.
801
- let role = team.parent().unwrap().join("w2-external-role.md");
802
- let role_body = "---\nname: w2\nrole: Second Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nUNIQUE-E5-BUG1-MARKER body for w2.\n";
803
- std::fs::write(&role, role_body).unwrap();
804
- let transport = OfflineTransport::new();
805
- // The spawn may not complete under OfflineTransport; we only assert the no-copy + spec-inject
806
- // observables, which happen BEFORE spawn. Ignore the spawn-stage Result.
807
- let _ = add_agent_with_transport(&team, &AgentId::new("w2"), &role, false, None, &transport);
808
-
809
- // (1) No copy landed in the platform agents dir.
810
- let copied = team.join("agents").join("w2.md");
811
- assert!(
812
- !copied.exists(),
813
- "add-agent must NOT copy the role file into <team_dir>/agents (anti-pattern + O_TRUNC bug)"
814
- );
815
- // (2) The external role file is untouched (not truncated by a self-copy).
816
- assert_eq!(
817
- std::fs::read_to_string(&role).unwrap(),
818
- role_body,
819
- "external role file must be left intact (no truncating self-copy)"
820
- );
821
- // (3) The compiled spec (under .team/runtime/<team_key>/, NOT the user team dir) carries w2.
822
- let runtime_spec = find_runtime_spec(&team, "teamdir").expect("runtime spec written");
823
- let spec_text = std::fs::read_to_string(&runtime_spec).unwrap();
824
- assert!(
825
- spec_text.contains("w2"),
826
- "compiled spec must inject the new agent w2 (read in place, not copied); spec=\n{spec_text}"
827
- );
828
- assert!(
829
- !team.join("team.spec.yaml").exists(),
830
- "E5: add_agent must NOT write spec into the user team dir"
831
- );
832
- }
833
-
834
- // E5 task#3 / E4 — restart rebuilds the runtime spec from role docs EVERY time: editing a role
835
- // doc (here: rename a role) is reflected in the freshly-written runtime spec after restart.
836
- #[test]
837
- fn e5_restart_rebuilds_runtime_spec_from_role_docs() {
838
- let ws = restart_ws_two_resumable_workers(); // has TEAM.md + agents/{alpha,bravo}.md + state
839
- // Edit a role doc AFTER initial compile: change alpha's role text.
840
- std::fs::write(
841
- ws.join("agents").join("alpha.md"),
842
- "---\nname: alpha\nrole: RENAMED Alpha Role\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nAlpha edited.\n",
843
- )
844
- .unwrap();
845
- let transport = OfflineTransport::new();
846
- let _ = restart_with_transport(&ws, false, None, &transport);
847
- // The runtime spec (rebuilt from role docs) must carry the edited role text.
848
- let runtime_spec = find_runtime_spec(&ws, "restartteam").expect("runtime spec rebuilt");
849
- let spec_text = std::fs::read_to_string(&runtime_spec).unwrap();
850
- assert!(
851
- spec_text.contains("RENAMED Alpha Role"),
852
- "restart must rebuild runtime spec from role docs (E4: TEAM.md/role edits take effect); spec=\n{spec_text}"
853
- );
854
- assert!(
855
- !ws.join("team.spec.yaml").exists(),
856
- "E5: rebuilt spec must land in .team/runtime, not the user team dir"
857
- );
858
- }
859
-
860
- // RED-2 (P0) — restart existence gate must use selected.spec_path (read-order B: runtime spec),
861
- // NOT the user-dir team.spec.yaml. spec-demote put spec under .team/runtime/<key>/, so the old
862
- // pre-resolve gate (`!workspace.join("team.spec.yaml").exists()`) falsely reported "missing spec".
863
- #[test]
864
- fn red2_restart_finds_runtime_spec_not_missing_when_user_dir_has_no_spec() {
865
- let ws = restart_ws_two_resumable_workers(); // has TEAM.md + agents + state
866
- // Simulate spec-demote: remove any user-dir spec the fixture wrote; restart must still find
867
- // the runtime spec (rebuilt from role docs / read-order B), NOT report "missing spec".
868
- let _ = std::fs::remove_file(ws.join("team.spec.yaml"));
869
- assert!(
870
- !ws.join("team.spec.yaml").exists(),
871
- "user-dir spec removed (spec-demote condition)"
872
- );
873
- let transport = OfflineTransport::new();
874
- let result = restart_with_transport(&ws, false, None, &transport);
875
- // The gate must NOT short-circuit with "missing spec for restart" — restart must proceed
876
- // (any later resume/rebuild outcome is fine; we only assert the spec-missing gate is gone).
877
- let text = format!("{result:?}");
878
- assert!(
879
- !text.contains("missing spec for restart"),
880
- "RED-2: restart must locate the runtime spec via read-order B, not report missing; got {text}"
881
- );
882
- }
883
-
884
- // RED-2 negative — a truly empty workspace (no role docs, no spec, no state) must STILL report
885
- // missing spec (gate moved, not removed).
886
- #[test]
887
- fn red2_restart_empty_workspace_still_reports_missing() {
888
- let ws = temp_ws(); // empty, no TEAM.md/agents/spec/state
889
- let transport = OfflineTransport::new();
890
- let result = restart_with_transport(&ws, false, None, &transport);
891
- let text = format!("{result:?}");
892
- assert!(
893
- text.contains("missing spec")
894
- || text.to_lowercase().contains("not found")
895
- || text.contains("no_local_team_context")
896
- || text.to_lowercase().contains("invalid workspace")
897
- || text.contains("role definitions missing"),
898
- "RED-2 negative: empty workspace restart must still error (missing/not-found); got {text}"
899
- );
900
- let _ = std::fs::remove_dir_all(&ws);
901
- }
902
-
903
- // RED-2-STILL (P0) — the ENTRY gate (input_has_no_local_team_context) must judge on the
904
- // canonical_run_workspace-resolved path, not raw. quick-start <team_dir> lands .team under the
905
- // resolved workspace (team_dir's parent when invoked from there); restart <team_dir> with raw gate
906
- // checks team_dir's own (empty) .team → false "no context" early-exit before the down-moved gate.
907
- //
908
- // Two forms (leader hard requirement — must lock BOTH, not the coincidental same-dir form):
909
- // Form A: .team in the team_dir's PARENT (standard quick-start <dir> from parent cwd).
910
- // Form B: .team in the team_dir itself (cwd == team_dir).
911
- #[test]
912
- fn red2still_entry_gate_resolves_parent_dot_team_form_a() {
913
- // Build: base/ (has .team) + base/teamdir/{TEAM.md, agents/} (role docs, NO own .team).
914
- let base = temp_ws();
915
- let team_dir = base.join("teamdir");
916
- std::fs::create_dir_all(team_dir.join("agents")).unwrap();
917
- std::fs::write(
918
- team_dir.join("TEAM.md"),
919
- "---\nname: teamdir\nobjective: o\nprovider: codex\n---\nt.\n",
920
- )
921
- .unwrap();
922
- std::fs::write(team_dir.join("agents").join("w1.md"), QS_VALID_ROLE).unwrap();
923
- // .team lives in the PARENT (base), with a runtime spec — mirrors quick-start <dir> from base cwd.
924
- let spec = crate::compiler::compile_team(&team_dir).unwrap();
925
- let runtime_spec = crate::model::paths::runtime_spec_path(&base, "teamdir");
926
- std::fs::create_dir_all(runtime_spec.parent().unwrap()).unwrap();
927
- std::fs::write(&runtime_spec, crate::model::yaml::dumps(&spec)).unwrap();
928
- // Seed minimal team state under base so resolve finds it.
929
- crate::state::persist::save_runtime_state(
930
- &base,
931
- &json!({"session_name": "team-teamdir", "team_dir": team_dir.to_string_lossy(),
932
- "spec_path": runtime_spec.to_string_lossy(),
933
- "agents": {"w1": {"status": "running", "provider": "fake"}}}),
934
- )
935
- .unwrap();
936
- // Entry gate on team_dir: raw team_dir has NO .team (it's in parent), but resolved → base has it.
937
- assert!(
938
- crate::lifecycle::restart::input_has_no_local_team_context(&team_dir),
939
- "precondition: raw team_dir has no local .team (it's in the parent)"
940
- );
941
- let resolved = crate::model::paths::canonical_run_workspace(&team_dir).unwrap();
942
- assert!(
943
- !crate::lifecycle::restart::input_has_no_local_team_context(&resolved),
944
- "RED-2-STILL: gate on canonical_run_workspace-resolved path must see parent .team (false)"
945
- );
946
- // Full restart on team_dir must NOT early-exit with missing spec.
947
- let transport = OfflineTransport::new();
948
- let text = format!(
949
- "{:?}",
950
- restart_with_transport(&team_dir, false, None, &transport)
951
- );
952
- assert!(
953
- !text.contains("missing spec for restart") && !text.contains("active team spec not found"),
954
- "RED-2-STILL Form A: restart <team_dir> (.team in parent) must not report missing; got {text}"
955
- );
956
- let _ = std::fs::remove_dir_all(&base);
957
- }
958
-
959
- #[test]
960
- fn red2still_entry_gate_same_dir_dot_team_form_b() {
961
- // Form B: .team in team_dir itself (cwd == team_dir at quick-start time).
962
- let team_dir = temp_ws();
963
- std::fs::create_dir_all(team_dir.join("agents")).unwrap();
964
- std::fs::write(
965
- team_dir.join("TEAM.md"),
966
- "---\nname: tb\nobjective: o\nprovider: codex\n---\nt.\n",
967
- )
968
- .unwrap();
969
- std::fs::write(team_dir.join("agents").join("w1.md"), QS_VALID_ROLE).unwrap();
970
- let spec = crate::compiler::compile_team(&team_dir).unwrap();
971
- let runtime_spec = crate::model::paths::runtime_spec_path(&team_dir, "tb");
972
- std::fs::create_dir_all(runtime_spec.parent().unwrap()).unwrap();
973
- std::fs::write(&runtime_spec, crate::model::yaml::dumps(&spec)).unwrap();
974
- crate::state::persist::save_runtime_state(
975
- &team_dir,
976
- &json!({"session_name": "team-tb", "team_dir": team_dir.to_string_lossy(),
977
- "spec_path": runtime_spec.to_string_lossy(),
978
- "agents": {"w1": {"status": "running", "provider": "fake"}}}),
979
- )
980
- .unwrap();
981
- let transport = OfflineTransport::new();
982
- let text = format!(
983
- "{:?}",
984
- restart_with_transport(&team_dir, false, None, &transport)
985
- );
986
- assert!(
987
- !text.contains("missing spec for restart") && !text.contains("active team spec not found"),
988
- "RED-2-STILL Form B: restart <team_dir> (.team in team_dir) must not report missing; got {text}"
989
- );
990
- let _ = std::fs::remove_dir_all(&team_dir);
991
- }
992
-
993
- // E5 task#3 / RC-A6b — restart with role definitions MISSING explicitly refuses (lists what's
994
- // missing) and leaves the previous runtime spec in place (no silent path, no data destruction).
995
- #[test]
996
- fn e5_restart_missing_role_docs_refuses_and_preserves_old_spec() {
997
- let ws = restart_ws_two_resumable_workers();
998
- // Pre-seed a previous runtime spec so we can assert it survives the refusal.
999
- let prev_spec = crate::model::paths::runtime_spec_path(&ws, "restartteam");
1000
- std::fs::create_dir_all(prev_spec.parent().unwrap()).unwrap();
1001
- std::fs::write(&prev_spec, "PREVIOUS-RUNTIME-SPEC-MARKER\n").unwrap();
1002
- // Remove the role definitions (TEAM.md) → role source gone.
1003
- std::fs::remove_file(ws.join("TEAM.md")).unwrap();
1004
- let transport = OfflineTransport::new();
1005
- let result = restart_with_transport(&ws, false, None, &transport);
1006
- let text = format!("{result:?}");
1007
- assert!(
1008
- text.contains("role definitions missing") || text.to_lowercase().contains("missing"),
1009
- "restart with missing role docs must explicitly refuse listing what's missing; got {text}"
1010
- );
1011
- // Old runtime spec preserved untouched (T2: no data destruction on refusal).
1012
- assert_eq!(
1013
- std::fs::read_to_string(&prev_spec).unwrap(),
1014
- "PREVIOUS-RUNTIME-SPEC-MARKER\n",
1015
- "previous runtime spec must be left in place on refusal"
1016
- );
1017
- }
1018
-
1019
- #[test]
1020
- fn e5_restart_missing_role_docs_refuses_even_after_endpoint_convergence_marker() {
1021
- let _harness_gate =
1022
- EnvVarGuard::unset("TEAM_AGENT_TEST_ENDPOINT_CONVERGENCE_HARNESS_SPEC_FALLBACK");
1023
- let ws = restart_ws_two_resumable_workers();
1024
- let prev_spec = crate::model::paths::runtime_spec_path(&ws, "restartteam");
1025
- std::fs::create_dir_all(prev_spec.parent().unwrap()).unwrap();
1026
- std::fs::write(&prev_spec, "PREVIOUS-RUNTIME-SPEC-MARKER\n").unwrap();
1027
-
1028
- let mut state = crate::state::persist::load_runtime_state(&ws).unwrap();
1029
- state["topology_convergence"] = json!({
1030
- "status": "converged",
1031
- "old_tmux_endpoint": "/tmp/old",
1032
- "new_tmux_endpoint": "/tmp/new",
1033
- "reason": "old_endpoint_dead"
1034
- });
1035
- crate::state::persist::save_runtime_state(&ws, &state).unwrap();
1036
- std::fs::remove_file(ws.join("TEAM.md")).unwrap();
1037
-
1038
- let result = restart_with_transport(&ws, false, None, &OfflineTransport::new());
1039
- let text = format!("{result:?}");
1040
- assert!(
1041
- text.contains("role definitions missing"),
1042
- "production marker alone must not enable runtime-spec fallback; got {text}"
1043
- );
1044
- assert_eq!(
1045
- std::fs::read_to_string(&prev_spec).unwrap(),
1046
- "PREVIOUS-RUNTIME-SPEC-MARKER\n",
1047
- "previous runtime spec must be preserved on missing role docs refusal"
1048
- );
1049
- }
1050
-
1051
- // E5 §3 解耦(tester 场景2)— add-agent on a team whose runtime spec already exists must still
1052
- // resolve team_dir to the USER role dir for compile_team (find TEAM.md/agents), not the runtime
1053
- // spec dir. Regression: SelectedTeam.spec_workspace=runtime was used as team_dir → compile_team
1054
- // looked for TEAM.md under .team/runtime/<key>/ → "missing TEAM.md".
1055
- #[test]
1056
- fn e5_add_agent_resolves_team_dir_to_role_dir_when_runtime_spec_exists() {
1057
- let team = quick_start_team_dir(QS_VALID_ROLE);
1058
- // Pre-create the runtime spec so the selector's runtime-first branch is taken (migrated team).
1059
- let runtime_spec = quick_start_runtime_spec_path(&team);
1060
- std::fs::create_dir_all(runtime_spec.parent().unwrap()).unwrap();
1061
- let base = crate::compiler::compile_team(&team).unwrap();
1062
- std::fs::write(&runtime_spec, crate::model::yaml::dumps(&base)).unwrap();
1063
- // External role file (relative-ish, outside agents/).
1064
- let role = team.join("w2-role.md");
1065
- std::fs::write(
1066
- &role,
1067
- "---\nname: w2\nrole: Second Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nw2.\n",
1068
- )
1069
- .unwrap();
1070
- let transport = OfflineTransport::new();
1071
- let result =
1072
- add_agent_with_transport(&team, &AgentId::new("w2"), &role, false, None, &transport);
1073
- // Core decoupling signature: must NOT fail because compile_team looked for TEAM.md/agents under
1074
- // the runtime spec dir. Before the fix, team_dir=spec_workspace(runtime) → "missing TEAM.md".
1075
- let text = format!("{result:?}");
1076
- assert!(
1077
- !text.contains("missing TEAM.md") && !text.to_lowercase().contains("missing agents"),
1078
- "add-agent must resolve team_dir to the role dir for compile_team (not the runtime spec dir); got {text}"
1079
- );
1080
- }
1081
-
1082
- // E5 grep guard G1 — writers must land spec via runtime_spec_path (.team/runtime/<team_key>/),
1083
- // never write team.spec.yaml into the user team_dir/agents_dir. Pins the spec-demote invariant.
1084
- #[test]
1085
- fn e5_guard_g1_writers_use_runtime_spec_path_not_user_dir() {
1086
- let source = launch_source();
1087
- let runtime_writes = source.matches("runtime_spec_path(").count();
1088
- assert!(
1089
- runtime_writes >= 2,
1090
- "G1: quick_start + add_agent must write spec via runtime_spec_path (found {runtime_writes})"
1091
- );
1092
- for forbidden in [
1093
- "let spec_path = agents_dir.join(\"team.spec.yaml\");\n std::fs::write",
1094
- "let spec_path = team_dir.join(\"team.spec.yaml\");\n std::fs::write",
1095
- ] {
1096
- assert!(
1097
- !source.contains(forbidden),
1098
- "G1: user-dir spec write idiom must be gone: {forbidden:?}"
1099
- );
1100
- }
1101
- }
1102
-
1103
- // E5 grep guard G2 — launch.rs must NOT copy a role file into the platform team dir.
1104
- // Pins the Bug1 fix: no `fs::copy` of a role file + no `materialize_added_role_file` reborn.
1105
- #[test]
1106
- fn e5_guard_g2_no_copy_role_into_platform_dir() {
1107
- let source = launch_source();
1108
- assert!(
1109
- !source.contains("materialize_added_role_file"),
1110
- "G2: materialize_added_role_file (role copy anti-pattern) must stay deleted"
1111
- );
1112
- assert!(
1113
- !source.contains("copy role file"),
1114
- "G2: no 'copy role file' into the platform agents dir (O_TRUNC self-copy bug)"
1115
- );
1116
- }
1117
-
1118
- // ═════════════════════════════════════════════════════════════════════════
1119
- // SPAWN sub-phase RED — launch(dry_run=false) must REALLY spawn (unlocks the acceptance
1120
- // framework's cheap real-machine Tier-1). Golden launch/core.py: create the session + one worker
1121
- // window per agent running its provider command (with workspace + agent-id context), populate the
1122
- // started list, attach the leader receiver. Today launch(dry_run=false) is the hardcoded stub
1123
- // RequirementUnmet("launch spawn requires live transport/provider boundary").
1124
- // ═════════════════════════════════════════════════════════════════════════
1125
-
1126
- // P0 — launch(dry_run=false) over a real compiled spec must run the real spawn chain (create session +
1127
- // spawn ≥1 worker, populating LaunchReport.started), NOT the hardcoded spawn stub. The recording-
1128
- // transport spawn-CALL assertion (spawn_first/spawn_into argv) needs a transport-injection seam in
1129
- // launch — flagged to the leader (launch takes no transport today); the real tmux new-session is the
1130
- // #[ignore] acceptance boundary (see quick_start_full_ready_real_spawn). Here we assert the seam-
1131
- // independent observable: the spawn stub is gone + LaunchReport.started is populated + dry_run=false.
1132
- //
1133
- // CONVERTED to #[ignore] (final real-daemon sub-phase): the porter wires PUBLIC launch() to the real
1134
- // TmuxBackend (today it uses NoopLaunchTransport), so once wired this test spawns REAL tmux — a unit
1135
- // test must not. The OS-edge-mocked spawn-orchestration coverage moved to
1136
- // `launch_with_transport_records_one_spawn_per_agent_carrying_build_command` (recording mock transport).
1137
- #[test]
1138
- #[ignore = "real-machine: public launch(dry_run=false) spawns real tmux once wired to TmuxBackend; \
1139
- in-process coverage is launch_with_transport_records_one_spawn_per_agent_carrying_build_command"]
1140
- fn spawn_launch_not_dry_run_is_no_longer_the_spawn_stub() {
1141
- let team = quick_start_team_dir(QS_VALID_ROLE);
1142
- let spec_path = compiled_spec_path(&team);
1143
-
1144
- let result = launch(&spec_path, false, true, true);
1145
-
1146
- match result {
1147
- Err(LifecycleError::RequirementUnmet(msg)) if msg.contains("requires live transport") => {
1148
- panic!(
1149
- "launch(dry_run=false) still returns the hardcoded spawn stub; the real spawn was never wired: {msg}"
1150
- );
1151
- }
1152
- Ok(report) => {
1153
- assert!(!report.dry_run, "a real launch must report dry_run=false");
1154
- assert!(
1155
- !report.started.is_empty(),
1156
- "launch(dry_run=false) must spawn >=1 worker and populate LaunchReport.started; got {:?}",
1157
- report.started
1158
- );
1159
- }
1160
- // any OTHER Err (a real transport/preflight error from the wired spawn) still proves the stub is gone.
1161
- Err(_) => {}
1162
- }
1163
- }
1164
-
1165
- // ═════════════════════════════════════════════════════════════════════════
1166
- // (C) public launch → real TmuxBackend. The OS edge is mocked by a RECORDING transport via the
1167
- // launch_with_transport seam; the REAL TmuxBackend swap is exercised by the acceptance framework
1168
- // (#[ignore] spawn_launch_not_dry_run_is_no_longer_the_spawn_stub). Golden launch/core.py.
1169
- // ═════════════════════════════════════════════════════════════════════════
1170
-
1171
- // (C) — launch_with_transport(dry_run=false, <recording transport>) creates one spawn per compiled
1172
- // agent, the recorded spawn argv carries that agent's provider build_command, and LaunchReport.started
1173
- // lists them. NOTE: GREEN today — spawn_agents already drives the injected transport; this LOCKS the
1174
- // spawn orchestration contract (replacing the now-#[ignore]'d public-launch test's in-process coverage).
1175
- // The genuine remaining gap — public launch() must construct a real TmuxBackend (today NoopLaunchTransport)
1176
- // — is not cleanly assertable in-process without spawning; it rides the porter's wiring + the #[ignore]
1177
- // real-machine test above.
1178
- #[test]
1179
- fn launch_with_transport_records_one_spawn_per_agent_carrying_build_command() {
1180
- let team = quick_start_team_dir(QS_VALID_ROLE); // one agent: implementer / provider fake
1181
- let spec_path = compiled_spec_path(&team);
1182
- let transport = OfflineTransport::new();
1183
-
1184
- let report = launch_with_transport(&spec_path, false, true, true, &transport)
1185
- .expect("launch_with_transport must spawn against the recording transport");
1186
-
1187
- let recorded = transport.spawn_records();
1188
- assert_eq!(
1189
- recorded.len(),
1190
- report.started.len(),
1191
- "exactly one spawn per started agent; recorded={recorded:?} started={:?}",
1192
- report.started
1193
- );
1194
- assert!(
1195
- !report.started.is_empty(),
1196
- "a real (non-dry-run) launch must spawn >=1 worker"
1197
- );
1198
- assert!(
1199
- !report.dry_run,
1200
- "launch_with_transport(dry_run=false) must report dry_run=false"
1201
- );
1202
- assert_eq!(
1203
- recorded[0].0, "spawn_first",
1204
- "the first worker uses new-session (spawn_first)"
1205
- );
1206
- assert!(
1207
- recorded
1208
- .iter()
1209
- .any(|(_, argv)| argv.iter().any(|a| a == "fake-worker")),
1210
- "each spawn argv must carry the agent's provider build_command (fake-worker); got {recorded:?}"
1211
- );
1212
- assert!(
1213
- report
1214
- .started
1215
- .iter()
1216
- .any(|s| s.agent_id.as_str() == "implementer"),
1217
- "LaunchReport.started must list the compiled agent; got {:?}",
1218
- report.started
1219
- );
1220
- let workspace = crate::model::paths::team_workspace(&team).unwrap();
1221
- let state = crate::state::persist::load_runtime_state(&workspace).unwrap();
1222
- let generation = report.started[0].spawned_at.as_str();
1223
- assert_eq!(state["generation"], generation);
1224
- let team_key = crate::state::projection::team_state_key(&state);
1225
- assert_eq!(state["teams"][&team_key]["generation"], generation);
1226
- let owner = transport.session_owner(&SessionName::new("team-quickteam")).unwrap().unwrap();
1227
- assert_eq!(owner.generation, generation);
1228
- }
1229
-
1230
- #[test]
1231
- #[serial(env)]
1232
- fn start_agent_session_generation_inherits_birth_or_stamps_recreated_session() {
1233
- for canonical_state in [false, true] {
1234
- for existing_session in [true, false] {
1235
- for explicit_generation in [true, false] {
1236
- let ws = restart_ws_one_resumable_worker();
1237
- let mut state = crate::state::persist::load_runtime_state(&ws).unwrap();
1238
- let birth = "2026-07-14T00:00:00+00:00";
1239
- state["agents"]["alpha"]["status"] = json!("stopped");
1240
- state["agents"]["alpha"]["spawned_at"] = json!(birth);
1241
- if explicit_generation {
1242
- state["generation"] = json!("explicit-session-birth");
1243
- }
1244
- let team_key = crate::state::projection::team_state_key(&state);
1245
- if canonical_state {
1246
- state["team_key"] = json!(team_key);
1247
- state["active_team_key"] = json!(team_key);
1248
- state["teams"] = json!({});
1249
- state["teams"][&team_key] = crate::state::projection::compact_team_state(&state);
1250
- }
1251
- let inherited = if explicit_generation { "explicit-session-birth" } else { birth };
1252
- crate::state::persist::save_runtime_state(&ws, &state).unwrap();
1253
- let transport = OfflineTransport::new()
1254
- .with_session_present(existing_session)
1255
- .with_session_owner(&ws, &team_key, inherited);
1256
- let result = start_agent_with_transport(
1257
- &ws, &aid("alpha"), false, false, false, None, &transport,
1258
- ).unwrap();
1259
- assert!(matches!(result, StartAgentOutcome::Running { .. }), "{result:?}");
1260
- let state = crate::state::persist::load_runtime_state(&ws).unwrap();
1261
- let spawned_at = state["agents"]["alpha"]["spawned_at"].as_str().unwrap();
1262
- assert_ne!(spawned_at, birth);
1263
- let expected = if existing_session { inherited } else { spawned_at };
1264
- assert_eq!(state["generation"], expected);
1265
- if canonical_state {
1266
- assert_eq!(state["teams"][&team_key]["generation"], expected);
1267
- } else {
1268
- // Legacy flat state stays flat; generation persistence does
1269
- // not implicitly migrate it to a canonical teams table.
1270
- assert!(state.get("teams").is_none());
1271
- }
1272
- let owner = transport.session_owner(&SessionName::new("team-restartone")).unwrap().unwrap();
1273
- assert_eq!(owner.generation, expected);
1274
- assert_eq!(transport.calls().contains(&"set_session_owner_with_generation"), !existing_session);
1275
- }
1276
- }
1277
- }
1278
- }
1279
-
1280
- // ═════════════════════════════════════════════════════════════════════════
1281
- // rt-host-a REGRESSION — `team-agent quick-start` compiles+seeds but NEVER spawns workers:
1282
- // quick_start_with_transport hardcodes launch dry_run=TRUE, so launch takes the started=Vec::new()
1283
- // branch and spawn_agents is never called. The 788-green missed it (no test drove quick_start through
1284
- // the spawn path). Golden: a real quick-start must spawn one worker per compiled agent into the session.
1285
- // ═════════════════════════════════════════════════════════════════════════
1286
-
1287
- /// Seed a HEALTHY coordinator at `workspace` (this process's pid + matching metadata + db schema) so
1288
- /// quick_start's internal start_coordinator returns AlreadyRunning — NO real daemon subprocess spawn.
1289
- pub(super) fn seed_healthy_coordinator(workspace: &std::path::Path) {
1290
- hermetic_guard::seed_in_process_coordinator(workspace);
1291
- }
1292
-
1293
- #[test]
1294
- #[cfg(unix)]
1295
- #[serial(env)]
1296
- fn issue337_owned_fixture_caller_admits_fresh_launch_without_guard_bypass() {
1297
- let env = hermetic_guard::HermeticTestEnv::enter_with_leader("issue337-fixture-caller");
1298
- let workspace = env.workspace("ws");
1299
- let team = workspace.join("roles");
1300
- std::fs::create_dir_all(team.join("agents")).unwrap();
1301
- std::fs::write(team.join("TEAM.md"), QS_TEAM_MD).unwrap();
1302
- std::fs::write(team.join("agents/implementer.md"), QS_VALID_ROLE).unwrap();
1303
- seed_healthy_coordinator(&workspace);
1304
- let transport = OfflineTransport::new();
1305
- let report = quick_start_with_transport_in_workspace(
1306
- &workspace, &team, None, true, Some("fixture-team"), &transport,
1307
- ).unwrap();
1308
- let QuickStartReport::Ready { launch, .. } = report else { panic!("owned caller must admit launch: {report:?}") };
1309
- assert!(launch.leader_receiver_attached);
1310
- assert_eq!(launch.started.len(), 1);
1311
- assert_eq!(transport.spawn_records().len(), 1);
1312
- let socket = std::env::var("TMUX").unwrap().split(',').next().unwrap().to_string();
1313
- assert!(std::path::Path::new(&socket).exists());
1314
- drop(env);
1315
- assert!(!std::path::Path::new(&socket).exists());
1316
- }
1317
-
1318
- fn seed_canonical_team_identity(workspace: &std::path::Path, team_key: &str) {
1319
- let mut state = crate::state::persist::load_runtime_state(workspace).unwrap();
1320
- state["active_team_key"] = json!(team_key);
1321
- crate::state::persist::save_runtime_state(workspace, &state).unwrap();
1322
- }
1323
-
1324
- // RED — quick_start_with_transport must drive the REAL spawn path: launch.dry_run==false, started
1325
- // non-empty (one per compiled agent), and the transport records >=1 spawn carrying that agent's
1326
- // provider build_command. Today the dry_run=true bug -> launch.started empty + ZERO spawns recorded ->
1327
- // RED at assertion (NOT a panic). OS-safe: recording transport (no real tmux) + seeded-healthy
1328
- // coordinator (start_coordinator AlreadyRunning -> no daemon subprocess).
1329
- #[test]
1330
- #[serial(env)]
1331
- fn quick_start_with_transport_spawns_workers_not_dry_run() {
1332
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-spawn-path");
1333
- let team = quick_start_team_dir(QS_VALID_ROLE); // one agent: implementer / provider fake
1334
- let workspace = team.parent().expect("team_workspace(team_dir) = parent"); // where start_coordinator runs
1335
- seed_healthy_coordinator(workspace);
1336
- let transport = OfflineTransport::new();
1337
-
1338
- let report = quick_start_with_transport(&team, None, true, None, &transport)
1339
- .expect("quick_start_with_transport must reach a report");
1340
-
1341
- let launch = match report {
1342
- QuickStartReport::Ready { launch, .. } => *launch,
1343
- other => panic!("quick_start must reach Ready (the spawn path); got {other:?}"),
1344
- };
1345
- // (1) the rt-host-a bug: launch dry_run hardcoded true -> this is the load-bearing regression assert.
1346
- assert!(
1347
- !launch.dry_run,
1348
- "quick_start must SPAWN workers (launch.dry_run == false); the rt-host-a bug hardcodes dry_run=true \
1349
- so launch takes the empty started branch and never spawns"
1350
- );
1351
- // (2) one started entry per compiled agent (the dry-run branch leaves this empty).
1352
- assert!(
1353
- !launch.started.is_empty(),
1354
- "quick_start must populate launch.started (>=1 worker spawned), not the dry-run empty Vec; got {:?}",
1355
- launch.started
1356
- );
1357
- assert!(
1358
- launch
1359
- .started
1360
- .iter()
1361
- .any(|s| s.agent_id.as_str() == "implementer"),
1362
- "launch.started must list the compiled agent 'implementer'; got {:?}",
1363
- launch.started
1364
- );
1365
- // (3) the transport actually recorded the spawn, carrying the provider build_command.
1366
- let recorded = transport.spawn_records();
1367
- assert!(
1368
- !recorded.is_empty(),
1369
- "quick_start must drive the transport spawn path (>=1 spawn recorded); the dry-run bug records ZERO spawns"
1370
- );
1371
- assert_eq!(
1372
- recorded[0].0, "spawn_first",
1373
- "the first worker uses new-session (spawn_first); got {recorded:?}"
1374
- );
1375
- assert!(
1376
- recorded
1377
- .iter()
1378
- .any(|(_, argv)| argv.iter().any(|a| a == "fake-worker")),
1379
- "the spawn argv must carry the agent's provider build_command (fake-worker); got {recorded:?}"
1380
- );
1381
- }
1382
-
1383
- #[test]
1384
- fn adaptive_layout_plan_8_workers_is_3_3_2() {
1385
- let agents = (1..=8)
1386
- .map(|i| AgentId::new(format!("w{i}")))
1387
- .collect::<Vec<_>>();
1388
- let plan = adaptive_layout_plan(&agents, 3);
1389
- let windows = plan
1390
- .iter()
1391
- .map(|placement| placement.layout_window.as_str().to_string())
1392
- .collect::<Vec<_>>();
1393
- assert_eq!(
1394
- windows,
1395
- vec![
1396
- "team-w1", "team-w1", "team-w1", "team-w2", "team-w2", "team-w2", "team-w3", "team-w3",
1397
- ]
1398
- );
1399
- let pane_counts = ["team-w1", "team-w2", "team-w3"]
1400
- .into_iter()
1401
- .map(|window| {
1402
- windows
1403
- .iter()
1404
- .filter(|actual| actual.as_str() == window)
1405
- .count()
1406
- })
1407
- .collect::<Vec<_>>();
1408
- assert_eq!(pane_counts, vec![3, 3, 2]);
1409
- assert_eq!(
1410
- plan.iter()
1411
- .filter(|placement| placement.starts_window)
1412
- .map(|placement| placement.agent_id.as_str().to_string())
1413
- .collect::<Vec<_>>(),
1414
- vec!["w1", "w4", "w7"]
1415
- );
1416
- }
1417
-
1418
- #[test]
1419
- #[serial(env)]
1420
- fn quick_start_default_adaptive_groups_workers_into_layout_panes() {
1421
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-adaptive-layout");
1422
- let roles = (1..=4)
1423
- .map(|i| {
1424
- let id = format!("w{i}");
1425
- (format!("{id}.md"), role_doc(&id))
1426
- })
1427
- .collect::<Vec<_>>();
1428
- let role_refs = roles
1429
- .iter()
1430
- .map(|(file, doc)| (file.as_str(), doc.as_str()))
1431
- .collect::<Vec<_>>();
1432
- let team = quick_start_team_dir_with_roles(&role_refs);
1433
- let workspace = team.parent().expect("team_workspace(team_dir) = parent");
1434
- seed_healthy_coordinator(workspace);
1435
- let transport = OfflineTransport::new();
1436
-
1437
- let report = quick_start_with_transport(&team, None, true, None, &transport)
1438
- .expect("quick_start_with_transport must reach Ready");
1439
-
1440
- let (launch, attach_commands) = match report {
1441
- QuickStartReport::Ready {
1442
- launch,
1443
- attach_commands,
1444
- ..
1445
- } => (*launch, attach_commands),
1446
- other => panic!("quick_start must reach Ready; got {other:?}"),
1447
- };
1448
- // 0.3.28 Step 4b: adaptive 3-pane tiling replaced with 1-window-per-agent
1449
- // Python-parity layout. 4 workers → spawn_first + 3×spawn_into, each in its
1450
- // own window named after the agent_id. No team-w<N> windows; no splits.
1451
- assert_eq!(
1452
- transport
1453
- .spawn_records()
1454
- .iter()
1455
- .map(|(kind, _)| kind.as_str())
1456
- .collect::<Vec<_>>(),
1457
- vec!["spawn_first", "spawn_into", "spawn_into", "spawn_into"],
1458
- "0.3.28 Step 4b: 4 workers → 1 spawn_first + 3 spawn_into; \
1459
- no splits in worker session"
1460
- );
1461
-
1462
- let (_raw, state) = raw_runtime_state(workspace);
1463
- assert!(
1464
- transport
1465
- .pane_title_records()
1466
- .iter()
1467
- .all(|(session, _, _, _)| Some(session.as_str())
1468
- == state
1469
- .get("session_name")
1470
- .and_then(serde_json::Value::as_str)),
1471
- "pane titles must be configured inside the team session"
1472
- );
1473
- // Each worker lives in its OWN window named `agent_id` (Python parity).
1474
- assert_eq!(state.pointer("/agents/w1/window"), Some(&json!("w1")));
1475
- assert_eq!(state.pointer("/agents/w4/window"), Some(&json!("w4")));
1476
- // attach commands point to the per-agent windows.
1477
- assert!(
1478
- attach_commands.iter().any(|cmd| cmd.contains(":w1")),
1479
- "attach commands must include the per-agent windows: {attach_commands:?}"
1480
- );
1481
- }
1482
-
1483
- #[test]
1484
- #[serial(env)]
1485
- fn quick_start_tmux_backend_uses_workspace_private_endpoint() {
1486
- let leader_socket = "/tmp/team-agent-layout-leader-socket";
1487
- let _tmux = EnvVarGuard::set("TMUX", &format!("{leader_socket},123,0"));
1488
- let workspace = std::path::Path::new("/tmp/layout-workspace");
1489
- let backend = quick_start_tmux_backend(workspace);
1490
- let expected = TmuxBackend::for_workspace(workspace);
1491
-
1492
- assert_eq!(
1493
- crate::transport::Transport::tmux_endpoint(&backend),
1494
- crate::transport::Transport::tmux_endpoint(&expected),
1495
- "quick-start workers must use the workspace-private socket, not ambient $TMUX"
1496
- );
1497
- assert_eq!(
1498
- selected_tmux_socket_source(&backend, workspace),
1499
- Some("workspace")
1500
- );
1501
- }
1502
-
1503
- #[test]
1504
- #[serial(env)]
1505
- fn quick_start_persists_selected_tmux_endpoint_and_attach_commands() {
1506
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-endpoint-attach");
1507
- let team = quick_start_team_dir(QS_VALID_ROLE);
1508
- let workspace = team.parent().expect("team_workspace(team_dir) = parent");
1509
- seed_healthy_coordinator(workspace);
1510
- let endpoint = "/tmp/team-agent-layout-selected-socket";
1511
- let transport = OfflineTransport::new().with_tmux_endpoint(endpoint);
1512
-
1513
- let report = quick_start_with_transport(&team, None, true, None, &transport)
1514
- .expect("quick_start_with_transport must reach Ready");
1515
- let attach_commands = match report {
1516
- QuickStartReport::Ready {
1517
- attach_commands, ..
1518
- } => attach_commands,
1519
- other => panic!("quick_start must reach Ready; got {other:?}"),
1520
- };
1521
-
1522
- assert!(
1523
- attach_commands
1524
- .iter()
1525
- .any(|cmd| cmd.contains(&format!("tmux -S {endpoint} attach -t "))),
1526
- "attach commands must use the selected socket endpoint: {attach_commands:?}"
1527
- );
1528
- assert!(
1529
- !attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1530
- "managed metadata does not prove an unreported leader window exists: {attach_commands:?}"
1531
- );
1532
- assert!(attach_commands.iter().any(|cmd| cmd.ends_with(":implementer")));
1533
- let (_raw, state) = raw_runtime_state(workspace);
1534
- assert_eq!(state["tmux_endpoint"], json!(endpoint));
1535
- assert_eq!(state["tmux_socket"], json!(endpoint));
1536
- assert_eq!(state["is_external_leader"], json!(false));
1537
- assert_eq!(
1538
- state["teams"]["quickteam"]["is_external_leader"],
1539
- json!(false)
1540
- );
1541
- }
1542
-
1543
- #[test]
1544
- fn annotate_runtime_tmux_endpoint_persists_workspace_socket_as_full_path() {
1545
- let workspace = temp_ws();
1546
- let short = crate::tmux_backend::socket_name_for_workspace(&workspace);
1547
- let expected = crate::tmux_backend::socket_path_for_workspace(&workspace)
1548
- .expect("workspace socket should have a physical path");
1549
- let transport = OfflineTransport::new().with_tmux_endpoint(short);
1550
- let mut state = json!({});
1551
-
1552
- annotate_runtime_tmux_endpoint(&mut state, &transport, &workspace);
1553
-
1554
- assert_eq!(
1555
- state["tmux_endpoint"],
1556
- json!(expected.to_string_lossy().to_string()),
1557
- "runtime endpoint state must persist the full tmux socket path, not the short -L name"
1558
- );
1559
- assert_eq!(
1560
- state["tmux_socket"], state["tmux_endpoint"],
1561
- "tmux_socket mirrors the canonical persisted endpoint"
1562
- );
1563
- }
1564
-
1565
- #[test]
1566
- #[serial(env)]
1567
- fn quick_start_preserves_managed_leader_topology_without_inventing_a_leader_window() {
1568
- let hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-managed-leader");
1569
- let workspace = hermetic.root();
1570
- let team = workspace.join("teamdir");
1571
- std::fs::create_dir_all(team.join("agents")).unwrap();
1572
- std::fs::write(team.join("TEAM.md"), QS_TEAM_MD).unwrap();
1573
- std::fs::write(team.join("agents/implementer.md"), QS_VALID_ROLE).unwrap();
1574
- seed_healthy_coordinator(workspace);
1575
- let endpoint = std::env::var("TMUX").unwrap().split(',').next().unwrap().to_string();
1576
- crate::state::persist::save_runtime_state(
1577
- workspace,
1578
- &json!({
1579
- "active_team_key": "teamdir",
1580
- "session_name": null,
1581
- "is_external_leader": false,
1582
- "leader_client": {"diagnostic_only": true, "attach_mode": "attach-session"},
1583
- "tmux_socket": endpoint,
1584
- "tmux_endpoint": endpoint,
1585
- "agents": {},
1586
- "teams": {
1587
- "teamdir": {
1588
- "session_name": null,
1589
- "is_external_leader": false,
1590
- "leader_client": {"diagnostic_only": true, "attach_mode": "attach-session"},
1591
- "agents": {}
1592
- }
1593
- }
1594
- }),
1595
- )
1596
- .expect("seed managed leader state");
1597
- let attached = crate::cli::cmd_attach_leader(&crate::cli::AttachLeaderArgs {
1598
- workspace: workspace.to_path_buf(), team: Some("teamdir".into()), pane: None,
1599
- provider: crate::model::enums::Provider::Fake, confirm: false, json: true,
1600
- }).expect("bind the real owned caller through the public lease port");
1601
- assert_eq!(attached.exit, crate::cli::ExitCode::Ok, "{attached:?}");
1602
- let mut state = crate::state::persist::load_runtime_state(workspace).unwrap();
1603
- assert!(state["session_name"].is_null(), "leader-only bootstrap has no worker session");
1604
- assert!(state["teams"]["teamdir"]["session_name"].is_null());
1605
- assert!(state["teams"]["teamdir"]["agents"].as_object().unwrap().is_empty());
1606
- // The owned fake caller models the already-managed launcher topology;
1607
- // retain the real binding while setting the presentation fixture metadata.
1608
- state["is_external_leader"] = json!(false);
1609
- state["leader_client"] = json!({"diagnostic_only": true, "attach_mode": "attach-session"});
1610
- state["teams"]["teamdir"]["is_external_leader"] = json!(false);
1611
- state["teams"]["teamdir"]["leader_client"] = state["leader_client"].clone();
1612
- crate::state::persist::save_runtime_state(workspace, &state).unwrap();
1613
- let transport = OfflineTransport::new();
1614
-
1615
- let report = quick_start_with_transport(&team, None, true, Some("teamdir"), &transport)
1616
- .expect("quick_start_with_transport must reach Ready");
1617
- let attach_commands = match report {
1618
- QuickStartReport::Ready {
1619
- attach_commands, ..
1620
- } => attach_commands,
1621
- other => panic!("quick_start must reach Ready; got {other:?}"),
1622
- };
1623
-
1624
- assert!(
1625
- !attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1626
- "managed ownership must survive, but a missing physical leader window is not an attach target: {attach_commands:?}"
1627
- );
1628
- assert!(attach_commands.iter().any(|cmd| cmd.ends_with(":implementer")));
1629
- let (_raw, state) = raw_runtime_state(workspace);
1630
- assert_eq!(state["is_external_leader"], json!(false));
1631
- assert_eq!(state["leader_client"]["diagnostic_only"], json!(true));
1632
- }
1633
-
1634
- #[test]
1635
- fn fresh_managed_state_without_receiver_is_not_attached() {
1636
- let workspace = temp_ws();
1637
- crate::state::persist::save_runtime_state(
1638
- &workspace,
1639
- &json!({
1640
- "active_team_key": "teamdir",
1641
- "session_name": "team-teamdir",
1642
- "is_external_leader": false,
1643
- "agents": {"implementer": {"status": "running"}},
1644
- "teams": {
1645
- "teamdir": {
1646
- "session_name": "team-teamdir",
1647
- "is_external_leader": false,
1648
- "agents": {"implementer": {"status": "running"}}
1649
- }
1650
- }
1651
- }),
1652
- )
1653
- .unwrap();
1654
-
1655
- assert!(
1656
- !crate::lifecycle::launch::launched_team_receiver_is_attached(&workspace, "teamdir"),
1657
- "managed topology with missing leader_receiver must not be reported attached"
1658
- );
1659
- }
1660
-
1661
- #[test]
1662
- fn attach_window_names_for_state_agents_include_managed_leader_and_layout_windows() {
1663
- let state = json!({
1664
- "is_external_leader": false,
1665
- "agents": {
1666
- "w1": {"layout_window": "team-w1", "window": "w1"},
1667
- "w2": {"layout_window": "team-w1", "window": "w2"},
1668
- "w4": {"layout_window": "team-w2", "window": "w4"}
1669
- }
1670
- });
1671
-
1672
- let windows = crate::lifecycle::launch::attach_window_names_for_state_agents(
1673
- &state,
1674
- ["w1", "w2", "w4"].into_iter(),
1675
- );
1676
-
1677
- assert_eq!(windows, vec!["leader", "team-w1", "team-w2"]);
1678
- }
1679
-
1680
- // REAL-MACHINE residency boundary (acceptance framework): the PUBLIC quick_start (real TmuxBackend +
1681
- // real start_coordinator) on a fresh ws must leave a LIVE tmux session AND a ps-verifiable resident
1682
- // coordinator daemon (start_coordinator -> live pid). The framework verifies residency via ps; here we
1683
- // only assert the in-report spawn observable. #[ignore] — spawns real tmux + a real daemon subprocess.
1684
- #[test]
1685
- #[ignore = "real-machine: live tmux session + resident coordinator daemon (framework verifies via ps)"]
1686
- fn quick_start_fresh_ws_spawns_resident_tmux_and_coordinator() {
1687
- let team = quick_start_team_dir(QS_VALID_ROLE);
1688
- let report = quick_start(&team, None, true, None).expect("quick_start");
1689
- match report {
1690
- QuickStartReport::Ready { launch, .. } => {
1691
- assert!(
1692
- !launch.dry_run,
1693
- "a real quick_start must spawn (not dry-run)"
1694
- );
1695
- assert!(
1696
- !launch.started.is_empty(),
1697
- "a real quick_start must spawn >=1 worker into a live tmux session; got {:?}",
1698
- launch.started
1699
- );
1700
- }
1701
- other => panic!("a fresh quick_start must reach Ready; got {other:?}"),
1702
- }
1703
- }
1704
-
1705
- // ═════════════════════════════════════════════════════════════════════════
1706
- // rt-host-a LOOP #2 — cli-handler DELEGATION sweep (same-class stub): restart / start_agent /
1707
- // add_agent return RequirementUnmet at the spawn boundary and NEVER drive the transport (zero spawns)
1708
- // nor start the coordinator. RED via the new *_with_transport seams + a RecordingTransport. OS-safe:
1709
- // recording transport (no real tmux) + seeded-healthy-coordinator (start_coordinator AlreadyRunning).
1710
- // Golden: restart/orchestration.py (Route-B resume spawn), lifecycle/start.py, lifecycle/operations.py.
1711
- // ═════════════════════════════════════════════════════════════════════════
1712
-
1713
- pub(super) const DELEG_ROLE_ALPHA: &str = "---\nname: alpha\nrole: Alpha Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nAlpha.\n";
1714
- pub(super) const DELEG_ROLE_BRAVO: &str = "---\nname: bravo\nrole: Bravo Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nBravo.\n";
1715
- const DELEG_ROLE_WORKER2: &str = "---\nname: worker2\nrole: Second Worker\nprovider: fake\nmodel: fake\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nSecond worker.\n";
1716
-
1717
- /// A workspace (= self-contained team dir) with a compiled 2-agent spec + state listing alpha/bravo as
1718
- /// running `fake` workers that were never captured (no session_id / first_send_at), so restart and
1719
- /// start-agent fresh-spawn them without --allow-fresh (fake has no resume) + a seeded HEALTHY
1720
- /// coordinator. Resume-path tests use [`restart_ws_two_copilot_resumable_workers`].
1721
- pub(super) fn restart_ws_two_resumable_workers() -> PathBuf {
1722
- restart_team_ws(
1723
- &[("alpha", DELEG_ROLE_ALPHA.to_string()), ("bravo", DELEG_ROLE_BRAVO.to_string())],
1724
- json!({
1725
- "alpha": {"status": "running", "provider": "fake"},
1726
- "bravo": {"status": "running", "provider": "fake"}
1727
- }),
1728
- )
1729
- }
1730
-
1731
- /// Same team as [`restart_ws_two_resumable_workers`], but alpha/bravo are Copilot workers whose
1732
- /// session ids exist in `<home>/.copilot/session-store.db` (the Copilot resume backing), so restart
1733
- /// takes the Route-B RESUME path. The caller holds `#[serial(env)]` with `HOME=<home>`.
1734
- pub(super) fn restart_ws_two_copilot_resumable_workers(home: &std::path::Path) -> PathBuf {
1735
- seed_copilot_session_store(home, &["sess-a", "sess-b"]);
1736
- restart_team_ws(
1737
- &[
1738
- ("alpha", provider_role_doc("alpha", "copilot", "gpt-5.5")),
1739
- ("bravo", provider_role_doc("bravo", "copilot", "gpt-5.5")),
1740
- ],
1741
- json!({
1742
- "alpha": {"status": "running", "provider": "copilot", "session_id": "sess-a", "first_send_at": "2026-05-27T10:00:00+00:00"},
1743
- "bravo": {"status": "running", "provider": "copilot", "session_id": "sess-b", "first_send_at": "2026-05-27T10:00:00+00:00"}
1744
- }),
1745
- )
1746
- }
1747
-
1748
- /// Copilot resume backing is a `sessions` row in `$HOME/.copilot/session-store.db`.
1749
- pub(super) fn seed_copilot_session_store(home: &std::path::Path, session_ids: &[&str]) {
1750
- let db = home.join(".copilot").join("session-store.db");
1751
- std::fs::create_dir_all(db.parent().unwrap()).unwrap();
1752
- let conn = rusqlite::Connection::open(db).unwrap();
1753
- conn.execute_batch("create table if not exists sessions (id text primary key);").unwrap();
1754
- for session_id in session_ids {
1755
- conn.execute(
1756
- "insert or replace into sessions(id) values (?1)",
1757
- [*session_id],
1758
- )
1759
- .unwrap();
1760
- }
1761
- }
1762
-
1763
- fn restart_team_ws(roles: &[(&str, String)], agents: serde_json::Value) -> PathBuf {
1764
- let ws = temp_ws().join("restartteam");
1765
- std::fs::create_dir_all(ws.join("agents")).unwrap();
1766
- std::fs::write(
1767
- ws.join("TEAM.md"),
1768
- "---\nname: restartteam\nobjective: Restart probe.\nprovider: codex\n---\n\nteam.\n",
1769
- )
1770
- .unwrap();
1771
- for (id, doc) in roles {
1772
- std::fs::write(ws.join("agents").join(format!("{id}.md")), doc).unwrap();
1773
- }
1774
- let spec = crate::compiler::compile_team(&ws).expect("compile 2-agent team");
1775
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
1776
- crate::state::persist::save_runtime_state(
1777
- &ws,
1778
- &json!({
1779
- "session_name": "team-restartteam",
1780
- "agents": agents
1781
- }),
1782
- )
1783
- .unwrap();
1784
- seed_healthy_coordinator(&ws); // start_coordinator -> AlreadyRunning (no real daemon subprocess)
1785
- ws
1786
- }
1787
-
1788
- fn restart_ws_one_resumable_worker() -> PathBuf {
1789
- let ws = temp_ws().join("restartone");
1790
- std::fs::create_dir_all(ws.join("agents")).unwrap();
1791
- std::fs::write(
1792
- ws.join("TEAM.md"),
1793
- "---\nname: restartone\nobjective: Restart readiness probe.\nprovider: codex\n---\n\nteam.\n",
1794
- )
1795
- .unwrap();
1796
- std::fs::write(ws.join("agents").join("alpha.md"), DELEG_ROLE_ALPHA).unwrap();
1797
- let spec = crate::compiler::compile_team(&ws).expect("compile 1-agent team");
1798
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
1799
- crate::state::persist::save_runtime_state(
1800
- &ws,
1801
- &json!({
1802
- "session_name": "team-restartone",
1803
- "agents": {
1804
- "alpha": {"status": "running", "provider": "fake"}
1805
- }
1806
- }),
1807
- )
1808
- .unwrap();
1809
- seed_healthy_coordinator(&ws);
1810
- ws
1811
- }
1812
-
1813
- // 2 [P0] — restart_with_transport must drive the REAL Route-B resume spawn: one spawn per resumable
1814
- // worker. The first resumed worker recreates the session with spawn_first; later workers may use
1815
- // spawn_into only after a live-session check proves that recreated session still exists. Each spawn
1816
- // carries the provider resume command, and the coordinator is started. Copilot is the resumable
1817
- // legacy provider; its backing is the hermetic HOME session store.
1818
- #[test]
1819
- #[serial(env)]
1820
- fn restart_with_transport_spawns_resumable_workers_not_stub() {
1821
- let hermetic = enter_hermetic("launch-spawn-restart-resume");
1822
- let ws = restart_ws_two_copilot_resumable_workers(hermetic.home());
1823
- let mut state = crate::state::persist::load_runtime_state(&ws).unwrap();
1824
- state["generation"] = json!("old-destroyed-session-birth");
1825
- crate::state::persist::save_runtime_state(&ws, &state).unwrap();
1826
- let transport = OfflineTransport::new();
1827
-
1828
- let result = restart_with_transport(&ws, false, None, &transport);
1829
-
1830
- let recorded = transport.spawn_records();
1831
- assert_eq!(
1832
- recorded.len(),
1833
- 2,
1834
- "restart must spawn ONE worker per resumable agent (alpha, bravo); the rt-host-a stub returns \
1835
- RequirementUnmet with ZERO spawns; got {recorded:?}"
1836
- );
1837
- assert_eq!(
1838
- recorded[0].0, "spawn_first",
1839
- "with has-session=false before alpha, restart must recreate the session with spawn_first; got {recorded:?}"
1840
- );
1841
- assert_eq!(
1842
- recorded[1].0, "spawn_into",
1843
- "with has-session=true after alpha spawn, restart may add bravo with spawn_into; this is liveness-based, not index-based; got {recorded:?}"
1844
- );
1845
- assert!(
1846
- recorded.iter().all(|(_, argv)| argv.iter().any(|a| a == "copilot")
1847
- && argv.iter().any(|a| a == "--resume")),
1848
- "each resumed worker's spawn argv must carry the provider resume command (copilot --resume); got {recorded:?}"
1849
- );
1850
- assert!(
1851
- matches!(result, Ok(RestartReport::Restarted { coordinator_started: true, .. })),
1852
- "restart must reach RestartReport::Restarted with coordinator_started=true (AlreadyRunning, seeded); got {result:?}"
1853
- );
1854
- let state = crate::state::persist::load_runtime_state(&ws).unwrap();
1855
- let generation = state["agents"]["alpha"]["spawned_at"].as_str().unwrap();
1856
- assert_ne!(generation, "old-destroyed-session-birth");
1857
- assert_eq!(state["generation"], generation);
1858
- assert!(state.get("teams").is_none(), "legacy flat state must remain flat");
1859
- let owner = transport.session_owner(&SessionName::new("team-restartteam")).unwrap().unwrap();
1860
- assert_eq!(owner.generation, generation);
1861
- let events = crate::event_log::EventLog::new(&ws).tail(20).unwrap();
1862
- let completed = events
1863
- .iter()
1864
- .find(|event| event.get("event").and_then(|v| v.as_str()) == Some("restart.completed"))
1865
- .expect("restart.completed event for successful restart");
1866
- assert_eq!(completed.get("rc").and_then(|v| v.as_str()), Some("ok"));
1867
-
1868
- let ws = restart_ws_two_copilot_resumable_workers(hermetic.home());
1869
- let dead_after_first = OfflineTransport::new().with_session_absent_after_spawn_first();
1870
- let result = restart_with_transport_with_readiness_deadline(
1871
- &ws,
1872
- false,
1873
- None,
1874
- &dead_after_first,
1875
- Some(0),
1876
- );
1877
- let recorded = dead_after_first.spawn_records();
1878
- assert_eq!(
1879
- recorded.len(),
1880
- 1,
1881
- "if a resumed session disappears after alpha, restart must fail fast before bravo; got result={result:?} recorded={recorded:?}"
1882
- );
1883
- assert!(
1884
- recorded.iter().all(|(kind, _)| kind == "spawn_first"),
1885
- "restart must not call spawn_into/new-window against a dead server; result={result:?} recorded={recorded:?}"
1886
- );
1887
- let result_debug = format!("{result:?}");
1888
- let report = result.expect("resume integrity failure should return a typed failed report");
1889
- let RestartReport::Failed { failed_agents, .. } = report else {
1890
- panic!("resume integrity failure must not be Partial/Restarted; got {report:?}");
1891
- };
1892
- assert_eq!(failed_agents.len(), 1);
1893
- assert_eq!(failed_agents[0].agent_id.as_str(), "alpha");
1894
- assert_eq!(failed_agents[0].phase, "resume");
1895
- assert!(
1896
- dead_after_first.calls().iter().all(|call| *call != "kill_session"),
1897
- "a single worker/session disappearance must not trigger another shared-session kill; calls={:?}",
1898
- dead_after_first.calls()
1899
- );
1900
- let events = crate::event_log::EventLog::new(&ws).tail(20).unwrap();
1901
- let failed = events
1902
- .iter()
1903
- .find(|event| event.get("event").and_then(|v| v.as_str()) == Some("restart.agent_failed"))
1904
- .expect("restart.agent_failed event for isolated alpha");
1905
- assert_eq!(
1906
- failed.get("agent_id").and_then(|v| v.as_str()),
1907
- Some("alpha")
1908
- );
1909
- assert!(
1910
- failed
1911
- .get("error")
1912
- .and_then(|v| v.as_str())
1913
- .is_some_and(|error| error.contains("session_disappeared_after_spawn")),
1914
- "restart must report the first resumed agent/session disappearance explicitly; event={failed} result={result_debug}"
1915
- );
1916
- }
1917
-
1918
- #[test]
1919
- fn restart_runtime_spec_spawns_from_run_workspace_not_runtime_dir() {
1920
- let workspace = temp_ws();
1921
- std::fs::create_dir_all(workspace.join("agents")).unwrap();
1922
- std::fs::write(
1923
- workspace.join("TEAM.md"),
1924
- "---\nname: current\nobjective: Restart cwd probe.\nprovider: codex\n---\n\nteam.\n",
1925
- )
1926
- .unwrap();
1927
- std::fs::write(workspace.join("agents").join("alpha.md"), DELEG_ROLE_ALPHA).unwrap();
1928
- let spec = crate::compiler::compile_team(&workspace).expect("compile project-root team");
1929
- let spec_path = crate::model::paths::runtime_spec_path(&workspace, "current");
1930
- std::fs::create_dir_all(spec_path.parent().unwrap()).unwrap();
1931
- std::fs::write(&spec_path, crate::model::yaml::dumps(&spec)).unwrap();
1932
- crate::state::persist::save_runtime_state(
1933
- &workspace,
1934
- &json!({
1935
- "active_team_key": "current",
1936
- "session_name": "team-current",
1937
- "spec_path": spec_path.to_string_lossy(),
1938
- "team_dir": workspace.to_string_lossy(),
1939
- "agents": {
1940
- "alpha": {
1941
- "status": "running",
1942
- "provider": "fake",
1943
- "spawn_cwd": null
1944
- }
1945
- }
1946
- }),
1947
- )
1948
- .unwrap();
1949
- seed_healthy_coordinator(&workspace);
1950
- let transport = OfflineTransport::new();
1951
-
1952
- let result = restart_with_transport(&workspace, false, Some("current"), &transport);
1953
-
1954
- assert!(
1955
- matches!(result, Ok(RestartReport::Restarted { .. })),
1956
- "restart should succeed for a never-captured project-root team: {result:?}"
1957
- );
1958
- assert_eq!(
1959
- transport.spawn_cwd_records(),
1960
- vec![workspace.clone()],
1961
- "restart must spawn from run_workspace, not .team/runtime/<team>"
1962
- );
1963
- let state = crate::state::persist::load_runtime_state(&workspace).unwrap();
1964
- assert_eq!(
1965
- state
1966
- .get("agents")
1967
- .and_then(|agents| agents.get("alpha"))
1968
- .and_then(|agent| agent.get("spawn_cwd"))
1969
- .and_then(serde_json::Value::as_str),
1970
- Some(workspace.to_string_lossy().as_ref()),
1971
- "restart must persist the actual spawn cwd for later diagnostics"
1972
- );
1973
- let rebuilt_spec =
1974
- crate::model::yaml::loads(&std::fs::read_to_string(&spec_path).unwrap()).unwrap();
1975
- assert_eq!(
1976
- rebuilt_spec
1977
- .get("team")
1978
- .and_then(|team| team.get("workspace"))
1979
- .and_then(crate::model::yaml::Value::as_str),
1980
- Some(workspace.to_string_lossy().as_ref()),
1981
- "restart spec rebuild must keep team.workspace at the project root"
1982
- );
1983
- for agent in rebuilt_spec
1984
- .get("agents")
1985
- .and_then(crate::model::yaml::Value::as_list)
1986
- .unwrap()
1987
- {
1988
- assert_eq!(
1989
- agent
1990
- .get("working_directory")
1991
- .and_then(crate::model::yaml::Value::as_str),
1992
- Some(workspace.to_string_lossy().as_ref()),
1993
- "restart spec rebuild must keep agent working_directory at the project root"
1994
- );
1995
- }
1996
- }
1997
-
1998
- #[test]
1999
- #[serial(env)]
2000
- fn restart_allow_fresh_does_not_force_fresh_other_agents_when_one_session_capture_times_out() {
2001
- let hermetic = enter_hermetic("launch-spawn-restart-atomic");
2002
- let ws = temp_ws().join("restartatomic");
2003
- std::fs::create_dir_all(ws.join("agents")).unwrap();
2004
- std::fs::write(
2005
- ws.join("TEAM.md"),
2006
- "---\nname: restartatomic\nobjective: Restart atomicity probe.\nprovider: codex\n---\n\nteam.\n",
2007
- )
2008
- .unwrap();
2009
- std::fs::write(
2010
- ws.join("agents").join("alpha.md"),
2011
- provider_role_doc("alpha", "copilot", "gpt-5.5"),
2012
- )
2013
- .unwrap();
2014
- std::fs::write(
2015
- ws.join("agents").join("bravo.md"),
2016
- provider_role_doc("bravo", "copilot", "gpt-5.5"),
2017
- )
2018
- .unwrap();
2019
-
2020
- // alpha's resume backing is its Copilot session-store row; bravo has none, so only bravo's
2021
- // session convergence times out.
2022
- let alpha_session = "019ee540-37ed-7a20-a141-1d654224d209";
2023
- seed_copilot_session_store(hermetic.home(), &[alpha_session]);
2024
-
2025
- let spec = crate::compiler::compile_team(&ws).expect("compile restart team");
2026
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
2027
- crate::state::persist::save_runtime_state(
2028
- &ws,
2029
- &json!({
2030
- "session_name": "team-restartatomic",
2031
- "agents": {
2032
- "alpha": {
2033
- "status": "running",
2034
- "provider": "copilot",
2035
- "session_id": alpha_session,
2036
- "first_send_at": "2026-05-27T10:00:00+00:00"
2037
- },
2038
- "bravo": {
2039
- "status": "running",
2040
- "provider": "copilot",
2041
- "session_id": null,
2042
- "spawn_cwd": ws.to_string_lossy(),
2043
- "first_send_at": "2026-05-27T10:00:00+00:00"
2044
- }
2045
- }
2046
- }),
2047
- )
2048
- .unwrap();
2049
- seed_healthy_coordinator(&ws);
2050
- let transport = OfflineTransport::new();
2051
-
2052
- let result = restart_with_transport_with_session_convergence_deadline(
2053
- &ws,
2054
- true,
2055
- None,
2056
- &transport,
2057
- Some(0),
2058
- None,
2059
- );
2060
-
2061
- assert!(
2062
- matches!(result, Ok(RestartReport::Restarted { .. })),
2063
- "allow-fresh restart should complete with alpha resumed and bravo fresh; got {result:?}"
2064
- );
2065
- let events = crate::event_log::EventLog::new(&ws).tail(80).unwrap();
2066
- let decisions = events
2067
- .iter()
2068
- .filter(|event| {
2069
- event.get("event").and_then(|v| v.as_str()) == Some("restart.resume_decision")
2070
- })
2071
- .collect::<Vec<_>>();
2072
- let alpha = decisions
2073
- .iter()
2074
- .find(|event| event.get("worker_id").and_then(|v| v.as_str()) == Some("alpha"))
2075
- .expect("alpha decision");
2076
- assert_eq!(
2077
- alpha.get("decision").and_then(|v| v.as_str()),
2078
- Some("resume"),
2079
- "alpha has session_id plus a matching Copilot session-store row and must not be forced fresh: {alpha}"
2080
- );
2081
- assert!(
2082
- alpha.get("forced_fresh").is_none(),
2083
- "alpha must not inherit bravo's convergence timeout: {alpha}"
2084
- );
2085
- let bravo = decisions
2086
- .iter()
2087
- .find(|event| event.get("worker_id").and_then(|v| v.as_str()) == Some("bravo"))
2088
- .expect("bravo decision");
2089
- assert_eq!(
2090
- bravo.get("decision").and_then(|v| v.as_str()),
2091
- Some("fresh_start")
2092
- );
2093
- assert_eq!(
2094
- bravo.get("forced_fresh").and_then(|v| v.as_bool()),
2095
- Some(true),
2096
- "only the missing-session agent should carry forced_fresh: {bravo}"
2097
- );
2098
- }
2099
-
2100
- #[test]
2101
- fn restart_spawn_failure_isolated_to_partial_report() {
2102
- let ws = restart_ws_two_resumable_workers();
2103
- let transport = OfflineTransport::new().with_spawn_failure("bravo", "injected bravo failure");
2104
-
2105
- let result = restart_with_transport(&ws, false, None, &transport);
2106
-
2107
- let report = result.expect("single worker failure must be represented as partial report");
2108
- let RestartReport::Partial {
2109
- agents,
2110
- failed_agents,
2111
- coordinator_started,
2112
- ..
2113
- } = report
2114
- else {
2115
- panic!("single worker failure must return RestartReport::Partial; got {report:?}");
2116
- };
2117
- assert!(
2118
- coordinator_started,
2119
- "partial restart still starts coordinator for successful agents"
2120
- );
2121
- assert_eq!(
2122
- agents
2123
- .iter()
2124
- .map(|agent| agent.agent_id.as_str())
2125
- .collect::<Vec<_>>(),
2126
- vec!["alpha"]
2127
- );
2128
- assert_eq!(failed_agents.len(), 1);
2129
- assert_eq!(failed_agents[0].agent_id.as_str(), "bravo");
2130
- assert_eq!(failed_agents[0].phase, "spawn");
2131
-
2132
- let state = crate::state::persist::load_runtime_state(&ws).unwrap();
2133
- assert_eq!(
2134
- state
2135
- .pointer("/agents/alpha/status")
2136
- .and_then(|v| v.as_str()),
2137
- Some("running")
2138
- );
2139
- assert_eq!(
2140
- state
2141
- .pointer("/agents/bravo/status")
2142
- .and_then(|v| v.as_str()),
2143
- Some("failed")
2144
- );
2145
- assert!(
2146
- state
2147
- .pointer("/agents/bravo/restart_error")
2148
- .and_then(|v| v.as_str())
2149
- .is_some_and(|error| error.contains("injected bravo failure")),
2150
- "failed agent must retain restart_error in state: {state}"
2151
- );
2152
-
2153
- let events = crate::event_log::EventLog::new(&ws).tail(20).unwrap();
2154
- let completed = events
2155
- .iter()
2156
- .find(|event| event.get("event").and_then(|v| v.as_str()) == Some("restart.completed"))
2157
- .expect("restart.completed event for partial restart");
2158
- assert_eq!(
2159
- completed.get("rc").and_then(|v| v.as_str()),
2160
- Some("partial")
2161
- );
2162
- assert!(
2163
- completed
2164
- .get("successful_agents")
2165
- .and_then(|v| v.as_array())
2166
- .is_some_and(|agents| agents.iter().any(|agent| agent.as_str() == Some("alpha"))),
2167
- "completed event must list successful agents: {completed}"
2168
- );
2169
- assert!(
2170
- completed
2171
- .get("failed_agents")
2172
- .and_then(|v| v.as_array())
2173
- .is_some_and(|agents| agents.iter().any(|agent| {
2174
- agent.get("agent_id").and_then(|v| v.as_str()) == Some("bravo")
2175
- && agent.get("phase").and_then(|v| v.as_str()) == Some("spawn")
2176
- })),
2177
- "completed event must list failed agents with phase: {completed}"
2178
- );
2179
- }
2180
-
2181
- #[test]
2182
- fn restart_all_spawn_failures_return_failed_report() {
2183
- let ws = restart_ws_one_resumable_worker();
2184
- let transport = OfflineTransport::new().with_spawn_failure("alpha", "injected alpha failure");
2185
-
2186
- let result = restart_with_transport(&ws, false, None, &transport);
2187
-
2188
- let report = result.expect("all worker failures should return typed failed report");
2189
- let RestartReport::Failed { failed_agents, .. } = report else {
2190
- panic!("all worker failures must return RestartReport::Failed; got {report:?}");
2191
- };
2192
- assert_eq!(failed_agents.len(), 1);
2193
- assert_eq!(failed_agents[0].agent_id.as_str(), "alpha");
2194
- assert_eq!(failed_agents[0].phase, "spawn");
2195
-
2196
- let events = crate::event_log::EventLog::new(&ws).tail(20).unwrap();
2197
- let completed = events
2198
- .iter()
2199
- .find(|event| event.get("event").and_then(|v| v.as_str()) == Some("restart.completed"))
2200
- .expect("restart.completed event for failed restart");
2201
- assert_eq!(completed.get("rc").and_then(|v| v.as_str()), Some("fail"));
2202
- }
2203
-
2204
- #[test]
2205
- fn restart_spawn_loop_keeps_failure_isolation_guard() {
2206
- let source = include_str!("../restart/rebuild.rs");
2207
- let start = source
2208
- .find("BEGIN_B5_RESTART_ISOLATION_LOOP")
2209
- .expect("B5 isolation loop start marker");
2210
- let end = source
2211
- .find("END_B5_RESTART_ISOLATION_LOOP")
2212
- .expect("B5 isolation loop end marker");
2213
- let body = &source[start..end];
2214
- for forbidden in ["?;", "break", "return "] {
2215
- assert!(
2216
- !body.contains(forbidden),
2217
- "B5 spawn loop must not fail-fast via {forbidden:?}; body={body}"
2218
- );
2219
- }
2220
- assert!(
2221
- body.contains("continue"),
2222
- "B5 spawn loop should isolate per-agent failures and continue; body={body}"
2223
- );
2224
- }
2225
-
2226
- #[test]
2227
- fn restart_times_out_when_spawned_worker_pane_is_not_addressable() {
2228
- let ws = restart_ws_one_resumable_worker();
2229
- let transport = OfflineTransport::new().with_spawned_panes_addressable(false);
2230
-
2231
- let result =
2232
- restart_with_transport_with_readiness_deadline(&ws, false, None, &transport, Some(0));
2233
-
2234
- let text = format!("{result:?}");
2235
- assert!(
2236
- text.contains("restart not ready")
2237
- && text.contains("worker pane addressable: no")
2238
- && text.contains("Action:")
2239
- && text.contains("Log:"),
2240
- "restart must refuse with N38 readiness timeout details, not return ok; got {text}"
2241
- );
2242
- assert!(
2243
- !matches!(result, Ok(RestartReport::Restarted { .. })),
2244
- "restart readiness timeout must not return Restarted ok"
2245
- );
2246
- let events = crate::event_log::EventLog::new(&ws).tail(20).unwrap();
2247
- let timeout = events
2248
- .iter()
2249
- .find(|event| {
2250
- event.get("event").and_then(|v| v.as_str()) == Some("restart.readiness_timeout")
2251
- })
2252
- .expect("restart.readiness_timeout event");
2253
- assert_eq!(
2254
- timeout
2255
- .get("worker_pane_addressable")
2256
- .and_then(|v| v.as_bool()),
2257
- Some(false),
2258
- "timeout event must carry the failed readiness condition: {timeout}"
2259
- );
2260
- }
2261
-
2262
- // 3 [P0] — start_agent_with_transport on a non-paused agent with a session_id must spawn EXACTLY ONE
2263
- // worker (resume) carrying the provider resume command. Today the stub returns RequirementUnmet with
2264
- // ZERO spawns -> RED at recorded.len(). Copilot is the resumable legacy provider; its backing is the
2265
- // hermetic HOME session store.
2266
- #[test]
2267
- #[serial(env)]
2268
- fn start_agent_with_transport_spawns_resume_not_stub() {
2269
- let hermetic = enter_hermetic("launch-spawn-start-agent-resume");
2270
- let ws = temp_ws().join("startagentws");
2271
- std::fs::create_dir_all(&ws).unwrap();
2272
- seed_copilot_session_store(hermetic.home(), &["sess-a"]);
2273
- crate::state::persist::save_runtime_state(
2274
- &ws,
2275
- &json!({
2276
- "session_name": "team-sa",
2277
- "agents": {"alpha": {"status": "running", "provider": "copilot", "session_id": "sess-a", "first_send_at": "2026-05-27T10:00:00+00:00"}}
2278
- }),
2279
- )
2280
- .unwrap();
2281
- seed_healthy_coordinator(&ws);
2282
- let transport = OfflineTransport::new();
2283
-
2284
- let _result = start_agent_with_transport(
2285
- &ws,
2286
- &AgentId::new("alpha"),
2287
- false,
2288
- false,
2289
- false,
2290
- None,
2291
- &transport,
2292
- );
2293
-
2294
- let recorded = transport.spawn_records();
2295
- assert_eq!(
2296
- recorded.len(),
2297
- 1,
2298
- "start_agent must spawn EXACTLY ONE worker (resume); the rt-host-a stub returns RequirementUnmet \
2299
- with ZERO spawns; got {recorded:?}"
2300
- );
2301
- assert!(
2302
- recorded[0].1.iter().any(|a| a == "copilot")
2303
- && recorded[0]
2304
- .1
2305
- .windows(2)
2306
- .any(|pair| pair[0] == "--resume" && pair[1] == "sess-a"),
2307
- "the resume spawn argv must carry the provider resume command (copilot --resume sess-a); got {:?}",
2308
- recorded[0].1
2309
- );
2310
- }
2311
-
2312
- // 4 [P0] — add_agent_with_transport must (a) recompile + write the spec (already works) AND (b) spawn
2313
- // the new worker window. Today the stub recompiles then returns RequirementUnmet with ZERO spawns ->
2314
- // RED at (b). OS-safe: the new role file is OUTSIDE agents/ (so it's not a dup), seeded healthy coordinator.
2315
- #[test]
2316
- fn add_agent_with_transport_spawns_new_worker_not_stub() {
2317
- let team = temp_ws().join("addteam");
2318
- std::fs::create_dir_all(team.join("agents")).unwrap();
2319
- std::fs::write(
2320
- team.join("TEAM.md"),
2321
- "---\nname: addteam\nobjective: Add probe.\nprovider: codex\n---\n\nteam.\n",
2322
- )
2323
- .unwrap();
2324
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap(); // existing agent
2325
- let role_file = team.join("worker2-role.md"); // OUTSIDE agents/ -> not a duplicate of an existing agent
2326
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
2327
- seed_healthy_coordinator(&team);
2328
- seed_canonical_team_identity(&team, "addteam");
2329
- let transport = OfflineTransport::new();
2330
-
2331
- let _result = add_agent_with_transport(
2332
- &team,
2333
- &AgentId::new("worker2"),
2334
- &role_file,
2335
- false,
2336
- None,
2337
- &transport,
2338
- );
2339
-
2340
- // (a) the recompiled spec was written (real subsystem step). E5: under .team/runtime/<team_key>/,
2341
- // NOT the user team dir.
2342
- let runtime_spec = find_runtime_spec(&team, "addteam");
2343
- assert!(
2344
- runtime_spec.is_some(),
2345
- "add_agent must recompile + write team.spec.yaml under .team/runtime/<team_key>/"
2346
- );
2347
- assert!(
2348
- !team.join("team.spec.yaml").exists(),
2349
- "E5: add_agent must NOT write spec into the user team dir"
2350
- );
2351
- // (b) the new worker window was spawned (RED: stub recompiles then RequirementUnmet -> ZERO spawns).
2352
- let recorded = transport.spawn_records();
2353
- assert!(
2354
- !recorded.is_empty(),
2355
- "add_agent must spawn the new worker window (>=1 recorded spawn); the rt-host-a stub recompiles \
2356
- then returns RequirementUnmet with ZERO spawns; got {recorded:?}"
2357
- );
2358
- assert!(
2359
- recorded.iter().any(|(_, argv)| argv.iter().any(|a| a == "fake-worker")),
2360
- "the new worker's spawn argv must carry the provider build_command (fake-worker); got {recorded:?}"
2361
- );
2362
- }
2363
-
2364
- #[test]
2365
- fn add_agent_role_doc_exists_runtime_missing_succeeds() {
2366
- let team = temp_ws().join("add_role_doc_team");
2367
- std::fs::create_dir_all(team.join("agents")).unwrap();
2368
- std::fs::write(
2369
- team.join("TEAM.md"),
2370
- "---\nname: addroledoc\nobjective: Add role-doc probe.\nprovider: codex\n---\n\nteam.\n",
2371
- )
2372
- .unwrap();
2373
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
2374
- let role_file = team.join("agents").join("worker2.md");
2375
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
2376
- crate::state::persist::save_runtime_state(
2377
- &team,
2378
- &json!({
2379
- "session_name": "team-addroledoc",
2380
- "agents": {
2381
- "implementer": {"status": "running", "provider": "fake", "window": "implementer"}
2382
- }
2383
- }),
2384
- )
2385
- .unwrap();
2386
- seed_healthy_coordinator(&team);
2387
- let transport = OfflineTransport::new();
2388
-
2389
- let result = add_agent_with_transport(
2390
- &team,
2391
- &AgentId::new("worker2"),
2392
- &role_file,
2393
- false,
2394
- None,
2395
- &transport,
2396
- );
2397
-
2398
- assert!(
2399
- result.is_ok(),
2400
- "a prepared agents/<id>.md role doc is not membership; runtime state is authoritative: {result:?}"
2401
- );
2402
- let state = crate::state::persist::load_runtime_state(&team).expect("load state");
2403
- assert!(
2404
- state.pointer("/agents/worker2").is_some(),
2405
- "add-agent must add worker2 to runtime state; state={state}"
2406
- );
2407
- assert_eq!(
2408
- transport.spawn_records().len(),
2409
- 1,
2410
- "add-agent must spawn exactly the new worker"
2411
- );
2412
- }
2413
-
2414
- #[test]
2415
- fn start_agent_runtime_missing_role_doc_exists_no_side_effect() {
2416
- let team = temp_ws().join("start_missing_team");
2417
- std::fs::create_dir_all(team.join("agents")).unwrap();
2418
- std::fs::write(
2419
- team.join("TEAM.md"),
2420
- "---\nname: startmissing\nobjective: Start missing probe.\nprovider: codex\n---\n\nteam.\n",
2421
- )
2422
- .unwrap();
2423
- std::fs::write(team.join("agents").join("reviewer.md"), DELEG_ROLE_WORKER2).unwrap();
2424
- crate::state::persist::save_runtime_state(
2425
- &team,
2426
- &json!({
2427
- "session_name": "team-startmissing",
2428
- "agents": {
2429
- "implementer": {"status": "running", "provider": "fake", "window": "implementer"}
2430
- }
2431
- }),
2432
- )
2433
- .unwrap();
2434
- let transport = OfflineTransport::new();
2435
-
2436
- let result = start_agent_with_transport(
2437
- &team,
2438
- &AgentId::new("reviewer"),
2439
- false,
2440
- false,
2441
- true,
2442
- None,
2443
- &transport,
2444
- );
2445
-
2446
- let text = format!("{result:?}");
2447
- assert!(
2448
- text.contains("not found"),
2449
- "start-agent must refuse runtime-missing agents before side effects; got {text}"
2450
- );
2451
- assert!(
2452
- transport.spawn_records().is_empty(),
2453
- "runtime-missing start-agent must not spawn a pane"
2454
- );
2455
- assert!(
2456
- !team
2457
- .join(".team")
2458
- .join("runtime")
2459
- .join("mcp")
2460
- .join("reviewer.json")
2461
- .exists(),
2462
- "runtime-missing start-agent must not write worker MCP config"
2463
- );
2464
- let events = crate::event_log::EventLog::new(&team)
2465
- .tail(20)
2466
- .unwrap_or_default();
2467
- assert!(
2468
- !events.iter().any(|event| {
2469
- event.get("event").and_then(|v| v.as_str()) == Some("start_agent.agent_start")
2470
- }),
2471
- "runtime-missing start-agent must not emit start_agent.agent_start; events={events:?}"
2472
- );
2473
- }
2474
-
2475
- /// 0.4.6 tuple-atomic contract (audit §Restart 修改清单, line 177): Copilot
2476
- /// fresh restart MUST leave `session_id=null` in persisted state. The argv
2477
- /// still carries `--session-id <uuid>` (planned capture hint), and the row
2478
- /// keeps `_pending_session_id=<uuid>` so the Copilot scanner can confirm
2479
- /// the sqlite entry on next tick and promote into the authoritative tuple.
2480
- /// Pre-0.4.6, restart promoted the planned uuid directly into `session_id`
2481
- /// without scanner confirmation, violating the capture-only-writer rule
2482
- /// (audit §Restart 当前违规 #1).
2483
- #[test]
2484
- fn restart_allow_fresh_copilot_keeps_session_id_null_until_capture_confirms() {
2485
- let ws = temp_ws().join("restartcopilot");
2486
- std::fs::create_dir_all(ws.join("agents")).unwrap();
2487
- std::fs::write(
2488
- ws.join("TEAM.md"),
2489
- "---\nname: restartcopilot\nobjective: Restart copilot probe.\nprovider: copilot\n---\n\nteam.\n",
2490
- )
2491
- .unwrap();
2492
- std::fs::write(
2493
- ws.join("agents").join("alpha.md"),
2494
- "---\nname: alpha\nrole: Alpha Worker\nprovider: copilot\nmodel: gpt-5.5\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nAlpha.\n",
2495
- )
2496
- .unwrap();
2497
- let spec = crate::compiler::compile_team(&ws).expect("compile copilot team");
2498
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
2499
- crate::state::persist::save_runtime_state(
2500
- &ws,
2501
- &json!({
2502
- "session_name": "team-restartcopilot",
2503
- "agents": {
2504
- "alpha": {
2505
- "status": "running",
2506
- "provider": "copilot",
2507
- "window": "alpha",
2508
- "first_send_at": "2026-05-27T10:00:00+00:00",
2509
- "session_id": null,
2510
- "rollout_path": "/tmp/stale-copilot-rollout.jsonl",
2511
- "captured_at": "2026-05-27T10:00:00+00:00",
2512
- "captured_via": "stale",
2513
- "attribution_confidence": "stale"
2514
- }
2515
- }
2516
- }),
2517
- )
2518
- .unwrap();
2519
- seed_healthy_coordinator(&ws);
2520
- let transport = OfflineTransport::new();
2521
-
2522
- let result = restart_with_transport(&ws, true, None, &transport);
2523
-
2524
- assert!(
2525
- matches!(result, Ok(RestartReport::Restarted { .. })),
2526
- "allow-fresh restart should fresh-spawn the copilot worker; got {result:?}"
2527
- );
2528
- let recorded = transport.spawn_records();
2529
- assert_eq!(
2530
- recorded.len(),
2531
- 1,
2532
- "expected one copilot spawn; got {recorded:?}"
2533
- );
2534
- let session_arg = recorded[0]
2535
- .1
2536
- .windows(2)
2537
- .find_map(|pair| (pair[0] == "--session-id").then(|| pair[1].clone()))
2538
- .expect("copilot fresh spawn argv must include --session-id");
2539
- let instructions =
2540
- std::fs::read_to_string(ws.join(".team/runtime/copilot-instructions/alpha/AGENTS.md"))
2541
- .expect("restart/add/clone spawn must materialize Copilot instructions");
2542
- assert!(instructions.contains("Alpha Worker"));
2543
- let state = crate::state::persist::load_runtime_state(&ws).expect("load state");
2544
- let agent = state.pointer("/agents/alpha").expect("alpha state");
2545
- // 0.4.6 contract: session_id stays null until scanner confirms sqlite.
2546
- assert_eq!(
2547
- agent.get("session_id"),
2548
- Some(&serde_json::Value::Null),
2549
- "fresh restart must NOT promote planned id into session_id; \
2550
- capture (scanner) is the only authoritative writer. agent={agent}"
2551
- );
2552
- // The pending hint is preserved so the Copilot scanner has the
2553
- // expected-id binding on the next coordinator tick.
2554
- assert_eq!(
2555
- agent
2556
- .get("_pending_session_id")
2557
- .and_then(serde_json::Value::as_str),
2558
- Some(session_arg.as_str()),
2559
- "fresh restart must retain _pending_session_id matching argv --session-id; \
2560
- this is the capture hint the scanner uses for sqlite confirmation"
2561
- );
2562
- for stale in [
2563
- "rollout_path",
2564
- "captured_at",
2565
- "captured_via",
2566
- "attribution_confidence",
2567
- ] {
2568
- let value = agent.get(stale);
2569
- assert!(
2570
- value.is_none() || value == Some(&serde_json::Value::Null),
2571
- "fresh restart must clear stale capture field {stale}; got {value:?}"
2572
- );
2573
- }
2574
- // Second classify must NOT silently refuse — the row has no session_id
2575
- // (caller still needs to use --allow-fresh or wait for capture).
2576
- let plan = crate::lifecycle::restart::classify_restart_plan(&state, false)
2577
- .expect("classify second restart");
2578
- // The worker has session_id=null + a non-empty _pending_session_id,
2579
- // so classify treats it as no-persisted-session-id (not backing-missing),
2580
- // which `--allow-fresh` resolves cleanly without loops.
2581
- let _ = plan; // shape verified above; details depend on classifier internals.
2582
- }
2583
-
2584
- /// 0.4.6 tuple-atomic contract (audit, line 268): a fresh restart of a
2585
- /// preassigned-session worker (Copilot) leaves session_id=null even when the
2586
- /// input row had a stale session_id.
2587
- /// The poisoned-row scenario (Bug 045 release-engineer state).
2588
- #[test]
2589
- fn restart_allow_fresh_copilot_clears_poisoned_session_id() {
2590
- let ws = temp_ws().join("restartcopilot046");
2591
- std::fs::create_dir_all(ws.join("agents")).unwrap();
2592
- std::fs::write(
2593
- ws.join("TEAM.md"),
2594
- "---\nname: restartcopilot046\nobjective: 0.4.6 contract.\nprovider: claude\n---\n\nteam.\n",
2595
- )
2596
- .unwrap();
2597
- std::fs::write(
2598
- ws.join("agents").join("alpha.md"),
2599
- "---\nname: alpha\nrole: Alpha\nprovider: copilot\nmodel: gpt-5.5\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nAlpha.\n",
2600
- )
2601
- .unwrap();
2602
- let spec = crate::compiler::compile_team(&ws).expect("compile");
2603
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
2604
- let stale_uuid = "bd68bfbd-b9b6-4e0e-8197-ce5a47c4a930";
2605
- crate::state::persist::save_runtime_state(
2606
- &ws,
2607
- &json!({
2608
- "session_name": "team-restartcopilot046",
2609
- "agents": {
2610
- "alpha": {
2611
- "status": "running",
2612
- "provider": "copilot",
2613
- "window": "alpha",
2614
- "first_send_at": "2026-06-23T10:00:00+00:00",
2615
- "session_id": stale_uuid,
2616
- "rollout_path": null,
2617
- "captured_at": null,
2618
- "captured_via": null
2619
- }
2620
- }
2621
- }),
2622
- )
2623
- .unwrap();
2624
- seed_healthy_coordinator(&ws);
2625
- let transport = OfflineTransport::new();
2626
-
2627
- let result = restart_with_transport(&ws, true, None, &transport);
2628
- assert!(
2629
- matches!(result, Ok(RestartReport::Restarted { .. })),
2630
- "allow-fresh restart should fresh-spawn the copilot worker; got {result:?}"
2631
- );
2632
-
2633
- let state = crate::state::persist::load_runtime_state(&ws).expect("load state");
2634
- let agent = state.pointer("/agents/alpha").expect("alpha");
2635
- assert_eq!(
2636
- agent.get("session_id"),
2637
- Some(&serde_json::Value::Null),
2638
- "0.4.6 contract: fresh restart must clear stale session_id; agent={agent}"
2639
- );
2640
- // C1 dual-projection: teams.<key>.agents.alpha.session_id must also be null.
2641
- if let Some(teams) = state.get("teams").and_then(serde_json::Value::as_object) {
2642
- for (team_key, team_state) in teams {
2643
- if let Some(team_alpha) = team_state.pointer("/agents/alpha") {
2644
- let team_session = team_alpha.get("session_id");
2645
- assert!(
2646
- team_session.is_none() || team_session == Some(&serde_json::Value::Null),
2647
- "0.4.6: teams.{team_key}.agents.alpha.session_id must be null; got {team_session:?}"
2648
- );
2649
- }
2650
- }
2651
- }
2652
- }
2653
-
2654
- /// 0.4.6 tuple-atomic contract (audit §Fork 修改清单, line 201): fork
2655
- /// with a scalar `session_id` but no rollout_path/captured_at/captured_via
2656
- /// must be REFUSED before the native fork. Pre-0.4.6 fork only checked
2657
- /// session_id non-empty, which let it attach to a session with no
2658
- /// confirmed backing.
2659
- #[test]
2660
- fn fork_refuses_source_with_partial_tuple() {
2661
- let ws = temp_ws().join("forkpartial046");
2662
- std::fs::create_dir_all(ws.join("agents")).unwrap();
2663
- std::fs::write(
2664
- ws.join("TEAM.md"),
2665
- "---\nname: forkpartial046\nobjective: fork tuple.\nprovider: codex\n---\n\nteam.\n",
2666
- )
2667
- .unwrap();
2668
- std::fs::write(
2669
- ws.join("agents").join("src.md"),
2670
- "---\nname: src\nrole: Source\nprovider: copilot\nmodel: gpt-5.5\nauth_mode: subscription\ndangerously_skip_permissions: false\ntools:\n - mcp_team\n---\n\nSrc.\n",
2671
- )
2672
- .unwrap();
2673
- let spec = crate::compiler::compile_team(&ws).expect("compile");
2674
- std::fs::write(ws.join("team.spec.yaml"), crate::model::yaml::dumps(&spec)).unwrap();
2675
- crate::state::persist::save_runtime_state(
2676
- &ws,
2677
- &json!({
2678
- "session_name": "team-forkpartial046",
2679
- "agents": {
2680
- "src": {
2681
- "status": "running",
2682
- "provider": "copilot",
2683
- "window": "src",
2684
- "first_send_at": "2026-06-25T10:00:00+00:00",
2685
- "session_id": "scalar-only-uuid",
2686
- "rollout_path": null,
2687
- "captured_at": null,
2688
- "captured_via": null
2689
- }
2690
- }
2691
- }),
2692
- )
2693
- .unwrap();
2694
- let transport = OfflineTransport::new();
2695
-
2696
- // fork_agent is the entry point; it should refuse with a clear message.
2697
- let src_id = crate::model::ids::AgentId::new("src");
2698
- let dst_id = crate::model::ids::AgentId::new("clone");
2699
- let result = crate::lifecycle::fork_agent_with_transport(
2700
- &ws, &src_id, &dst_id, None, // label
2701
- false, // open_display
2702
- None, // team
2703
- &transport,
2704
- );
2705
- assert!(
2706
- result.is_err(),
2707
- "0.4.6: fork with partial source tuple must be refused; got Ok({result:?})"
2708
- );
2709
- let err = result.unwrap_err().to_string();
2710
- assert!(
2711
- err.contains("unverified")
2712
- || err.contains("未验证")
2713
- || err.contains("backing")
2714
- || err.contains("incomplete"),
2715
- "0.4.6/in-window: unverified providers refuse before backing check; got error={err}"
2716
- );
2717
- }
2718
-
2719
- #[test]
2720
- fn stop_agent_adaptive_kills_target_pane_not_shared_layout_window() {
2721
- let roles = [("w1.md", role_doc("w1")), ("w2.md", role_doc("w2"))];
2722
- let role_refs = roles
2723
- .iter()
2724
- .map(|(file, doc)| (*file, doc.as_str()))
2725
- .collect::<Vec<_>>();
2726
- let team = quick_start_team_dir_with_roles(&role_refs);
2727
- let spec = crate::compiler::compile_team(&team).unwrap();
2728
- std::fs::write(
2729
- team.join("team.spec.yaml"),
2730
- crate::model::yaml::dumps(&spec),
2731
- )
2732
- .unwrap();
2733
- let session = "team-layout-stop";
2734
- crate::state::persist::save_runtime_state(
2735
- &team,
2736
- &json!({
2737
- "session_name": session,
2738
- "legacy_display_key": "adaptive",
2739
- "agents": {
2740
- "w1": {"status": "running", "provider": "fake", "window": "team-w1", "layout_window": "team-w1", "layout_index": 0, "pane_index": 0, "pane_id": "%1"},
2741
- "w2": {"status": "running", "provider": "fake", "window": "team-w1", "layout_window": "team-w1", "layout_index": 0, "pane_index": 1, "pane_id": "%2"}
2742
- }
2743
- }),
2744
- )
2745
- .unwrap();
2746
- let transport = OfflineTransport::new()
2747
- .with_targets(vec![
2748
- layout_pane(session, "team-w1", "%1", 0),
2749
- layout_pane(session, "team-w1", "%2", 1),
2750
- ])
2751
- .with_pane_presence("%2", true);
2752
-
2753
- let report = stop_agent_with_transport(&team, &AgentId::new("w2"), None, &transport).unwrap();
2754
-
2755
- assert!(report.stopped);
2756
- assert_eq!(report.target, "%2");
2757
- assert!(
2758
- transport.calls().iter().any(|call| *call == "kill_pane"),
2759
- "adaptive stop must kill only the target pane"
2760
- );
2761
- assert!(
2762
- !transport.calls().iter().any(|call| *call == "kill_window"),
2763
- "adaptive stop must not kill the shared layout window"
2764
- );
2765
- let (_raw, state) = raw_runtime_state(&team);
2766
- assert_eq!(state.pointer("/agents/w1/pane_id"), Some(&json!("%1")));
2767
- assert_eq!(
2768
- state.pointer("/agents/w1/layout_window"),
2769
- Some(&json!("team-w1"))
2770
- );
2771
- }
2772
-
2773
- // ═════════════════════════════════════════════════════════════════════════
2774
- // WAVE 2 · LANE A — agent-lifecycle byte-parity contracts. stop_agent / reset_agent / remove_agent /
2775
- // fork_agent are stubs (OwnerRefused / RequirementUnmet / "session_id missing"). These RED contracts
2776
- // LOCK the golden behavior (lifecycle/operations.py + agents.py). The existing tolerant tests accept the
2777
- // stub; these are STRICTER (RED today). OS-safe: no-owner ws + seeded spec/state, non-running agents
2778
- // (pure fs/state). Transport-asserting parts (kill_window / native-fork spawn) -> seam + #[ignore].
2779
- // ═════════════════════════════════════════════════════════════════════════
2780
-
2781
- // ═══════════════════════════════════════════════════════════════════════════
2782
- // collect #223 — task-scoped seeding (RED). Golden launch/core.py:69 ALWAYS seeds the runtime
2783
- // state's `tasks` key from spec.tasks (≥ []); the doc compiler emits a default task
2784
- // {id:"task_initial",…} (compiler.rs:308). Rust initial_runtime_state (launch.rs) emits only
2785
- // {session_name,team_dir,agents} — NO tasks key → send/collect cannot resolve the task. RED.
2786
- // OS-safe: OfflineTransport (zero real spawn).
2787
- // ═══════════════════════════════════════════════════════════════════════════
2788
- #[test]
2789
- #[serial(env)]
2790
- fn quick_start_seeds_tasks_key_from_compiled_spec() {
2791
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-tasks-key");
2792
- let team = quick_start_team_dir(QS_VALID_ROLE);
2793
- seed_healthy_coordinator(&crate::model::paths::team_workspace(&team).unwrap());
2794
- let transport = OfflineTransport::new();
2795
- let _ = quick_start_with_transport(&team, None, true, None, &transport);
2796
- let workspace = team
2797
- .parent()
2798
- .expect("team_workspace(<base>/teamdir) = <base>");
2799
- let state = crate::state::persist::load_runtime_state(workspace)
2800
- .expect("runtime state.json must exist after quick_start");
2801
- // (b) the tasks KEY must always be present and a JSON array (golden launch/core.py:69 default []).
2802
- let tasks = match state.get("tasks") {
2803
- Some(t) => t,
2804
- None => panic!(
2805
- "initial_runtime_state MUST seed a `tasks` key (golden launch/core.py:69 `tasks=[…spec.tasks]`); \
2806
- state keys = {:?}",
2807
- state.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>())
2808
- ),
2809
- };
2810
- let tasks = tasks
2811
- .as_array()
2812
- .expect("`tasks` must be a JSON array (golden default [])");
2813
- // (a) spec.tasks must be carried into runtime state — the doc compiler's default task id.
2814
- assert!(
2815
- tasks
2816
- .iter()
2817
- .any(|t| t.get("id").and_then(|v| v.as_str()) == Some("task_initial")),
2818
- "state.tasks must carry the compiled spec's task (id=task_initial); got {tasks:?}"
2819
- );
2820
- }
2821
-
2822
- // Stage A — golden launch/core.py:62-71 seeded top-level runtime state in insertion order:
2823
- // spec_path, workspace, team_dir, team_key, session_name, leader, agents, tasks.
2824
- //
2825
- // The runtime state is tmux-only; no display backend is persisted.
2826
- // NEW (Bug 1/2 — team-in-team state scope, see tests/team_in_team_state_scope_red.rs):
2827
- // `active_team_key` and `teams` are appended at the tail so the runtime can carry the
2828
- // nested team-in-team scope alongside the original flat fields. Owner-binding fields
2829
- // (`leader_receiver` / `team_owner` / `owner_epoch`) live ONLY under
2830
- // `teams[<active_team_key>]` — Bug 2 owner team-scope (N1/N12/N18/N29) deliberately
2831
- // keeps them OFF the root so per-team isolation has a single source of truth and
2832
- // cross-team reads cannot accidentally pick up another team's binding from the root.
2833
- // The post-launch hook drops the top-level owner triple when the launched pane is
2834
- // unbound (empty pane_id), and only the per-team entry retains the binding.
2835
- // R1: topology is explicit; fresh managed teams carry `is_external_leader=false`
2836
- // before the team-in-team suffix. Canonical `team_key` is seeded before owner
2837
- // binding; the remaining order stays the golden prefix + topology marker + new
2838
- // suffix (active_team_key, teams).
2839
- #[test]
2840
- #[serial(env)]
2841
- fn quick_start_unbound_state_producer_seeds_spec_path_workspace_leader() {
2842
- let _hermetic = enter_hermetic("launch-spawn-state-seeds");
2843
- // Bug 2 owner team-scope: top-level owner triple is dropped when the seeded
2844
- // pane is empty; an ambient TMUX_PANE (tests run inside the dev's tmux session)
2845
- // would otherwise leak into the caller-identity seed, inflate the seeded owner
2846
- // with a non-empty pane, and keep the top-level keys present — masking the
2847
- // per-team-isolation invariant this assertion locks. Force-unset for the test.
2848
- let _tmux_pane = EnvVarGuard::unset("TMUX_PANE");
2849
- let _tmux = EnvVarGuard::unset("TMUX");
2850
- let team = quick_start_team_dir(QS_VALID_ROLE);
2851
- let transport = OfflineTransport::new();
2852
- let workspace = team
2853
- .parent()
2854
- .expect("team_workspace(<base>/teamdir) = <base>");
2855
- // Test the real unbound state producer plus recording-only worker stage.
2856
- // Public start correctly refuses this absent caller (separate regressions).
2857
- crate::lifecycle::launch::materialize_unbound_state_for_test(
2858
- workspace, &team, "quickteam", &transport,
2859
- ).expect("materialize the unbound producer fixture without public start");
2860
- // E5: spec_path in state now points to .team/runtime/<team_key>/, team_dir stays the user role dir.
2861
- let spec_path = quick_start_runtime_spec_path(&team);
2862
- let (raw, state) = raw_runtime_state(workspace);
2863
- let keys = state
2864
- .as_object()
2865
- .expect("state root object")
2866
- .keys()
2867
- .cloned()
2868
- .collect::<Vec<_>>();
2869
- assert_eq!(
2870
- keys,
2871
- vec![
2872
- "spec_path",
2873
- "workspace",
2874
- "team_dir",
2875
- // Seed canonical identity before owner binding so the initial
2876
- // receiver is written under the same team key as the saved state.
2877
- "team_key",
2878
- "session_name",
2879
- "leader",
2880
- "agents",
2881
- "tasks",
2882
- "is_external_leader",
2883
- // 0.5.x Phase 1d hot-path 接线 (裁决1 msg_76e1d98202b8):
2884
- // `transport = { kind, source }` inserted here by
2885
- // `annotate_runtime_transport`. Kind is `"tmux"` for the
2886
- // default tmux path (byte-equivalent behavior + new metadata
2887
- // field); source is `"unknown"` until Phase 2 threads
2888
- // `ResolvedTransport.source` through the launch call site.
2889
- "transport",
2890
- "active_team_key",
2891
- // Persist physical session birth independently of worker respawns.
2892
- "generation",
2893
- "teams",
2894
- ],
2895
- "state.json top-level key order must match golden launch/core.py:62-71 \
2896
- plus R1 topology marker and Bug 1/2 team-in-team suffix \
2897
- (is_external_leader, active_team_key, teams). \
2898
- Bug 2 owner team-scope (N1/N12/N18/N29) deliberately keeps owner / \
2899
- leader_receiver / owner_epoch OFF the top level — they live ONLY under \
2900
- teams[<active_team_key>] so per-team isolation has a single source of \
2901
- truth (no shadow copy on the root that callers could read across teams); \
2902
- raw={raw}"
2903
- );
2904
- assert_eq!(
2905
- state["spec_path"],
2906
- json!(spec_path.canonicalize().unwrap().to_string_lossy())
2907
- );
2908
- assert_eq!(state["workspace"], json!(workspace.to_string_lossy()));
2909
- assert_eq!(state["team_dir"], json!(team.to_string_lossy()));
2910
- assert_eq!(state["session_name"], json!("team-quickteam"));
2911
- assert_eq!(
2912
- state["leader"]["id"],
2913
- json!("leader"),
2914
- "leader must be copied from compiled spec.leader"
2915
- );
2916
- assert!(
2917
- state["agents"]
2918
- .as_object()
2919
- .is_some_and(|agents| agents.contains_key("implementer")),
2920
- "existing agents value must remain seeded from compiled spec; got {:?}",
2921
- state["agents"]
2922
- );
2923
- assert!(
2924
- state["tasks"].as_array().is_some_and(|tasks| {
2925
- tasks
2926
- .iter()
2927
- .any(|task| task.get("id").and_then(|id| id.as_str()) == Some("task_initial"))
2928
- }),
2929
- "existing tasks value must remain seeded from compiled spec; got {:?}",
2930
- state["tasks"]
2931
- );
2932
- assert_eq!(state["is_external_leader"], json!(false));
2933
- }
2934
-
2935
- // Stage B1 — golden launch/core.py:238-255 writes the running agent state only after
2936
- // a successful spawn. The fixed clock is a test seam for `spawned_at`; capture intentionally
2937
- // misses, so session/capture fields remain present JSON nulls. MCP install is deterministic:
2938
- // provider_cli/adapter.py:111-114 writes workspace/.team/runtime/mcp/<agent>.json.
2939
- #[test]
2940
- #[serial(env)]
2941
- fn quick_start_running_agent_state_shape_after_spawn_is_golden() {
2942
- let _hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-running-state");
2943
- const FIXED_SPAWNED_AT: &str = "2026-06-04T00:00:00+00:00";
2944
- let _clock_guard = EnvVarGuard::set("TEAM_AGENT_TEST_FIXED_SPAWNED_AT", FIXED_SPAWNED_AT);
2945
- let team = quick_start_team_dir(QS_VALID_ROLE);
2946
- seed_healthy_coordinator(&crate::model::paths::team_workspace(&team).unwrap());
2947
- let transport = OfflineTransport::new();
2948
- let _ = quick_start_with_transport(&team, None, true, None, &transport);
2949
- let workspace = team
2950
- .parent()
2951
- .expect("team_workspace(<base>/teamdir) = <base>");
2952
- let (raw, state) = raw_runtime_state(workspace);
2953
- let agent = state
2954
- .pointer("/agents/implementer")
2955
- .unwrap_or_else(|| panic!("implementer agent state missing; raw={raw}"));
2956
- let keys = agent
2957
- .as_object()
2958
- .expect("agent state object")
2959
- .keys()
2960
- .cloned()
2961
- .collect::<Vec<_>>();
2962
- // 0.3.28 Step 4b: adaptive layout fields (layout_window, layout_index,
2963
- // pane_index, display) removed from running agent state — 1-window-per-agent
2964
- // means no layout bookkeeping needed.
2965
- assert_eq!(
2966
- keys,
2967
- vec![
2968
- "status",
2969
- "provider",
2970
- "agent_id",
2971
- "model",
2972
- "auth_mode",
2973
- "profile",
2974
- "window",
2975
- "mcp_config",
2976
- "effective_approval_policy",
2977
- // 0.5.66 bypass 单源:fresh spawn 记录运行面 bypass 值(restart drift 挡板)。
2978
- "as_launched_dangerously_skip_permissions",
2979
- "session_id",
2980
- "rollout_path",
2981
- "captured_at",
2982
- "captured_via",
2983
- "attribution_confidence",
2984
- "capture_state",
2985
- "spawn_cwd",
2986
- "spawned_at",
2987
- "pane_id",
2988
- ],
2989
- "the fake worker has no pre-assigned session id, so no framework _pending_session_id; raw={raw}"
2990
- );
2991
- assert_eq!(agent["status"], json!("running"));
2992
- assert_eq!(agent["provider"], json!("fake"));
2993
- assert_eq!(agent["agent_id"], json!("implementer"));
2994
- assert_eq!(agent["model"], json!("fake"));
2995
- assert_eq!(agent["auth_mode"], json!("subscription"));
2996
- assert!(agent["profile"].is_null());
2997
- assert_eq!(agent["window"], json!("implementer"));
2998
- assert_eq!(
2999
- agent["mcp_config"],
3000
- json!(workspace
3001
- .join(".team/runtime/mcp/implementer.json")
3002
- .to_string_lossy())
3003
- );
3004
- assert!(agent["session_id"].is_null());
3005
- assert!(agent["rollout_path"].is_null());
3006
- assert!(agent["captured_at"].is_null());
3007
- assert!(agent["captured_via"].is_null());
3008
- assert!(agent["attribution_confidence"].is_null());
3009
- // 0.3.28 Step 4b: layout_window/layout_index/pane_index/display removed.
3010
- // No adaptive bookkeeping needed — each worker has its own window named
3011
- // after the agent_id.
3012
- assert!(agent.get("layout_window").is_none());
3013
- assert!(agent.get("layout_index").is_none());
3014
- assert!(agent.get("pane_index").is_none());
3015
- assert!(agent.get("display").is_none());
3016
- // D5 (#264) / Python launch/core.py:253 — fresh launch persists spawn_cwd=workspace.
3017
- assert_eq!(agent["spawn_cwd"], json!(workspace.to_string_lossy()));
3018
- assert_eq!(agent["spawned_at"], json!(FIXED_SPAWNED_AT));
3019
- assert_eq!(
3020
- agent["pane_id"],
3021
- json!("%0"),
3022
- "#252 RC2: launch must persist the real pane_id returned by the transport, not drop it when pane_pid is unavailable"
3023
- );
3024
- let events = crate::event_log::EventLog::new(workspace)
3025
- .tail(0)
3026
- .expect("read event log");
3027
- let spawn_event = events
3028
- .iter()
3029
- .find(|event| {
3030
- event.get("event").and_then(serde_json::Value::as_str)
3031
- == Some("provider.worker.spawn_argv")
3032
- && event.get("agent_id").and_then(serde_json::Value::as_str) == Some("implementer")
3033
- })
3034
- .unwrap_or_else(|| panic!("provider.worker.spawn_argv missing; events={events:?}"));
3035
- assert_eq!(spawn_event["spawn_cwd"], json!(workspace.to_string_lossy()));
3036
- assert_eq!(spawn_event["spawned_at"], json!(FIXED_SPAWNED_AT));
3037
- assert_eq!(spawn_event["source"], json!("launch"));
3038
- assert_eq!(spawn_event["spawn_epoch"], json!(0));
3039
- let actual_keys = spawn_event
3040
- .as_object()
3041
- .expect("spawn event object")
3042
- .keys()
3043
- .map(String::as_str)
3044
- .collect::<std::collections::BTreeSet<_>>();
3045
- let expected_keys = [
3046
- "agent_id",
3047
- "argv",
3048
- "env_overlay_keys",
3049
- "env_unset",
3050
- "event",
3051
- "expected_session_id",
3052
- "provider",
3053
- "session_id_in_argv",
3054
- "source",
3055
- "spawn_cwd",
3056
- "spawn_epoch",
3057
- "spawned_at",
3058
- "tmux_endpoint",
3059
- "tmux_endpoint_source",
3060
- "tmux_start_mode",
3061
- "ts",
3062
- ]
3063
- .into_iter()
3064
- .collect::<std::collections::BTreeSet<_>>();
3065
- assert_eq!(
3066
- actual_keys, expected_keys,
3067
- "spawn event schema must be canonical"
3068
- );
3069
- }
3070
-
3071
- // Stage B2 — golden launch/core.py:171-173 writes paused workers as exactly
3072
- // {status, provider} and skips spawn entirely.
3073
- #[test]
3074
- fn quick_start_paused_agent_state_is_paused_provider_only_and_not_spawned() {
3075
- let team = quick_start_team_dir(QS_VALID_ROLE);
3076
- let spec_path = compiled_spec_path_with_paused_agent(&team);
3077
- let workspace = team
3078
- .parent()
3079
- .expect("team_workspace(<base>/teamdir) = <base>");
3080
- crate::state::persist::save_runtime_state(
3081
- workspace,
3082
- &json!({
3083
- "session_name": "team-quickteam",
3084
- "team_dir": team.to_string_lossy(),
3085
- "agents": {
3086
- "implementer": {
3087
- "provider": "fake",
3088
- "role": "Implementation Engineer",
3089
- "model": "fake",
3090
- "auth_mode": "subscription"
3091
- }
3092
- },
3093
- "tasks": []
3094
- }),
3095
- )
3096
- .expect("seed pre-launch runtime state");
3097
- let transport = OfflineTransport::new();
3098
- let _ = launch_with_transport(&spec_path, false, true, true, &transport);
3099
- let (raw, state) = raw_runtime_state(workspace);
3100
- let agent = state
3101
- .pointer("/agents/implementer")
3102
- .unwrap_or_else(|| panic!("implementer agent state missing; raw={raw}"));
3103
- let keys = agent
3104
- .as_object()
3105
- .expect("agent state object")
3106
- .keys()
3107
- .cloned()
3108
- .collect::<Vec<_>>();
3109
- assert_eq!(
3110
- keys,
3111
- vec!["status", "provider"],
3112
- "paused agent state must be exactly golden launch/core.py:171-173; raw={raw}"
3113
- );
3114
- assert_eq!(agent["status"], json!("paused"));
3115
- assert_eq!(agent["provider"], json!("fake"));
3116
- assert!(
3117
- transport.spawn_records().is_empty(),
3118
- "paused agent must not spawn any terminal window; got {:?}",
3119
- transport.spawn_records()
3120
- );
3121
- }
3122
-
3123
- // ═════════════════════════════════════════════════════════════════════════════
3124
- // 0.3.24 add-agent socket drift fix (macmini demo-director startup blocker).
3125
- //
3126
- // Root cause: `launch.rs::add_agent` / `fork_agent` hardcoded
3127
- // `TmuxBackend::for_workspace(...)` (workspace-hash socket, e.g.
3128
- // `/private/tmp/tmux-501/ta-<hash>/termclaud`) instead of consulting the
3129
- // team's persisted `tmux_endpoint` (set at `team-agent launch` time, e.g.
3130
- // `/private/tmp/tmux-501/default`). The orphan `claude` process then spawned
3131
- // onto the wrong socket; the leader (running on the persisted socket) never
3132
- // saw the window; state never registered; `add_agent` returned `ok=true`
3133
- // (假绿) because the lifecycle layer didn't verify reachability post-spawn.
3134
- //
3135
- // Architect-approved fix has 4 调整:
3136
- // 1. Reuse state-aware resolver (`lifecycle::restart::lifecycle_worker_tmux_backend_for_selected_state`).
3137
- // 2. fork-agent same path.
3138
- // 3. Endpoint annotate folded into start_agent state-save (no parallel
3139
- // `annotate_runtime_tmux_endpoint` race with coordinator).
3140
- // 4. Strict-non-capture reachability gate post-spawn (uses `has_pane` /
3141
- // `liveness` / `list_targets` only — never `capture` to avoid E31 timing).
3142
- // ═════════════════════════════════════════════════════════════════════════════
3143
-
3144
- /// **RED**: `add_agent` must read the team's persisted `tmux_endpoint` (set at
3145
- /// `team-agent launch` time and stored in the runtime state) and resolve the
3146
- /// transport's socket to that endpoint — NOT the workspace-hash for_workspace
3147
- /// socket. We exercise the resolver directly (the public surface
3148
- /// `lifecycle::restart::lifecycle_worker_tmux_backend_for_selected_state`) so
3149
- /// the contract is independent of CLI plumbing.
3150
- #[test]
3151
- fn add_agent_resolves_to_persisted_endpoint_socket_not_workspace_hash() {
3152
- let team = temp_ws().join("addteam-persisted-endpoint");
3153
- std::fs::create_dir_all(&team).unwrap();
3154
- let live_endpoint = "/private/tmp/tmux-501/default".to_string();
3155
- crate::state::persist::save_runtime_state(
3156
- &team,
3157
- &json!({
3158
- "session_name": "team-persisted",
3159
- "tmux_endpoint": live_endpoint.clone(),
3160
- "tmux_socket": live_endpoint.clone(),
3161
- "agents": {}
3162
- }),
3163
- )
3164
- .unwrap();
3165
-
3166
- let resolved =
3167
- crate::lifecycle::restart::lifecycle_worker_tmux_backend_for_selected_state(&team, None)
3168
- .expect("resolver must succeed when state is present");
3169
-
3170
- let endpoint =
3171
- <crate::tmux_backend::TmuxBackend as crate::transport::Transport>::tmux_endpoint(&resolved);
3172
- assert_eq!(
3173
- endpoint.as_deref(),
3174
- Some(live_endpoint.as_str()),
3175
- "0.3.24 add-agent socket drift fix: the state-aware resolver must \
3176
- route to the PERSISTED tmux_endpoint ({live_endpoint}), not the \
3177
- workspace-hash for_workspace socket. Got: {endpoint:?}. macmini \
3178
- repro: add-agent demo-director spawned `claude` on the wrong socket \
3179
- while the live team ran on the persisted default socket — orphan \
3180
- process + ok=true假绿."
3181
- );
3182
- }
3183
-
3184
- /// **Regression guard**: lifecycle worker resolution must ignore the leader
3185
- /// receiver endpoint. The receiver may live on the caller's default socket
3186
- /// while workers/coordinator remain on their persisted private socket.
3187
- #[test]
3188
- fn lifecycle_worker_resolver_prefers_persisted_worker_over_leader_receiver() {
3189
- let team = temp_ws().join("addteam-split-leader-worker-endpoints");
3190
- std::fs::create_dir_all(&team).unwrap();
3191
- let worker_endpoint = "/private/tmp/tmux-501/ta-worker";
3192
- let leader_endpoint = "/private/tmp/tmux-501/default";
3193
- crate::state::persist::save_runtime_state(
3194
- &team,
3195
- &json!({
3196
- "session_name": "team-split",
3197
- "tmux_endpoint": worker_endpoint,
3198
- "tmux_socket": worker_endpoint,
3199
- "leader_receiver": {
3200
- "pane_id": "%169",
3201
- "tmux_socket": leader_endpoint,
3202
- "status": "attached"
3203
- },
3204
- "agents": {}
3205
- }),
3206
- )
3207
- .unwrap();
3208
-
3209
- let resolved = crate::lifecycle::restart::lifecycle_worker_tmux_backend_for_selected_state(
3210
- &team, None,
3211
- )
3212
- .expect("resolver must succeed when state has worker and receiver endpoints");
3213
- let endpoint = <crate::tmux_backend::TmuxBackend as crate::transport::Transport>::tmux_endpoint(
3214
- &resolved,
3215
- );
3216
- assert_eq!(
3217
- endpoint.as_deref(),
3218
- Some(worker_endpoint),
3219
- "worker lifecycle operations must stay on persisted worker endpoint, not leader receiver"
3220
- );
3221
- }
3222
-
3223
- /// **Regression guard**: annotating a worker spawn must not overwrite a
3224
- /// persisted worker endpoint with the independent leader receiver endpoint.
3225
- #[test]
3226
- fn annotate_runtime_tmux_endpoint_does_not_follow_leader_receiver() {
3227
- let worker_endpoint = "/private/tmp/tmux-501/ta-worker";
3228
- let leader_endpoint = "/private/tmp/tmux-501/default";
3229
- let mut state = json!({
3230
- "tmux_endpoint": worker_endpoint,
3231
- "tmux_socket": worker_endpoint,
3232
- "leader_receiver": {"tmux_socket": leader_endpoint}
3233
- });
3234
- let transport = OfflineTransport::new().with_tmux_endpoint(worker_endpoint);
3235
- crate::lifecycle::launch::annotate_runtime_tmux_endpoint(
3236
- &mut state,
3237
- &transport,
3238
- std::path::Path::new("/tmp/annotate-split"),
3239
- );
3240
- assert_eq!(state["tmux_endpoint"], json!(worker_endpoint));
3241
- assert_eq!(state["tmux_socket"], json!(worker_endpoint));
3242
- }
3243
-
3244
- /// **Regression guard**: cold workspace (no persisted endpoint) must safely
3245
- /// fall back to `TmuxBackend::for_workspace(workspace)`. Encodes the
3246
- /// first-agent / fresh-launch path so a future refactor doesn't accidentally
3247
- /// panic/None there.
3248
- #[test]
3249
- fn add_agent_resolver_falls_back_to_workspace_socket_when_no_persisted_endpoint() {
3250
- let team = temp_ws().join("addteam-cold-fallback");
3251
- std::fs::create_dir_all(&team).unwrap();
3252
- // NOTE: no save_runtime_state — cold workspace, no persisted endpoint.
3253
-
3254
- let resolved =
3255
- crate::lifecycle::restart::lifecycle_worker_tmux_backend_for_selected_state(&team, None)
3256
- .expect("resolver must succeed (fall back to for_workspace) on cold workspace");
3257
-
3258
- let endpoint =
3259
- <crate::tmux_backend::TmuxBackend as crate::transport::Transport>::tmux_endpoint(&resolved);
3260
- let fallback = <crate::tmux_backend::TmuxBackend as crate::transport::Transport>::tmux_endpoint(
3261
- &crate::tmux_backend::TmuxBackend::for_workspace(&team),
3262
- );
3263
- assert_eq!(
3264
- endpoint, fallback,
3265
- "0.3.24 regression guard: when state has no persisted tmux_endpoint, \
3266
- resolver must fall back to TmuxBackend::for_workspace (workspace-hash \
3267
- socket). Got endpoint={endpoint:?} expected fallback={fallback:?}."
3268
- );
3269
- }
3270
-
3271
- /// **RED**: `add_agent` must verify reachability AFTER spawn (strict,
3272
- /// non-capture). A spawn that lands on the wrong tmux socket (or on the right
3273
- /// socket but produces no addressable pane) must surface as a structured
3274
- /// `Err`, NOT `ok=true`. Models the macmini假绿 root cause: the spawn
3275
- /// recorded into the OfflineTransport but `has_pane` / `liveness` /
3276
- /// `list_targets` all say "not addressable" (`spawned_panes_addressable=false`).
3277
- #[test]
3278
- fn add_agent_reachability_gate_returns_error_when_spawn_pane_not_addressable() {
3279
- let team = temp_ws().join("addteam-reachability-gate");
3280
- std::fs::create_dir_all(team.join("agents")).unwrap();
3281
- std::fs::write(
3282
- team.join("TEAM.md"),
3283
- "---\nname: reachgate\nobjective: Reachability probe.\nprovider: codex\n---\n\nteam.\n",
3284
- )
3285
- .unwrap();
3286
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
3287
- let role_file = team.join("worker2-role.md");
3288
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3289
- seed_healthy_coordinator(&team);
3290
- seed_canonical_team_identity(&team, "reachgate");
3291
-
3292
- // Models "spawn to wrong socket" / "spawn succeeded but pane orphan": the
3293
- // OfflineTransport records the spawn but reports the new pane is NOT
3294
- // addressable (has_pane→Some(false), liveness defaults to Unknown=fall
3295
- // through, list_targets doesn't include it).
3296
- let transport = OfflineTransport::new()
3297
- .with_spawned_panes_addressable(false)
3298
- .with_default_liveness(crate::transport::PaneLiveness::Dead);
3299
-
3300
- let result = crate::lifecycle::add_agent_with_transport(
3301
- &team,
3302
- &AgentId::new("worker2"),
3303
- &role_file,
3304
- false,
3305
- None,
3306
- &transport,
3307
- );
3308
-
3309
- // The spawn DID record (proving we reached the spawn step), but the gate
3310
- // must NOT let the function return Ok — pane is not addressable so the
3311
- // caller must see the structured failure and roll back / retry.
3312
- assert!(
3313
- !transport.spawn_records().is_empty(),
3314
- "add-agent must still attempt the spawn (gate fires post-spawn); \
3315
- got no spawn records — indicates a regression where the gate fires \
3316
- too early."
3317
- );
3318
- assert!(
3319
- result.is_err(),
3320
- "0.3.24 reachability gate: add-agent must return Err when the spawned \
3321
- pane is not addressable on the transport's socket (macmini假绿 root \
3322
- cause). Got Ok(...) — gate did not fire."
3323
- );
3324
- let err_msg = result.unwrap_err().to_string();
3325
- assert!(
3326
- err_msg.contains("unreachable")
3327
- || err_msg.contains("not addressable")
3328
- || err_msg.contains("socket drift"),
3329
- "0.3.24 reachability gate: error message must name the unreachable / \
3330
- socket-drift symptom so operators can diagnose. Got: {err_msg}"
3331
- );
3332
- }
3333
-
3334
- /// **Regression guard**: when the spawned pane IS addressable (default
3335
- /// `OfflineTransport` state), reachability gate passes and add-agent returns
3336
- /// Ok as before. Ensures the gate is precision, not blanket.
3337
- #[test]
3338
- fn add_agent_reachability_gate_passes_when_spawn_pane_addressable() {
3339
- let team = temp_ws().join("addteam-gate-pass");
3340
- std::fs::create_dir_all(team.join("agents")).unwrap();
3341
- std::fs::write(
3342
- team.join("TEAM.md"),
3343
- "---\nname: gatepass\nobjective: Gate-pass probe.\nprovider: codex\n---\n\nteam.\n",
3344
- )
3345
- .unwrap();
3346
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
3347
- let role_file = team.join("worker2-role.md");
3348
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3349
- seed_healthy_coordinator(&team);
3350
- seed_canonical_team_identity(&team, "gatepass");
3351
-
3352
- // Default OfflineTransport: spawned_panes_addressable=true, liveness=Unknown
3353
- // (treated as not-Dead by the gate's fallthrough).
3354
- let transport = OfflineTransport::new();
3355
-
3356
- let result = crate::lifecycle::add_agent_with_transport(
3357
- &team,
3358
- &AgentId::new("worker2"),
3359
- &role_file,
3360
- false,
3361
- None,
3362
- &transport,
3363
- );
3364
-
3365
- assert!(
3366
- result.is_ok(),
3367
- "0.3.24 reachability gate regression guard: when spawn pane is \
3368
- addressable, add-agent must still return Ok. Got: {result:?}"
3369
- );
3370
- }
3371
-
3372
- // ═════════════════════════════════════════════════════════════════════════════
3373
- // E43 add-agent window layout drift (0.3.24 bug#3, demo-director startup blocker).
3374
- //
3375
- // Root cause (architect res_f27ff9b29957): with `legacy_display_key=adaptive` in
3376
- // state AND stale `agents.<id>.layout_window="team-w2"` residue, the existing
3377
- // `adaptive_placement_for_agent` validates a layout_window claim by checking
3378
- // whether the existing agent's `pane_id` is in `live_panes` — but it does NOT
3379
- // verify that the live pane's `window_name` actually equals the claimed
3380
- // `layout_window`. So a live `%X` whose REAL window_name is "architect" still
3381
- // "validates" the stale "team-w2" claim, the placement returns
3382
- // `layout_window=team-w2, starts_window=false`, and `spawn_agent_window`
3383
- // issues `tmux split-window -t :team-w2` which fails with
3384
- // "can't find window: team-w2". macmini repro: demo-director add-agent blocks.
3385
- //
3386
- // Architect-approved minimal fix (3 调整, NO restructure of display/topology):
3387
- // Fix A — `adaptive_placement_for_agent`: validate the live pane's
3388
- // window_name MATCHES the agent's claimed layout_window. If pane_id is
3389
- // live but lives under a different window_name, treat the agent's
3390
- // layout_window claim as stale and skip it (don't count toward the
3391
- // "windows with room" map).
3392
- // Fix B — `adaptive_existing_placement_for_agent`: when the agent's
3393
- // claimed layout_window is NOT present in live_windows, fall back to a
3394
- // `starts_window=true` placement with `layout_window=agent_id` instead
3395
- // of synthesising a fresh stale-named window.
3396
- // Fix C — `spawn_agent_window`: pre-split guard. When `!starts_window` and
3397
- // the target window is NOT in live_windows, downgrade to spawn_into
3398
- // (a new window named `agent_id`) instead of splitting a phantom.
3399
- // ═════════════════════════════════════════════════════════════════════════════
3400
-
3401
- /// **RED — Fix A**: `adaptive_placement_for_agent` must skip an existing
3402
- /// agent whose live pane resides under a window_name that differs from the
3403
- /// agent's claimed `layout_window`. Real-machine state: agent "architect"
3404
- /// carries `layout_window="team-w2"` (stale residue) but its live pane lives
3405
- /// under `window_name="architect"`. The new placement for demo-director must
3406
- /// NOT inherit the stale "team-w2" claim.
3407
- #[test]
3408
- fn e43_adaptive_placement_skips_existing_agent_whose_live_pane_window_name_differs_from_claim() {
3409
- use crate::lifecycle::launch::{adaptive_placement_for_agent, LayoutPlacement};
3410
- use crate::model::ids::AgentId;
3411
- use crate::transport::{SessionName, WindowName};
3412
-
3413
- let state = json!({
3414
- "legacy_display_key": "adaptive",
3415
- "session_name": "team-iso",
3416
- "agents": {
3417
- "architect": {
3418
- "status": "running",
3419
- "provider": "fake",
3420
- "window": "architect",
3421
- // Stale residue — placement must NOT inherit this name.
3422
- "layout_window": "team-w2",
3423
- "pane_id": "%1",
3424
- }
3425
- }
3426
- });
3427
-
3428
- let transport = OfflineTransport::new()
3429
- .with_targets(vec![layout_pane("team-iso", "architect", "%1", 0)])
3430
- .with_windows(vec![WindowName::new("architect")]);
3431
-
3432
- let placement = adaptive_placement_for_agent(
3433
- &state,
3434
- &transport,
3435
- &SessionName::new("team-iso"),
3436
- &AgentId::new("demo-director"),
3437
- );
3438
-
3439
- // **E45 amendment (0.3.24 bug#4)**: when the live session has NO real
3440
- // adaptive layout window (the topology is effectively per-agent — live
3441
- // windows are `architect` not `team-wN`), placement returns None. The
3442
- // caller (`start_agent_at_paths` → `spawn_agent_window`) then falls back
3443
- // to opening a new window named after `agent_id`. This is the macmini
3444
- // demo-director repro fix: per-agent topology must NOT be tricked into
3445
- // adaptive mode by stale `layout_window=team-w2` residue.
3446
- //
3447
- // Pre-E45 expectation was Some(starts_window=true) with a fresh
3448
- // team-w<next> name, but that forced an adaptive shape onto a session
3449
- // that was already per-agent — which led to E45 bug#4 (split-window
3450
- // into the developer worker after stale state pointed there).
3451
- if let Some(p) = placement {
3452
- // If we ever do return Some here, the STALE name must still not
3453
- // survive — this branch shouldn't fire post-E45 but guards against
3454
- // future regressions where placement re-enables adaptive on
3455
- // per-agent live topology.
3456
- assert_ne!(
3457
- p.layout_window.as_str(),
3458
- "team-w2",
3459
- "E43 Fix A still applies: stale layout_window 'team-w2' must \
3460
- NEVER survive. Got {p:?}"
3461
- );
3462
- let _: LayoutPlacement = p; // type witness
3463
- }
3464
- }
3465
-
3466
- /// **RED — Fix C end-to-end**: `add_agent` end-to-end must NOT emit a
3467
- /// spawn_split with the stale window name. With state carrying
3468
- /// `legacy_display_key=adaptive` + stale `layout_window=team-w2` residue and
3469
- /// live tmux windows named per-agent, the spawn must be a `spawn_into`
3470
- /// (new window) — NOT `spawn_split` against the missing 'team-w2'.
3471
- #[test]
3472
- fn e43_add_agent_does_not_split_against_phantom_layout_window() {
3473
- use crate::transport::WindowName;
3474
-
3475
- let team = temp_ws().join("e43-add-agent-phantom-window");
3476
- std::fs::create_dir_all(team.join("agents")).unwrap();
3477
- std::fs::write(
3478
- team.join("TEAM.md"),
3479
- "---\nname: e43probe\nobjective: E43 probe.\nprovider: codex\n---\n\nteam.\n",
3480
- )
3481
- .unwrap();
3482
- std::fs::write(team.join("agents").join("architect.md"), QS_VALID_ROLE).unwrap();
3483
- let role_file = team.join("worker2-role.md");
3484
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3485
- // Real-machine repro: existing 'architect' carries stale layout_window=team-w2
3486
- // residue; live tmux shows it under window_name='architect' (per-agent
3487
- // layout). adaptive_layout flag is on.
3488
- crate::state::persist::save_runtime_state(
3489
- &team,
3490
- &json!({
3491
- "session_name": "team-iso",
3492
- "legacy_display_key": "adaptive",
3493
- "agents": {
3494
- "architect": {
3495
- "status": "running",
3496
- "provider": "fake",
3497
- "window": "architect",
3498
- "layout_window": "team-w2",
3499
- "pane_id": "%1",
3500
- }
3501
- }
3502
- }),
3503
- )
3504
- .unwrap();
3505
- seed_healthy_coordinator(&team);
3506
-
3507
- let transport = OfflineTransport::new()
3508
- .with_targets(vec![layout_pane("team-iso", "architect", "%1", 0)])
3509
- .with_windows(vec![WindowName::new("architect")])
3510
- .with_session_present(true);
3511
-
3512
- let _result = crate::lifecycle::add_agent_with_transport(
3513
- &team,
3514
- &AgentId::new("worker2"),
3515
- &role_file,
3516
- false,
3517
- None,
3518
- &transport,
3519
- );
3520
-
3521
- let spawn_window_records = transport.spawn_window_records();
3522
- // The macmini failure mode: split-window -t :team-w2. We must not split,
3523
- // and we definitely must not target "team-w2".
3524
- let stale_split = spawn_window_records
3525
- .iter()
3526
- .any(|(kind, window)| kind == "spawn_split" && window == "team-w2");
3527
- assert!(
3528
- !stale_split,
3529
- "E43 Fix C end-to-end: add-agent must NOT issue spawn_split with \
3530
- stale window name 'team-w2' (real-machine macmini error: \
3531
- 'tmux split-window -t :team-w2 → can't find window: team-w2'). \
3532
- spawn_window_records={spawn_window_records:?}"
3533
- );
3534
- // The agent must actually be spawned somewhere (new window or split into
3535
- // a valid live window). We at least expect one spawn recorded.
3536
- assert!(
3537
- !spawn_window_records.is_empty(),
3538
- "E43 Fix C: add-agent must still attempt the spawn; got no records."
3539
- );
3540
- }
3541
-
3542
- // ═════════════════════════════════════════════════════════════════════════════
3543
- // E45 per-agent window drift (0.3.24 task#326 P0).
3544
- //
3545
- // Surfaced AFTER E43 (c5ed576) fixed the team-w2 phantom split. New repro:
3546
- // state has legacy_display_key=adaptive + an existing `developer` worker whose
3547
- // state row carries `layout_window=developer, layout_index=0, pane_id=%519`,
3548
- // live tmux shows `developer` window with that pane. add-agent demo-director
3549
- // resolves placement via `adaptive_placement_for_agent`, which finds the
3550
- // `developer` window valid (pane_id live + window_name matches), groups
3551
- // demo-director into it (count<3) → returns
3552
- // `layout_window=developer, starts_window=false` → `spawn_agent_window`
3553
- // issues `split-window -t :developer` which SUCCEEDS — splitting into the
3554
- // developer worker's pane. macmini repro: add-agent demo-director hijacked
3555
- // the developer worker's window @453 (2 panes), no new window.
3556
- //
3557
- // Root cause (architect): adaptive_placement_for_agent accepts ANY state
3558
- // layout_window/window as adaptive (including per-agent names like
3559
- // `developer`). E45 fix: only canonical `team-w<N>[-suffix]` windows count
3560
- // as adaptive layout windows.
3561
- // ═════════════════════════════════════════════════════════════════════════════
3562
-
3563
- /// **RED — Fix #2**: `adaptive_placement_for_agent` must NOT count a
3564
- /// per-agent window (e.g. `developer`) as adaptive layout space, even when
3565
- /// it has matching live pane + window_name. With no real adaptive
3566
- /// `team-w<N>` window in the live session, placement returns None so the
3567
- /// caller opens a new per-agent window.
3568
- #[test]
3569
- fn e45_adaptive_placement_returns_none_when_no_real_team_w_window_present_in_state() {
3570
- use crate::lifecycle::launch::adaptive_placement_for_agent;
3571
- use crate::model::ids::AgentId;
3572
- use crate::transport::{SessionName, WindowName};
3573
-
3574
- // Real-machine state: adaptive on, developer's layout_window is
3575
- // literally `developer` (per-agent name, NOT team-wN), pane_id %519
3576
- // lives under the `developer` window.
3577
- let state = json!({
3578
- "legacy_display_key": "adaptive",
3579
- "session_name": "team-iso",
3580
- "agents": {
3581
- "developer": {
3582
- "status": "running",
3583
- "provider": "fake",
3584
- "window": "developer",
3585
- "layout_window": "developer",
3586
- "layout_index": 0u64,
3587
- "pane_id": "%519",
3588
- },
3589
- "test-engineer": {
3590
- "status": "running",
3591
- "provider": "fake",
3592
- "window": "test-engineer",
3593
- "layout_window": "test-engineer",
3594
- "pane_id": "%521",
3595
- }
3596
- }
3597
- });
3598
-
3599
- let transport = OfflineTransport::new()
3600
- .with_targets(vec![
3601
- layout_pane("team-iso", "developer", "%519", 0),
3602
- layout_pane("team-iso", "test-engineer", "%521", 0),
3603
- ])
3604
- .with_windows(vec![
3605
- WindowName::new("developer"),
3606
- WindowName::new("test-engineer"),
3607
- ]);
3608
-
3609
- let placement = adaptive_placement_for_agent(
3610
- &state,
3611
- &transport,
3612
- &SessionName::new("team-iso"),
3613
- &AgentId::new("demo-director"),
3614
- );
3615
-
3616
- assert!(
3617
- placement.is_none(),
3618
- "E45 (0.3.24 bug#4): placement must return None when the live \
3619
- session has NO real `team-w<N>` adaptive window. Per-agent windows \
3620
- like `developer` are NOT adaptive layout windows — they are \
3621
- per-agent topology, even if legacy_display_key=adaptive lingers in \
3622
- state. With no real adaptive layout, the caller falls back to \
3623
- opening a new per-agent window named after agent_id. Got \
3624
- {placement:?} — must be None to prevent split-window -t :developer \
3625
- hijacking the developer worker's pane (macmini repro)."
3626
- );
3627
- }
3628
-
3629
- /// **RED — Fix #3**: `adaptive_existing_placement_for_agent` must return
3630
- /// None when the agent's claimed layout_window is per-agent (not team-wN).
3631
- /// The caller then falls back to non-placement spawn path which opens /
3632
- /// reuses a window named after agent_id.
3633
- #[test]
3634
- fn e45_adaptive_existing_placement_returns_none_when_claim_is_per_agent_window() {
3635
- use crate::lifecycle::launch::adaptive_existing_placement_for_agent;
3636
- use crate::model::ids::AgentId;
3637
- use crate::transport::{SessionName, WindowName};
3638
-
3639
- let state = json!({
3640
- "legacy_display_key": "adaptive",
3641
- "session_name": "team-iso",
3642
- "agents": {
3643
- "developer": {
3644
- "status": "running",
3645
- "provider": "fake",
3646
- "window": "developer",
3647
- "layout_window": "developer",
3648
- "layout_index": 0u64,
3649
- "pane_id": "%519",
3650
- }
3651
- }
3652
- });
3653
-
3654
- let transport = OfflineTransport::new()
3655
- .with_targets(vec![layout_pane("team-iso", "developer", "%519", 0)])
3656
- .with_windows(vec![WindowName::new("developer")]);
3657
-
3658
- let placement = adaptive_existing_placement_for_agent(
3659
- &state,
3660
- &transport,
3661
- &SessionName::new("team-iso"),
3662
- &AgentId::new("developer"),
3663
- );
3664
-
3665
- assert!(
3666
- placement.is_none(),
3667
- "E45 (0.3.24 bug#4): existing-placement must return None when \
3668
- claimed layout_window is per-agent (e.g. `developer`). Only real \
3669
- `team-w<N>[-suffix]` windows are honored as existing adaptive \
3670
- placements. Got {placement:?}."
3671
- );
3672
- }
3673
-
3674
- /// **RED — end-to-end Fix #2 + Fix #3 + defence**: add-agent against a
3675
- /// per-agent live topology + adaptive backend in state must issue
3676
- /// spawn_into (new window named after agent_id) and MUST NOT spawn_split
3677
- /// into any existing per-agent window. macmini repro: split-window
3678
- /// -t :developer would hijack the developer worker's pane.
3679
- #[test]
3680
- fn e45_add_agent_opens_new_window_does_not_split_into_per_agent_window() {
3681
- use crate::transport::WindowName;
3682
-
3683
- let team = temp_ws().join("e45-per-agent-no-split");
3684
- std::fs::create_dir_all(team.join("agents")).unwrap();
3685
- std::fs::write(
3686
- team.join("TEAM.md"),
3687
- "---\nname: e45probe\nobjective: E45 probe.\nprovider: codex\n---\n\nteam.\n",
3688
- )
3689
- .unwrap();
3690
- std::fs::write(team.join("agents").join("developer.md"), QS_VALID_ROLE).unwrap();
3691
- let role_file = team.join("worker2-role.md");
3692
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3693
-
3694
- // Real-machine state: legacy_display_key=adaptive, but the existing
3695
- // `developer` worker carries per-agent layout_window=developer with
3696
- // layout_index=0. macmini-equivalent state shape.
3697
- crate::state::persist::save_runtime_state(
3698
- &team,
3699
- &json!({
3700
- "session_name": "team-iso",
3701
- "legacy_display_key": "adaptive",
3702
- "agents": {
3703
- "developer": {
3704
- "status": "running",
3705
- "provider": "fake",
3706
- "window": "developer",
3707
- "layout_window": "developer",
3708
- "layout_index": 0u64,
3709
- "pane_id": "%519",
3710
- }
3711
- }
3712
- }),
3713
- )
3714
- .unwrap();
3715
- seed_healthy_coordinator(&team);
3716
-
3717
- let transport = OfflineTransport::new()
3718
- .with_targets(vec![layout_pane("team-iso", "developer", "%519", 0)])
3719
- .with_windows(vec![WindowName::new("developer")])
3720
- .with_session_present(true);
3721
-
3722
- let _result = crate::lifecycle::add_agent_with_transport(
3723
- &team,
3724
- &AgentId::new("worker2"),
3725
- &role_file,
3726
- false,
3727
- None,
3728
- &transport,
3729
- );
3730
-
3731
- let spawn_records = transport.spawn_window_records();
3732
- // PRIMARY assertion: no spawn_split anywhere — adaptive placement
3733
- // refused to group into the per-agent `developer` window.
3734
- let any_split = spawn_records.iter().any(|(kind, _)| kind == "spawn_split");
3735
- assert!(
3736
- !any_split,
3737
- "E45 end-to-end: add-agent against a per-agent live topology must \
3738
- NOT issue spawn_split into any window (macmini repro: \
3739
- split-window -t :developer would hijack the developer worker's \
3740
- pane). Got spawn_records={spawn_records:?}"
3741
- );
3742
- // Defence: the spawn target name must not be `developer` (the existing
3743
- // per-agent window) — if it were, the spawn would hijack.
3744
- let spawned_into_developer = spawn_records
3745
- .iter()
3746
- .any(|(_, window)| window == "developer");
3747
- assert!(
3748
- !spawned_into_developer,
3749
- "E45 end-to-end: spawn target must NOT be `developer` (the existing \
3750
- worker's window). Got spawn_records={spawn_records:?}"
3751
- );
3752
- // The new worker must have been spawned somewhere (proves we reached
3753
- // the spawn step and didn't refuse silently).
3754
- assert!(
3755
- !spawn_records.is_empty(),
3756
- "E45 end-to-end: add-agent must still attempt the spawn; got no \
3757
- records."
3758
- );
3759
- }
3760
-
3761
- /// **Regression guard**: helper `is_adaptive_layout_window` golden cases.
3762
- /// `team-w1`, `team-w42`, `team-w7-foo` are adaptive; agent_id names and
3763
- /// other shapes are not.
3764
- #[test]
3765
- fn e45_is_adaptive_layout_window_recognises_team_w_pattern_only() {
3766
- use crate::lifecycle::launch::is_adaptive_layout_window_pub as is_adapt;
3767
-
3768
- assert!(is_adapt("team-w1"), "team-w1 must be adaptive");
3769
- assert!(is_adapt("team-w2"), "team-w2 must be adaptive");
3770
- assert!(is_adapt("team-w42"), "team-w42 must be adaptive");
3771
- assert!(
3772
- is_adapt("team-w7-suffix"),
3773
- "team-w7-suffix must be adaptive"
3774
- );
3775
-
3776
- assert!(
3777
- !is_adapt("developer"),
3778
- "developer is per-agent, not adaptive"
3779
- );
3780
- assert!(
3781
- !is_adapt("architect"),
3782
- "architect is per-agent, not adaptive"
3783
- );
3784
- assert!(!is_adapt("demo-director"), "demo-director is per-agent");
3785
- assert!(!is_adapt("leader"), "leader is not adaptive");
3786
- assert!(!is_adapt(""), "empty is not adaptive");
3787
- assert!(!is_adapt("team-w"), "team-w (no index) is not adaptive");
3788
- assert!(
3789
- !is_adapt("team-w0"),
3790
- "team-w0 (index 0 invalid post-subtract) is not adaptive"
3791
- );
3792
- assert!(
3793
- !is_adapt("team-wfoo"),
3794
- "team-wfoo (non-numeric) is not adaptive"
3795
- );
3796
- }
3797
-
3798
- // ═════════════════════════════════════════════════════════════════════════════
3799
- // E42 (0.3.24 P0, double-spec deadlock) — add-agent / remove-agent must read
3800
- // the SAME canonical spec, and add-agent's writes must be atomic (rollback on
3801
- // any downstream failure).
3802
- // ═════════════════════════════════════════════════════════════════════════════
3803
-
3804
- /// **E42 RED (a) round-trip**: stale `state.spec_path` points at a legacy
3805
- /// user-dir spec while the canonical runtime spec is authoritative.
3806
- /// add-agent writes to canonical; remove-agent (from_spec=true, force=true)
3807
- /// must succeed because the fix routes lifecycle_paths::spec_workspace to
3808
- /// canonical, not the stale legacy path.
3809
- #[test]
3810
- fn e42_add_then_remove_round_trip_resolves_canonical_spec_not_legacy() {
3811
- let team = temp_ws().join("e42-roundtrip");
3812
- std::fs::create_dir_all(team.join("agents")).unwrap();
3813
- std::fs::write(
3814
- team.join("TEAM.md"),
3815
- "---\nname: e42rt\nobjective: E42 round-trip probe.\nprovider: codex\n---\n\nteam.\n",
3816
- )
3817
- .unwrap();
3818
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
3819
- let role_file = team.join("newagent.md");
3820
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3821
- seed_healthy_coordinator(&team);
3822
- // Pre-populate the state with a STALE spec_path pointing at a legacy
3823
- // user-dir spec that does NOT carry the new agent we are about to add.
3824
- // canonical runtime spec is what add-agent writes to.
3825
- let team_ws = crate::model::paths::team_workspace(&team).unwrap();
3826
- let legacy_spec_dir = team_ws.join(".team").join("e42rt");
3827
- std::fs::create_dir_all(&legacy_spec_dir).unwrap();
3828
- let legacy_spec_path = legacy_spec_dir.join("team.spec.yaml");
3829
- std::fs::write(
3830
- &legacy_spec_path,
3831
- "name: e42rt\nagents: []\nrouting:\n rules: []\n",
3832
- )
3833
- .unwrap();
3834
- crate::state::persist::save_runtime_state(
3835
- &team,
3836
- &json!({
3837
- "session_name": "team-iso",
3838
- "spec_path": legacy_spec_path.to_string_lossy(),
3839
- "agents": {
3840
- "implementer": {"status": "running", "provider": "fake", "window": "implementer"}
3841
- }
3842
- }),
3843
- )
3844
- .unwrap();
3845
- let transport = OfflineTransport::new();
3846
-
3847
- // (1) add-agent succeeds (writes canonical spec + state)
3848
- let add_result = crate::lifecycle::add_agent_with_transport(
3849
- &team,
3850
- &AgentId::new("worker2"),
3851
- &role_file,
3852
- false,
3853
- None,
3854
- &transport,
3855
- );
3856
- assert!(
3857
- add_result.is_ok(),
3858
- "E42 (a) round-trip: add-agent must succeed even with stale state.spec_path; \
3859
- got {add_result:?}"
3860
- );
3861
- // (2) remove-agent must find the agent (lifecycle_paths resolves canonical,
3862
- // not the stale legacy spec)
3863
- let remove_result = crate::lifecycle::remove_agent_with_transport(
3864
- &team,
3865
- &AgentId::new("worker2"),
3866
- true,
3867
- true,
3868
- None,
3869
- &transport,
3870
- );
3871
- assert!(
3872
- remove_result.is_ok(),
3873
- "E42 (a) round-trip: remove-agent must find the agent add-agent just wrote \
3874
- (canonical-first lifecycle_paths). Pre-fix: stale state.spec_path wins → \
3875
- remove sees legacy spec without the new agent → 'unknown'. Got {remove_result:?}"
3876
- );
3877
- }
3878
-
3879
- /// **E42 RED (b) re-add symmetry**: after add(x), a second add(x) must say
3880
- /// "already exists" AND remove(x) must recognise x — never give relative
3881
- /// existence judgments. Same canonical truth source on both sides.
3882
- #[test]
3883
- fn e42_re_add_and_remove_agree_on_existence_after_add() {
3884
- let team = temp_ws().join("e42-readdsym");
3885
- std::fs::create_dir_all(team.join("agents")).unwrap();
3886
- std::fs::write(
3887
- team.join("TEAM.md"),
3888
- "---\nname: e42sym\nobjective: E42 symmetry probe.\nprovider: codex\n---\n\nteam.\n",
3889
- )
3890
- .unwrap();
3891
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
3892
- let role_file = team.join("newagent.md");
3893
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3894
- seed_healthy_coordinator(&team);
3895
- seed_canonical_team_identity(&team, "e42sym");
3896
- let transport = OfflineTransport::new();
3897
- // (1) first add
3898
- let r1 = crate::lifecycle::add_agent_with_transport(
3899
- &team,
3900
- &AgentId::new("worker2"),
3901
- &role_file,
3902
- false,
3903
- None,
3904
- &transport,
3905
- );
3906
- assert!(r1.is_ok(), "first add must succeed; got {r1:?}");
3907
- // (2) second add must report already-exists Err (not Ok)
3908
- let r2 = crate::lifecycle::add_agent_with_transport(
3909
- &team,
3910
- &AgentId::new("worker2"),
3911
- &role_file,
3912
- false,
3913
- None,
3914
- &transport,
3915
- );
3916
- assert!(
3917
- r2.is_err(),
3918
- "E42 (b) symmetry: second add must Err 'already exists'; got {r2:?}"
3919
- );
3920
- // (3) remove must also see the agent (no relative judgments)
3921
- let r3 = crate::lifecycle::remove_agent_with_transport(
3922
- &team,
3923
- &AgentId::new("worker2"),
3924
- true,
3925
- true,
3926
- None,
3927
- &transport,
3928
- );
3929
- assert!(
3930
- r3.is_ok(),
3931
- "E42 (b) symmetry: remove must see what add wrote — both reading canonical. \
3932
- Got {r3:?}"
3933
- );
3934
- }
3935
-
3936
- /// **E42 RED (d) projection consistency**: after add(x), canonical runtime
3937
- /// spec AND runtime state agents map BOTH contain x; lifecycle_paths
3938
- /// resolves spec_workspace to canonical (not legacy).
3939
- #[test]
3940
- fn e42_add_writes_to_canonical_runtime_spec_and_state_consistently() {
3941
- let team = temp_ws().join("e42-projection");
3942
- std::fs::create_dir_all(team.join("agents")).unwrap();
3943
- std::fs::write(
3944
- team.join("TEAM.md"),
3945
- "---\nname: e42proj\nobjective: E42 projection probe.\nprovider: codex\n---\n\nteam.\n",
3946
- )
3947
- .unwrap();
3948
- std::fs::write(team.join("agents").join("implementer.md"), QS_VALID_ROLE).unwrap();
3949
- let role_file = team.join("newagent.md");
3950
- std::fs::write(&role_file, DELEG_ROLE_WORKER2).unwrap();
3951
- seed_healthy_coordinator(&team);
3952
- seed_canonical_team_identity(&team, "e42proj");
3953
- let transport = OfflineTransport::new();
3954
- let _ = crate::lifecycle::add_agent_with_transport(
3955
- &team,
3956
- &AgentId::new("worker2"),
3957
- &role_file,
3958
- false,
3959
- None,
3960
- &transport,
3961
- )
3962
- .expect("add must succeed");
3963
-
3964
- // (a) runtime state has worker2 — read same way add_agent does (team_workspace
3965
- // resolves the run_workspace, and select_runtime_state reads canonical-scoped).
3966
- let state = crate::state::persist::load_runtime_state(&team).unwrap();
3967
- assert!(
3968
- state.pointer("/agents/worker2").is_some(),
3969
- "E42 (d): runtime state must contain worker2 after add; state={state}"
3970
- );
3971
-
3972
- // (b) canonical runtime spec has worker2
3973
- let runtime_spec = find_runtime_spec(&team, "e42proj");
3974
- let canonical_spec_path = runtime_spec.expect("canonical runtime spec must exist");
3975
- let canonical_spec_text = std::fs::read_to_string(&canonical_spec_path).unwrap();
3976
- assert!(
3977
- canonical_spec_text.contains("worker2"),
3978
- "E42 (d): canonical runtime spec must contain worker2; \
3979
- canonical_spec={canonical_spec_text}"
3980
- );
3981
- }