@team-agent/installer 0.5.128 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +37 -20
  5. package/skills/team-agent/command-coverage.json +169 -183
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +64 -30
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +64 -30
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1288
  15. package/crates/team-agent/src/cli/arguments.rs +0 -405
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1721
  18. package/crates/team-agent/src/cli/emit.rs +0 -2930
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1216
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -912
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -689
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6545
  29. package/crates/team-agent/src/cli/models.rs +0 -1206
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/schedule.rs +0 -175
  34. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  35. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  36. package/crates/team-agent/src/cli/send/persist.rs +0 -156
  37. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  38. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  39. package/crates/team-agent/src/cli/send.rs +0 -199
  40. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  41. package/crates/team-agent/src/cli/spec.rs +0 -165
  42. package/crates/team-agent/src/cli/status.rs +0 -280
  43. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  44. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  45. package/crates/team-agent/src/cli/status_port/brief.rs +0 -1981
  46. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  47. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  48. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  49. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  50. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  51. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  52. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  53. package/crates/team-agent/src/cli/status_port.rs +0 -92
  54. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  55. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  56. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  57. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -322
  58. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  59. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  60. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  61. package/crates/team-agent/src/cli/tests/named_address.rs +0 -761
  62. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  63. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -484
  64. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  65. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  66. package/crates/team-agent/src/cli/tests/status_send.rs +0 -888
  67. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  68. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  69. package/crates/team-agent/src/cli/triage.rs +0 -234
  70. package/crates/team-agent/src/cli/types.rs +0 -591
  71. package/crates/team-agent/src/codex_app_server.rs +0 -546
  72. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  73. package/crates/team-agent/src/compiler/tests.rs +0 -827
  74. package/crates/team-agent/src/compiler.rs +0 -890
  75. package/crates/team-agent/src/conpty/backend.rs +0 -829
  76. package/crates/team-agent/src/conpty/mod.rs +0 -33
  77. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1744
  78. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  79. package/crates/team-agent/src/contract_runtime/config.rs +0 -364
  80. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -76
  81. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -449
  82. package/crates/team-agent/src/contract_runtime/fork.rs +0 -361
  83. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  84. package/crates/team-agent/src/contract_runtime/framework.rs +0 -367
  85. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -394
  86. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  87. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  88. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  89. package/crates/team-agent/src/contract_runtime/registry.rs +0 -553
  90. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  91. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  92. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  93. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  94. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  95. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  96. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  97. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  98. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  99. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  101. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  102. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  104. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  105. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  106. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  107. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -300
  108. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  109. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  110. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  111. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -503
  112. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  113. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  114. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  115. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  116. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  117. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  118. package/crates/team-agent/src/coordinator/tick.rs +0 -3024
  119. package/crates/team-agent/src/coordinator/types.rs +0 -540
  120. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  121. package/crates/team-agent/src/db/message_store.rs +0 -1527
  122. package/crates/team-agent/src/db/migration.rs +0 -984
  123. package/crates/team-agent/src/db/mod.rs +0 -26
  124. package/crates/team-agent/src/db/schema.rs +0 -663
  125. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  126. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  127. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  128. package/crates/team-agent/src/direct_delivery.rs +0 -368
  129. package/crates/team-agent/src/event_log.rs +0 -502
  130. package/crates/team-agent/src/fake_worker.rs +0 -303
  131. package/crates/team-agent/src/inbox_store.rs +0 -169
  132. package/crates/team-agent/src/kill_audit.rs +0 -106
  133. package/crates/team-agent/src/layout/manager.rs +0 -248
  134. package/crates/team-agent/src/layout/mod.rs +0 -36
  135. package/crates/team-agent/src/layout/overlay.rs +0 -134
  136. package/crates/team-agent/src/layout/placement.rs +0 -52
  137. package/crates/team-agent/src/layout/recovery.rs +0 -106
  138. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  139. package/crates/team-agent/src/layout/sessions.rs +0 -294
  140. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  141. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  142. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  143. package/crates/team-agent/src/leader/helpers.rs +0 -178
  144. package/crates/team-agent/src/leader/incident.rs +0 -6
  145. package/crates/team-agent/src/leader/lease.rs +0 -3356
  146. package/crates/team-agent/src/leader/mod.rs +0 -104
  147. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  148. package/crates/team-agent/src/leader/prompt.rs +0 -905
  149. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  150. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  151. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  152. package/crates/team-agent/src/leader/registry.rs +0 -888
  153. package/crates/team-agent/src/leader/start.rs +0 -4501
  154. package/crates/team-agent/src/leader/takeover.rs +0 -65
  155. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  156. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  157. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  158. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  159. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  160. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  161. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  162. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  163. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  164. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  165. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -268
  166. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  167. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  168. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  169. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  170. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  171. package/crates/team-agent/src/leader/types.rs +0 -534
  172. package/crates/team-agent/src/lib.rs +0 -147
  173. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  174. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -881
  175. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -598
  176. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  177. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -204
  178. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -107
  179. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -144
  180. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  181. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  182. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  183. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -160
  184. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  185. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -899
  186. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -225
  187. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  188. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5200
  189. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  190. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  191. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  192. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -473
  193. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  194. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  195. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  196. package/crates/team-agent/src/lifecycle/launch.rs +0 -557
  197. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  198. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  199. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  200. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -1067
  201. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  202. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2199
  203. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1798
  204. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +0 -163
  205. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2362
  206. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  207. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  208. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  209. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  210. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  211. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  212. package/crates/team-agent/src/lifecycle/restart.rs +0 -227
  213. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1230
  214. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  215. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  216. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  217. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  218. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  219. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  220. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -447
  221. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1638
  222. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  223. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -770
  224. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -419
  225. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2035
  226. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1327
  227. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  228. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  229. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  230. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -72
  231. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  232. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  233. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -512
  234. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  235. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  236. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  237. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3983
  238. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  239. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  240. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  241. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  242. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  243. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  244. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -164
  245. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -200
  246. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  247. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -527
  248. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -1062
  249. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1419
  250. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -98
  251. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -550
  252. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -226
  253. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -332
  254. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  255. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  256. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  257. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  258. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  259. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  260. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  261. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  262. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  263. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  264. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  265. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  266. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -342
  267. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  268. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  269. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  270. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  271. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  272. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  273. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  274. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -995
  275. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -836
  276. package/crates/team-agent/src/lifecycle/tests.rs +0 -105
  277. package/crates/team-agent/src/lifecycle/types.rs +0 -877
  278. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -363
  279. package/crates/team-agent/src/main.rs +0 -52
  280. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  281. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  282. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  283. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  284. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  285. package/crates/team-agent/src/mcp_server/readiness.rs +0 -527
  286. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -348
  287. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  288. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  289. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -158
  290. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -353
  291. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -341
  292. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  293. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  294. package/crates/team-agent/src/mcp_server/tools.rs +0 -889
  295. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  296. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  297. package/crates/team-agent/src/messaging/activity.rs +0 -461
  298. package/crates/team-agent/src/messaging/address.rs +0 -87
  299. package/crates/team-agent/src/messaging/delivery.rs +0 -3727
  300. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  301. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  302. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  303. package/crates/team-agent/src/messaging/helpers.rs +0 -336
  304. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  305. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  306. package/crates/team-agent/src/messaging/mod.rs +0 -167
  307. package/crates/team-agent/src/messaging/persist.rs +0 -377
  308. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  309. package/crates/team-agent/src/messaging/reminders.rs +0 -316
  310. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  311. package/crates/team-agent/src/messaging/results.rs +0 -1415
  312. package/crates/team-agent/src/messaging/scheduler.rs +0 -223
  313. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  314. package/crates/team-agent/src/messaging/send.rs +0 -981
  315. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  316. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -657
  317. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  318. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  319. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  320. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  321. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  322. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3549
  323. package/crates/team-agent/src/messaging/tests/spine.rs +0 -853
  324. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  325. package/crates/team-agent/src/messaging/trust.rs +0 -215
  326. package/crates/team-agent/src/messaging/types.rs +0 -472
  327. package/crates/team-agent/src/messaging/wait.rs +0 -366
  328. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  329. package/crates/team-agent/src/model/enums.rs +0 -356
  330. package/crates/team-agent/src/model/errors.rs +0 -18
  331. package/crates/team-agent/src/model/ids.rs +0 -165
  332. package/crates/team-agent/src/model/mod.rs +0 -29
  333. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  334. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  335. package/crates/team-agent/src/model/paths.rs +0 -257
  336. package/crates/team-agent/src/model/routing.rs +0 -387
  337. package/crates/team-agent/src/model/spec.rs +0 -1184
  338. package/crates/team-agent/src/model/task_graph.rs +0 -321
  339. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  340. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  341. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  342. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  343. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  344. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  345. package/crates/team-agent/src/model/yaml.rs +0 -802
  346. package/crates/team-agent/src/os_probe.rs +0 -280
  347. package/crates/team-agent/src/packaging/install.rs +0 -219
  348. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  349. package/crates/team-agent/src/packaging/mod.rs +0 -91
  350. package/crates/team-agent/src/packaging/repair.rs +0 -33
  351. package/crates/team-agent/src/packaging/tests.rs +0 -822
  352. package/crates/team-agent/src/packaging/types.rs +0 -417
  353. package/crates/team-agent/src/platform/argv.rs +0 -331
  354. package/crates/team-agent/src/platform/errors.rs +0 -104
  355. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  356. package/crates/team-agent/src/platform/mod.rs +0 -5
  357. package/crates/team-agent/src/platform/process.rs +0 -545
  358. package/crates/team-agent/src/provider/adapter.rs +0 -1150
  359. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  360. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  361. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  362. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  363. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  364. package/crates/team-agent/src/provider/adapters/mod.rs +0 -30
  365. package/crates/team-agent/src/provider/adapters/pi.rs +0 -106
  366. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  367. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  368. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  369. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  370. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  371. package/crates/team-agent/src/provider/classify.rs +0 -708
  372. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  373. package/crates/team-agent/src/provider/faults.rs +0 -165
  374. package/crates/team-agent/src/provider/helpers.rs +0 -52
  375. package/crates/team-agent/src/provider/mod.rs +0 -78
  376. package/crates/team-agent/src/provider/model_catalog.rs +0 -910
  377. package/crates/team-agent/src/provider/session/capture.rs +0 -2731
  378. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  379. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -172
  380. package/crates/team-agent/src/provider/session/context_fork.rs +0 -396
  381. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  382. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  383. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  384. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  385. package/crates/team-agent/src/provider/session_scan/common.rs +0 -654
  386. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  387. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -185
  388. package/crates/team-agent/src/provider/session_scan.rs +0 -71
  389. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  390. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  391. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  392. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  393. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  394. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  395. package/crates/team-agent/src/provider/tests/adapter.rs +0 -441
  396. package/crates/team-agent/src/provider/tests/classify.rs +0 -148
  397. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -35
  398. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  399. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  400. package/crates/team-agent/src/provider/tests/idle.rs +0 -177
  401. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  402. package/crates/team-agent/src/provider/tests.rs +0 -32
  403. package/crates/team-agent/src/provider/types.rs +0 -529
  404. package/crates/team-agent/src/provider/wire.rs +0 -394
  405. package/crates/team-agent/src/redaction.rs +0 -259
  406. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  407. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  408. package/crates/team-agent/src/state/identity.rs +0 -914
  409. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  410. package/crates/team-agent/src/state/mod.rs +0 -74
  411. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  412. package/crates/team-agent/src/state/ownership.rs +0 -563
  413. package/crates/team-agent/src/state/paths.rs +0 -395
  414. package/crates/team-agent/src/state/persist.rs +0 -3811
  415. package/crates/team-agent/src/state/projection.rs +0 -1508
  416. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  417. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  418. package/crates/team-agent/src/state/repository.rs +0 -866
  419. package/crates/team-agent/src/state/selector.rs +0 -160
  420. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  421. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
  422. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  423. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  424. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  425. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  426. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4103
  427. package/crates/team-agent/src/tmux_backend.rs +0 -4492
  428. package/crates/team-agent/src/topology.rs +0 -537
  429. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  430. package/crates/team-agent/src/transport/native_input.rs +0 -491
  431. package/crates/team-agent/src/transport/test_support.rs +0 -743
  432. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  433. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  434. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  435. package/crates/team-agent/src/transport.rs +0 -1655
  436. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,2035 +0,0 @@
1
- //! Copilot provider contracts (zero model sessions; owned physical caller fixture).
2
- //!
3
- //! Basis docs (sole truth sources — where the in-tree implementation deviates, these
4
- //! contracts stay red):
5
- //! - `.team/artifacts/copilot-provider-design.md` (fable-architect; §C1 argv shape,
6
- //! §C2 instructions degradation, §C5 permission mapping, §E test architecture)
7
- //! - `.team/artifacts/copilot-provider-cr-verdict.md` (constitution-reviewer; 26
8
- //! constraints C-1-1..C-7-3, 22 reverse cases — the deterministic subset lands here;
9
- //! real-session-only cases (§E3: must4 identity self-report, runtime prompt gating,
10
- //! dangerous live verify, status_patterns sampling) stay on the user acceptance list).
11
- //!
12
- //! Python parity note: 0.2.11 ships copilot as an EXPLICIT unsupported plug
13
- //! (provider_cli/copilot.py:6-8 -> ProviderCapabilityError), so there is no Python
14
- //! behavior to diff against — the design doc IS the truth source (B2 lesson).
15
- //!
16
- //! Faces covered (leader task §1-7):
17
- //! 1. worker argv golden (§C1 + C-5-1/3) — copilot_argv_* tests
18
- //! 2. per-worker AGENTS.md == compiled prompt — copilot_agents_md_* tests (C-1-1/2,
19
- //! identity-first per the 0.3.4 B2/D6 lock)
20
- //! 3. tools metadata transparency (C-2-1, no prompt permission note or argv deny flags)
21
- //! 4. fork = structured CapabilityUnsupported (C-4-2/3)
22
- //! 5. startup recognizer supports copilot trust/ready; turn-state Unknown never idles
23
- //! (N11, C-3-1/4)
24
- //! 6. leader session naming falls under the B5 `team-agent-leader-` prefix protection
25
- //! 7. session capture = sqlite point query, no directory traversal (PERF P2 lock)
26
-
27
- #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
28
-
29
- #[path = "../../../tests/support/hermetic.rs"]
30
- mod hermetic_guard;
31
- #[allow(dead_code)]
32
- fn _hermetic_boundary_marker(_: &hermetic_guard::HermeticTestEnv) {}
33
-
34
- fn enter_hermetic(tag: &str) -> hermetic_guard::HermeticTestEnv {
35
- hermetic_guard::HermeticTestEnv::enter_with_leader(tag)
36
- }
37
-
38
- use std::collections::{BTreeMap, BTreeSet};
39
- use std::path::{Path, PathBuf};
40
- use std::process::{Command, Stdio};
41
- use std::sync::Mutex;
42
-
43
- use serial_test::serial;
44
- use team_agent::lifecycle::quick_start_with_transport_in_workspace;
45
- use team_agent::model::enums::Provider;
46
- use team_agent::state::persist::load_runtime_state;
47
- use team_agent::transport::{
48
- AttachOutcome, BackendKind, CaptureRange, CapturedText, InjectPayload, InjectReport,
49
- InjectStage, InjectVerification, Key, PaneField, PaneId, PaneInfo, SessionName, SetEnvOutcome,
50
- SpawnResult, SubmitVerification, Target, Transport, TransportError, TurnVerification,
51
- WindowName,
52
- };
53
-
54
- #[path = "../../../tests/support/temp_workspace.rs"]
55
- mod temp_workspace;
56
- use temp_workspace::TempWorkspace;
57
-
58
- const ANCESTRY_KEY: &str = "TEAM_AGENT_TEST_PROCESS_ANCESTRY_ARGV_JSON";
59
- const NEUTRAL_ANCESTRY: &str = "[\"/bin/zsh\"]";
60
- const COPILOT_TMP_PREFIX: &str = "ta-rs-copilot";
61
-
62
- /// Face 1+3 (§C1 golden + C-5-3, verdict case `copilot_argv_golden_per_role_tools`):
63
- /// a copilot worker (mcp_team only) gets the full §C1 argv — noise control,
64
- /// inline/`@file` MCP config carrying team_orchestrator, a pre-assigned
65
- /// `--session-id` equal to the persisted `_pending_session_id`, and `-C <workspace>`.
66
- /// Tools metadata must not derive deny flags; non-dangerous workers still omit the
67
- /// --allow-all family flag.
68
- #[test]
69
- #[serial(env)]
70
- fn copilot_argv_golden_restricted_role() {
71
- let _hermetic = enter_hermetic("copilot-argv-restricted");
72
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
73
- let ws = tmp_ws("argv-restricted");
74
- let team_dir = write_copilot_team(&ws, "cp-restricted", &["mcp_team"], false);
75
- seed_healthy_coordinator(&ws);
76
- let transport = RecordingTransport::new();
77
-
78
- quick_start_with_transport_in_workspace(
79
- &ws,
80
- &team_dir,
81
- None,
82
- true,
83
- Some("cprestricted"),
84
- &transport,
85
- )
86
- .expect("quick-start should reach copilot command construction");
87
- let spawn = transport.single_spawn();
88
- let argv = &spawn.argv;
89
- let mut failures = Vec::new();
90
-
91
- if argv.first().map(String::as_str) != Some("copilot") {
92
- failures.push(format!("§C1: argv[0] must be `copilot`; argv={argv:?}"));
93
- }
94
- // RC-2 (C-1-2 v2): noise control now includes --no-remote (remote control off).
95
- for noise in ["--no-color", "--no-auto-update", "--no-remote"] {
96
- if !argv.iter().any(|arg| arg == noise) {
97
- failures.push(format!("RC-2/C-1-2: argv must contain {noise}"));
98
- }
99
- }
100
- // RC-6 (C-3-1): worker must disable the built-in github-mcp-server.
101
- if !argv.iter().any(|arg| arg == "--disable-builtin-mcps") {
102
- failures.push("RC-6/C-3-1: argv must carry --disable-builtin-mcps".to_string());
103
- }
104
- // RC-21 (C-7-1): session named by agent id (resume-by-name dividend).
105
- if flag_value(argv, "-n").as_deref() != Some("worker_a")
106
- && flag_value(argv, "--name").as_deref() != Some("worker_a")
107
- {
108
- failures.push(format!(
109
- "RC-21/C-7-1: argv must name the session `-n worker_a`; got {:?}",
110
- flag_value(argv, "-n")
111
- ));
112
- }
113
- // RC-20 (C-6-2): per-worker directed log dir + info level (idle aux source).
114
- let log_dir = flag_value(argv, "--log-dir").unwrap_or_default();
115
- if !(log_dir.contains(".team/logs/copilot") && log_dir.contains("worker_a")) {
116
- failures.push(format!(
117
- "RC-20/C-6-2: argv must carry --log-dir <ws>/.team/logs/copilot/<agent_id>; got {log_dir:?}"
118
- ));
119
- }
120
- if flag_value(argv, "--log-level").as_deref() != Some("info") {
121
- failures.push(format!(
122
- "RC-20/C-6-2: argv must carry --log-level info; got {:?}",
123
- flag_value(argv, "--log-level")
124
- ));
125
- }
126
- // RC-1/RC-16/C-5-8: forbidden flags must never appear.
127
- for forbidden in [
128
- "-i",
129
- "--interactive",
130
- "-p",
131
- "--share",
132
- "--share-gist",
133
- "--no-ask-user",
134
- "--yolo",
135
- ] {
136
- if argv.iter().any(|arg| arg == forbidden) {
137
- failures.push(format!("RC-1/RC-16: forbidden flag {forbidden} in argv"));
138
- }
139
- }
140
- // MCP: --additional-mcp-config with either inline {"mcpServers":...} JSON or the
141
- // @file form pointing at the per-agent .team/runtime/mcp/<agent>.json (§C1 note).
142
- match flag_value(argv, "--additional-mcp-config") {
143
- None => failures.push("§C1: argv must carry --additional-mcp-config".to_string()),
144
- Some(value) => {
145
- let inline_ok = value.contains("mcpServers") && value.contains("team_orchestrator");
146
- let file_ok =
147
- value.starts_with('@') && value.contains(".team/runtime/mcp/worker_a.json");
148
- if !(inline_ok || file_ok) {
149
- failures.push(format!(
150
- "§C1: --additional-mcp-config must be inline mcpServers JSON with \
151
- team_orchestrator or @<.team/runtime/mcp/worker_a.json>; got {value:?}"
152
- ));
153
- }
154
- }
155
- }
156
- // Session pre-assignment (capture without scans, §C4): --session-id == persisted
157
- // _pending_session_id.
158
- let state = load_runtime_state(&ws).expect("state after quick-start");
159
- let pending = state
160
- .pointer("/agents/worker_a/_pending_session_id")
161
- .and_then(serde_json::Value::as_str)
162
- .map(str::to_string);
163
- match (flag_value(argv, "--session-id"), pending) {
164
- (Some(argv_sid), Some(state_sid)) if argv_sid == state_sid => {}
165
- (argv_sid, state_sid) => failures.push(format!(
166
- "§C4: --session-id must be pre-assigned and equal state._pending_session_id \
167
- (claude --session-id parity); argv={argv_sid:?} state={state_sid:?}"
168
- )),
169
- }
170
- if flag_value(argv, "-C").as_deref() != Some(&*ws.to_string_lossy()) {
171
- failures.push(format!(
172
- "§C1: argv must pin the workspace via `-C <workspace>`; got {:?}",
173
- flag_value(argv, "-C")
174
- ));
175
- }
176
- // Tools metadata is transparent compatibility data; it must not derive
177
- // provider-specific deny flags (shell/write/url or any other category).
178
- if argv.iter().any(|arg| arg == "--deny-tool") {
179
- failures.push(format!(
180
- "C-5-3: tools metadata must not derive copilot --deny-tool flags; argv={argv:?}"
181
- ));
182
- }
183
- // RC-10 (C-3-5/C-5-2): mcp_team is allowlisted by server name (no approval prompt).
184
- let allow_tools = flag_values(argv, "--allow-tool");
185
- if !allow_tools
186
- .iter()
187
- .any(|tool| tool.contains("team_orchestrator"))
188
- {
189
- failures.push(format!(
190
- "RC-10/C-3-5: argv must carry --allow-tool 'team_orchestrator'; allow={allow_tools:?}"
191
- ));
192
- }
193
- if argv
194
- .iter()
195
- .any(|arg| arg == "--allow-all" || arg == "--allow-all-tools")
196
- {
197
- failures.push(format!(
198
- "C-5-3: a non-dangerous worker must NOT carry --allow-all/--allow-all-tools; argv={argv:?}"
199
- ));
200
- }
201
- // C-1-5 (verdict `fallback_options_rejected`): the rejected fallbacks must not
202
- // appear — no `-i <prompt>` first-message injection, no --no-custom-instructions,
203
- // and the compiled system prompt text must NOT ride in the argv (it travels via
204
- // the instructions file + env, B2 degradation path).
205
- if argv
206
- .iter()
207
- .any(|arg| arg == "-i" || arg == "--interactive" || arg == "--no-custom-instructions")
208
- {
209
- failures.push(format!(
210
- "C-1-5: rejected fallback flag present (-i/--interactive/--no-custom-instructions); argv={argv:?}"
211
- ));
212
- }
213
- if argv
214
- .iter()
215
- .any(|arg| arg.contains("Team Agent Teammate Runtime Contract"))
216
- {
217
- failures.push("C-1-5/B2: the system prompt must not be smuggled into the argv".to_string());
218
- }
219
- assert!(
220
- failures.is_empty(),
221
- "copilot restricted argv golden failed:\n{}\nargv={argv:?}",
222
- failures.join("\n")
223
- );
224
- }
225
-
226
- /// Face 1 dangerous tier (C-5-1, verdict `dangerous_auto_approve_argv_contains_allow_all`):
227
- /// role `dangerously_skip_permissions: true` must map to `--allow-all` (claude
228
- /// `--dangerously-skip-permissions` parity, paths+urls included) — NOT the
229
- /// silently-narrower `--allow-all-tools`. 0.5.66 bypass 单源:bypass 由角色字段驱动。
230
- #[test]
231
- #[serial(env)]
232
- fn copilot_argv_dangerous_maps_to_allow_all() {
233
- let _hermetic = enter_hermetic("copilot-argv-dangerous");
234
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
235
- let ws = tmp_ws("argv-dangerous");
236
- let team_dir = write_copilot_team(&ws, "cp-dangerous", &["mcp_team"], true);
237
- seed_healthy_coordinator(&ws);
238
- let transport = RecordingTransport::new();
239
-
240
- quick_start_with_transport_in_workspace(
241
- &ws,
242
- &team_dir,
243
- None,
244
- true,
245
- Some("cpdangerous"),
246
- &transport,
247
- )
248
- .expect("quick-start should reach copilot command construction");
249
- let argv = &transport.single_spawn().argv;
250
-
251
- let mut failures = Vec::new();
252
- if !argv.iter().any(|arg| arg == "--allow-all") {
253
- failures.push(format!(
254
- "C-5-1: dangerously_skip_permissions=true must produce `--allow-all` (=--yolo, claude \
255
- parity incl. paths+urls); argv={argv:?}"
256
- ));
257
- }
258
- if argv.iter().any(|arg| arg == "--allow-all-tools") {
259
- failures.push(format!(
260
- "C-5-1: `--allow-all-tools` is the silently-narrower flag and must not be \
261
- used for the dangerous tier; argv={argv:?}"
262
- ));
263
- }
264
- assert!(
265
- failures.is_empty(),
266
- "copilot dangerous argv contract failed:\n{}",
267
- failures.join("\n")
268
- );
269
- }
270
-
271
- /// Face 2 (C-1-1/2, C-6-1..4; verdict `copilot_instructions_dir_env_injected`,
272
- /// `agents_md_content_equals_compile_worker_system_prompt`,
273
- /// `copilot_instructions_dir_path_contains_agent_id`,
274
- /// `copilot_env_overlay_works_without_profile`,
275
- /// `agents_md_per_agent_isolated_no_global_pollution`):
276
- /// the spawn env must carry COPILOT_CUSTOM_INSTRUCTIONS_DIRS pointing at the
277
- /// per-worker dir (path contains the agent id; works with NO profile configured), the
278
- /// AGENTS.md there must BE the compiled worker system prompt (single source: identity
279
- /// first, runtime contract, role body, and output contract), and no global
280
- /// ~/.copilot/AGENTS.md may be written.
281
- #[test]
282
- #[serial(env)]
283
- fn copilot_agents_md_is_the_compiled_prompt_and_env_points_at_it() {
284
- let _hermetic = enter_hermetic("copilot-agents-md");
285
- let home = tmp_ws("fake-home");
286
- let _guard = EnvGuard::set(&[
287
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
288
- (
289
- "HOME",
290
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
291
- ),
292
- ]);
293
- let ws = tmp_ws("agents-md");
294
- let team_dir = write_copilot_team(&ws, "cp-instructions", &["mcp_team"], false);
295
- seed_healthy_coordinator(&ws);
296
- let transport = RecordingTransport::new();
297
-
298
- quick_start_with_transport_in_workspace(
299
- &ws,
300
- &team_dir,
301
- None,
302
- true,
303
- Some("cpinstr"),
304
- &transport,
305
- )
306
- .expect("quick-start should spawn the copilot worker");
307
- let spawn = transport.single_spawn();
308
-
309
- let mut failures = Vec::new();
310
- let dir = spawn
311
- .env
312
- .get("COPILOT_CUSTOM_INSTRUCTIONS_DIRS")
313
- .cloned()
314
- .unwrap_or_default();
315
- if dir.is_empty() {
316
- failures.push(
317
- "C-6-1: spawn env must carry COPILOT_CUSTOM_INSTRUCTIONS_DIRS (env overlay, \
318
- no profile required)"
319
- .to_string(),
320
- );
321
- }
322
- if !dir.contains("worker_a") {
323
- failures.push(format!(
324
- "C-6-2/4: the instructions dir must be per-agent (path contains the agent \
325
- id); got {dir:?}"
326
- ));
327
- }
328
- if !dir.contains(".team/runtime/copilot-instructions") {
329
- failures.push(format!(
330
- "C-6-2: the instructions dir must live under \
331
- <workspace>/.team/runtime/copilot-instructions/<agent_id>/; got {dir:?}"
332
- ));
333
- }
334
- let agents_md = std::fs::read_to_string(Path::new(&dir).join("AGENTS.md")).unwrap_or_default();
335
- if agents_md.is_empty() {
336
- failures.push(format!("C-1-1: per-worker AGENTS.md must exist in {dir:?}"));
337
- } else {
338
- let identity = "You are Team Agent worker `worker_a` with role `Copilot Worker`. \
339
- When asked about your role or identity, answer with this Team Agent worker identity first, \
340
- not only the generic provider product identity.";
341
- if !agents_md.starts_with(identity) {
342
- failures.push(format!(
343
- "C-1-1 + B2/D6 lock: AGENTS.md must BE compile_worker_system_prompt output \
344
- with the identity section FIRST; head={:?}",
345
- agents_md.chars().take(160).collect::<String>()
346
- ));
347
- }
348
- for marker in [
349
- "# Team Agent Teammate Runtime Contract",
350
- "COPILOT ROLE BODY SENTINEL",
351
- "exclusively for findings, progress, questions, and completion updates",
352
- ] {
353
- if !agents_md.contains(marker) {
354
- failures.push(format!(
355
- "C-1-1: AGENTS.md is missing the compiled prompt section marker {marker:?}"
356
- ));
357
- }
358
- }
359
- }
360
- if home.join(".copilot/AGENTS.md").exists() {
361
- failures.push(
362
- "C-1-2/C-6-4: the framework must never write the GLOBAL ~/.copilot/AGENTS.md \
363
- (per-worker isolation only)"
364
- .to_string(),
365
- );
366
- }
367
- assert!(
368
- failures.is_empty(),
369
- "copilot AGENTS.md/env contract failed:\n{}\nenv={:?}",
370
- failures.join("\n"),
371
- spawn.env.get("COPILOT_CUSTOM_INSTRUCTIONS_DIRS")
372
- );
373
- }
374
-
375
- /// Face 3: tools metadata is transparent compatibility data and must not produce
376
- /// a provider-specific Permission note in the compiled Copilot prompt.
377
- #[test]
378
- #[serial(env)]
379
- fn copilot_prompt_omits_removed_permission_note() {
380
- let _hermetic = enter_hermetic("copilot-permission-note");
381
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
382
- let ws = tmp_ws("enforcement");
383
- let team_dir = write_copilot_team(
384
- &ws,
385
- "cp-enforcement",
386
- &[
387
- "execute_bash",
388
- "fs_read",
389
- "fs_write",
390
- "fs_list",
391
- "git_diff",
392
- "mcp_team",
393
- "provider_builtin",
394
- ],
395
- false,
396
- );
397
- seed_healthy_coordinator(&ws);
398
- let transport = RecordingTransport::new();
399
-
400
- quick_start_with_transport_in_workspace(
401
- &ws,
402
- &team_dir,
403
- None,
404
- true,
405
- Some("cpenforce"),
406
- &transport,
407
- )
408
- .expect("quick-start should spawn the copilot worker");
409
- let spawn = transport.single_spawn();
410
- let dir = spawn
411
- .env
412
- .get("COPILOT_CUSTOM_INSTRUCTIONS_DIRS")
413
- .cloned()
414
- .expect("Copilot spawn must carry COPILOT_CUSTOM_INSTRUCTIONS_DIRS");
415
- assert!(
416
- !dir.is_empty(),
417
- "Copilot instructions directory must not be empty"
418
- );
419
- let agents_md = std::fs::read_to_string(Path::new(&dir).join("AGENTS.md"))
420
- .expect("per-worker Copilot AGENTS.md must be readable");
421
- let identity = "You are Team Agent worker `worker_a` with role `Copilot Worker`.";
422
- assert!(
423
- agents_md.starts_with(identity) && agents_md.contains("COPILOT ROLE BODY SENTINEL"),
424
- "C-2-1: compiled Copilot prompt must include its identity and role body; content={agents_md:?}"
425
- );
426
- assert!(
427
- !agents_md.contains("Permission note:"),
428
- "C-2-1: removed provider tool enforcement must not emit a Permission note; content={agents_md:?}"
429
- );
430
- }
431
-
432
- /// Face 4 re-charter: Copilot has a real store-fork primitive, so the blanket
433
- /// capability refusal is retired. Missing backing must still fail closed before
434
- /// spawn rather than silently degrading to a fresh session.
435
- #[test]
436
- #[serial(env)]
437
- fn copilot_fork_is_supported_but_missing_backing_never_falls_back_fresh() {
438
- let _hermetic = enter_hermetic("copilot-fork-missing-backing");
439
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
440
- let ws = tmp_ws("fork");
441
- let team_dir = write_copilot_team(&ws, "cp-fork", &["mcp_team"], false);
442
- seed_healthy_coordinator(&ws);
443
- let transport = RecordingTransport::new();
444
- quick_start_with_transport_in_workspace(&ws, &team_dir, None, true, Some("cpfork"), &transport)
445
- .expect("quick-start should seed the team");
446
- // Give the source a session id so the capability gate (not a missing-session gate)
447
- // is what fires.
448
- seed_session_id(&ws, "worker_a");
449
-
450
- let fork_transport = RecordingTransport::new();
451
- let result = team_agent::lifecycle::launch::fork_agent_with_transport(
452
- &team_dir,
453
- &team_agent::model::ids::AgentId::new("worker_a"),
454
- &team_agent::model::ids::AgentId::new("worker_fork"),
455
- None,
456
- false,
457
- None,
458
- &fork_transport,
459
- );
460
-
461
- let text = format!("{result:?}").to_lowercase();
462
- assert!(
463
- team_agent::provider::get_adapter(Provider::Copilot)
464
- .caps()
465
- .fork,
466
- "Copilot store fork is a supported capability"
467
- );
468
- assert!(
469
- result.is_err(),
470
- "fixture has no Copilot store backing: {result:?}"
471
- );
472
- assert!(
473
- text.contains("unverified") || text.contains("未验证"),
474
- "Copilot in-window fork is unverified (not a store-fork capability gate): {result:?}"
475
- );
476
- assert!(
477
- fork_transport.spawns.lock().unwrap().is_empty(),
478
- "missing Copilot backing must fail before spawn, never fresh-fallback"
479
- );
480
- }
481
-
482
- /// Face 5 (B12 + C-3-1/4 + N11): copilot startup trust/ready recognition is
483
- /// supported from the fixture-backed recognizer, so a real tick over a copilot
484
- /// worker must no longer emit the old `provider.classify.unsupported` event or
485
- /// disturb an attached leader receiver. Turn-state facts remain absent for phase
486
- /// 1, and an unknown copilot node still blocks idle take-over (unknown ≠ idle).
487
- #[test]
488
- #[serial(env)]
489
- fn copilot_phase1_classify_is_explicit_unknown_and_never_idles() {
490
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
491
- let mut failures = Vec::new();
492
-
493
- // C-3-1: no turn-state facts for copilot, even over an error-shaped record.
494
- let fact = team_agent::provider::latest_explicit_error_fact(
495
- Provider::Copilot,
496
- "{\"method\":\"turn/completed\",\"params\":{\"turn\":{\"id\":\"t1\",\"status\":\"failed\"}}}\n",
497
- );
498
- if fact.is_some() {
499
- failures.push(format!(
500
- "C-3-1: phase-1 copilot must not claim turn-state facts (classify -> None/Unknown); got {fact:?}"
501
- ));
502
- }
503
-
504
- if team_agent::provider::classify_copilot_startup_screen(
505
- team_agent::provider::COPILOT_TRUST_PROMPT_MARKER,
506
- ) != team_agent::provider::StartupScreenDecision::AnswerWorkspaceTrust
507
- {
508
- failures.push("B12: copilot trust fixture must be recognized as actionable".to_string());
509
- }
510
- if team_agent::provider::classify_copilot_startup_screen(
511
- team_agent::provider::COPILOT_READY_MARKER,
512
- ) != team_agent::provider::StartupScreenDecision::Ready
513
- {
514
- failures.push("B12: copilot ready fixture must be recognized as ready".to_string());
515
- }
516
-
517
- // C-3-4/B12: the old unsupported event was a phase-1 placeholder. Once the
518
- // fixture-backed recognizer exists, a real tick over a copilot worker must
519
- // not re-emit it or poison leader receiver attachment.
520
- let ws = tmp_ws("classify");
521
- let rollout = ws.join("rollout-cp1.jsonl");
522
- std::fs::write(&rollout, "{\"junk\":true}\n").unwrap();
523
- team_agent::state::persist::save_runtime_state(
524
- &ws,
525
- &serde_json::json!({
526
- "session_name": "team-cp",
527
- "active_team_key": "team-cp",
528
- "agents": {
529
- "cp1": {
530
- "status": "running", "provider": "copilot", "agent_id": "cp1",
531
- "window": "cp1", "pane_id": "%41",
532
- "session_id": "88888888-9999-4aaa-8bbb-cccccccccccc",
533
- "rollout_path": rollout.to_string_lossy(),
534
- "spawn_cwd": ws.to_string_lossy(),
535
- },
536
- },
537
- "leader_receiver": {
538
- "status": "attached",
539
- "mode": "direct_tmux",
540
- "pane_id": "%leader",
541
- "provider": "copilot",
542
- "tmux_socket": "default",
543
- },
544
- }),
545
- )
546
- .unwrap();
547
- let coord = team_agent::coordinator::Coordinator::new(
548
- team_agent::coordinator::WorkspacePath::new(ws.to_path_buf()),
549
- Box::new(RealAdapterRegistry),
550
- Box::new(RecordingTransport::with_session_present()),
551
- );
552
- let _ = coord.tick();
553
- let events = std::fs::read_to_string(ws.join(".team/logs/events.jsonl")).unwrap_or_default();
554
- let unsupported_line = events
555
- .lines()
556
- .find(|line| line.contains("classify") && line.contains("unsupported"));
557
- if let Some(line) = unsupported_line {
558
- failures.push(format!(
559
- "B12/C-3-4: copilot startup classify is supported; tick must not emit the old \
560
- provider.classify.unsupported placeholder event; line={line}"
561
- ));
562
- }
563
- let after = team_agent::state::persist::load_runtime_state(&ws).unwrap();
564
- if after
565
- .pointer("/leader_receiver/status")
566
- .and_then(serde_json::Value::as_str)
567
- != Some("attached")
568
- {
569
- failures.push(format!(
570
- "B12: copilot leader_receiver must remain attached after tick; events tail={} state={after}",
571
- events.lines().rev().take(4).collect::<Vec<_>>().join(" | ")
572
- ));
573
- }
574
-
575
- // N11: an unknown copilot node must BLOCK the take-over ping.
576
- let nodes = vec![serde_json::json!({"node_id": "cp1", "role": "worker", "state": "unknown"})];
577
- let reminder = team_agent::provider::evaluate_takeover_reminder(&nodes, None, 100.0, 60.0)
578
- .expect("evaluate ok");
579
- if reminder.should_ping {
580
- failures.push("N11: an Unknown copilot worker must never be counted as idle".to_string());
581
- }
582
- assert!(
583
- failures.is_empty(),
584
- "copilot phase-1 classify contract failed:\n{}",
585
- failures.join("\n")
586
- );
587
- }
588
-
589
- struct RealAdapterRegistry;
590
-
591
- impl team_agent::coordinator::ProviderRegistry for RealAdapterRegistry {
592
- fn adapter_for(&self, provider: Provider) -> Box<dyn team_agent::provider::ProviderAdapter> {
593
- team_agent::provider::get_adapter(provider)
594
- }
595
- }
596
-
597
- /// Face 6 (verdict `copilot_leader_session_name_prefix_protected_by_b5`): the
598
- /// `team-agent copilot` leader entry derives its session from the REAL
599
- /// leader_session_name generator, so the name carries the `team-agent-leader-` prefix
600
- /// that the B5 shutdown protection keys on (pure-function tier; the behavioral
601
- /// shutdown survival run lives with the B5 suite on the lane carrying c92b716).
602
- #[test]
603
- fn copilot_leader_session_name_carries_b5_protected_prefix() {
604
- let ws = tmp_ws("leader-name");
605
- let name = team_agent::leader::leader_session_name(Provider::Copilot, &ws);
606
- assert!(
607
- name.as_str().starts_with("team-agent-leader-copilot-"),
608
- "the copilot leader session must be named team-agent-leader-copilot-<folder>-<hash> \
609
- (leader/start.rs naming; the B5 kill_server/protection sparing keys on the \
610
- team-agent-leader- prefix); got {}",
611
- name.as_str()
612
- );
613
- }
614
-
615
- /// Face 7 (PERF P2 lock; design §B session capture row + §C4): copilot session capture
616
- /// must be a sqlite point query against ~/.copilot/session-store.db — no recursive
617
- /// directory traversal of the copilot home. A poisoned (invalid UTF-8) decoy file in
618
- /// the home must not break the capture, and the matching sessions row (cwd ==
619
- /// spawn_cwd) must be found.
620
- #[test]
621
- #[serial(env)]
622
- fn copilot_session_capture_is_sqlite_point_query_not_directory_scan() {
623
- let home = tmp_ws("capture-home");
624
- let _guard = EnvGuard::set(&[(
625
- "HOME",
626
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
627
- )]);
628
- let spawn_cwd = tmp_ws("capture-cwd");
629
- let copilot_dir = home.join(".copilot");
630
- std::fs::create_dir_all(copilot_dir.join("logs")).unwrap();
631
- // Poisoned decoy: a whole-directory scanner would read this and fail/skip.
632
- let mut poison = b"{\"junk\":true}\n".to_vec();
633
- poison.extend_from_slice(&[0xFF, 0xFE, 0xFF]);
634
- std::fs::write(
635
- copilot_dir.join("logs").join("process-rollout-1.jsonl"),
636
- &poison,
637
- )
638
- .unwrap();
639
- let conn = rusqlite::Connection::open(copilot_dir.join("session-store.db")).unwrap();
640
- conn.execute_batch(
641
- "create table sessions (id text primary key, cwd text, created_at text, updated_at text);
642
- create table turns (session_id text, turn_index integer, user_message text, assistant_response text);",
643
- )
644
- .unwrap();
645
- conn.execute(
646
- "insert into sessions(id, cwd, created_at, updated_at) values (?1, ?2, '2026-06-10T00:00:00Z', '2026-06-10T00:00:01Z')",
647
- rusqlite::params![
648
- "66666666-7777-4888-9999-aaaaaaaaaaaa",
649
- spawn_cwd.to_string_lossy()
650
- ],
651
- )
652
- .unwrap();
653
- drop(conn);
654
-
655
- // 断言1(方法锁·PERF P2):expected-id 点查命中(==seed 的那行 id)+ poison decoy 保留 →
656
- // capture 返回含该 id 的 candidate。证 sqlite 点查命中而非扫目录被毒文件炸。
657
- // (E11 后点查路径是 `where id = expected`,故 expected 必须 == seed 的 session id。)
658
- let method_lock = team_agent::provider::get_adapter(Provider::Copilot)
659
- .capture_session_candidates(
660
- &team_agent::provider::CaptureSessionContext {
661
- agent_id: "worker_a".to_string(),
662
- spawn_cwd: spawn_cwd.to_path_buf(),
663
- pane_id: None,
664
- pane_pid: None,
665
- spawned_at: None,
666
- expected_session_id: Some(team_agent::provider::SessionId::new(
667
- "66666666-7777-4888-9999-aaaaaaaaaaaa",
668
- )),
669
- provider_projects_root: None,
670
- },
671
- 0,
672
- )
673
- .expect("copilot capture scan must not error on a poisoned home file (point query, not traversal)");
674
- assert!(
675
- method_lock.iter().any(|candidate| {
676
- candidate.captured.session_id.as_ref().map(|id| id.as_str())
677
- == Some("66666666-7777-4888-9999-aaaaaaaaaaaa")
678
- }),
679
- "PERF P2 lock: the session must come from the session-store.db sqlite point \
680
- query (id == expected_session_id), not from scanning provider-home files; candidates={method_lock:?}"
681
- );
682
-
683
- // 断言2(安全锁·E11 语义):同 db、同 cwd,expected_session_id: None → 返回空。
684
- // no-expected 不 cwd-latest 猜(防 leader+worker 同 cwd 共享 db 时抓 leader 的 latest)。
685
- let safety_lock = team_agent::provider::get_adapter(Provider::Copilot)
686
- .capture_session_candidates(
687
- &team_agent::provider::CaptureSessionContext {
688
- agent_id: "worker_a".to_string(),
689
- spawn_cwd: spawn_cwd.to_path_buf(),
690
- pane_id: None,
691
- pane_pid: None,
692
- spawned_at: None,
693
- expected_session_id: None,
694
- provider_projects_root: None,
695
- },
696
- 0,
697
- )
698
- .expect("copilot capture must not error with no expected id");
699
- assert!(
700
- safety_lock.is_empty(),
701
- "E11 safety lock: no expected_session_id → empty (no cwd-latest guess that could grab \
702
- leader's session); candidates={safety_lock:?}"
703
- );
704
- }
705
-
706
- /// Q4 P0 (C-4-1/4/7, RC-11/RC-12): the worker spawn env MUST carry
707
- /// `COPILOT_DISABLE_TERMINAL_TITLE=1` (updateTerminalTitle defaults to true and would
708
- /// rewrite the tmux window name = an N39 addressing-anchor drift, same severity as the
709
- /// B5 leader misfire). The worker must spawn into the stable adaptive layout window.
710
- #[test]
711
- #[serial(env)]
712
- fn copilot_p0_terminal_title_disabled_and_window_name_stable() {
713
- let _hermetic = enter_hermetic("copilot-terminal-title");
714
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
715
- let ws = tmp_ws("p0-title");
716
- let team_dir = write_copilot_team(&ws, "cp-title", &["mcp_team"], false);
717
- seed_healthy_coordinator(&ws);
718
- let transport = RecordingTransport::new();
719
-
720
- quick_start_with_transport_in_workspace(
721
- &ws,
722
- &team_dir,
723
- None,
724
- true,
725
- Some("cptitle"),
726
- &transport,
727
- )
728
- .expect("quick-start should spawn the copilot worker");
729
- let spawn = transport.single_spawn();
730
-
731
- let mut failures = Vec::new();
732
- if spawn
733
- .env
734
- .get("COPILOT_DISABLE_TERMINAL_TITLE")
735
- .map(String::as_str)
736
- != Some("1")
737
- {
738
- failures.push(format!(
739
- "RC-11/C-4-1 (P0): worker spawn env MUST set COPILOT_DISABLE_TERMINAL_TITLE=1 \
740
- (updateTerminalTitle defaults true -> window-name rewrite = N39 addressing drift, B5-class \
741
- incident); got {:?}",
742
- spawn.env.get("COPILOT_DISABLE_TERMINAL_TITLE")
743
- ));
744
- }
745
- // 0.3.28 Step 4b: 1-window-per-agent; window name = agent_id (`worker_a`),
746
- // not team-w1 (the pre-0.3.28 adaptive layout anchor).
747
- if spawn.window != "worker_a" {
748
- failures.push(format!(
749
- "0.3.28 Step 4b / RC-12: the worker window must be the per-agent \
750
- window named after agent_id (`worker_a`); got {:?}",
751
- spawn.window
752
- ));
753
- }
754
- assert!(
755
- failures.is_empty(),
756
- "copilot P0 terminal-title contract failed:\n{}\nenv_keys={:?}",
757
- failures.join("\n"),
758
- spawn.env.keys().collect::<Vec<_>>()
759
- );
760
- }
761
-
762
- /// Q3 (C-3-2/3/7, RC-7/RC-8): a user-global ~/.copilot/mcp-config.json carrying a
763
- /// non-team_orchestrator server (`foo`) must be observed and named-disabled — the
764
- /// worker argv must add `--disable-mcp-server foo`, a
765
- /// `provider.copilot.mcp_residual_detected` event must land, and the residual file
766
- /// must be written (no silent unbounded MCP surface).
767
- #[test]
768
- #[serial(env)]
769
- fn copilot_mcp_residual_named_disabled_and_recorded() {
770
- let _hermetic = enter_hermetic("copilot-mcp-residual-named");
771
- let home = tmp_ws("mcp-home");
772
- let _guard = EnvGuard::set(&[
773
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
774
- (
775
- "HOME",
776
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
777
- ),
778
- ]);
779
- // Real-machine grounded: copilot 1.0.59 `mcp list` under this HOME reads
780
- // ~/.copilot/mcp-config.json and prints, under a "User servers:" section,
781
- // ` foo (local)`. The adapter's residual scan must turn that into a
782
- // --disable-mcp-server foo (verified the CLI output shape directly).
783
- std::fs::create_dir_all(home.join(".copilot")).unwrap();
784
- std::fs::write(
785
- home.join(".copilot/mcp-config.json"),
786
- "{\"mcpServers\":{\"foo\":{\"command\":\"foo-bin\"}}}",
787
- )
788
- .unwrap();
789
- // Hermetic shim (0.3.5 ship-gate fix): the residual scan execs the REAL `copilot`
790
- // binary, absent on CI runners — a PATH shim replays the te-verified 1.0.59
791
- // `mcp list` output so the parse+wiring contract is deterministic everywhere.
792
- let shim_dir = home.join("bin");
793
- std::fs::create_dir_all(&shim_dir).unwrap();
794
- std::fs::write(
795
- shim_dir.join("copilot"),
796
- "#!/bin/sh\nif [ \"$1\" = \"mcp\" ] && [ \"$2\" = \"list\" ]; then\n printf 'User servers:\\n foo (local)\\n'\n exit 0\nfi\nexit 0\n",
797
- )
798
- .unwrap();
799
- #[cfg(unix)]
800
- {
801
- use std::os::unix::fs::PermissionsExt;
802
- std::fs::set_permissions(
803
- shim_dir.join("copilot"),
804
- std::fs::Permissions::from_mode(0o755),
805
- )
806
- .unwrap();
807
- }
808
- let old_path = std::env::var("PATH").unwrap_or_default();
809
- std::env::set_var("PATH", format!("{}:{old_path}", shim_dir.to_string_lossy()));
810
- let ws = tmp_ws("mcp-residual");
811
- let team_dir = write_copilot_team(&ws, "cp-residual", &["mcp_team"], false);
812
- seed_healthy_coordinator(&ws);
813
- let transport = RecordingTransport::new();
814
-
815
- quick_start_with_transport_in_workspace(
816
- &ws,
817
- &team_dir,
818
- None,
819
- true,
820
- Some("cpresidual"),
821
- &transport,
822
- )
823
- .expect("quick-start should spawn the copilot worker");
824
- let spawn = transport.single_spawn();
825
-
826
- let mut failures = Vec::new();
827
- if flag_values(&spawn.argv, "--disable-mcp-server")
828
- .iter()
829
- .all(|name| name != "foo")
830
- {
831
- failures.push(format!(
832
- "RC-7/C-3-2: a user-global MCP server `foo` must be named-disabled \
833
- (--disable-mcp-server foo); argv={:?}",
834
- spawn.argv
835
- ));
836
- }
837
- let events = std::fs::read_to_string(ws.join(".team/logs/events.jsonl")).unwrap_or_default();
838
- if !events.contains("mcp_residual_detected") {
839
- failures.push(format!(
840
- "RC-8/C-3-3: a non-empty MCP residual must emit \
841
- provider.copilot.mcp_residual_detected (user-visible, not silent); events tail={}",
842
- events.lines().rev().take(3).collect::<Vec<_>>().join(" | ")
843
- ));
844
- }
845
- let residual_file = ws.join(".team/logs/copilot/worker_a/mcp-residual.txt");
846
- if !residual_file.exists() {
847
- failures.push(format!(
848
- "C-3-3: the residual scan must land a per-agent record at {}",
849
- residual_file.display()
850
- ));
851
- }
852
- std::env::set_var("PATH", &old_path);
853
- assert!(
854
- failures.is_empty(),
855
- "copilot MCP residual contract failed:\n{}",
856
- failures.join("\n")
857
- );
858
- }
859
-
860
- /// Q3 downgrade branch (C-3-3, RC-8 negative): when the `copilot` binary is NOT on
861
- /// PATH (e.g. CI runners), the residual scan must degrade honestly — it must NOT emit
862
- /// a false-positive `provider.copilot.mcp_residual_detected`, must add NO
863
- /// `--disable-mcp-server` flags, and must still land a per-agent `mcp-residual.txt`
864
- /// recording the `unavailable` outcome. This is the coverage the populated-residual
865
- /// case alone could not give (0.3.5 ship-gate hermetic follow-up).
866
- #[test]
867
- #[serial(env)]
868
- fn copilot_mcp_residual_scan_unavailable_degrades_honestly_no_false_positive() {
869
- let _hermetic = enter_hermetic("copilot-mcp-residual-unavailable");
870
- // Empty isolated HOME (no ~/.copilot config) and a PATH with NO copilot binary, so
871
- // the scan exercises the `Err(_)` / unavailable arm deterministically.
872
- let home = tmp_ws("residual-unavail-home");
873
- std::fs::create_dir_all(home.join(".copilot")).unwrap();
874
- let empty_bin = tmp_ws("no-copilot-bin");
875
- #[cfg(unix)]
876
- std::os::unix::fs::symlink(hermetic_guard::fixture_tmux_binary(), empty_bin.join("tmux")).unwrap();
877
- let _guard = EnvGuard::set(&[
878
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
879
- (
880
- "HOME",
881
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
882
- ),
883
- (
884
- "PATH",
885
- Box::leak(empty_bin.to_string_lossy().to_string().into_boxed_str()),
886
- ),
887
- ]);
888
- let ws = tmp_ws("residual-unavail");
889
- let team_dir = write_copilot_team(&ws, "cp-residual-unavail", &["mcp_team"], false);
890
- seed_healthy_coordinator(&ws);
891
- let transport = RecordingTransport::new();
892
-
893
- quick_start_with_transport_in_workspace(
894
- &ws,
895
- &team_dir,
896
- None,
897
- true,
898
- Some("cpresidunavail"),
899
- &transport,
900
- )
901
- .expect("quick-start should spawn the copilot worker even without copilot on PATH");
902
- let spawn = transport.single_spawn();
903
-
904
- let mut failures = Vec::new();
905
- if spawn.argv.iter().any(|arg| arg == "--disable-mcp-server") {
906
- failures.push(format!(
907
- "C-3-3 downgrade: an unavailable copilot scan must add NO --disable-mcp-server \
908
- flags (nothing was actually observed); argv={:?}",
909
- spawn.argv
910
- ));
911
- }
912
- let events = std::fs::read_to_string(ws.join(".team/logs/events.jsonl")).unwrap_or_default();
913
- if events.contains("mcp_residual_detected") {
914
- failures.push(
915
- "RC-8 negative: an unavailable scan must NOT emit a false-positive \
916
- provider.copilot.mcp_residual_detected (only a real non-empty residual emits)"
917
- .to_string(),
918
- );
919
- }
920
- let residual_file = ws.join(".team/logs/copilot/worker_a/mcp-residual.txt");
921
- match std::fs::read_to_string(&residual_file) {
922
- Err(_) => failures.push(format!(
923
- "C-3-3: the residual record must still be written at {} even when copilot is \
924
- unavailable (honest 'I could not check')",
925
- residual_file.display()
926
- )),
927
- Ok(text) => {
928
- if !text.contains("unavailable") {
929
- failures.push(format!(
930
- "C-3-3: the residual record must state the unavailable outcome; got {text:?}"
931
- ));
932
- }
933
- }
934
- }
935
- assert!(
936
- failures.is_empty(),
937
- "copilot MCP residual downgrade contract failed:\n{}",
938
- failures.join("\n")
939
- );
940
- }
941
-
942
- /// Q3 (C-3-4, RC-9): the `--additional-mcp-config` JSON the adapter writes must use
943
- /// copilot's expected field name. Copilot's `mcp add` schema field is `transport`
944
- /// (stdio|http|sse), NOT the `type` field used by claude/codex configs — the contract
945
- /// locks the adapter to the copilot field name so the worker actually loads the server.
946
- #[test]
947
- #[serial(env)]
948
- fn copilot_mcp_config_uses_copilot_field_name() {
949
- let _hermetic = enter_hermetic("copilot-mcp-config");
950
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
951
- let ws = tmp_ws("mcp-schema");
952
- let team_dir = write_copilot_team(&ws, "cp-schema", &["mcp_team"], false);
953
- seed_healthy_coordinator(&ws);
954
- let transport = RecordingTransport::new();
955
-
956
- quick_start_with_transport_in_workspace(
957
- &ws,
958
- &team_dir,
959
- None,
960
- true,
961
- Some("cpschema"),
962
- &transport,
963
- )
964
- .expect("quick-start should spawn the copilot worker");
965
- let argv = &transport.single_spawn().argv;
966
-
967
- // Resolve the config text whether inline or @file.
968
- let value = flag_value(argv, "--additional-mcp-config").unwrap_or_default();
969
- let config_text = if let Some(path) = value.strip_prefix('@') {
970
- std::fs::read_to_string(path).unwrap_or_default()
971
- } else {
972
- value
973
- };
974
- assert!(
975
- config_text.contains("transport") && !config_text.contains("\"type\""),
976
- "RC-9/C-3-4: the copilot MCP config must use the `transport` field (copilot \
977
- `mcp add` schema), not the claude/codex `type` field; config={config_text:?}"
978
- );
979
- }
980
-
981
- fn assert_rules_t02_final_mcp(argv: &[String], ws: &Path, agent_id: &str, team: &str) {
982
- let argument = flag_value(argv, "--additional-mcp-config").expect("final MCP flag");
983
- let path = argument
984
- .strip_prefix('@')
985
- .expect("final plan references a file");
986
- let config: serde_json::Value =
987
- serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
988
- let server = &config["mcpServers"]["team_orchestrator"];
989
- assert_eq!(server["transport"], "stdio", "{config}");
990
- assert!(server.get("type").is_none(), "{config}");
991
- assert!(Path::new(server["command"].as_str().unwrap()).is_absolute());
992
- assert_eq!(
993
- server["args"],
994
- serde_json::json!(["mcp-server", "--workspace", ws])
995
- );
996
- assert_eq!(
997
- server["env"]["TEAM_AGENT_WORKSPACE"],
998
- ws.to_string_lossy().as_ref()
999
- );
1000
- assert_eq!(server["env"]["TEAM_AGENT_ID"], agent_id);
1001
- assert_eq!(server["env"]["TEAM_AGENT_OWNER_TEAM_ID"], team);
1002
- eprintln!("T02 final MCP: agent={agent_id} team={team} argv={argv:?} config={config}");
1003
- }
1004
-
1005
- #[test]
1006
- #[serial(env)]
1007
- fn rules_t02_final_mcp_across_fresh_start_restart_and_add() {
1008
- let hermetic = enter_hermetic("rules-t02-final-mcp");
1009
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
1010
- let ws = hermetic.workspace("mcp");
1011
- let team_dir = write_copilot_team(&ws, "cp-resume", &["mcp_team"], false);
1012
- seed_healthy_coordinator(&ws);
1013
- let health = team_agent::coordinator::coordinator_health(
1014
- &team_agent::coordinator::WorkspacePath::new(ws.clone()),
1015
- );
1016
- assert!(
1017
- health.ok,
1018
- "seeded coordinator must prevent daemon spawn: {health:?}"
1019
- );
1020
- let fresh = RecordingTransport::new();
1021
- quick_start_with_transport_in_workspace(&ws, &team_dir, None, true, Some("cpresume"), &fresh)
1022
- .expect("fresh entry");
1023
- let argv = fresh.single_spawn().argv;
1024
- assert_rules_t02_final_mcp(&argv, &ws, "worker_a", "cpresume");
1025
- assert!(flag_value(&argv, "--session-id").is_some());
1026
- assert!(flag_value(&argv, "--resume").is_none());
1027
-
1028
- seed_running_resumable(&ws, "worker_a");
1029
- seed_copilot_session_store(hermetic.home(), "99999999-aaaa-4bbb-8ccc-dddddddddddd");
1030
- for single in [true, false] {
1031
- // A previous file is an output, never the authority for the next spawn.
1032
- std::fs::write(ws.join(".team/runtime/mcp/worker_a.json"),
1033
- r#"{"mcpServers":{"team_orchestrator":{"type":"stdio","env":{"TEAM_AGENT_ID":"foreign"}}}}"#,
1034
- ).unwrap();
1035
- let transport = RecordingTransport::new();
1036
- if single {
1037
- team_agent::lifecycle::start_agent_with_transport(
1038
- &ws,
1039
- &team_agent::model::ids::AgentId::new("worker_a"),
1040
- true,
1041
- false,
1042
- false,
1043
- Some("cpresume"),
1044
- &transport,
1045
- )
1046
- .expect("single start entry");
1047
- } else {
1048
- team_agent::lifecycle::restart_with_transport(&ws, true, Some("cpresume"), &transport)
1049
- .expect("team restart entry");
1050
- }
1051
- let argv = transport.single_spawn().argv;
1052
- assert_rules_t02_final_mcp(&argv, &ws, "worker_a", "cpresume");
1053
- assert_eq!(
1054
- flag_value(&argv, "--resume").as_deref(),
1055
- Some("99999999-aaaa-4bbb-8ccc-dddddddddddd")
1056
- );
1057
- assert!(flag_value(&argv, "--session-id").is_none());
1058
- }
1059
-
1060
- let role_file = ws.join("worker_b.md");
1061
- let role = std::fs::read_to_string(team_dir.join("agents/worker_a.md")).unwrap();
1062
- std::fs::write(&role_file, role.replace("worker_a", "worker_b")).unwrap();
1063
- let added = RecordingTransport::with_session_present();
1064
- team_agent::lifecycle::add_agent_with_transport(
1065
- &team_dir,
1066
- &team_agent::model::ids::AgentId::new("worker_b"),
1067
- &role_file,
1068
- false,
1069
- Some("cpresume"),
1070
- &added,
1071
- )
1072
- .expect("add entry");
1073
- assert_rules_t02_final_mcp(&added.single_spawn().argv, &ws, "worker_b", "cpresume");
1074
- }
1075
-
1076
- #[test]
1077
- fn rules_t02_inline_server_map_preserves_unknown_and_non_object_values() {
1078
- use team_agent::provider::adapters::copilot::copilot_translate_mcp_config;
1079
- let raw = serde_json::json!({
1080
- "stdio": {"type": "stdio", "command": "synthetic", "unknown": {"type": "nested"}},
1081
- "http": {"type": "http", "url": "https://example.invalid"},
1082
- "opaque": 7,
1083
- });
1084
- let translated = copilot_translate_mcp_config(&raw);
1085
- assert_eq!(
1086
- translated,
1087
- serde_json::json!({
1088
- "stdio": {"transport": "stdio", "command": "synthetic", "unknown": {"type": "nested"}},
1089
- "http": {"transport": "http", "url": "https://example.invalid"},
1090
- "opaque": 7,
1091
- })
1092
- );
1093
- assert!(translated.get("mcpServers").is_none());
1094
- for raw in [serde_json::json!(null), serde_json::json!([1, "opaque"])] {
1095
- assert_eq!(copilot_translate_mcp_config(&raw), raw);
1096
- }
1097
- }
1098
-
1099
- #[test]
1100
- #[serial(env)]
1101
- fn rules_t02_non_copilot_writer_keeps_canonical_schema() {
1102
- let hermetic = enter_hermetic("rules-t02-canonical");
1103
- let ws = hermetic.workspace("canonical");
1104
- let config = team_agent::provider::get_adapter(Provider::ClaudeCode)
1105
- .mcp_config(team_agent::provider::AuthMode::Subscription)
1106
- .unwrap();
1107
- let path = team_agent::lifecycle::launch::write_worker_mcp_config_for_provider(
1108
- &ws,
1109
- "synthetic",
1110
- &config,
1111
- Some(Provider::ClaudeCode),
1112
- )
1113
- .unwrap();
1114
- let written: serde_json::Value =
1115
- serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
1116
- assert_eq!(written["mcpServers"], config.raw);
1117
- assert_eq!(written["mcpServers"]["team_orchestrator"]["type"], "stdio");
1118
- }
1119
-
1120
- /// C-7-3 / RC-24: a resume command line must not carry `--session-id` and `--resume`
1121
- /// together (conflicting session semantics). Driven through the real restart path so
1122
- /// the public resume builder is exercised end to end.
1123
- #[test]
1124
- #[serial(env)]
1125
- fn copilot_resume_argv_has_no_session_id_resume_conflict() {
1126
- let _hermetic = enter_hermetic("copilot-resume-argv");
1127
- let home = tmp_ws("resume-home");
1128
- let _guard = EnvGuard::set(&[
1129
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
1130
- (
1131
- "HOME",
1132
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
1133
- ),
1134
- ]);
1135
- let ws = tmp_ws("resume");
1136
- let team_dir = write_copilot_team(&ws, "cp-resume", &["mcp_team"], false);
1137
- seed_healthy_coordinator(&ws);
1138
- quick_start_with_transport_in_workspace(
1139
- &ws,
1140
- &team_dir,
1141
- None,
1142
- true,
1143
- Some("cpresume"),
1144
- &RecordingTransport::new(),
1145
- )
1146
- .expect("quick-start should seed the team");
1147
- seed_running_resumable(&ws, "worker_a");
1148
- seed_copilot_session_store(&home, "99999999-aaaa-4bbb-8ccc-dddddddddddd");
1149
-
1150
- let restart_transport = RecordingTransport::new();
1151
- let _ = team_agent::lifecycle::restart_with_transport(
1152
- &ws,
1153
- true,
1154
- Some("cpresume"),
1155
- &restart_transport,
1156
- );
1157
- let argv = restart_transport.single_spawn().argv;
1158
-
1159
- let has_session_id = argv.iter().any(|arg| arg == "--session-id");
1160
- let has_resume = argv.iter().any(|arg| arg == "--resume");
1161
- assert!(
1162
- has_resume && !has_session_id,
1163
- "RC-24/C-7-3: a copilot resume must carry --resume and NOT --session-id \
1164
- (conflicting session semantics); argv={argv:?}"
1165
- );
1166
- }
1167
-
1168
- // ───────────────────── subscription tier (design §E2.5 A-layer) ─────────────────────
1169
-
1170
- /// A-1 (design §E2.5): a subscription worker with a role model carries `--model <m>`;
1171
- /// a worker with NO model configured must NOT carry --model (no hardcoded default
1172
- /// guess — leave it to the account/config default).
1173
- #[test]
1174
- #[serial(env)]
1175
- fn copilot_subscription_model_argv_only_when_configured() {
1176
- let _hermetic = enter_hermetic("copilot-subscription-model");
1177
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
1178
-
1179
- let ws = tmp_ws("model-set");
1180
- let team_dir = write_copilot_team_model(&ws, "cp-model", &["mcp_team"], Some("gpt-5.5"));
1181
- seed_healthy_coordinator(&ws);
1182
- let transport = RecordingTransport::new();
1183
- quick_start_with_transport_in_workspace(
1184
- &ws,
1185
- &team_dir,
1186
- None,
1187
- true,
1188
- Some("cpmodel"),
1189
- &transport,
1190
- )
1191
- .expect("quick-start with a role model");
1192
- let with_model = transport.single_spawn().argv;
1193
-
1194
- let ws2 = tmp_ws("model-none");
1195
- let team_dir2 = write_copilot_team_model(&ws2, "cp-nomodel", &["mcp_team"], None);
1196
- seed_healthy_coordinator(&ws2);
1197
- let transport2 = RecordingTransport::new();
1198
- quick_start_with_transport_in_workspace(
1199
- &ws2,
1200
- &team_dir2,
1201
- None,
1202
- true,
1203
- Some("cpnomodel"),
1204
- &transport2,
1205
- )
1206
- .expect("quick-start without a role model");
1207
- let no_model = transport2.single_spawn().argv;
1208
-
1209
- let mut failures = Vec::new();
1210
- if flag_value(&with_model, "--model").as_deref() != Some("gpt-5.5") {
1211
- failures.push(format!(
1212
- "A-1: a configured role model must produce --model gpt-5.5; argv={with_model:?}"
1213
- ));
1214
- }
1215
- if no_model.iter().any(|arg| arg == "--model") {
1216
- failures.push(format!(
1217
- "A-1: no configured model must mean NO --model flag (no hardcoded default); argv={no_model:?}"
1218
- ));
1219
- }
1220
- assert!(
1221
- failures.is_empty(),
1222
- "A-1 subscription model argv failed:\n{}",
1223
- failures.join("\n")
1224
- );
1225
- }
1226
-
1227
- /// A-2 (design §E2.5): net model precedence agent.model > profile MODEL — the same
1228
- /// command_overrides ordering #264 locked, reused cross-provider. With a profile MODEL
1229
- /// and a role model both present, the role model wins in argv.
1230
- #[test]
1231
- #[serial(env)]
1232
- fn copilot_subscription_model_precedence_role_over_profile() {
1233
- let _hermetic = enter_hermetic("copilot-subscription-precedence");
1234
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
1235
- let ws = tmp_ws("model-prec");
1236
- let team_dir = write_copilot_team_model(&ws, "cp-prec", &["mcp_team"], Some("role-model-x"));
1237
- // A subscription profile carrying a different MODEL.
1238
- let profiles = team_dir.join("profiles");
1239
- std::fs::create_dir_all(&profiles).unwrap();
1240
- std::fs::write(
1241
- profiles.join("subm.env"),
1242
- "AUTH_MODE=subscription\nMODEL=profile-model-y\n",
1243
- )
1244
- .unwrap();
1245
- // point the agent at the profile
1246
- let agent_md = team_dir.join("agents/worker_a.md");
1247
- let body = std::fs::read_to_string(&agent_md).unwrap().replace(
1248
- "auth_mode: subscription\ndangerously_skip_permissions: false\n",
1249
- "auth_mode: subscription\ndangerously_skip_permissions: false\nprofile: subm\n",
1250
- );
1251
- std::fs::write(&agent_md, body).unwrap();
1252
- seed_healthy_coordinator(&ws);
1253
- let transport = RecordingTransport::new();
1254
- quick_start_with_transport_in_workspace(&ws, &team_dir, None, true, Some("cpprec"), &transport)
1255
- .expect("quick-start with role+profile model");
1256
- let argv = transport.single_spawn().argv;
1257
- assert_eq!(
1258
- flag_value(&argv, "--model").as_deref(),
1259
- Some("role-model-x"),
1260
- "A-2: agent.model must win over profile MODEL (command_overrides net order, #264 \
1261
- cross-provider reuse); argv={argv:?}"
1262
- );
1263
- }
1264
-
1265
- /// A-3 (design §E2.5): a subscription worker must NOT inject any COPILOT_PROVIDER_* or
1266
- /// token env (auth rides the user's logged-in state), and the env overlay must NOT
1267
- /// overwrite a user's COPILOT_GITHUB_TOKEN already in the environment.
1268
- #[test]
1269
- #[serial(env)]
1270
- fn copilot_subscription_env_no_provider_or_token_injection() {
1271
- let _hermetic = enter_hermetic("copilot-subscription-env");
1272
- let _guard = EnvGuard::set(&[
1273
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
1274
- ("COPILOT_GITHUB_TOKEN", "user-tok-keepme"),
1275
- ]);
1276
- let ws = tmp_ws("sub-env");
1277
- let team_dir = write_copilot_team(&ws, "cp-subenv", &["mcp_team"], false);
1278
- seed_healthy_coordinator(&ws);
1279
- let transport = RecordingTransport::new();
1280
- quick_start_with_transport_in_workspace(
1281
- &ws,
1282
- &team_dir,
1283
- None,
1284
- true,
1285
- Some("cpsubenv"),
1286
- &transport,
1287
- )
1288
- .expect("quick-start subscription worker");
1289
- let env = transport.single_spawn().env;
1290
-
1291
- let mut failures = Vec::new();
1292
- for injected in env.keys().filter(|key| key.starts_with("COPILOT_PROVIDER")) {
1293
- failures.push(format!(
1294
- "A-3: subscription worker must not inject {injected}"
1295
- ));
1296
- }
1297
- for token_key in ["COPILOT_API_KEY", "COPILOT_PROVIDER_API_KEY", "GH_TOKEN"] {
1298
- if env.contains_key(token_key) {
1299
- failures.push(format!(
1300
- "A-3: subscription worker must not inject token env {token_key}"
1301
- ));
1302
- }
1303
- }
1304
- // overlay must inherit, not overwrite, the user's token
1305
- if env.get("COPILOT_GITHUB_TOKEN").map(String::as_str) != Some("user-tok-keepme") {
1306
- failures.push(format!(
1307
- "A-3: env overlay must not overwrite the user's COPILOT_GITHUB_TOKEN; got {:?}",
1308
- env.get("COPILOT_GITHUB_TOKEN")
1309
- ));
1310
- }
1311
- assert!(
1312
- failures.is_empty(),
1313
- "A-3 subscription env contract failed:\n{}",
1314
- failures.join("\n")
1315
- );
1316
- }
1317
-
1318
- /// A-4 (design §E2.5): a compatible_api (BYOK) copilot profile must export
1319
- /// COPILOT_PROVIDER_BASE_URL/TYPE/API_KEY/WIRE_API + COPILOT_MODEL into the worker
1320
- /// spawn env, and a BYOK profile WITHOUT a model must fail the launch ("A model is
1321
- /// required for BYOK", help-providers). Driven through the public quick-start path.
1322
- #[test]
1323
- #[serial(env)]
1324
- fn copilot_byok_profile_exports_provider_env_and_requires_model() {
1325
- let _hermetic = enter_hermetic("copilot-byok-profile");
1326
- let _guard = EnvGuard::set(&[(ANCESTRY_KEY, NEUTRAL_ANCESTRY)]);
1327
- let mut failures = Vec::new();
1328
-
1329
- // BYOK profile WITH a model → spawn env carries the provider tuple.
1330
- let ws = tmp_ws("byok-ok");
1331
- let team_dir = write_copilot_byok_team(&ws, "cp-byok", Some("byok-model-z"));
1332
- seed_healthy_coordinator(&ws);
1333
- let transport = RecordingTransport::new();
1334
- match quick_start_with_transport_in_workspace(
1335
- &ws,
1336
- &team_dir,
1337
- None,
1338
- true,
1339
- Some("cpbyok"),
1340
- &transport,
1341
- ) {
1342
- Err(error) => failures.push(format!(
1343
- "A-4: a complete BYOK profile must launch; got Err({error})"
1344
- )),
1345
- Ok(_) => {
1346
- let env = transport.single_spawn().env;
1347
- for (key, expected) in [
1348
- ("COPILOT_PROVIDER_BASE_URL", "https://byok.example/v1"),
1349
- ("COPILOT_PROVIDER_API_KEY", "sk-byok"),
1350
- ("COPILOT_PROVIDER_WIRE_API", "chat"),
1351
- ("COPILOT_MODEL", "byok-model-z"),
1352
- ] {
1353
- if env.get(key).map(String::as_str) != Some(expected) {
1354
- failures.push(format!(
1355
- "A-4: BYOK worker env must carry {key}={expected}; got {:?}",
1356
- env.get(key)
1357
- ));
1358
- }
1359
- }
1360
- if !env.contains_key("COPILOT_PROVIDER_TYPE") {
1361
- failures.push("A-4: BYOK worker env must carry COPILOT_PROVIDER_TYPE".to_string());
1362
- }
1363
- }
1364
- }
1365
-
1366
- // BYOK profile WITHOUT a model → launch must be refused.
1367
- let ws2 = tmp_ws("byok-nomodel");
1368
- let team_dir2 = write_copilot_byok_team(&ws2, "cp-byok-nm", None);
1369
- seed_healthy_coordinator(&ws2);
1370
- match quick_start_with_transport_in_workspace(
1371
- &ws2,
1372
- &team_dir2,
1373
- None,
1374
- true,
1375
- Some("cpbyoknm"),
1376
- &RecordingTransport::new(),
1377
- ) {
1378
- Ok(_) => failures.push(
1379
- "A-4: a BYOK profile without a model must fail (help-providers: 'A model is \
1380
- required for BYOK'); got Ok"
1381
- .to_string(),
1382
- ),
1383
- Err(error) => {
1384
- if !error.to_string().to_lowercase().contains("model") {
1385
- failures.push(format!(
1386
- "A-4: the BYOK no-model error must name the missing model; got {error}"
1387
- ));
1388
- }
1389
- }
1390
- }
1391
- assert!(
1392
- failures.is_empty(),
1393
- "A-4 BYOK contract failed:\n{}",
1394
- failures.join("\n")
1395
- );
1396
- }
1397
-
1398
- /// A-5 (design §E2.5): copilot has NO `auth status` subcommand (main-help Commands),
1399
- /// so the subscription auth hint must be a WEAK/honest signal — it must NOT strongly
1400
- /// claim "logged in" (AuthHintStatus::Present). A weak/unknown status is the honest
1401
- /// answer (MUST-NOT-13: no false-green logged-in claim).
1402
- #[test]
1403
- fn copilot_subscription_auth_hint_is_weak_not_strong_present() {
1404
- let status = team_agent::provider::get_adapter(Provider::Copilot)
1405
- .auth_hint(team_agent::provider::AuthMode::Subscription);
1406
- assert_ne!(
1407
- format!("{status:?}"),
1408
- "Present",
1409
- "A-5: copilot has no `auth status` subcommand, so a strong Present is a false \
1410
- green; the hint must be weak/unknown (honest — can't confirm logged-in); got {status:?}"
1411
- );
1412
- }
1413
-
1414
- /// A-6 (design §E2.5): when the user shell carries GITHUB_TOKEN/GH_TOKEN (which copilot
1415
- /// prioritizes over the credential store — cmd-login), spawning a copilot worker must
1416
- /// emit a passthrough-warning event (phase-1 observe-only, no stripping).
1417
- #[test]
1418
- #[serial(env)]
1419
- fn copilot_token_passthrough_emits_warning_event() {
1420
- let _hermetic = enter_hermetic("copilot-token-passthrough");
1421
- // Fake HOME so the residual MCP scan reads an empty copilot config (isolation:
1422
- // otherwise it reads the real ~/.copilot and muddies this token-focused case).
1423
- let home = tmp_ws("token-home");
1424
- std::fs::create_dir_all(home.join(".copilot")).unwrap();
1425
- let _guard = EnvGuard::set(&[
1426
- (ANCESTRY_KEY, NEUTRAL_ANCESTRY),
1427
- (
1428
- "HOME",
1429
- Box::leak(home.to_string_lossy().to_string().into_boxed_str()),
1430
- ),
1431
- ("GITHUB_TOKEN", "ghp-shell-passthrough"),
1432
- ]);
1433
- let ws = tmp_ws("token-warn");
1434
- let team_dir = write_copilot_team(&ws, "cp-token", &["mcp_team"], false);
1435
- seed_healthy_coordinator(&ws);
1436
- let transport = RecordingTransport::new();
1437
- quick_start_with_transport_in_workspace(
1438
- &ws,
1439
- &team_dir,
1440
- None,
1441
- true,
1442
- Some("cptoken"),
1443
- &transport,
1444
- )
1445
- .expect("quick-start with a shell token present");
1446
-
1447
- let events = std::fs::read_to_string(ws.join(".team/logs/events.jsonl")).unwrap_or_default();
1448
- assert!(
1449
- events.contains("token")
1450
- && (events.contains("passthrough") || events.contains("github_token")),
1451
- "A-6: a shell GITHUB_TOKEN/GH_TOKEN (copilot prioritizes it over the credential \
1452
- store) must emit a passthrough-warning event at spawn (phase-1 observe-only); events tail={}",
1453
- events.lines().rev().take(4).collect::<Vec<_>>().join(" | ")
1454
- );
1455
- }
1456
-
1457
- #[test]
1458
- #[serial(env)]
1459
- fn copilot_tmp_workspace_guard_cleans_and_sweeps_dead_pid_stale_roots() {
1460
- if TempWorkspace::keep_enabled() {
1461
- let _kept = tmp_ws("keep-escape");
1462
- assert!(
1463
- !copilot_tmp_entries().is_empty(),
1464
- "TEAM_AGENT_KEEP_TEST_TMP=1 should preserve copilot tmp roots for debugging"
1465
- );
1466
- return;
1467
- }
1468
-
1469
- sweep_stale_copilot_tmp_roots();
1470
- assert_eq!(
1471
- copilot_tmp_entries().len(),
1472
- 0,
1473
- "test precondition: stale dead-pid ta-rs-copilot-* roots should be cleaned before assertion"
1474
- );
1475
-
1476
- let stale = std::env::temp_dir().join("ta-rs-copilot-stale-dead-999999999-0");
1477
- let _ = std::fs::remove_dir_all(&stale);
1478
- std::fs::create_dir_all(&stale).unwrap();
1479
- {
1480
- let guarded = tmp_ws("drop-check");
1481
- assert!(
1482
- !stale.exists(),
1483
- "tmp_ws must sweep stale ta-rs-copilot-* roots before creating a new root"
1484
- );
1485
- assert!(
1486
- guarded.exists(),
1487
- "guarded copilot tmp root should exist while the guard is alive"
1488
- );
1489
- }
1490
-
1491
- assert_eq!(
1492
- copilot_tmp_entries().len(),
1493
- 0,
1494
- "TempWorkspace Drop must remove copilot tmp roots after normal test exit"
1495
- );
1496
- }
1497
-
1498
- // ───────────────────────────────────── fixtures ─────────────────────────────────────
1499
-
1500
- struct TeamOpts;
1501
-
1502
- fn write_copilot_team_model(ws: &Path, name: &str, tools: &[&str], model: Option<&str>) -> PathBuf {
1503
- let team = write_copilot_team(ws, name, tools, false);
1504
- let agent_md = team.join("agents/worker_a.md");
1505
- let stripped = std::fs::read_to_string(&agent_md)
1506
- .unwrap()
1507
- .lines()
1508
- .filter(|line| !line.trim_start().starts_with("model:"))
1509
- .map(|line| format!("{line}\n"))
1510
- .collect::<String>();
1511
- let body = match model {
1512
- Some(model) => stripped.replace(
1513
- "provider: copilot\n",
1514
- &format!("provider: copilot\nmodel: {model}\n"),
1515
- ),
1516
- None => stripped,
1517
- };
1518
- std::fs::write(&agent_md, body).unwrap();
1519
- team
1520
- }
1521
-
1522
- /// Compiled copilot team whose worker uses a compatible_api (BYOK) profile. When
1523
- /// `model` is None the profile omits MODEL (the "A model is required for BYOK" case).
1524
- fn write_copilot_byok_team(ws: &Path, name: &str, model: Option<&str>) -> PathBuf {
1525
- let team = ws.join(name);
1526
- std::fs::create_dir_all(team.join("agents")).unwrap();
1527
- std::fs::create_dir_all(team.join("profiles")).unwrap();
1528
- std::fs::write(
1529
- team.join("TEAM.md"),
1530
- format!("---\nname: {name}\nobjective: copilot BYOK fixture.\nprovider: copilot\n---\n\nTeam.\n"),
1531
- )
1532
- .unwrap();
1533
- let model_field = model.map(|m| format!("model: {m}\n")).unwrap_or_default();
1534
- std::fs::write(
1535
- team.join("agents/worker_a.md"),
1536
- format!(
1537
- "---\nname: worker_a\nrole: Copilot Worker\nprovider: copilot\n{model_field}auth_mode: compatible_api\ndangerously_skip_permissions: false\nprofile: byok\ntools:\n - mcp_team\n---\n\nCOPILOT ROLE BODY SENTINEL: BYOK worker.\n"
1538
- ),
1539
- )
1540
- .unwrap();
1541
- let model_line = model.map(|m| format!("MODEL={m}\n")).unwrap_or_default();
1542
- std::fs::write(
1543
- team.join("profiles/byok.env"),
1544
- format!(
1545
- "AUTH_MODE=compatible_api\nBASE_URL=https://byok.example/v1\nAPI_KEY=sk-byok\nWIRE_API=chat\nPROVIDER_TYPE=openai\n{model_line}"
1546
- ),
1547
- )
1548
- .unwrap();
1549
- let spec = team_agent::compiler::compile_team(&team).expect("compile BYOK fixture team");
1550
- std::fs::write(
1551
- team.join("team.spec.yaml"),
1552
- team_agent::model::yaml::dumps(&spec),
1553
- )
1554
- .unwrap();
1555
- team
1556
- }
1557
-
1558
- fn write_copilot_team(ws: &Path, name: &str, tools: &[&str], dangerous: bool) -> PathBuf {
1559
- let _ = TeamOpts;
1560
- let team = ws.join(name);
1561
- std::fs::create_dir_all(team.join("agents")).unwrap();
1562
- // 0.5.66 bypass 单源:bypass 由角色字段驱动,不再是 TEAM.md dangerous_auto_approve。
1563
- let role_bypass = if dangerous { "true" } else { "false" };
1564
- std::fs::write(
1565
- team.join("TEAM.md"),
1566
- format!(
1567
- "---\nname: {name}\nobjective: copilot provider contract fixture.\nprovider: copilot\n---\n\nTeam fixture.\n"
1568
- ),
1569
- )
1570
- .unwrap();
1571
- let tool_lines = tools
1572
- .iter()
1573
- .map(|tool| format!(" - {tool}\n"))
1574
- .collect::<String>();
1575
- std::fs::write(
1576
- team.join("agents/worker_a.md"),
1577
- format!(
1578
- "---\nname: worker_a\nrole: Copilot Worker\nprovider: copilot\nmodel: gpt-5\nauth_mode: subscription\ndangerously_skip_permissions: {role_bypass}\ntools:\n{tool_lines}---\n\nCOPILOT ROLE BODY SENTINEL: serve the copilot adapter contract.\n"
1579
- ),
1580
- )
1581
- .unwrap();
1582
- team
1583
- }
1584
-
1585
- fn seed_running_resumable(ws: &Path, agent: &str) {
1586
- let mut state = load_runtime_state(ws).expect("load state before restart");
1587
- let patch = serde_json::json!({
1588
- "status": "running",
1589
- "provider": "copilot",
1590
- "session_id": "99999999-aaaa-4bbb-8ccc-dddddddddddd",
1591
- "first_send_at": "2026-06-10T00:00:00+00:00",
1592
- "window": agent,
1593
- });
1594
- for pointer in [
1595
- format!("/agents/{agent}"),
1596
- format!("/teams/cpresume/agents/{agent}"),
1597
- ] {
1598
- if let Some(obj) = state
1599
- .pointer_mut(&pointer)
1600
- .and_then(serde_json::Value::as_object_mut)
1601
- {
1602
- for (key, value) in patch.as_object().unwrap() {
1603
- obj.insert(key.clone(), value.clone());
1604
- }
1605
- }
1606
- }
1607
- team_agent::state::persist::save_runtime_state(ws, &state).unwrap();
1608
- }
1609
-
1610
- fn seed_copilot_session_store(home: &Path, session_id: &str) {
1611
- let db = home.join(".copilot").join("session-store.db");
1612
- std::fs::create_dir_all(db.parent().unwrap()).unwrap();
1613
- let conn = rusqlite::Connection::open(db).unwrap();
1614
- conn.execute_batch(
1615
- "create table if not exists sessions (
1616
- id text primary key,
1617
- name text,
1618
- created_at text
1619
- );",
1620
- )
1621
- .unwrap();
1622
- conn.execute(
1623
- "insert or replace into sessions(id, name, created_at) values (?1, 'resume-test', '2026-06-10T00:00:00Z')",
1624
- rusqlite::params![session_id],
1625
- )
1626
- .unwrap();
1627
- }
1628
-
1629
- fn seed_session_id(ws: &Path, agent: &str) {
1630
- // 0.4.6 tuple-atomic contract: fork now requires a complete source
1631
- // tuple (session_id + rollout_path + captured_at + captured_via).
1632
- // Tests that exercise downstream fork behaviour (capability gate,
1633
- // adapter error path) need the source row to PASS the backing check
1634
- // so the test reaches the behaviour it actually asserts. Seed the
1635
- // full tuple with a real rollout file so the guard is satisfied.
1636
- let rollout = ws.join(format!("{agent}-rollout.jsonl"));
1637
- if !rollout.exists() {
1638
- std::fs::write(&rollout, "{}\n").expect("seed rollout");
1639
- }
1640
- let mut state = load_runtime_state(ws).unwrap();
1641
- for pointer in [
1642
- format!("/agents/{agent}"),
1643
- format!("/teams/cpfork/agents/{agent}"),
1644
- ] {
1645
- if let Some(obj) = state
1646
- .pointer_mut(&pointer)
1647
- .and_then(serde_json::Value::as_object_mut)
1648
- {
1649
- obj.insert(
1650
- "session_id".to_string(),
1651
- serde_json::json!("77777777-8888-4999-aaaa-bbbbbbbbbbbb"),
1652
- );
1653
- obj.insert(
1654
- "rollout_path".to_string(),
1655
- serde_json::json!(rollout.to_string_lossy()),
1656
- );
1657
- obj.insert(
1658
- "captured_at".to_string(),
1659
- serde_json::json!("2026-06-25T10:00:00+00:00"),
1660
- );
1661
- obj.insert(
1662
- "captured_via".to_string(),
1663
- serde_json::json!("session.captured"),
1664
- );
1665
- }
1666
- }
1667
- team_agent::state::persist::save_runtime_state(ws, &state).unwrap();
1668
- }
1669
-
1670
- fn seed_healthy_coordinator(workspace: &Path) {
1671
- let workspace = team_agent::coordinator::WorkspacePath::new(workspace.to_path_buf());
1672
- let pid = team_agent::coordinator::Pid::new(std::process::id());
1673
- std::fs::create_dir_all(
1674
- team_agent::coordinator::coordinator_pid_path(&workspace)
1675
- .parent()
1676
- .unwrap(),
1677
- )
1678
- .unwrap();
1679
- team_agent::coordinator::write_coordinator_metadata(
1680
- &workspace,
1681
- pid,
1682
- team_agent::coordinator::MetadataSource::Boot,
1683
- )
1684
- .expect("write coordinator metadata");
1685
- std::fs::write(
1686
- team_agent::coordinator::coordinator_pid_path(&workspace),
1687
- pid.to_string(),
1688
- )
1689
- .expect("write coordinator pid");
1690
- }
1691
-
1692
- fn flag_value(argv: &[String], flag: &str) -> Option<String> {
1693
- argv.windows(2)
1694
- .find_map(|pair| (pair[0] == flag).then(|| pair[1].clone()))
1695
- }
1696
-
1697
- fn flag_values(argv: &[String], flag: &str) -> Vec<String> {
1698
- argv.windows(2)
1699
- .filter_map(|pair| (pair[0] == flag).then(|| pair[1].clone()))
1700
- .collect()
1701
- }
1702
-
1703
- struct EnvGuard {
1704
- previous: Vec<(&'static str, Option<String>)>,
1705
- _owned_paths: Vec<TempWorkspace>,
1706
- }
1707
-
1708
- impl EnvGuard {
1709
- fn set(values: &[(&'static str, &'static str)]) -> Self {
1710
- let mut owned_paths = Vec::new();
1711
- let mut resolved = values
1712
- .iter()
1713
- .map(|(key, value)| (*key, (*value).to_string()))
1714
- .collect::<Vec<_>>();
1715
- if !values.iter().any(|(key, _)| *key == "PATH") {
1716
- let shim = copilot_empty_mcp_list_shim("path-shim");
1717
- resolved.push(("PATH", shim.path().to_string_lossy().into_owned()));
1718
- owned_paths.push(shim);
1719
- }
1720
- Self::set_owned(resolved, owned_paths)
1721
- }
1722
-
1723
- fn set_owned(values: Vec<(&'static str, String)>, owned_paths: Vec<TempWorkspace>) -> Self {
1724
- let previous = values
1725
- .iter()
1726
- .map(|(key, _)| (*key, std::env::var(key).ok()))
1727
- .collect::<Vec<_>>();
1728
- for (key, value) in &values {
1729
- std::env::set_var(key, value);
1730
- }
1731
- Self {
1732
- previous,
1733
- _owned_paths: owned_paths,
1734
- }
1735
- }
1736
- }
1737
-
1738
- impl Drop for EnvGuard {
1739
- fn drop(&mut self) {
1740
- for (key, value) in self.previous.drain(..).rev() {
1741
- match value {
1742
- Some(value) => std::env::set_var(key, value),
1743
- None => std::env::remove_var(key),
1744
- }
1745
- }
1746
- }
1747
- }
1748
-
1749
- #[derive(Debug, Clone)]
1750
- struct RecordedSpawn {
1751
- argv: Vec<String>,
1752
- env: BTreeMap<String, String>,
1753
- window: String,
1754
- }
1755
-
1756
- #[derive(Default)]
1757
- struct RecordingTransport {
1758
- spawns: Mutex<Vec<RecordedSpawn>>,
1759
- session_present: Mutex<bool>,
1760
- panes: Mutex<Vec<PaneInfo>>,
1761
- }
1762
-
1763
- impl RecordingTransport {
1764
- fn new() -> Self {
1765
- Self::default()
1766
- }
1767
-
1768
- fn with_session_present() -> Self {
1769
- let transport = Self::default();
1770
- *transport.session_present.lock().unwrap() = true;
1771
- transport
1772
- }
1773
-
1774
- fn single_spawn(&self) -> RecordedSpawn {
1775
- let spawns = self.spawns.lock().unwrap();
1776
- assert_eq!(
1777
- spawns.len(),
1778
- 1,
1779
- "fixture should record one spawn; got {spawns:?}"
1780
- );
1781
- spawns[0].clone()
1782
- }
1783
- }
1784
-
1785
- impl Transport for RecordingTransport {
1786
- fn kind(&self) -> BackendKind {
1787
- BackendKind::Tmux
1788
- }
1789
-
1790
- fn spawn_first(
1791
- &self,
1792
- session: &SessionName,
1793
- window: &WindowName,
1794
- argv: &[String],
1795
- _cwd: &Path,
1796
- env: &BTreeMap<String, String>,
1797
- ) -> Result<SpawnResult, TransportError> {
1798
- let mut spawns = self.spawns.lock().unwrap();
1799
- spawns.push(RecordedSpawn {
1800
- argv: argv.to_vec(),
1801
- env: env.clone(),
1802
- window: window.as_str().to_string(),
1803
- });
1804
- *self.session_present.lock().unwrap() = true;
1805
- let pane_id = PaneId::new(format!("%{}", spawns.len()));
1806
- self.panes.lock().unwrap().push(PaneInfo {
1807
- pane_id: pane_id.clone(),
1808
- session: session.clone(),
1809
- window_index: None,
1810
- window_name: Some(window.clone()),
1811
- pane_index: None,
1812
- tty: None,
1813
- current_command: None,
1814
- current_path: None,
1815
- active: false,
1816
- pane_pid: Some(30_000 + spawns.len() as u32),
1817
- leader_env: BTreeMap::new(),
1818
- });
1819
- Ok(SpawnResult {
1820
- pane_id,
1821
- session: session.clone(),
1822
- window: window.clone(),
1823
- child_pid: Some(30_000 + spawns.len() as u32),
1824
- })
1825
- }
1826
-
1827
- fn spawn_into(
1828
- &self,
1829
- session: &SessionName,
1830
- window: &WindowName,
1831
- argv: &[String],
1832
- cwd: &Path,
1833
- env: &BTreeMap<String, String>,
1834
- ) -> Result<SpawnResult, TransportError> {
1835
- self.spawn_first(session, window, argv, cwd, env)
1836
- }
1837
-
1838
- fn inject(
1839
- &self,
1840
- _target: &Target,
1841
- _payload: &InjectPayload,
1842
- _submit: Key,
1843
- _bracketed: bool,
1844
- ) -> Result<InjectReport, TransportError> {
1845
- Ok(InjectReport {
1846
- stage_reached: InjectStage::Submit,
1847
- inject_verification: InjectVerification::CaptureContainsToken,
1848
- submit_verification: SubmitVerification::EnterSentWithoutPlaceholderCheck,
1849
- turn_verification: TurnVerification::NotYetObserved,
1850
- attempts: 1,
1851
- submit_diagnostics: None,
1852
- })
1853
- }
1854
-
1855
- fn send_keys(&self, _target: &Target, _keys: &[Key]) -> Result<(), TransportError> {
1856
- Ok(())
1857
- }
1858
-
1859
- fn capture(
1860
- &self,
1861
- _target: &Target,
1862
- range: CaptureRange,
1863
- ) -> Result<CapturedText, TransportError> {
1864
- Ok(CapturedText {
1865
- text: "Claude Code\n> \nOpenAI Codex\ncodex>\nCopilot".to_string(),
1866
- range,
1867
- })
1868
- }
1869
-
1870
- fn query(&self, _target: &Target, field: PaneField) -> Result<Option<String>, TransportError> {
1871
- match field {
1872
- PaneField::PaneWidth => Ok(Some("120".to_string())),
1873
- _ => Ok(None),
1874
- }
1875
- }
1876
-
1877
- fn liveness(
1878
- &self,
1879
- _pane: &PaneId,
1880
- ) -> Result<team_agent::transport::PaneLiveness, TransportError> {
1881
- Ok(team_agent::transport::PaneLiveness::Live)
1882
- }
1883
-
1884
- fn list_targets(&self) -> Result<Vec<PaneInfo>, TransportError> {
1885
- Ok(self.panes.lock().unwrap().clone())
1886
- }
1887
-
1888
- fn has_session(&self, _session: &SessionName) -> Result<bool, TransportError> {
1889
- Ok(*self.session_present.lock().unwrap())
1890
- }
1891
-
1892
- fn list_windows(&self, _session: &SessionName) -> Result<Vec<WindowName>, TransportError> {
1893
- Ok(Vec::new())
1894
- }
1895
-
1896
- fn set_session_env(
1897
- &self,
1898
- _session: &SessionName,
1899
- _key: &str,
1900
- _value: &str,
1901
- ) -> Result<SetEnvOutcome, TransportError> {
1902
- Ok(SetEnvOutcome::Applied)
1903
- }
1904
-
1905
- fn kill_session(&self, _session: &SessionName) -> Result<(), TransportError> {
1906
- *self.session_present.lock().unwrap() = false;
1907
- self.panes
1908
- .lock()
1909
- .unwrap()
1910
- .retain(|pane| &pane.session != _session);
1911
- Ok(())
1912
- }
1913
-
1914
- fn kill_window(&self, target: &Target) -> Result<(), TransportError> {
1915
- self.panes.lock().unwrap().retain(|pane| match target {
1916
- Target::Pane(id) => &pane.pane_id != id,
1917
- Target::SessionWindow { session, window } => {
1918
- &pane.session != session || pane.window_name.as_ref() != Some(window)
1919
- }
1920
- });
1921
- Ok(())
1922
- }
1923
-
1924
- fn attach_session(&self, _session: &SessionName) -> Result<AttachOutcome, TransportError> {
1925
- Ok(AttachOutcome::Attached)
1926
- }
1927
- }
1928
-
1929
- fn tmp_ws(tag: &str) -> TempWorkspace {
1930
- sweep_stale_copilot_tmp_roots();
1931
- TempWorkspace::new(COPILOT_TMP_PREFIX, tag)
1932
- }
1933
-
1934
- fn copilot_empty_mcp_list_shim(tag: &str) -> TempWorkspace {
1935
- let bin = tmp_ws(tag);
1936
- std::fs::write(
1937
- bin.join("copilot"),
1938
- "#!/bin/sh\nif [ \"$1\" = \"mcp\" ] && [ \"$2\" = \"list\" ]; then\n exit 0\nfi\nexit 0\n",
1939
- )
1940
- .unwrap();
1941
- #[cfg(unix)]
1942
- {
1943
- use std::os::unix::fs::PermissionsExt;
1944
- // Only the explicit owned caller needs tmux; no provider is exposed by
1945
- // this symlink and the worker transport remains the recording fixture.
1946
- std::os::unix::fs::symlink(hermetic_guard::fixture_tmux_binary(), bin.join("tmux")).unwrap();
1947
- // coordinator health needs the seeded test PID's real non-zombie status.
1948
- // Keep PATH isolated and refuse any broader process inspection.
1949
- std::fs::write(
1950
- bin.join("ps"),
1951
- format!(
1952
- "#!/bin/sh\nif [ \"$#\" = 4 ] && [ \"$1\" = -p ] && [ \"$2\" = {} ] && [ \"$3\" = -o ] && [ \"$4\" = stat= ]; then\n exec /bin/ps \"$@\"\nfi\nexit 1\n",
1953
- std::process::id(),
1954
- ),
1955
- )
1956
- .unwrap();
1957
- std::fs::set_permissions(bin.join("ps"), std::fs::Permissions::from_mode(0o755)).unwrap();
1958
- std::fs::set_permissions(bin.join("copilot"), std::fs::Permissions::from_mode(0o755))
1959
- .unwrap();
1960
- }
1961
- bin
1962
- }
1963
-
1964
- fn copilot_tmp_search_roots() -> Vec<PathBuf> {
1965
- let mut seen = BTreeSet::new();
1966
- let mut roots = Vec::new();
1967
- for root in [std::env::temp_dir(), PathBuf::from("/private/tmp")] {
1968
- if !root.is_dir() {
1969
- continue;
1970
- }
1971
- let canonical = std::fs::canonicalize(&root).unwrap_or(root);
1972
- if seen.insert(canonical.clone()) {
1973
- roots.push(canonical);
1974
- }
1975
- }
1976
- roots
1977
- }
1978
-
1979
- fn copilot_tmp_entries() -> Vec<PathBuf> {
1980
- let mut out = Vec::new();
1981
- for root in copilot_tmp_search_roots() {
1982
- let Ok(entries) = std::fs::read_dir(root) else {
1983
- continue;
1984
- };
1985
- for entry in entries.flatten() {
1986
- let path = entry.path();
1987
- let Ok(file_type) = entry.file_type() else {
1988
- continue;
1989
- };
1990
- if !file_type.is_dir() {
1991
- continue;
1992
- }
1993
- let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1994
- continue;
1995
- };
1996
- if name.starts_with("ta-rs-copilot-") {
1997
- out.push(path);
1998
- }
1999
- }
2000
- }
2001
- out
2002
- }
2003
-
2004
- fn sweep_stale_copilot_tmp_roots() {
2005
- for path in copilot_tmp_entries() {
2006
- if copilot_tmp_path_has_dead_owner_pid(&path) {
2007
- let _ = std::fs::remove_dir_all(path);
2008
- }
2009
- }
2010
- }
2011
-
2012
- fn copilot_tmp_path_has_dead_owner_pid(path: &Path) -> bool {
2013
- let Some(pid) = path
2014
- .file_name()
2015
- .and_then(|name| name.to_str())
2016
- .and_then(copilot_tmp_pid_from_name)
2017
- else {
2018
- return false;
2019
- };
2020
- pid != std::process::id() && !pid_is_live(pid)
2021
- }
2022
-
2023
- fn copilot_tmp_pid_from_name(name: &str) -> Option<u32> {
2024
- if !name.starts_with("ta-rs-copilot-") {
2025
- return None;
2026
- }
2027
- name.rsplit('-').nth(1)?.parse().ok()
2028
- }
2029
-
2030
- fn pid_is_live(pid: u32) -> bool {
2031
- !matches!(
2032
- crate::platform::process::pid_liveness(pid),
2033
- Ok(crate::platform::process::ProcessLiveness::Dead)
2034
- )
2035
- }