@team-agent/installer 0.5.127 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/README.md +15 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +41 -26
  5. package/skills/team-agent/command-coverage.json +170 -184
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +66 -32
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +66 -32
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1298
  15. package/crates/team-agent/src/cli/arguments.rs +0 -401
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1675
  18. package/crates/team-agent/src/cli/emit.rs +0 -2898
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1189
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -821
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -691
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6528
  29. package/crates/team-agent/src/cli/models.rs +0 -449
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  34. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  35. package/crates/team-agent/src/cli/send/persist.rs +0 -192
  36. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  37. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  38. package/crates/team-agent/src/cli/send.rs +0 -201
  39. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  40. package/crates/team-agent/src/cli/spec.rs +0 -159
  41. package/crates/team-agent/src/cli/status.rs +0 -280
  42. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  43. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  44. package/crates/team-agent/src/cli/status_port/brief.rs +0 -2043
  45. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  46. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  47. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  48. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  49. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  50. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  51. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  52. package/crates/team-agent/src/cli/status_port.rs +0 -92
  53. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  54. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  55. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  56. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -372
  57. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  58. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  59. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  60. package/crates/team-agent/src/cli/tests/named_address.rs +0 -760
  61. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  62. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -481
  63. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  64. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  65. package/crates/team-agent/src/cli/tests/status_send.rs +0 -1091
  66. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  67. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  68. package/crates/team-agent/src/cli/triage.rs +0 -234
  69. package/crates/team-agent/src/cli/types.rs +0 -591
  70. package/crates/team-agent/src/codex_app_server.rs +0 -546
  71. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  72. package/crates/team-agent/src/compiler/tests.rs +0 -842
  73. package/crates/team-agent/src/compiler.rs +0 -691
  74. package/crates/team-agent/src/conpty/backend.rs +0 -829
  75. package/crates/team-agent/src/conpty/mod.rs +0 -33
  76. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1610
  77. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  78. package/crates/team-agent/src/contract_runtime/config.rs +0 -354
  79. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -56
  80. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -438
  81. package/crates/team-agent/src/contract_runtime/fork.rs +0 -368
  82. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  83. package/crates/team-agent/src/contract_runtime/framework.rs +0 -350
  84. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -399
  85. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  86. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  87. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  88. package/crates/team-agent/src/contract_runtime/registry.rs +0 -589
  89. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  90. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  91. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  92. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  93. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  94. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  95. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  96. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  97. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  98. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  99. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  101. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  102. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  104. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  105. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  106. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -338
  107. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  108. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  109. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  110. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -461
  111. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  112. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  113. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  114. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  115. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  116. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  117. package/crates/team-agent/src/coordinator/tick.rs +0 -3112
  118. package/crates/team-agent/src/coordinator/types.rs +0 -540
  119. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  120. package/crates/team-agent/src/db/message_store.rs +0 -1585
  121. package/crates/team-agent/src/db/migration.rs +0 -984
  122. package/crates/team-agent/src/db/mod.rs +0 -26
  123. package/crates/team-agent/src/db/schema.rs +0 -663
  124. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  125. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  126. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  127. package/crates/team-agent/src/event_log.rs +0 -502
  128. package/crates/team-agent/src/fake_worker.rs +0 -303
  129. package/crates/team-agent/src/kill_audit.rs +0 -106
  130. package/crates/team-agent/src/layout/manager.rs +0 -248
  131. package/crates/team-agent/src/layout/mod.rs +0 -36
  132. package/crates/team-agent/src/layout/overlay.rs +0 -134
  133. package/crates/team-agent/src/layout/placement.rs +0 -52
  134. package/crates/team-agent/src/layout/recovery.rs +0 -106
  135. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  136. package/crates/team-agent/src/layout/sessions.rs +0 -294
  137. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  138. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  139. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  140. package/crates/team-agent/src/leader/helpers.rs +0 -178
  141. package/crates/team-agent/src/leader/incident.rs +0 -6
  142. package/crates/team-agent/src/leader/lease.rs +0 -3356
  143. package/crates/team-agent/src/leader/mod.rs +0 -104
  144. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  145. package/crates/team-agent/src/leader/prompt.rs +0 -905
  146. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  147. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  148. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  149. package/crates/team-agent/src/leader/registry.rs +0 -883
  150. package/crates/team-agent/src/leader/start.rs +0 -4500
  151. package/crates/team-agent/src/leader/takeover.rs +0 -65
  152. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  153. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  154. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  155. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  156. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  157. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  158. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  159. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  160. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  161. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  162. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -267
  163. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  164. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  165. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  166. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  167. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  168. package/crates/team-agent/src/leader/types.rs +0 -534
  169. package/crates/team-agent/src/lib.rs +0 -145
  170. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  171. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -848
  172. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -393
  173. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  174. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -178
  175. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -82
  176. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -63
  177. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  178. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  179. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  180. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -152
  181. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  182. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -629
  183. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -226
  184. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  185. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5176
  186. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  187. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  188. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  189. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -450
  190. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  191. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  192. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  193. package/crates/team-agent/src/lifecycle/launch.rs +0 -534
  194. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  195. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  196. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  197. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -757
  198. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  199. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2198
  200. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2052
  201. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  202. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  203. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  204. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  205. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  206. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  207. package/crates/team-agent/src/lifecycle/restart.rs +0 -223
  208. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1205
  209. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  210. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  211. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  212. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  213. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  214. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -135
  215. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1415
  216. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  217. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -396
  218. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -418
  219. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2039
  220. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1298
  221. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  222. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  223. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  224. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -71
  225. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  226. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  227. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -472
  228. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  229. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  230. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  231. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3981
  232. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  233. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  234. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  235. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  236. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  237. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  238. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -152
  239. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -182
  240. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -374
  241. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -546
  242. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -31
  243. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -528
  244. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -134
  245. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -333
  246. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  247. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  248. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  249. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  250. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  251. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  252. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  253. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  254. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  255. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  256. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  257. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  258. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -90
  259. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  260. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  261. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  262. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  263. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  264. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  265. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  266. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -996
  267. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -827
  268. package/crates/team-agent/src/lifecycle/tests.rs +0 -102
  269. package/crates/team-agent/src/lifecycle/types.rs +0 -861
  270. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -370
  271. package/crates/team-agent/src/main.rs +0 -52
  272. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  273. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  274. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  275. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  276. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  277. package/crates/team-agent/src/mcp_server/readiness.rs +0 -546
  278. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -369
  279. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  280. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  281. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -168
  282. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -388
  283. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -343
  284. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  285. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  286. package/crates/team-agent/src/mcp_server/tools.rs +0 -1015
  287. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  288. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  289. package/crates/team-agent/src/messaging/activity.rs +0 -461
  290. package/crates/team-agent/src/messaging/address.rs +0 -87
  291. package/crates/team-agent/src/messaging/delivery.rs +0 -3785
  292. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  293. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  294. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  295. package/crates/team-agent/src/messaging/helpers.rs +0 -354
  296. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  297. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  298. package/crates/team-agent/src/messaging/mod.rs +0 -166
  299. package/crates/team-agent/src/messaging/persist.rs +0 -377
  300. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  301. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  302. package/crates/team-agent/src/messaging/results.rs +0 -1415
  303. package/crates/team-agent/src/messaging/scheduler.rs +0 -217
  304. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  305. package/crates/team-agent/src/messaging/send.rs +0 -981
  306. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  307. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -551
  308. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  309. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  310. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  311. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  312. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  313. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3655
  314. package/crates/team-agent/src/messaging/tests/spine.rs +0 -837
  315. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  316. package/crates/team-agent/src/messaging/trust.rs +0 -215
  317. package/crates/team-agent/src/messaging/types.rs +0 -471
  318. package/crates/team-agent/src/messaging/wait.rs +0 -366
  319. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  320. package/crates/team-agent/src/model/enums.rs +0 -356
  321. package/crates/team-agent/src/model/errors.rs +0 -18
  322. package/crates/team-agent/src/model/ids.rs +0 -165
  323. package/crates/team-agent/src/model/mod.rs +0 -29
  324. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  325. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  326. package/crates/team-agent/src/model/paths.rs +0 -257
  327. package/crates/team-agent/src/model/routing.rs +0 -387
  328. package/crates/team-agent/src/model/spec.rs +0 -1184
  329. package/crates/team-agent/src/model/task_graph.rs +0 -321
  330. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  331. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  332. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  333. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  334. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  335. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  336. package/crates/team-agent/src/model/yaml.rs +0 -802
  337. package/crates/team-agent/src/os_probe.rs +0 -280
  338. package/crates/team-agent/src/packaging/install.rs +0 -219
  339. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  340. package/crates/team-agent/src/packaging/mod.rs +0 -91
  341. package/crates/team-agent/src/packaging/repair.rs +0 -33
  342. package/crates/team-agent/src/packaging/tests.rs +0 -822
  343. package/crates/team-agent/src/packaging/types.rs +0 -417
  344. package/crates/team-agent/src/platform/argv.rs +0 -331
  345. package/crates/team-agent/src/platform/errors.rs +0 -104
  346. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  347. package/crates/team-agent/src/platform/mod.rs +0 -5
  348. package/crates/team-agent/src/platform/process.rs +0 -545
  349. package/crates/team-agent/src/provider/adapter.rs +0 -898
  350. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  351. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  352. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  353. package/crates/team-agent/src/provider/adapters/mod.rs +0 -28
  354. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  355. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  356. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  357. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  358. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  359. package/crates/team-agent/src/provider/classify.rs +0 -773
  360. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  361. package/crates/team-agent/src/provider/faults.rs +0 -165
  362. package/crates/team-agent/src/provider/helpers.rs +0 -52
  363. package/crates/team-agent/src/provider/mod.rs +0 -78
  364. package/crates/team-agent/src/provider/model_catalog.rs +0 -722
  365. package/crates/team-agent/src/provider/session/capture.rs +0 -2631
  366. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -168
  367. package/crates/team-agent/src/provider/session/context_fork.rs +0 -264
  368. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  369. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  370. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  371. package/crates/team-agent/src/provider/session_scan/common.rs +0 -618
  372. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  373. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -152
  374. package/crates/team-agent/src/provider/session_scan.rs +0 -61
  375. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  376. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  377. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  378. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  379. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  380. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  381. package/crates/team-agent/src/provider/tests/adapter.rs +0 -354
  382. package/crates/team-agent/src/provider/tests/classify.rs +0 -201
  383. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -26
  384. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  385. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  386. package/crates/team-agent/src/provider/tests/idle.rs +0 -140
  387. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  388. package/crates/team-agent/src/provider/tests.rs +0 -32
  389. package/crates/team-agent/src/provider/types.rs +0 -529
  390. package/crates/team-agent/src/provider/wire.rs +0 -406
  391. package/crates/team-agent/src/redaction.rs +0 -259
  392. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  393. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  394. package/crates/team-agent/src/state/identity.rs +0 -914
  395. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  396. package/crates/team-agent/src/state/mod.rs +0 -74
  397. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  398. package/crates/team-agent/src/state/ownership.rs +0 -563
  399. package/crates/team-agent/src/state/paths.rs +0 -395
  400. package/crates/team-agent/src/state/persist.rs +0 -3811
  401. package/crates/team-agent/src/state/projection.rs +0 -1508
  402. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  403. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  404. package/crates/team-agent/src/state/repository.rs +0 -866
  405. package/crates/team-agent/src/state/selector.rs +0 -160
  406. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  407. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  408. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  409. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  410. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  411. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4254
  412. package/crates/team-agent/src/tmux_backend.rs +0 -4527
  413. package/crates/team-agent/src/topology.rs +0 -537
  414. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  415. package/crates/team-agent/src/transport/native_input.rs +0 -491
  416. package/crates/team-agent/src/transport/test_support.rs +0 -743
  417. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  418. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  419. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  420. package/crates/team-agent/src/transport.rs +0 -1655
  421. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,2898 +0,0 @@
1
- //!
2
- //! cli · emit — `emit`(--json vs 人读 dict 逐键)+ 顶层 `run` 调度(parser.py `main`)+
3
- //! 人读标量/集合渲染(`human_value` / `json_dumps_like`)。
4
-
5
- use super::models::cmd_models;
6
- use super::spec::{command_spec, CommandKind, COMMAND_SPECS};
7
- #[cfg(test)]
8
- use super::spec::{CommandTier, ALL_DISPATCH_KINDS};
9
- use super::*;
10
- use std::io::{ErrorKind, Write as _};
11
-
12
- ///
13
- /// `emit`(`helpers.py:12-23`):`--json`→`json.dumps(indent=2, ensure_ascii=False, sort_keys=True)`;
14
- /// 否则 dict 逐键 `key: value`(嵌套 dict/list 内联 compact json,`ensure_ascii=False`)、非 dict 直接 print。
15
- /// 返回应打印到 stdout 的字符串(bin main 负责实际 println)。
16
- pub fn emit(output: &CmdOutput, as_json: bool) -> Option<String> {
17
- emit_with_json_order(output, as_json, false)
18
- }
19
-
20
- fn emit_with_json_order(
21
- output: &CmdOutput,
22
- as_json: bool,
23
- preserve_json_order: bool,
24
- ) -> Option<String> {
25
- match output {
26
- CmdOutput::None => None,
27
- CmdOutput::Human(text) => Some(crate::redaction::redact_external_text(text)),
28
- CmdOutput::Json(value) => {
29
- let value = crate::redaction::redact_external_value(value);
30
- if as_json {
31
- return if preserve_json_order {
32
- serde_json::to_string_pretty(&value).ok()
33
- } else {
34
- serde_json::to_string_pretty(&sort_json(&value)).ok()
35
- };
36
- }
37
- if let Value::Object(obj) = value {
38
- let lines: Vec<String> = obj
39
- .iter()
40
- .map(|(key, value)| format!("{key}: {}", human_value(value)))
41
- .collect();
42
- Some(lines.join("\n"))
43
- } else {
44
- Some(human_value(&value))
45
- }
46
- }
47
- }
48
- }
49
-
50
- ///
51
- /// `main(argv)`(`parser.py:84`):**CLI 唯一进程入口**。codex/claude/copilot/grok passthrough 早返回 →
52
- /// 解析 argv 到 subcommand → 调对应 handler → 异常落盘 + 信封 + `ExitCode::Error` →
53
- /// `consume_leader_inbox_summary` → `emit` → `result.ok is False ? Error : Ok`。
54
- /// **行为入口**:契约可端到端跑 argv→(stdout, exit code)。
55
- pub fn run(argv: &[String], cwd: &Path) -> ExitCode {
56
- let Some(command) = argv.first().map(String::as_str) else {
57
- println!("{}", default_help());
58
- return ExitCode::Ok;
59
- };
60
- if command == "route" {
61
- return super::route::run(&argv[1..]);
62
- }
63
- if command == "leader-prompt" {
64
- return super::leader_prompt::run(&argv[1..]);
65
- }
66
- if is_leader_passthrough_command(command) {
67
- return match cmd_leader_passthrough(command, &argv[1..], cwd) {
68
- Ok(result) => emit_result(result),
69
- Err(error) => emit_cli_error(command, &argv[1..], cwd, &error),
70
- };
71
- }
72
- if matches!(command, "-h" | "--help" | "help") {
73
- println!("{}", command_help(None));
74
- return ExitCode::Ok;
75
- }
76
- if matches!(command, "-V" | "--version") {
77
- println!("team-agent {}", env!("CARGO_PKG_VERSION"));
78
- return ExitCode::Ok;
79
- }
80
- if let Some(result) = super::intent::run(command, &argv[1..], cwd) {
81
- return match result {
82
- Ok(result) => emit_result(result),
83
- Err(error) => emit_cli_error_for_command(command, &argv[1..], cwd, &error),
84
- };
85
- }
86
- // Classify syntax/scope errors before dispatch; contextual status refusals
87
- // retain their existing stderr-only contract. Resolve the scope only once.
88
- if is_machine_command(command)
89
- || matches!(command_spec(command).map(|spec| spec.kind), Some(CommandKind::Dispatch(_)))
90
- {
91
- let checked = match prepare_control_args(command, &argv[1..], cwd) {
92
- Ok(checked) => checked,
93
- Err(error) => return emit_parser_usage(command, &argv[1..], &error),
94
- };
95
- let error_args = checked.tokens.clone();
96
- return match dispatch_prepared(command, checked, cwd) {
97
- Ok(exit) => exit,
98
- Err(error) => emit_cli_error_for_command(command, &error_args, cwd, &error),
99
- };
100
- }
101
- match dispatch(command, &argv[1..], cwd) {
102
- Ok(exit) => exit,
103
- Err(error) => emit_cli_error_for_command(command, &argv[1..], cwd, &error),
104
- }
105
- }
106
-
107
- fn emit_cli_error_for_command(
108
- command: &str,
109
- args: &[String],
110
- cwd: &Path,
111
- error: &CliError,
112
- ) -> ExitCode {
113
- let missing_input = matches!(error, CliError::Usage(message) if message.starts_with("missing ") || message.starts_with("Provide ") || matches!(message.as_str(), "add-agent requires --provider <name>" | "add-agent requires --bypass <true|false>" | "--source is required unless --uninstall"));
114
- if command_spec(command).is_some() && missing_input {
115
- let help = command_help(Some(command));
116
- let explanation = match error {
117
- CliError::Usage(message) => match message.as_str() {
118
- "missing agent" | "missing source_agent" => "Provide an agent name.".to_string(),
119
- "missing profile command" => {
120
- "Provide a profile operation: init, doctor or show.".to_string()
121
- }
122
- "missing profile name" => "Provide an authentication/proxy profile name.".to_string(),
123
- "add-agent requires --provider <name>" => {
124
- "Select a provider with --provider, or supply a role file with --role-file.".to_string()
125
- }
126
- "add-agent requires --bypass <true|false>" => {
127
- "Explicitly retain permission prompts with --bypass false, or declare bypass in the role file.".to_string()
128
- }
129
- other => other
130
- .strip_prefix("missing ")
131
- .map(|field| format!("Provide the required argument: {field}."))
132
- .unwrap_or_else(|| other.to_string()),
133
- },
134
- _ => error.to_string(),
135
- };
136
- if super::arguments::has_flag(command, args, "--json") {
137
- let payload = error.to_payload(Path::new(""), command);
138
- let mut value = serde_json::to_value(payload)
139
- .unwrap_or_else(|_| serde_json::json!({"ok": false, "error": error.to_string()}));
140
- value["error"] = serde_json::json!(explanation);
141
- value["action"] = serde_json::json!(format!("team-agent {command} --help"));
142
- value["next_actions"] = serde_json::json!([format!(
143
- "Complete the required arguments using the Examples in team-agent {command} --help"
144
- )]);
145
- println!("{}", python_compact_json(&value));
146
- } else {
147
- eprintln!("{explanation}\n\n{help}");
148
- }
149
- ExitCode::Usage
150
- } else if command == "status" {
151
- emit_status_cli_error(error)
152
- } else if matches!(error, CliError::Usage(_)) {
153
- emit_parser_usage(command, args, error)
154
- } else {
155
- emit_cli_error(command, args, cwd, error)
156
- }
157
- }
158
-
159
- #[cfg(test)]
160
- pub(crate) fn __test_runtime_error_emitter(command: &str, cwd: &Path, error: &CliError) -> ExitCode {
161
- emit_cli_error(command, &[], cwd, error)
162
- }
163
-
164
- fn emit_status_cli_error(error: &CliError) -> ExitCode {
165
- let normalized = normalize_cli_error(error);
166
- let payload_error = normalized.as_ref().unwrap_or(error);
167
- let safe_error = crate::redaction::redact_external_text(&payload_error.to_string());
168
- eprintln!("error: {safe_error}");
169
- ExitCode::Error
170
- }
171
-
172
- /// Print a handler's CmdResult to stdout (emit formats json/human), then surface its exit code.
173
- /// (parser.py: `print(emit(result, as_json))` then the ok→exit mapping.)
174
- pub(super) fn emit_result(r: CmdResult) -> ExitCode {
175
- let persisted_message_id = match &r.output {
176
- CmdOutput::Json(value) => value
177
- .get("message_id")
178
- .and_then(Value::as_str)
179
- .map(ToString::to_string),
180
- _ => None,
181
- };
182
- if let Some(text) = emit_with_json_order(&r.output, r.as_json, r.preserve_json_order) {
183
- if let Err(error) = write_stdout_line(&text) {
184
- if let Some(message_id) = persisted_message_id {
185
- let stderr = std::io::stderr();
186
- let mut stderr = stderr.lock();
187
- let _ = writeln!(
188
- stderr,
189
- "Output unavailable; the message was persisted with message_id={message_id}. Use team-agent inbox leader -n 3 for replies; do not resend."
190
- );
191
- }
192
- return if error.kind() == ErrorKind::BrokenPipe {
193
- r.exit
194
- } else {
195
- ExitCode::Error
196
- };
197
- }
198
- }
199
- r.exit
200
- }
201
-
202
- fn write_stdout_line(text: &str) -> std::io::Result<()> {
203
- let stdout = std::io::stdout();
204
- let mut stdout = stdout.lock();
205
- stdout.write_all(text.as_bytes())?;
206
- stdout.write_all(b"\n")
207
- }
208
-
209
- #[cfg(test)]
210
- pub(crate) fn __test_dispatch(
211
- command: &str,
212
- args: &[String],
213
- cwd: &Path,
214
- ) -> Result<ExitCode, CliError> {
215
- dispatch(command, args, cwd)
216
- }
217
-
218
- fn dispatch(command: &str, args: &[String], cwd: &Path) -> Result<ExitCode, CliError> {
219
- if command == "route" {
220
- return Ok(super::route::run(args));
221
- }
222
- if command == "leader-prompt" {
223
- return Ok(super::leader_prompt::run(args));
224
- }
225
- if let Some(result) = super::intent::run(command, args, cwd) {
226
- return result.map(emit_result);
227
- }
228
- let machine = is_machine_command(command);
229
- if !machine && !matches!(command_spec(command).map(|spec| spec.kind), Some(CommandKind::Dispatch(_))) {
230
- return Ok(emit_unknown_subcommand_usage(command));
231
- }
232
- dispatch_prepared(command, prepare_control_args(command, args, cwd)?, cwd)
233
- }
234
-
235
- fn prepare_control_args(command: &str, args: &[String], cwd: &Path) -> Result<super::arguments::CheckedArgs, CliError> {
236
- let mut checked = super::arguments::parse(command, args)?;
237
- if !checked.help { checked.tokens = resolve_command_scope(command, checked.tokens, cwd)?; }
238
- Ok(checked)
239
- }
240
-
241
- fn dispatch_prepared(command: &str, checked: super::arguments::CheckedArgs, cwd: &Path) -> Result<ExitCode, CliError> {
242
- let machine = is_machine_command(command);
243
- if checked.help {
244
- if machine {
245
- eprintln!("{HUMAN_NAVIGATION}");
246
- return Ok(ExitCode::Usage);
247
- }
248
- println!("{}", command_help(Some(command)));
249
- return Ok(ExitCode::Ok);
250
- }
251
- let args = checked.tokens.as_slice();
252
- if machine { return dispatch_machine(command, args, cwd); }
253
- if args.iter().all(|arg| arg == "--json")
254
- && matches!(
255
- command,
256
- "send"
257
- | "inbox"
258
- | "add-agent"
259
- | "start-agent"
260
- | "stop-agent"
261
- | "reset-agent"
262
- | "clone-agent"
263
- | "fork-agent"
264
- | "remove-agent"
265
- | "profile"
266
- )
267
- {
268
- return Err(CliError::Usage(
269
- "Provide the agent name, task message or required command settings; see Usage and Examples below".to_string(),
270
- ));
271
- }
272
- match command {
273
- "quick-start" => cmd_quick_start(&quick_start_args(args, cwd)?).map(emit_result),
274
- "send" => cmd_send(&send_args(args, cwd)?).map(emit_result),
275
- "status" => cmd_status_for_team(&status_args(args, cwd), parse_args(args).team.as_deref())
276
- .map(emit_result),
277
- "shutdown" => cmd_shutdown(&shutdown_args(args, cwd)?).map(emit_result),
278
- "restart" => cmd_restart(&restart_args(args, cwd)?).map(emit_result),
279
- "start-agent" => cmd_start_agent(&start_agent_args(args, cwd)?).map(emit_result),
280
- "stop-agent" => cmd_stop_agent(&stop_agent_args(args, cwd)?).map(emit_result),
281
- "reset-agent" => cmd_reset_agent(&reset_agent_args(args, cwd)?).map(emit_result),
282
- "add-agent" => cmd_add_agent(&add_agent_args(args, cwd)?).map(emit_result),
283
- "clone-agent" => cmd_clone_agent(&clone_agent_args(args, cwd)?).map(emit_result),
284
- "fork-agent" => cmd_fork_agent(&fork_agent_args(args, cwd)?).map(emit_result),
285
- "remove-agent" => cmd_remove_agent(&remove_agent_args(args, cwd)?).map(emit_result),
286
- "takeover" => cmd_takeover(&takeover_args(args, cwd)).map(emit_result),
287
- "claim-leader" => cmd_claim_leader(&claim_leader_args(args, cwd)).map(emit_result),
288
- // Real dispatch: `cmd_attach_leader` writes the `leader_receiver` binding.
289
- "attach-leader" => cmd_attach_leader(&attach_leader_args(args, cwd)?).map(emit_result),
290
-
291
- "approvals" => cmd_approvals(&approvals_args(args, cwd)).map(emit_result),
292
- "inbox" => cmd_inbox(&inbox_args(args, cwd)?).map(emit_result),
293
- "doctor" => cmd_doctor(&doctor_args(args, cwd)).map(emit_result),
294
-
295
- // 0.5.9 E7 host-leader-registry: `leaders` is the host-level derived
296
- // discovery command. It reads ~/.team-agent/leaders, validates each
297
- // entry against canonical state, and reports LIVE/STALE/AMBIGUOUS
298
- // status. `--to-leader NAME` on `send` uses the same registry to
299
- // resolve short/qualified/hash-qualified names to a canonical
300
- // (workspace, team_key) tuple and delegates to the E6 named-leader
301
- // delivery path — no separate route authority.
302
- "leaders" => cmd_leaders(&leaders_args(args, cwd)?).map(emit_result),
303
- "models" => cmd_models(&models_args(args)?).map(emit_result),
304
- "kiro" => Ok(emit_result(cmd_kiro_leader(args))),
305
-
306
- "install-skill" => cmd_install_skill(&install_skill_args(args)?).map(emit_result),
307
- "profile" => cmd_profile(&profile_args(args, cwd)?).map(emit_result),
308
-
309
- _ => Ok(emit_unknown_subcommand_usage(command)),
310
- }
311
- }
312
-
313
- // Script compatibility is deliberately outside the human catalog and suggestions.
314
- fn is_machine_command(command: &str) -> bool {
315
- matches!(command, "wait" | "coordinator" | "attach-app-server-leader")
316
- }
317
-
318
- fn dispatch_machine(command: &str, args: &[String], cwd: &Path) -> Result<ExitCode, CliError> {
319
- match command {
320
- "wait" => cmd_wait(&wait_args(args, cwd)?).map(emit_result),
321
- "coordinator" => run_coordinator(args, cwd),
322
- "attach-app-server-leader" => {
323
- cmd_attach_app_server_leader(&attach_app_server_leader_args(args, cwd)?)
324
- .map(emit_result)
325
- }
326
- _ => Ok(emit_unknown_subcommand_usage(command)),
327
- }
328
- }
329
-
330
- // Command grammar, not provider identity parsing: these are top-level CLI
331
- // passthrough verbs for starting a leader under a provider executable.
332
- const LEADER_PASSTHROUGH_COMMANDS: &[&str] =
333
- &["codex", "claude", "copilot", "grok", "pi"];
334
-
335
- pub(crate) fn is_leader_passthrough_command(command: &str) -> bool {
336
- LEADER_PASSTHROUGH_COMMANDS.contains(&command)
337
- && matches!(
338
- command_spec(command).map(|spec| spec.kind),
339
- Some(CommandKind::LeaderPassthrough { .. })
340
- )
341
- }
342
-
343
- /// Registered subcommands (the dispatch table) plus spec-only verbs that have no
344
- /// dispatch arm yet but must still respond to `--help` per CR-063/G4.
345
- /// Used by the `--help` short-circuit gate so unknown commands keep falling through
346
- /// to the argparse invalid-choice path.
347
- fn is_known_subcommand(command: &str) -> bool {
348
- command_spec(command).is_some_and(|spec| spec.command_help)
349
- }
350
-
351
- pub(crate) fn default_help() -> String {
352
- let mut out = String::from("Team Agent: create a team, send tasks, read replies and shut down safely.\n\n1. Prepare agents\n Prepare TEAM.md and agents/*.md with explicit provider and bypass decisions; use --from for an external source.\n2. Open a leader and create the team\n With Pi installed and signed in, run team-agent pi.\n Run team-agent start in that leader's tool context. Verified live members stay unchanged; stopped members are started.\n Use team restart for a deliberate restart (session auto); legacy bare restart retains preserve. Do not take over or delete an existing team.\n3. Send tasks and read replies\n team-agent send worker 'Calculate 245 * 37 and reply to the leader.'\n team-agent inbox leader -n 3\n team-agent status\n Sending is not completion; wait for an actual reply.\n4. Diagnose and stop\n team-agent doctor --workspace .\n team-agent stop --workspace . --json\n Verify this team's residual resources are empty, then diagnose the selected workspace.\n\nSelect workspace/team scope with --workspace/--team. Discover model names with models.\nWindows ConPTY requires a Windows host and an installed shim; tmux commands are not a generic Windows path.\n");
353
- append_help_section(
354
- &mut out,
355
- "Getting started",
356
- &["start", "quick-start", "send", "status", "models", "inbox"],
357
- );
358
- append_help_section(&mut out, "Team lifecycle", &["stop", "team", "restart", "shutdown"]);
359
- append_help_section(
360
- &mut out,
361
- "Agent lifecycle",
362
- &[
363
- "agent",
364
- "add-agent",
365
- "start-agent",
366
- "stop-agent",
367
- "reset-agent",
368
- "clone-agent",
369
- "fork-agent",
370
- "remove-agent",
371
- ],
372
- );
373
- append_help_section(
374
- &mut out,
375
- "Observation and collaboration",
376
- &["leaders", "doctor", "approvals"],
377
- );
378
- append_help_section(
379
- &mut out,
380
- "Configuration",
381
- &["route", "leader-prompt", "profile", "install-skill"],
382
- );
383
- append_help_section(
384
- &mut out,
385
- "Guided recovery",
386
- &["claim-leader", "takeover", "attach-leader"],
387
- );
388
- append_help_section(
389
- &mut out,
390
- "Leader launch",
391
- &["pi", "codex", "claude", "copilot", "grok", "kiro"],
392
- );
393
- out.push_str("\nCommand arguments and examples: team-agent <command> --help");
394
- out
395
- }
396
-
397
- fn append_help_section(out: &mut String, title: &str, names: &[&str]) {
398
- out.push('\n');
399
- out.push_str(title);
400
- out.push_str(":\n");
401
- for name in names {
402
- if let Some(spec) = command_spec(name).filter(|spec| spec.default_help) {
403
- out.push_str(&format!(" {:<13} {}\n", spec.name, spec.summary));
404
- }
405
- }
406
- }
407
-
408
- ///
409
- /// Test-only public accessor for `command_help` — allows integration
410
- /// tests to grep the help copy without depending on internal parser
411
- /// machinery.
412
- pub fn __test_command_help(command: Option<&str>) -> String {
413
- command_help(command)
414
- }
415
-
416
- ///
417
- /// Test-only public accessor for `quick_start_args` — allows
418
- /// integration tests to exercise the parser without going through
419
- /// stdio + the full `main` entrypoint.
420
- pub fn __test_quick_start_args(
421
- args: &[String],
422
- cwd: &std::path::Path,
423
- ) -> Result<crate::cli::types::QuickStartArgs, crate::cli::CliError> {
424
- quick_start_args(args, cwd)
425
- }
426
-
427
- pub(super) const TEAM_TEMPLATE: &str =
428
- "---\nname: current\n---\nA small team for a command-line example.\n";
429
- pub(super) const WORKER_TEMPLATE: &str = "---\nname: worker\nrole: assistant\nprovider: pi\nmodel: openai-codex/gpt-6-luna\nauth_mode: subscription\ndangerously_skip_permissions: false\n---\nComplete the task and send a concise reply to the leader.\n";
430
- const HUMAN_NAVIGATION: &str = "Use team-agent --help to list available commands.";
431
-
432
- pub(super) fn command_help(command: Option<&str>) -> String {
433
- if let Some(name) = command.filter(|name| matches!(*name, "start" | "stop" | "team" | "agent")) {
434
- return super::intent::help(name);
435
- }
436
- let Some(name) = command else {
437
- return default_help();
438
- };
439
- let Some(spec) = command_spec(name) else {
440
- return HUMAN_NAVIGATION.to_string();
441
- };
442
- if name == "route" {
443
- return super::route::HELP.to_string();
444
- }
445
- if name == "leader-prompt" {
446
- return super::leader_prompt::HELP.to_string();
447
- }
448
- let (details, examples, next) = match name {
449
- "quick-start" => (
450
- "TEAMDIR contains TEAM.md and agents/; --workspace selects the runtime project.\n--name sets the team name; --team/--team-id selects the team; --yes retains compatibility; --detail includes full diagnostics.\nProviders must be installed and signed in. Declare provider/model/effort in role files; permission bypass defaults to false.\n--backend tmux is for POSIX; conpty requires a Windows host and an installed ConPTY shim.",
451
- "team-agent quick-start\nteam-agent quick-start ./roles --workspace ./project\nteam-agent quick-start . --json",
452
- "Compatibility bridge only. In the authorized Leader context, prefer team-agent start --from TEAMDIR for complete new configuration and team-agent start for later activation. Check models and native sign-in first; inspect status and actual replies after starting."),
453
- "send" => ("<agent> is an agent name from status; MESSAGE is the task text.\n--mailbox stores a message without injecting it into the current conversation; default delivery targets the agent conversation.",
454
- "team-agent send worker 'Calculate 245 * 37 and reply to the leader.'\nteam-agent send worker 'Review the changes' --workspace . --team help-demo\nteam-agent send worker 'Read this when next available' --mailbox",
455
- "Acceptance is not delivery or completion. Wait for an actual reply; use team-agent inbox leader -n 3. Diagnose with status/doctor rather than repeated sends."),
456
- "inbox" => ("<agent> is the recipient name; -n/--limit bounds the message count. Reading replies does not resend messages.",
457
- "team-agent inbox leader -n 3\nteam-agent inbox worker --limit 5\nteam-agent inbox leader --workspace . --team help-demo --json", "Wait for a natural reply, then check team-agent status if needed. Do not inspect worker terminal content."),
458
- "status" => ("Optional <agent> selects one agent. --summary/--detail retain compatibility and do not add fields.\nNine fields: name/provider/model/effort/runtime_status/activity/health/session_name/tmux_command.\nRuntime, activity and health are distinct. unknown means insufficient evidence; null means unset. No default model is guessed.",
459
- "team-agent status\nteam-agent status worker\nteam-agent status --workspace . --team help-demo --json", "Read replies with team-agent inbox leader -n 3; diagnose problems with team-agent doctor --workspace ."),
460
- "models" => ("--provider selects the provider, default pi. QUERY or --search performs keyword search; they are mutually exclusive.\nUse cursor (or cursor-agent, agent, cursor_agent) for the contract-native Cursor catalog. Copilot has no model discovery entrypoint here. Results come from the native catalog, not guesses.",
461
- "team-agent models --provider pi\nteam-agent models --provider pi --search luna\nteam-agent models --provider cursor --json", "Use the exact returned model in a role file or team-agent start AGENT --model MODEL; stop a running seat before changing its settings."),
462
- "restart" => ("restart AGENT and team restart default to --session auto; bare/explicit-path restart keeps preserve.\n--session preserve requires continuation evidence; auto permits only the original legal fresh fallback, not guaranteed saved memory.\n--dry-run plans without lifecycle effects. --allow-fresh is the legacy authorized opt-in; --session-converge-deadline is in seconds.",
463
- "team-agent restart worker --dry-run --json\nteam-agent restart worker --session preserve --workspace . --dry-run --json", "Use team-agent team restart for deliberate team recovery; choose --session preserve when context must be retained. Team restart leaves explicitly stopped/paused seats alone; team-agent start intentionally activates the non-paused roster. Inspect partial/unknown outcomes with status/doctor, never blind reset or retry."),
464
- "shutdown" => ("Compatibility bridge: stop only the selected workspace/team. Logs are retained by default; --keep-logs remains compatible.\n--json reports scope, degradation and owned residuals. Success does not mean other teams were shut down.",
465
- "team-agent shutdown --workspace .\nteam-agent shutdown --workspace . --team help-demo --json", "Prefer team-agent stop --workspace . --team KEY --json. Verify this team's owned residuals are empty; use team-agent start for authorized later activation. Do not clean up other teams or shared servers."),
466
- "add-agent" => ("Compatibility add-only entry. <agent> names the new seat; --provider/--model/--effort select intentional launch settings.\n--bypass requires true|false; --prompt sets responsibilities; --profile selects a local profile.\nProvider and bypass must be explicit in arguments or --role-file. Conflicting settings are refused before writes. --force requires explicit authorization, a positively dead old pane and no live cohort;\nfor a removed seat, --force re-adopts the role file it left behind and CLI values override it.",
467
- "team-agent add-agent reviewer --provider pi --model openai-codex/gpt-6-luna --bypass false --prompt 'Review tasks'\nteam-agent add-agent reviewer --role-file ./agents/reviewer.md", "Prefer team-agent start reviewer --role-file FILE for add-or-wake, or team-agent agent add reviewer for strict new-seat behavior. Keep provider/bypass explicit; check status and send a task after actual startup."),
468
- "start-agent" => ("Compatibility entry starts an existing stopped seat only; a running seat is refused.\n--provider/--model/--effort/--bypass select intentional settings; --prompt replaces permanent instructions and --profile selects local authentication.\nA different provider is refused. Use --allow-fresh only after explicit authorization to lose saved context.",
469
- "team-agent start-agent worker\nteam-agent start-agent worker --model openai-codex/gpt-6-luna", "Prefer team-agent start worker for daily add-or-wake or verified live no-op. Use team-agent stop worker before applying changed settings; inspect status and send a task afterward. A no-op is not role synchronization or business readiness."),
470
- "stop-agent" => ("Compatibility single-agent stop; configuration and saved session associations are retained, not removed.",
471
- "team-agent stop-agent worker\nteam-agent stop-agent worker --workspace . --team help-demo --json", "Prefer team-agent stop worker. Verify the stopped result; intentionally wake with team-agent start worker, then check status before sending new work."),
472
- "reset-agent" => ("Compatibility entry requires explicit --discard-session. Stops the old process, clears the saved association and attempts fresh startup. Paused agents stay paused; not all native history is deleted.",
473
- "team-agent reset-agent worker --discard-session\nteam-agent reset-agent worker --discard-session --workspace . --team help-demo --json", "Prefer team-agent agent reset worker --discard-session only after explicit context-loss approval. Never use reset as a resume-refusal fallback; check the actual result/status before sending new work."),
474
- "clone-agent" => ("Compatibility entry: <agent> is the source; --as names the new agent; --label sets a readable label.\nCopies configuration, not a complete conversation.",
475
- "team-agent clone-agent worker --as reviewer\nteam-agent clone-agent worker --as reviewer --label 'Review agent' --workspace .", "Prefer team-agent agent clone worker --as reviewer. Check the new agent with status, then send it an independent task; original capability gates still apply."),
476
- "fork-agent" => ("Compatibility entry: <agent> is the source; --as names the new agent; --label sets a readable label.\nRequires captured context and admitted new-seat fork capability. Unsupported providers refuse without fallback.",
477
- "team-agent fork-agent worker --as experiment\nteam-agent fork-agent worker --as experiment --workspace . --team help-demo --json", "Prefer team-agent agent fork worker --as experiment where admitted. Inspect status before sending work; finish with team-agent stop experiment or the explicit agent remove operation."),
478
- "remove-agent" => ("Compatibility entry requires --confirm. Spec-defined agents also require --from-spec; dynamic agents do not.\nDeletes only the managed role copy, not external user files. Stop a running agent first.\n--force stops/removes a running agent only with explicit authorization and the original safety checks.",
479
- "team-agent remove-agent reviewer --confirm\nteam-agent remove-agent reviewer --from-spec --confirm --workspace . --team help-demo --json", "Prefer team-agent agent remove reviewer --confirm with any required --from-spec. Save replies first and verify the resulting scope/status; do not force-clean other agents."),
480
- "leaders" => ("Lists live leaders by default; --all includes stale registrations and --stale selects stale entries.\nQUERY/--search filters workspace/team/name. --prune removes verified retired registrations; preview with --dry-run.",
481
- "team-agent leaders\nteam-agent leaders --all --json\nteam-agent leaders --prune --dry-run", "Select --workspace/--team from the reported scope. Registry cleanup is not process shutdown."),
482
- "doctor" => ("Read-only diagnosis by default; SPEC is an optional configuration path.\n--comms/--gate comms checks channels, not actual replies; --gate orphans checks residual resources.\nUse --fix/--fix-schema/--cleanup-orphans only within authorized scope. Dangerous repairs require --confirm.",
483
- "team-agent doctor --workspace .\nteam-agent doctor --workspace . --team help-demo --json", "Follow the actual issue and selected-team scope. A suggested repair is not an executed repair."),
484
- "approvals" => ("Optional <agent> selects one agent. Observes permission prompts without granting approval.",
485
- "team-agent approvals\nteam-agent approvals worker --json", "Verify the requested permission, handle it in the actual provider prompt, then check status."),
486
- "profile" => ("init creates a profile; doctor checks it; show displays settings. NAME is the profile name.\n--auth-mode selects authentication; --proxy-mode direct bypasses proxies and inherit uses the environment proxy.\nProfiles belong to the selected workspace, not automatically to an isolated --team. Do not expose credentials.",
487
- "team-agent profile init local --auth-mode subscription\nteam-agent profile doctor local\nteam-agent profile show local", "After validation, use team-agent start AGENT --profile local; stop a running seat before changing settings. Use native sign-in when needed, never copy external credentials."),
488
- "install-skill" => ("--source must be a verified skill directory; --target selects codex/claude/copilot/all.\n--dest overrides the destination; --dry-run previews; --uninstall removes the target skill. Installation is not required to create a team.",
489
- "team-agent install-skill --source \"$SKILL_DIR\" --target codex --dry-run\nteam-agent install-skill --source \"$SKILL_DIR\" --target codex", "Set SKILL_DIR to a verified directory and inspect the preview before installation. Do not overwrite unknown user files."),
490
- "claim-leader" => ("Use only when doctor recommends leader registration and this terminal is the actual leader.\n--confirm authorizes registration; it does not open a new provider.",
491
- "team-agent claim-leader --workspace . --json\nteam-agent claim-leader --workspace . --team help-demo --confirm --json", "Verify doctor findings and terminal ownership first. A refusal without confirmation is not successful registration."),
492
- "takeover" => ("Use only when doctor recommends takeover and the user has authorized it. This changes leader ownership.\nWith a usable team terminal, takeover may execute even without --confirm; it is not a read-only preview. Use team restart --session preserve for normal context-preserving recovery.",
493
- "team-agent takeover --workspace . --team help-demo --confirm\nteam-agent takeover --workspace . --team help-demo --confirm --json", "Verify leader/team ownership before confirmation. Check status/doctor afterwards; do not take over someone else's team."),
494
- "attach-leader" => ("PANE must be a verified leader terminal, not a guessed pane id.\n--provider selects the actual provider; --confirm authorizes attachment to an existing leader. Use only when doctor recommends it.",
495
- "team-agent attach-leader --pane \"$PANE\" --provider pi --workspace .\nteam-agent attach-leader --pane \"$PANE\" --provider pi --workspace . --team help-demo --confirm --json", "Set PANE to the verified terminal. Confirm attachment with doctor before sending a task."),
496
- "kiro" => ("Kiro leader launching is not admitted by this candidate. This entry returns the stable capability refusal kiro_leader_not_admitted (exit 1).\nNo native process, leader binding, attach or provider fallback is attempted. --help/-h is read-only and exits 0.",
497
- "team-agent kiro\nteam-agent kiro --json", "Use provider: kiro in a complete worker role source with team-agent start --from TEAMDIR; worker support does not grant Leader capability."),
498
- _ => ("Install the provider and complete native sign-in first. The current directory is the workspace.\nUse --attach-existing/--confirm only after verifying leader ownership and receiving authorization; --attach-session selects a verified session.\n--external-leader selects an external leader; --allow-nested-attach requires explicit authorization for nested terminals.\nArguments after -- pass through unchanged. Bare --help/-h displays this help without starting the provider.",
499
- "", "Prepare complete TEAM.md/roles with explicit user choices, then run team-agent start in the opened Leader's tool context, never an ordinary worker conversation."),
500
- };
501
- let examples = if matches!(spec.kind, CommandKind::LeaderPassthrough { .. }) {
502
- let native = name;
503
- if name == "pi" {
504
- "team-agent pi\nteam-agent pi -- --model openai-codex/gpt-6-luna\npi --help".to_string()
505
- } else {
506
- format!("team-agent {name}\nteam-agent {name} --help\n{native} --help")
507
- }
508
- } else {
509
- examples.to_string()
510
- };
511
- let scope = if name == "kiro" {
512
- "Use --json for the structured capability refusal. Native arguments and attach options cannot enable this capability."
513
- } else if matches!(spec.kind, CommandKind::LeaderPassthrough { .. }) {
514
- "Use --json for structured output. --workspace/--team are not launcher options here; they pass to the native provider."
515
- } else {
516
- "Use --json for structured output. --workspace selects the project; supported commands use --team to select the team."
517
- };
518
- let mut out = format!(
519
- "Purpose:\n{}.\nUsage: {}\n\nOptions:\n{}\n{}\nExamples:\n{}\n\nNext Action:\n{}",
520
- spec.summary, spec.usage, details, scope, examples, next
521
- );
522
- if name == "quick-start" {
523
- out.push_str(&format!("\n\nMinimal two-file configuration (create manually; not written automatically):\nTEAM.md:\n{TEAM_TEMPLATE}\nagents/worker.md:\n{WORKER_TEMPLATE}"));
524
- }
525
- if name == "restart" {
526
- out.push_str("\nRestart forms: restart AGENT selects one registered agent (default session auto); use agent restart ID to disambiguate a same-named directory. Legacy bare or explicit-path restart retains preserve and original receipts. New team restart defaults to auto. auto never means reset; native capability refusals remain authoritative.");
527
- }
528
- if name == "copilot" {
529
- out.push_str(
530
- "\nCopilot has no team-agent models entrypoint; consult native provider help.",
531
- );
532
- }
533
- out
534
- }
535
-
536
- fn emit_unknown_subcommand_usage(command: &str) -> ExitCode {
537
- emit_usage_error(&format!(
538
- "Unknown command: '{command}'. Use team-agent --help to list available commands."
539
- ));
540
- // E8 (N38): 错路引导 —— 拼写近似时建议最接近的真子命令(additive,不改既有 golden 行)。
541
- if let Some(suggestion) = nearest_subcommand(command) {
542
- eprintln!("Did you mean `{suggestion}`? See team-agent {suggestion} --help for examples.");
543
- }
544
- // 0.5.45 naming-addressing (RED-6): unknown subcommand exits 1
545
- // (Error), aligned with the family of typo refusals throughout
546
- // send/named. Pre-0.5.45 mapped to Usage (2) argparse-style; the
547
- // shared refusal shape ("typo diagnostic + advisory suggestion +
548
- // exit 1") is the invariant callers of `team-agent send` /
549
- // `--to-name` also see, so keeping unknown-subcommand at 2 was
550
- // internal drift.
551
- ExitCode::Error
552
- }
553
-
554
- /// 在已知子命令里找与 `input` 最接近的一个。0.5.45 naming-addressing
555
- /// (design §3.2/§4.1) 抽公 shared `model::name_similarity` — 距离
556
- /// 阈值与排序规则跟 CLI `--to-name` typo suggestion 走同一份纯函数,
557
- /// 避免两套 fuzzy 逻辑漂移。既有 `statu -> status` 行为保留(RED-6
558
- /// grep guard + prefix-hit priority)。
559
- fn nearest_subcommand(input: &str) -> Option<&'static str> {
560
- use crate::model::name_similarity::{rank, Candidate};
561
- let candidates: Vec<Candidate<&'static str>> = COMMAND_SPECS
562
- .iter()
563
- .filter(|spec| spec.suggestion_index)
564
- .map(|spec| Candidate {
565
- match_key: spec.name.to_string(),
566
- stable_key: spec.name.to_string(),
567
- payload: spec.name,
568
- })
569
- .collect();
570
- rank(input, &candidates).into_iter().next()
571
- }
572
-
573
- fn emit_usage_error(message: &str) {
574
- eprintln!("Usage: team-agent <command>; list commands with team-agent --help");
575
- eprintln!("Error: {message}");
576
- }
577
-
578
- /// `install-skill` 参数(RED-1 根治:把 skill 安装单源收敛到二进制,install.mjs 调它)。
579
- struct InstallSkillArgs {
580
- target: crate::packaging::SkillTarget,
581
- dest: Option<PathBuf>,
582
- dry_run: bool,
583
- /// `--uninstall`:删 target 的 skill 目标目录(单源,走同一 SkillTarget 表),不需 --source。
584
- uninstall: bool,
585
- source: Option<PathBuf>,
586
- json: bool,
587
- }
588
-
589
- fn install_skill_args(args: &[String]) -> Result<InstallSkillArgs, CliError> {
590
- let parsed = parse_args(args);
591
- // `--target` 复用 parse_args.targets(codex|claude|copilot|all,默认 all)。
592
- let target = match parsed.targets.as_deref() {
593
- None | Some("all") => crate::packaging::SkillTarget::All,
594
- Some("codex") => crate::packaging::SkillTarget::Codex,
595
- Some("claude") => crate::packaging::SkillTarget::Claude,
596
- Some("copilot") => crate::packaging::SkillTarget::Copilot,
597
- Some(other) => {
598
- return Err(CliError::Usage(format!(
599
- "invalid --target: {other} (choose from codex, claude, copilot, all)"
600
- )))
601
- }
602
- };
603
- let uninstall = args.iter().any(|a| a == "--uninstall");
604
- // `--source <dir>` 安装时必需(npm 包的 skills/team-agent;运行期无 CARGO_MANIFEST_DIR);
605
- // 卸载不需要。
606
- let source = flag_value(args, "--source").map(PathBuf::from);
607
- if !uninstall && source.is_none() {
608
- return Err(CliError::Usage("missing --source <skill dir>".to_string()));
609
- }
610
- let dest = flag_value(args, "--dest").map(PathBuf::from);
611
- let dry_run = args.iter().any(|a| a == "--dry-run");
612
- Ok(InstallSkillArgs {
613
- target,
614
- dest,
615
- dry_run,
616
- uninstall,
617
- source,
618
- json: parsed.json,
619
- })
620
- }
621
-
622
- /// 取 `--flag <value>` 的值(用于 install-skill 的 --source/--dest,parse_args 不覆盖的旗标)。
623
- fn flag_value(args: &[String], flag: &str) -> Option<String> {
624
- for (index, argument) in args.iter().enumerate() {
625
- if argument == "--" { break; }
626
- if argument == flag { return args.get(index + 1).cloned(); }
627
- if let Some((key, value)) = argument.split_once('=') {
628
- if key == flag { return Some(value.to_string()); }
629
- }
630
- }
631
- None
632
- }
633
-
634
- /// `team-agent install-skill`(RED-1 单源):repo `skills/team-agent` → `~/.codex|.claude|.copilot`。
635
- /// install.mjs 删 JS 拷贝逻辑、改调本命令(`--target all --source <pkg>/skills/team-agent`)。
636
- fn cmd_install_skill(args: &InstallSkillArgs) -> Result<CmdResult, CliError> {
637
- // 卸载分支(单源:走同一 SkillTarget 表的 dest_dir;all → SINGLE_TARGETS 全集)。
638
- if args.uninstall {
639
- let home = std::env::var_os("HOME")
640
- .map(PathBuf::from)
641
- .unwrap_or_else(|| PathBuf::from("."));
642
- let targets: Vec<crate::packaging::SkillTarget> = match args.target {
643
- crate::packaging::SkillTarget::All => {
644
- crate::packaging::SkillTarget::SINGLE_TARGETS.to_vec()
645
- }
646
- t => vec![t],
647
- };
648
- let mut removed: Vec<serde_json::Value> = Vec::new();
649
- for t in targets {
650
- if let Some(dest) = t.dest_dir(&home) {
651
- let existed = dest.0.exists();
652
- if existed && !args.dry_run {
653
- std::fs::remove_dir_all(&dest.0)
654
- .map_err(|e| CliError::Runtime(e.to_string()))?;
655
- }
656
- removed.push(serde_json::json!({
657
- "target": t,
658
- "dest": dest.0.to_string_lossy(),
659
- "removed": existed,
660
- "dry_run": args.dry_run,
661
- }));
662
- }
663
- }
664
- return Ok(CmdResult::from_json(
665
- serde_json::json!({"ok": true, "uninstalled": removed}),
666
- args.json,
667
- ));
668
- }
669
- let source = args
670
- .source
671
- .clone()
672
- .ok_or_else(|| CliError::Usage("missing --source <skill dir>".to_string()))?;
673
- let outcomes =
674
- crate::packaging::install::install_skill(&crate::packaging::SkillInstallOptions {
675
- target: args.target,
676
- dest: args.dest.clone(),
677
- dry_run: args.dry_run,
678
- source,
679
- })
680
- .map_err(|e| CliError::Runtime(e.to_string()))?;
681
- let installed: Vec<serde_json::Value> = outcomes
682
- .iter()
683
- .map(|o| {
684
- serde_json::json!({
685
- "target": o.target,
686
- "dest": o.dest.0.to_string_lossy(),
687
- "dry_run": o.dry_run,
688
- "removed_stale": o.removed_stale.len(),
689
- })
690
- })
691
- .collect();
692
- Ok(CmdResult::from_json(
693
- serde_json::json!({"ok": true, "installed": installed}),
694
- args.json,
695
- ))
696
- }
697
-
698
- fn resolve_path(path: &Path) -> PathBuf {
699
- std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
700
- }
701
-
702
- fn emit_parser_usage(command: &str, args: &[String], error: &CliError) -> ExitCode {
703
- if super::arguments::has_flag(command, args, "--json") {
704
- let mut payload = error.to_payload(Path::new(""), command);
705
- payload.action = format!("Use team-agent {command} --help to correct the command arguments.");
706
- if let Ok(value) = serde_json::to_value(payload) {
707
- println!("{}", python_compact_json(&crate::redaction::redact_external_value(&value)));
708
- }
709
- } else {
710
- eprintln!("error: {}\nUse team-agent {command} --help.", crate::redaction::redact_external_text(&error.to_string()));
711
- }
712
- ExitCode::Usage
713
- }
714
-
715
- fn emit_cli_error(command: &str, args: &[String], cwd: &Path, error: &CliError) -> ExitCode {
716
- if matches!(error, CliError::Usage(_)) { return emit_parser_usage(command, args, error); }
717
- let parsed = parse_args(args);
718
- let workspace = workspace(&parsed, cwd);
719
- let log_path = cli_error_log_path(&workspace);
720
- if let Some(parent) = log_path.parent() {
721
- let _ = std::fs::create_dir_all(parent);
722
- }
723
- let normalized = normalize_cli_error(error);
724
- let payload_error = normalized.as_ref().unwrap_or(error);
725
- let safe_error = crate::redaction::redact_external_text(&payload_error.to_string());
726
- let _ = std::fs::write(&log_path, format!("{safe_error}\n"));
727
- let mut payload = payload_error.to_payload(&log_path, command);
728
- payload.error = safe_error;
729
- if let CliError::AddressRefusal { error, action, .. } = payload_error {
730
- if !super::arguments::has_flag(command, args, "--json") {
731
- payload.error = crate::redaction::redact_external_text(error);
732
- payload.action = action.clone();
733
- }
734
- } else if let Some(reason) = payload
735
- .error
736
- .strip_prefix("usage error: ")
737
- .unwrap_or(&payload.error)
738
- .strip_prefix("Error: ")
739
- .and_then(|text| text.split_once(':').map(|(reason, _)| reason))
740
- {
741
- if let Some(message) = super::named_address::human_address_reason(reason) {
742
- payload.error = message.to_string();
743
- payload.action = "Run team-agent status and use an agent name from the list. Select scope with --workspace/--team; diagnose channel issues with doctor.".to_string();
744
- }
745
- }
746
- if command_spec(command).is_some()
747
- && payload.action
748
- == "Run team-agent doctor --workspace . for the selected team, or inspect the error log shown here."
749
- {
750
- let mut doctor = format!(
751
- "team-agent doctor --workspace {}",
752
- super::adapters::shell_quote(&workspace.to_string_lossy())
753
- );
754
- if let Some(team) = parsed.team.as_deref() {
755
- doctor.push_str(&format!(" --team {}", super::adapters::shell_quote(team)));
756
- }
757
- payload.action = format!("Run {doctor} for the selected team, or inspect the error log shown here.");
758
- }
759
- payload.action = crate::redaction::redact_external_text(&payload.action);
760
- payload.log = crate::redaction::redact_external_text(&payload.log);
761
- payload.reason = payload
762
- .reason
763
- .map(|value| crate::redaction::redact_external_text(&value));
764
- payload.session_name = payload
765
- .session_name
766
- .map(|value| crate::redaction::redact_external_text(&value));
767
- payload.next_actions = payload.next_actions.map(|values| {
768
- values
769
- .into_iter()
770
- .map(|value| crate::redaction::redact_external_text(&value))
771
- .collect()
772
- });
773
- if super::arguments::has_flag(command, args, "--json") {
774
- if let Ok(value) = serde_json::to_value(payload) {
775
- println!("{}", python_compact_json(&value));
776
- }
777
- } else {
778
- eprintln!("error: {}", payload.error);
779
- eprintln!("action: {}", payload.action);
780
- if matches!(payload_error, CliError::AddressRefusal { .. }) {
781
- eprintln!("log: {:?}", payload.log);
782
- } else {
783
- eprintln!("log: {}", payload.log);
784
- }
785
- }
786
- ExitCode::Error
787
- }
788
-
789
- fn normalize_cli_error(error: &CliError) -> Option<CliError> {
790
- match error {
791
- CliError::Runtime(message) => Some(CliError::Runtime(
792
- message
793
- .strip_prefix("validation error: ")
794
- .unwrap_or(message)
795
- .to_string(),
796
- )),
797
- _ => None,
798
- }
799
- }
800
-
801
- fn cli_error_log_path(workspace: &Path) -> PathBuf {
802
- let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f");
803
- workspace
804
- .join(".team")
805
- .join("logs")
806
- .join(format!("cli-error-{stamp}.log"))
807
- }
808
-
809
- struct PythonCompactFormatter;
810
-
811
- impl serde_json::ser::Formatter for PythonCompactFormatter {
812
- fn begin_array_value<W: ?Sized + std::io::Write>(
813
- &mut self,
814
- w: &mut W,
815
- first: bool,
816
- ) -> std::io::Result<()> {
817
- if first {
818
- Ok(())
819
- } else {
820
- w.write_all(b", ")
821
- }
822
- }
823
-
824
- fn begin_object_key<W: ?Sized + std::io::Write>(
825
- &mut self,
826
- w: &mut W,
827
- first: bool,
828
- ) -> std::io::Result<()> {
829
- if first {
830
- Ok(())
831
- } else {
832
- w.write_all(b", ")
833
- }
834
- }
835
-
836
- fn begin_object_value<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
837
- w.write_all(b": ")
838
- }
839
- }
840
-
841
- fn python_compact_json(value: &Value) -> String {
842
- let mut bytes = Vec::new();
843
- let mut ser = serde_json::Serializer::with_formatter(&mut bytes, PythonCompactFormatter);
844
- if value.serialize(&mut ser).is_err() {
845
- return "{}".to_string();
846
- }
847
- String::from_utf8(bytes).unwrap_or_else(|_| "{}".to_string())
848
- }
849
-
850
- fn has_arg(args: &[String], needle: &str) -> bool {
851
- args.iter().take_while(|arg| arg.as_str() != "--").any(|arg| arg == needle)
852
- }
853
-
854
- #[derive(Debug, Default)]
855
- struct ParsedArgs {
856
- positionals: Vec<String>,
857
- workspace: Option<PathBuf>,
858
- team: Option<String>,
859
- json: bool,
860
- yes: bool,
861
- name: Option<String>,
862
- team_id: Option<String>,
863
- targets: Option<String>,
864
- task: Option<String>,
865
- watch_result: bool,
866
- requires_ack: bool,
867
- no_ack: bool,
868
- no_wait: bool,
869
- timeout: Option<f64>,
870
- confirm_human: bool,
871
- detail: bool,
872
- summary: bool,
873
- keep_logs: bool,
874
- allow_fresh: bool,
875
- session_converge_deadline_ms: Option<u64>,
876
- force: bool,
877
- discard_session: bool,
878
- role_file: Option<String>,
879
- as_agent: Option<String>,
880
- label: Option<String>,
881
- from_spec: bool,
882
- confirm: bool,
883
- limit: Option<usize>,
884
- gate: Option<String>,
885
- comms: bool,
886
- fix: bool,
887
- fix_schema: bool,
888
- cleanup_orphans: bool,
889
- once: bool,
890
- tick_interval: Option<f64>,
891
- status_value: Option<String>,
892
- search: Option<String>,
893
- file: Option<PathBuf>,
894
- result: Option<String>,
895
- assignee: Option<String>,
896
- auth_mode: Option<String>,
897
- proxy_mode: Option<String>,
898
- pane: Option<String>,
899
- to_name: Option<String>,
900
- /// E7 (0.5.9 host-leader-registry-design §4.2): `send --to-leader NAME`
901
- /// resolves NAME through `~/.team-agent/leaders` to a canonical target
902
- /// (workspace, team_key) then delegates to the E6 leader delivery path.
903
- /// Mutually exclusive with `--to-name`, TARGET, `--pane`, and `--to`.
904
- to_leader: Option<String>,
905
- provider: Option<String>,
906
- socket: Option<String>,
907
- thread_id: Option<String>,
908
- message_id: Option<String>,
909
- mailbox: bool,
910
- presentation_sink: Option<String>,
911
- message_class: Option<String>,
912
- case_id: Option<String>,
913
- content: Option<String>,
914
- primary_error: Option<String>,
915
- agent_id: Option<String>,
916
- task_id: Option<String>,
917
- result_json: Option<String>,
918
- /// 0.5.x Phase 1d Batch 2: quick-start `--backend <tmux|conpty>`.
919
- /// Raw string (validated at the quick-start builder); the factory
920
- /// enforces literal semantics.
921
- backend: Option<String>,
922
- }
923
-
924
- fn parse_args(args: &[String]) -> ParsedArgs {
925
- let mut expanded = Vec::new();
926
- let mut literal = false;
927
- for argument in args {
928
- if argument == "--" { literal = true; }
929
- if !literal && argument.starts_with("--") {
930
- if let Some((flag, value)) = argument.split_once('=') {
931
- expanded.extend([flag.to_string(), value.to_string()]);
932
- continue;
933
- }
934
- }
935
- expanded.push(argument.clone());
936
- }
937
- let args = expanded.as_slice();
938
- let mut parsed = ParsedArgs::default();
939
- let mut i = 0usize;
940
- while i < args.len() {
941
- let Some(arg) = args.get(i) else {
942
- break;
943
- };
944
- match arg.as_str() {
945
- "--" => {
946
- parsed.positionals.extend_from_slice(&args[i + 1..]);
947
- break;
948
- }
949
- "--workspace" => {
950
- parsed.workspace = next_arg(args, &mut i).map(PathBuf::from);
951
- }
952
- "--team" => parsed.team = next_arg(args, &mut i),
953
- "--json" => parsed.json = true,
954
- "--yes" => parsed.yes = true,
955
- "--name" => parsed.name = next_arg(args, &mut i),
956
- "--team-id" => parsed.team_id = next_arg(args, &mut i),
957
- "--targets" | "--target" | "--to" => parsed.targets = next_arg(args, &mut i),
958
- "--task" => parsed.task = next_arg(args, &mut i),
959
- "--task-id" => parsed.task_id = next_arg(args, &mut i),
960
- "--agent-id" => parsed.agent_id = next_arg(args, &mut i),
961
- "--watch-result" => parsed.watch_result = true,
962
- "--requires-ack" => parsed.requires_ack = true,
963
- "--no-ack" => parsed.no_ack = true,
964
- "--no-wait" => parsed.no_wait = true,
965
- "--timeout" => {
966
- parsed.timeout = next_arg(args, &mut i).and_then(|v| v.parse::<f64>().ok())
967
- }
968
- "--confirm-human" => parsed.confirm_human = true,
969
- "--detail" => parsed.detail = true,
970
- "--summary" => parsed.summary = true,
971
- "--keep-logs" => parsed.keep_logs = true,
972
- "--allow-fresh" => parsed.allow_fresh = true,
973
- "--session-converge-deadline" => {
974
- parsed.session_converge_deadline_ms =
975
- next_arg(args, &mut i).and_then(|v| parse_seconds_ms(&v));
976
- }
977
- "--force" => parsed.force = true,
978
- "--backend" => parsed.backend = next_arg(args, &mut i),
979
- "--discard-session" => parsed.discard_session = true,
980
- "--role-file" => parsed.role_file = next_arg(args, &mut i),
981
- "--as" => parsed.as_agent = next_arg(args, &mut i),
982
- "--label" => parsed.label = next_arg(args, &mut i),
983
- "--from-spec" => parsed.from_spec = true,
984
- "--confirm" => parsed.confirm = true,
985
- "-n" | "--limit" => {
986
- parsed.limit = next_arg(args, &mut i).and_then(|v| v.parse::<usize>().ok())
987
- }
988
- "--gate" => parsed.gate = next_arg(args, &mut i),
989
- "--comms" => parsed.comms = true,
990
- "--fix" => parsed.fix = true,
991
- "--fix-schema" => parsed.fix_schema = true,
992
- "--cleanup-orphans" => parsed.cleanup_orphans = true,
993
- "--once" => parsed.once = true,
994
- "--tick-interval" => {
995
- parsed.tick_interval = next_arg(args, &mut i).and_then(|v| v.parse::<f64>().ok())
996
- }
997
- "--status" => parsed.status_value = next_arg(args, &mut i),
998
- "--search" => parsed.search = next_arg(args, &mut i),
999
- "--file" => parsed.file = next_arg(args, &mut i).map(PathBuf::from),
1000
- "--result" => parsed.result = next_arg(args, &mut i),
1001
- "--assignee" => parsed.assignee = next_arg(args, &mut i),
1002
- "--auth-mode" => parsed.auth_mode = next_arg(args, &mut i),
1003
- "--proxy-mode" => parsed.proxy_mode = next_arg(args, &mut i),
1004
- "--pane" => parsed.pane = next_arg(args, &mut i),
1005
- "--to-name" => parsed.to_name = next_arg(args, &mut i),
1006
- "--to-leader" => parsed.to_leader = next_arg(args, &mut i),
1007
- "--provider" => parsed.provider = next_arg(args, &mut i),
1008
- "--socket" => parsed.socket = next_arg(args, &mut i),
1009
- "--thread-id" => parsed.thread_id = next_arg(args, &mut i),
1010
- "--message-id" => parsed.message_id = next_arg(args, &mut i),
1011
- "--mailbox" => parsed.mailbox = true,
1012
- "--presentation-sink" => parsed.presentation_sink = next_arg(args, &mut i),
1013
- "--message-class" => parsed.message_class = next_arg(args, &mut i),
1014
- "--case-id" => parsed.case_id = next_arg(args, &mut i),
1015
- "--content" => parsed.content = next_arg(args, &mut i),
1016
- "--primary-error" => parsed.primary_error = next_arg(args, &mut i),
1017
- "--result-json" => parsed.result_json = next_arg(args, &mut i),
1018
- "-h" | "--help" => {}
1019
- other if other.starts_with("--team=") => {
1020
- parsed.team = Some(other.trim_start_matches("--team=").to_string());
1021
- }
1022
- other if other.starts_with("--proxy-mode=") => {
1023
- parsed.proxy_mode = Some(other.trim_start_matches("--proxy-mode=").to_string());
1024
- }
1025
- other if other.starts_with("--pane=") => {
1026
- parsed.pane = Some(other.trim_start_matches("--pane=").to_string());
1027
- }
1028
- other if other.starts_with("--to-name=") => {
1029
- parsed.to_name = Some(other.trim_start_matches("--to-name=").to_string());
1030
- }
1031
- other if other.starts_with("--to-leader=") => {
1032
- parsed.to_leader = Some(other.trim_start_matches("--to-leader=").to_string());
1033
- }
1034
- other if other.starts_with("--presentation-sink=") => {
1035
- parsed.presentation_sink =
1036
- Some(other.trim_start_matches("--presentation-sink=").to_string());
1037
- }
1038
- other if other.starts_with("--message-class=") => {
1039
- parsed.message_class =
1040
- Some(other.trim_start_matches("--message-class=").to_string());
1041
- }
1042
- other if other.starts_with("--case-id=") => {
1043
- parsed.case_id = Some(other.trim_start_matches("--case-id=").to_string());
1044
- }
1045
- other if other.starts_with("--provider=") => {
1046
- parsed.provider = Some(other.trim_start_matches("--provider=").to_string());
1047
- }
1048
- other if other.starts_with("--search=") => {
1049
- parsed.search = Some(other.trim_start_matches("--search=").to_string());
1050
- }
1051
- other if other.starts_with("--socket=") => {
1052
- parsed.socket = Some(other.trim_start_matches("--socket=").to_string());
1053
- }
1054
- other if other.starts_with("--thread-id=") => {
1055
- parsed.thread_id = Some(other.trim_start_matches("--thread-id=").to_string());
1056
- }
1057
- other if other.starts_with('-') => {}
1058
- other => parsed.positionals.push(other.to_string()),
1059
- }
1060
- i = i.saturating_add(1);
1061
- }
1062
- parsed
1063
- }
1064
-
1065
- fn next_arg(args: &[String], index: &mut usize) -> Option<String> {
1066
- *index = index.saturating_add(1);
1067
- args.get(*index).cloned()
1068
- }
1069
-
1070
- pub(super) fn parse_seconds_ms(raw: &str) -> Option<u64> {
1071
- let seconds = raw.parse::<f64>().ok()?;
1072
- if seconds.is_finite() && seconds >= 0.0 {
1073
- Some((seconds * 1000.0).round() as u64)
1074
- } else {
1075
- None
1076
- }
1077
- }
1078
-
1079
- fn parse_cli_provider(raw: &str) -> Result<crate::provider::Provider, CliError> {
1080
- serde_json::from_value::<crate::provider::Provider>(serde_json::json!(raw))
1081
- .map_err(|_| CliError::Usage(format!("unknown provider: {raw}")))
1082
- }
1083
-
1084
- pub(super) fn explicit_path(value: &str) -> bool {
1085
- value == "." || value == ".." || value.contains('/') || value.contains('\\')
1086
- || Path::new(value).is_absolute()
1087
- || (value.as_bytes().get(1) == Some(&b':') && value.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
1088
- }
1089
-
1090
- fn checked_workspace(path: &Path, cwd: &Path) -> Result<PathBuf, CliError> {
1091
- let path = resolve_cli_path(cwd, path);
1092
- let canonical = std::fs::canonicalize(&path).map_err(|_| CliError::Usage(format!(
1093
- "workspace does not exist or is unavailable: {}", path.display()
1094
- )))?;
1095
- if !canonical.is_dir() {
1096
- return Err(CliError::Usage(format!("workspace is not a directory: {}", path.display())));
1097
- }
1098
- Ok(canonical)
1099
- }
1100
-
1101
- fn resolve_command_scope(command: &str, mut args: Vec<String>, cwd: &Path) -> Result<Vec<String>, CliError> {
1102
- let mut selected = None;
1103
- for argument in &mut args {
1104
- if argument == "--" { break; }
1105
- if let Some(path) = argument.strip_prefix("--workspace=") {
1106
- let canonical = checked_workspace(Path::new(path), cwd)?;
1107
- *argument = format!("--workspace={}", canonical.display());
1108
- selected = Some(canonical);
1109
- }
1110
- }
1111
- if command == "restart" {
1112
- let index = args.iter().position(|arg| arg == "--")
1113
- .and_then(|index| (index + 1 < args.len()).then_some(index + 1))
1114
- .or_else(|| args.iter().position(|arg| !arg.starts_with('-')));
1115
- if let Some(index) = index {
1116
- if !explicit_path(&args[index]) {
1117
- return Err(CliError::Usage("bare restart targets are ambiguous; use restart --workspace PATH or restart ./PATH for a team".to_string()));
1118
- }
1119
- let canonical = checked_workspace(Path::new(&args[index]), cwd)?;
1120
- if selected.as_ref().is_some_and(|selected| selected != &canonical) {
1121
- return Err(CliError::Usage("restart WORKSPACE conflicts with --workspace".to_string()));
1122
- }
1123
- args[index] = canonical.to_string_lossy().into_owned();
1124
- }
1125
- }
1126
- Ok(args)
1127
- }
1128
-
1129
- fn workspace(parsed: &ParsedArgs, cwd: &Path) -> PathBuf {
1130
- parsed
1131
- .workspace
1132
- .clone()
1133
- .unwrap_or_else(|| cwd.to_path_buf())
1134
- }
1135
-
1136
- fn required_pos(parsed: &ParsedArgs, index: usize, name: &str) -> Result<String, CliError> {
1137
- parsed
1138
- .positionals
1139
- .get(index)
1140
- .cloned()
1141
- .ok_or_else(|| CliError::Usage(format!("missing {name}")))
1142
- }
1143
-
1144
- fn quick_start_args(args: &[String], cwd: &Path) -> Result<QuickStartArgs, CliError> {
1145
- if has_arg(args, "--fresh") {
1146
- return Err(CliError::Usage(
1147
- "quick-start no longer accepts --fresh. Reset semantics moved to \
1148
- `team-agent restart --allow-fresh`, which requires explicit user \
1149
- confirmation."
1150
- .to_string(),
1151
- ));
1152
- }
1153
- let parsed = parse_args(args);
1154
- let explicit_workspace = parsed
1155
- .workspace
1156
- .as_deref()
1157
- .map(|path| resolve_cli_path(cwd, path));
1158
- let positional_agents_dir = parsed.positionals.first().map(PathBuf::from).map(|path| {
1159
- if path.is_absolute() {
1160
- path
1161
- } else if let Some(workspace) = explicit_workspace.as_ref() {
1162
- workspace.join(path)
1163
- } else {
1164
- cwd.join(path)
1165
- }
1166
- });
1167
- let workspace = explicit_workspace
1168
- .or_else(|| {
1169
- let path = positional_agents_dir.as_ref()?;
1170
- if let Some(run_workspace) = path
1171
- .ancestors()
1172
- .find(|ancestor| {
1173
- ancestor.file_name().and_then(|name| name.to_str()) == Some(".team")
1174
- })
1175
- .and_then(Path::parent)
1176
- {
1177
- return Some(run_workspace.to_path_buf());
1178
- }
1179
- path.join("TEAM.md").is_file().then(|| path.to_path_buf())
1180
- })
1181
- .unwrap_or_else(|| cwd.to_path_buf());
1182
- // A positional team directory containing TEAM.md is a complete standalone
1183
- // workspace. Use it as the runtime workspace unless --workspace explicitly
1184
- // selects another root; this prevents host owner context/state leaking into
1185
- // an independent quick-start target.
1186
- let agents_dir = positional_agents_dir.unwrap_or_else(|| workspace.clone());
1187
- // 0.5.x Phase 1d Batch 2: validate the `--backend` literal up-front
1188
- // so users get a fast, actionable error instead of a downstream
1189
- // factory refusal. Accept the same literals as the factory
1190
- // `RequestedTransportBackend::parse_literal`.
1191
- if let Some(literal) = parsed.backend.as_deref() {
1192
- let normalized = literal.trim().to_ascii_lowercase();
1193
- if normalized != "tmux" && normalized != "conpty" {
1194
- return Err(CliError::Usage(format!(
1195
- "--backend must be tmux or conpty; received {literal:?}. Use tmux on POSIX. ConPTY requires a Windows host and an installed shim."
1196
- )));
1197
- }
1198
- }
1199
- Ok(QuickStartArgs {
1200
- workspace,
1201
- agents_dir,
1202
- name: parsed.name,
1203
- team_id: parsed.team_id.or(parsed.team),
1204
- yes: parsed.yes,
1205
- json: parsed.json,
1206
- detail: parsed.detail,
1207
- backend: parsed.backend,
1208
- })
1209
- }
1210
-
1211
- fn models_args(args: &[String]) -> Result<ModelsArgs, CliError> {
1212
- let parsed = parse_args(args);
1213
- let provider = parsed.provider.unwrap_or_else(|| "pi".to_string());
1214
- if parsed.search.is_some() && !parsed.positionals.is_empty() {
1215
- return Err(CliError::Usage(
1216
- "models accepts either QUERY or --search TEXT, not both".to_string(),
1217
- ));
1218
- }
1219
- let search = parsed
1220
- .search
1221
- .or_else(|| (!parsed.positionals.is_empty()).then(|| parsed.positionals.join(" ")))
1222
- .filter(|query| !query.trim().is_empty());
1223
- Ok(ModelsArgs {
1224
- provider,
1225
- search,
1226
- json: parsed.json,
1227
- })
1228
- }
1229
-
1230
- fn resolve_cli_path(cwd: &Path, path: &Path) -> PathBuf {
1231
- if path.is_absolute() {
1232
- path.to_path_buf()
1233
- } else {
1234
- cwd.join(path)
1235
- }
1236
- }
1237
-
1238
- fn send_args(args: &[String], cwd: &Path) -> Result<SendArgs, CliError> {
1239
- validate_send_flags(args)?;
1240
- warn_send_legacy_delivery_flags(args);
1241
- let parsed = parse_args(args);
1242
- if parsed.targets.is_none()
1243
- && parsed.pane.is_none()
1244
- && parsed.to_name.is_none()
1245
- && parsed.to_leader.is_none()
1246
- && parsed.positionals.len() < 2
1247
- {
1248
- return Err(CliError::Usage(
1249
- "Provide a recipient agent name and task message, such as team-agent send worker 'Review the changes'".to_string(),
1250
- ));
1251
- }
1252
- let target = if parsed.targets.is_some()
1253
- || parsed.pane.is_some()
1254
- || parsed.to_name.is_some()
1255
- || parsed.to_leader.is_some()
1256
- {
1257
- None
1258
- } else {
1259
- parsed.positionals.first().cloned()
1260
- };
1261
- let message_start = usize::from(target.is_some());
1262
- let workspace = workspace(&parsed, cwd);
1263
- let sender = trusted_cli_sender(&workspace, parsed.team.as_deref())?;
1264
- let presentation_value = if parsed.presentation_sink.is_some()
1265
- || parsed.message_class.is_some()
1266
- || parsed.case_id.is_some()
1267
- {
1268
- Some(serde_json::json!({
1269
- "sink": parsed.presentation_sink.clone(),
1270
- "class": parsed.message_class.clone(),
1271
- "case_id": parsed.case_id.clone(),
1272
- }))
1273
- } else {
1274
- None
1275
- };
1276
- let mailbox_value = parsed.mailbox.then(|| serde_json::json!(true));
1277
- let normalized = crate::messaging::presentation::normalize_send_presentation(
1278
- mailbox_value.as_ref(),
1279
- presentation_value.as_ref(),
1280
- )
1281
- .map_err(|error| CliError::Usage(format!("invalid send routing: {error}")))?;
1282
- if normalized.deprecation.is_some() {
1283
- eprintln!("Warning: legacy send settings are deprecated. Use team-agent send <agent> 'task message'; add --mailbox for storage without injection.");
1284
- }
1285
- Ok(SendArgs {
1286
- target,
1287
- message: parsed
1288
- .positionals
1289
- .iter()
1290
- .skip(message_start)
1291
- .cloned()
1292
- .collect(),
1293
- targets: parsed.targets,
1294
- workspace,
1295
- team: parsed.team,
1296
- task: None,
1297
- sender,
1298
- no_ack: false,
1299
- no_wait: true,
1300
- watch_result: false,
1301
- timeout: 0.0,
1302
- confirm_human: false,
1303
- json: parsed.json,
1304
- message_id: None,
1305
- presentation: normalized.request,
1306
- pane: parsed.pane.clone(),
1307
- to_name: parsed.to_name.clone(),
1308
- to_leader: parsed.to_leader.clone(),
1309
- })
1310
- }
1311
-
1312
- fn trusted_cli_sender(workspace: &Path, team: Option<&str>) -> Result<TrustedSender, CliError> {
1313
- let agent_id = std::env::var("TEAM_AGENT_ID")
1314
- .ok()
1315
- .map(|value| value.trim().to_string())
1316
- .filter(|value| !value.is_empty());
1317
- let worker_context = ["TEAM_AGENT_OWNER_TEAM_ID", "TEAM_AGENT_AGENT_ID"]
1318
- .into_iter()
1319
- .any(|key| {
1320
- std::env::var(key)
1321
- .ok()
1322
- .is_some_and(|value| !value.trim().is_empty())
1323
- });
1324
- let Some(agent_id) = agent_id else {
1325
- if worker_context {
1326
- return Err(CliError::Usage(
1327
- "send requires framework-injected TEAM_AGENT_ID; refusing leader identity fallback"
1328
- .to_string(),
1329
- ));
1330
- }
1331
- return Ok(TrustedSender::leader());
1332
- };
1333
- let source_workspace = std::env::var("TEAM_AGENT_WORKSPACE")
1334
- .ok()
1335
- .filter(|value| !value.trim().is_empty())
1336
- .unwrap_or_else(|| workspace.display().to_string());
1337
- let source_team = std::env::var("TEAM_AGENT_OWNER_TEAM_ID")
1338
- .ok()
1339
- .or_else(|| std::env::var("TEAM_AGENT_TEAM_ID").ok())
1340
- .or_else(|| team.map(ToOwned::to_owned))
1341
- .filter(|value| !value.trim().is_empty())
1342
- .unwrap_or_else(|| "unknown".to_string());
1343
- Ok(TrustedSender::from_runtime_identity_with_source(
1344
- crate::model::ids::AgentId::new(agent_id),
1345
- source_workspace,
1346
- &source_team,
1347
- ))
1348
- }
1349
-
1350
- fn warn_send_legacy_delivery_flags(args: &[String]) {
1351
- const FLAGS: &[&str] = &[
1352
- "--task",
1353
- "--watch-result",
1354
- "--requires-ack",
1355
- "--no-ack",
1356
- "--no-wait",
1357
- "--timeout",
1358
- "--confirm-human",
1359
- "--message-id",
1360
- ];
1361
- let spec = command_spec("send");
1362
- let sunset = spec
1363
- .and_then(|spec| spec.sunset)
1364
- .unwrap_or("a future compatibility release");
1365
- let action = spec.and_then(|spec| spec.action).unwrap_or(
1366
- "Use team-agent send <agent> 'task message'; select scope with --workspace/--team",
1367
- );
1368
- for flag in FLAGS {
1369
- if args
1370
- .iter()
1371
- .take_while(|arg| arg.as_str() != "--")
1372
- .any(|arg| arg == flag || arg.starts_with(&format!("{flag}=")))
1373
- {
1374
- eprintln!(
1375
- "Warning: {flag} is deprecated and will be removed in {sunset}. Next: {action}"
1376
- );
1377
- }
1378
- }
1379
- }
1380
-
1381
- fn validate_send_flags(args: &[String]) -> Result<(), CliError> {
1382
- super::arguments::parse("send", args).map(|_| ())
1383
- }
1384
-
1385
- /// Stage 4 of identity-boundary unified plan (architect direction
1386
- /// 2026-06-24, .team/artifacts/identity-boundary-unified-plan.md §2 Stage
1387
- /// 4): destructive command ambiguity gate. When the workspace has 2+
1388
- /// alive teams and the caller did not pass `--team`, refuse with a
1389
- /// usage error listing the candidates so the operator picks explicitly.
1390
- /// Single-team workspaces (the 0.4.x baseline) are unaffected — the
1391
- /// `CommandScope::resolve` helper returns `Resolved` and this function
1392
- /// is a no-op.
1393
- fn refuse_if_multi_alive_team_missing_scope(
1394
- command: &str,
1395
- workspace: &Path,
1396
- requested_team: Option<&str>,
1397
- ) -> Result<(), CliError> {
1398
- let scope = crate::state::paths::CommandScope::resolve(workspace, requested_team);
1399
- if scope.is_ambiguous() {
1400
- let candidates = scope.candidates().join(", ");
1401
- return Err(CliError::Usage(format!(
1402
- "{command}: workspace has multiple alive teams ({candidates}); \
1403
- pass `--team <key>` to choose one (refusing to default to any \
1404
- single team — Stage 4 identity-boundary contract)"
1405
- )));
1406
- }
1407
- Ok(())
1408
- }
1409
-
1410
- fn status_args(args: &[String], cwd: &Path) -> StatusArgs {
1411
- let parsed = parse_args(args);
1412
- StatusArgs {
1413
- agent: parsed.positionals.first().cloned(),
1414
- workspace: workspace(&parsed, cwd),
1415
- detail: parsed.detail,
1416
- summary: parsed.summary,
1417
- json: parsed.json,
1418
- team: parsed.team,
1419
- }
1420
- }
1421
-
1422
- fn wait_args(args: &[String], cwd: &Path) -> Result<WaitArgs, CliError> {
1423
- let parsed = parse_args(args);
1424
- let workspace = workspace(&parsed, cwd);
1425
- Ok(WaitArgs {
1426
- task_id: parsed
1427
- .task
1428
- .ok_or_else(|| CliError::Usage("wait requires --task <id>".to_string()))?,
1429
- workspace,
1430
- json: parsed.json,
1431
- })
1432
- }
1433
-
1434
- fn approvals_args(args: &[String], cwd: &Path) -> ApprovalsArgs {
1435
- let parsed = parse_args(args);
1436
- ApprovalsArgs {
1437
- agent: parsed.positionals.first().cloned(),
1438
- workspace: workspace(&parsed, cwd),
1439
- json: parsed.json,
1440
- team: parsed.team,
1441
- }
1442
- }
1443
-
1444
- fn inbox_args(args: &[String], cwd: &Path) -> Result<InboxArgs, CliError> {
1445
- if args
1446
- .iter()
1447
- .any(|arg| arg == "--since" || arg.starts_with("--since="))
1448
- {
1449
- return Err(CliError::Usage(
1450
- "inbox only supports -n/--limit; --since is not supported".to_string(),
1451
- ));
1452
- }
1453
- let parsed = parse_args(args);
1454
- Ok(InboxArgs {
1455
- agent: required_pos(&parsed, 0, "agent")?,
1456
- workspace: workspace(&parsed, cwd),
1457
- limit: parsed.limit.unwrap_or(3),
1458
- json: parsed.json,
1459
- team: parsed.team,
1460
- })
1461
- }
1462
-
1463
- fn takeover_args(args: &[String], cwd: &Path) -> TakeoverArgs {
1464
- let parsed = parse_args(args);
1465
- TakeoverArgs {
1466
- workspace: workspace(&parsed, cwd),
1467
- team: parsed.team,
1468
- confirm: parsed.confirm,
1469
- json: parsed.json,
1470
- }
1471
- }
1472
-
1473
- fn claim_leader_args(args: &[String], cwd: &Path) -> ClaimLeaderArgs {
1474
- let parsed = parse_args(args);
1475
- ClaimLeaderArgs {
1476
- workspace: workspace(&parsed, cwd),
1477
- team: parsed.team,
1478
- confirm: parsed.confirm,
1479
- json: parsed.json,
1480
- detail: parsed.detail,
1481
- }
1482
- }
1483
-
1484
- fn attach_leader_args(args: &[String], cwd: &Path) -> Result<AttachLeaderArgs, CliError> {
1485
- let parsed = parse_args(args);
1486
- Ok(AttachLeaderArgs {
1487
- workspace: workspace(&parsed, cwd),
1488
- team: parsed.team,
1489
- pane: parsed
1490
- .pane
1491
- .filter(|pane| !pane.is_empty())
1492
- .map(crate::transport::PaneId::new),
1493
- provider: parse_cli_provider(parsed.provider.as_deref()
1494
- .filter(|provider| !provider.trim().is_empty())
1495
- .ok_or_else(|| CliError::Usage("attach-leader requires --provider <name>".to_string()))?)?,
1496
- confirm: parsed.confirm,
1497
- json: parsed.json,
1498
- })
1499
- }
1500
-
1501
- fn attach_app_server_leader_args(
1502
- args: &[String],
1503
- cwd: &Path,
1504
- ) -> Result<AttachAppServerLeaderArgs, CliError> {
1505
- let parsed = parse_args(args);
1506
- Ok(AttachAppServerLeaderArgs {
1507
- workspace: workspace(&parsed, cwd),
1508
- team: parsed.team,
1509
- socket: parsed
1510
- .socket
1511
- .filter(|socket| !socket.is_empty())
1512
- .ok_or_else(|| CliError::Usage("missing --socket".to_string()))?,
1513
- thread_id: parsed
1514
- .thread_id
1515
- .filter(|thread_id| !thread_id.is_empty())
1516
- .ok_or_else(|| CliError::Usage("missing --thread-id".to_string()))?,
1517
- json: parsed.json,
1518
- })
1519
- }
1520
-
1521
- fn shutdown_args(args: &[String], cwd: &Path) -> Result<ShutdownArgs, CliError> {
1522
- let parsed = parse_args(args);
1523
- let workspace = workspace(&parsed, cwd);
1524
- refuse_if_multi_alive_team_missing_scope("shutdown", &workspace, parsed.team.as_deref())?;
1525
- Ok(ShutdownArgs {
1526
- workspace,
1527
- team: parsed.team,
1528
- keep_logs: parsed.keep_logs,
1529
- json: parsed.json,
1530
- })
1531
- }
1532
-
1533
- fn restart_args(args: &[String], cwd: &Path) -> Result<RestartArgs, CliError> {
1534
- let parsed = parse_args(args);
1535
- let workspace = if let Some(path) = parsed.positionals.first() {
1536
- if !explicit_path(path) {
1537
- return Err(CliError::Usage("bare restart targets are ambiguous; use restart --workspace PATH or restart ./PATH for a team".to_string()));
1538
- }
1539
- resolve_cli_path(cwd, Path::new(path))
1540
- } else { workspace(&parsed, cwd) };
1541
- refuse_if_multi_alive_team_missing_scope("restart", &workspace, parsed.team.as_deref())?;
1542
- Ok(RestartArgs {
1543
- workspace,
1544
- team: parsed.team,
1545
- allow_fresh: parsed.allow_fresh,
1546
- session_converge_deadline_ms: parsed.session_converge_deadline_ms,
1547
- json: parsed.json,
1548
- detail: parsed.detail,
1549
- })
1550
- }
1551
-
1552
- // Keep strict role CLI parsing separate from the legacy shared parser.
1553
- pub(super) fn intent_source_workspace(source: &Path, cwd: &Path) -> Result<PathBuf, CliError> {
1554
- quick_start_args(&[source.to_string_lossy().into_owned()], cwd).map(|args| args.workspace)
1555
- }
1556
-
1557
- pub(super) fn intent_role_patch(args: &[String]) -> Result<crate::lifecycle::role_config::RoleConfigPatch, CliError> {
1558
- role_agent_args(args, false).map(|(_, patch)| patch)
1559
- }
1560
-
1561
- /// Explicit object aliases reuse the same syntax checks, typed builders and handlers.
1562
- pub(super) fn intent_alias(command: &str, args: &[String], cwd: &Path) -> Result<CmdResult, CliError> {
1563
- let mut checked = prepare_control_args(command, args, cwd)?;
1564
- if checked.help { return Ok(CmdResult::human(command_help(Some(command)))); }
1565
- for token in &mut checked.tokens {
1566
- if let Some(path) = token.strip_prefix("--role-file=") {
1567
- let path = Path::new(path);
1568
- let path = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
1569
- let path = path.canonicalize().map_err(|e| CliError::Usage(format!("invalid explicit role file: {e}")))?;
1570
- *token = format!("--role-file={}", path.display());
1571
- }
1572
- }
1573
- let args = checked.tokens.as_slice();
1574
- match command {
1575
- "status" => {
1576
- let parsed = status_args(args, cwd);
1577
- cmd_status_for_team(&parsed, parsed.team.as_deref())
1578
- }
1579
- "add-agent" => cmd_add_agent(&add_agent_args(args, cwd)?),
1580
- "remove-agent" => cmd_remove_agent(&remove_agent_args(args, cwd)?),
1581
- "reset-agent" => cmd_reset_agent(&reset_agent_args(args, cwd)?),
1582
- "clone-agent" => cmd_clone_agent(&clone_agent_args(args, cwd)?),
1583
- "fork-agent" => cmd_fork_agent(&fork_agent_args(args, cwd)?),
1584
- _ => Err(CliError::Usage("unsupported lifecycle alias".into())),
1585
- }
1586
- }
1587
-
1588
- fn role_agent_args(
1589
- args: &[String],
1590
- add: bool,
1591
- ) -> Result<(ParsedArgs, crate::lifecycle::role_config::RoleConfigPatch), CliError> {
1592
- let mut role = crate::lifecycle::role_config::RoleConfigPatch::default();
1593
- let mut forwarded = Vec::new();
1594
- let mut seen = std::collections::BTreeSet::new();
1595
- let mut index = 0;
1596
- while index < args.len() {
1597
- let argument = &args[index];
1598
- if !argument.starts_with('-') {
1599
- forwarded.push(argument.clone());
1600
- index += 1;
1601
- continue;
1602
- }
1603
- let (flag, inline) = argument
1604
- .split_once('=')
1605
- .map_or((argument.as_str(), None), |(key, value)| (key, Some(value)));
1606
- if !seen.insert(flag.to_string()) {
1607
- return Err(CliError::Usage(format!("duplicate {flag}")));
1608
- }
1609
- if matches!(flag, "--json" | "--allow-fresh" | "--force") {
1610
- if inline.is_some() || (add && flag == "--allow-fresh") {
1611
- return Err(CliError::Usage(format!("unsupported option: {argument}")));
1612
- }
1613
- forwarded.push(flag.to_string());
1614
- index += 1;
1615
- continue;
1616
- }
1617
- if !matches!(
1618
- flag,
1619
- "--provider"
1620
- | "--model"
1621
- | "--effort"
1622
- | "--bypass"
1623
- | "--prompt"
1624
- | "--profile"
1625
- | "--workspace"
1626
- | "--team"
1627
- | "--role-file"
1628
- ) || (!add && flag == "--role-file")
1629
- {
1630
- return Err(CliError::Usage(format!("unknown option: {flag}")));
1631
- }
1632
- let value = if let Some(value) = inline {
1633
- value.to_string()
1634
- } else {
1635
- index += 1;
1636
- args.get(index)
1637
- .filter(|value| flag == "--prompt" || !value.starts_with("--"))
1638
- .ok_or_else(|| CliError::Usage(format!("missing value for {flag}")))?
1639
- .clone()
1640
- };
1641
- if value.trim().is_empty() {
1642
- return Err(CliError::Usage(format!("empty value for {flag}")));
1643
- }
1644
- match flag {
1645
- "--provider" => {
1646
- // A contract name is written as the leaf's public name (`agent` →
1647
- // `cursor`, `claude_code` → `claude`, `codex_cli` → `codex`); it
1648
- // declares the same leaf.
1649
- #[cfg(unix)]
1650
- let contract = crate::contract_runtime::registry::declared(&value)
1651
- .map(crate::contract_runtime::registry::public_name);
1652
- #[cfg(not(unix))]
1653
- let contract: Option<&str> = None;
1654
- let provider = match contract {
1655
- Some(id) => id,
1656
- None => crate::provider::wire::provider_wire(
1657
- crate::provider::wire::parse_provider(&value)
1658
- .ok_or_else(|| CliError::Usage(format!("unknown provider: {value}")))?,
1659
- ),
1660
- };
1661
- role.provider = Some(provider.to_string());
1662
- }
1663
- "--bypass" => {
1664
- role.bypass = Some(match value.as_str() {
1665
- "true" => true,
1666
- "false" => false,
1667
- _ => return Err(CliError::Usage("--bypass requires true or false".into())),
1668
- })
1669
- }
1670
- "--model" => role.model = Some(value),
1671
- "--effort" => {
1672
- if crate::model::enums::ProviderEffort::parse(&value).is_none() {
1673
- return Err(CliError::Usage(format!("unknown effort: {value}")));
1674
- }
1675
- role.effort = Some(value);
1676
- }
1677
- "--prompt" => role.prompt = Some(value),
1678
- "--profile" => role.profile = Some(value),
1679
- _ => {
1680
- forwarded.push(flag.to_string());
1681
- forwarded.push(value);
1682
- }
1683
- }
1684
- index += 1;
1685
- }
1686
- let parsed = parse_args(&forwarded);
1687
- if add && parsed.role_file.is_none() {
1688
- if role.provider.is_none() {
1689
- return Err(CliError::Usage(
1690
- "add-agent requires --provider <name>".into(),
1691
- ));
1692
- }
1693
- if role.bypass.is_none() {
1694
- return Err(CliError::Usage(
1695
- "add-agent requires --bypass <true|false>".into(),
1696
- ));
1697
- }
1698
- }
1699
- if parsed.positionals.len() != 1 {
1700
- return Err(CliError::Usage(
1701
- if parsed.positionals.is_empty() {
1702
- "missing agent"
1703
- } else {
1704
- "expected exactly one agent id"
1705
- }
1706
- .into(),
1707
- ));
1708
- }
1709
- Ok((parsed, role))
1710
- }
1711
-
1712
- #[cfg(test)]
1713
- mod role_cli_tests {
1714
- use super::*;
1715
- fn strings(values: &[&str]) -> Vec<String> {
1716
- values.iter().map(|value| (*value).to_string()).collect()
1717
- }
1718
-
1719
- #[test]
1720
- fn add_requires_decisions_without_a_template_but_accepts_file_input() {
1721
- for args in [
1722
- vec!["w"],
1723
- vec!["w", "--provider", "pi"],
1724
- vec!["w", "--bypass", "false"],
1725
- ] {
1726
- assert!(role_agent_args(&strings(&args), true).is_err());
1727
- }
1728
- assert!(role_agent_args(&strings(&["w", "--role-file", "w.md"]), true).is_ok());
1729
- let (parsed, _) =
1730
- role_agent_args(&strings(&["w", "--role-file", "w.md", "--force"]), true).unwrap();
1731
- assert!(parsed.force);
1732
- assert!(role_agent_args(
1733
- &strings(&["w", "--role-file", "w.md", "--force=true"]),
1734
- true
1735
- )
1736
- .is_err());
1737
- assert!(role_agent_args(
1738
- &strings(&["w", "--role-file", "w.md", "--allow-fresh"]),
1739
- true
1740
- )
1741
- .is_err());
1742
- let (_, patch) =
1743
- role_agent_args(&strings(&["w", "--provider=pi", "--bypass=false"]), true).unwrap();
1744
- assert_eq!(patch.provider.as_deref(), Some("pi"));
1745
- assert_eq!(patch.bypass, Some(false));
1746
- }
1747
-
1748
- #[cfg(unix)]
1749
- #[test]
1750
- fn provider_accepts_contract_names_as_their_leaf_id() {
1751
- for (name, leaf) in [
1752
- ("cursor", "cursor"), ("cursor-agent", "cursor"), ("agent", "cursor"),
1753
- ("cursor_agent", "cursor"), ("kiro", "kiro"),
1754
- // Claude Code, Codex, Grok Build and Pi keep their public command
1755
- // names, which declare the leaf.
1756
- ("claude", "claude"), ("claude_code", "claude"), ("claude-code", "claude"),
1757
- ("claude_tui", "claude"), ("codex", "codex"), ("codex_cli", "codex"),
1758
- ("codex-cli", "codex"), ("codex_tui", "codex"), ("grok", "grok"),
1759
- ("grok_build", "grok"), ("pi", "pi"), ("pi_tui", "pi"),
1760
- ] {
1761
- let (_, patch) = role_agent_args(
1762
- &strings(&["w", "--provider", name, "--bypass", "true"]), true,
1763
- ).unwrap_or_else(|error| panic!("{name}: {error}"));
1764
- assert_eq!(patch.provider.as_deref(), Some(leaf), "{name}");
1765
- }
1766
- assert!(role_agent_args(&strings(&["w", "--provider", "Cursor", "--bypass", "true"]), true).is_err());
1767
- }
1768
-
1769
- #[test]
1770
- fn strict_role_options_reject_ambiguous_values() {
1771
- for args in [
1772
- vec!["w", "--bypass"],
1773
- vec!["w", "--bypass", "yes"],
1774
- vec!["w", "--no-bypass"],
1775
- vec!["w", "--bypass", "true", "--bypass=false"],
1776
- vec!["w", "--unknown", "x"],
1777
- vec!["w", "extra"],
1778
- ] {
1779
- assert!(role_agent_args(&strings(&args), false).is_err());
1780
- }
1781
- let (_, patch) = role_agent_args(&strings(&["w"]), false).unwrap();
1782
- assert_eq!(
1783
- patch,
1784
- crate::lifecycle::role_config::RoleConfigPatch::default()
1785
- );
1786
- }
1787
- }
1788
-
1789
- fn start_agent_args(args: &[String], cwd: &Path) -> Result<StartAgentArgs, CliError> {
1790
- let (parsed, role_config) = role_agent_args(args, false)?;
1791
- if parsed.force {
1792
- return Err(CliError::Usage("start-agent does not support --force; use stop-agent AGENT followed by start-agent AGENT for a safe restart".to_string()));
1793
- }
1794
- Ok(StartAgentArgs {
1795
- role_config,
1796
- agent: required_pos(&parsed, 0, "agent")?,
1797
- workspace: workspace(&parsed, cwd),
1798
- team: parsed.team,
1799
- force: parsed.force,
1800
- allow_fresh: parsed.allow_fresh,
1801
- json: parsed.json,
1802
- })
1803
- }
1804
-
1805
- fn stop_agent_args(args: &[String], cwd: &Path) -> Result<StopAgentArgs, CliError> {
1806
- let parsed = parse_args(args);
1807
- Ok(StopAgentArgs {
1808
- agent: required_pos(&parsed, 0, "agent")?,
1809
- workspace: workspace(&parsed, cwd),
1810
- team: parsed.team,
1811
- json: parsed.json,
1812
- })
1813
- }
1814
-
1815
- fn reset_agent_args(args: &[String], cwd: &Path) -> Result<ResetAgentArgs, CliError> {
1816
- let parsed = parse_args(args);
1817
- let agent = required_pos(&parsed, 0, "agent")?;
1818
- if !parsed.discard_session {
1819
- return Err(CliError::Usage(
1820
- "missing --discard-session; add this option only after explicit authorization to discard the saved session association".to_string(),
1821
- ));
1822
- }
1823
- let workspace = workspace(&parsed, cwd);
1824
- refuse_if_multi_alive_team_missing_scope("reset-agent", &workspace, parsed.team.as_deref())?;
1825
- Ok(ResetAgentArgs {
1826
- agent,
1827
- workspace,
1828
- team: parsed.team,
1829
- discard_session: parsed.discard_session,
1830
- json: parsed.json,
1831
- })
1832
- }
1833
-
1834
- fn add_agent_args(args: &[String], cwd: &Path) -> Result<AddAgentArgs, CliError> {
1835
- let (parsed, role_config) = role_agent_args(args, true)?;
1836
- Ok(AddAgentArgs {
1837
- role_config,
1838
- agent: required_pos(&parsed, 0, "agent")?,
1839
- workspace: workspace(&parsed, cwd),
1840
- team: parsed.team,
1841
- role_file: parsed.role_file.unwrap_or_default(),
1842
- force: parsed.force,
1843
- json: parsed.json,
1844
- })
1845
- }
1846
-
1847
- fn fork_agent_args(args: &[String], cwd: &Path) -> Result<ForkAgentArgs, CliError> {
1848
- let parsed = parse_args(args);
1849
- Ok(ForkAgentArgs {
1850
- source_agent: required_pos(&parsed, 0, "source_agent")?,
1851
- workspace: workspace(&parsed, cwd),
1852
- team: parsed.team,
1853
- as_agent: parsed
1854
- .as_agent
1855
- .ok_or_else(|| CliError::Usage("missing --as".to_string()))?,
1856
- label: parsed.label,
1857
- json: parsed.json,
1858
- })
1859
- }
1860
-
1861
- fn clone_agent_args(args: &[String], cwd: &Path) -> Result<CloneAgentArgs, CliError> {
1862
- let parsed = parse_args(args);
1863
- Ok(CloneAgentArgs {
1864
- source_agent: required_pos(&parsed, 0, "source_agent")?,
1865
- workspace: workspace(&parsed, cwd),
1866
- team: parsed.team,
1867
- as_agent: parsed
1868
- .as_agent
1869
- .ok_or_else(|| CliError::Usage("missing --as".to_string()))?,
1870
- label: parsed.label,
1871
- json: parsed.json,
1872
- })
1873
- }
1874
-
1875
- fn remove_agent_args(args: &[String], cwd: &Path) -> Result<RemoveAgentArgs, CliError> {
1876
- let parsed = parse_args(args);
1877
- let agent = required_pos(&parsed, 0, "agent")?;
1878
- let workspace = workspace(&parsed, cwd);
1879
- refuse_if_multi_alive_team_missing_scope("remove-agent", &workspace, parsed.team.as_deref())?;
1880
- Ok(RemoveAgentArgs {
1881
- agent,
1882
- workspace,
1883
- team: parsed.team,
1884
- from_spec: parsed.from_spec,
1885
- confirm: parsed.confirm,
1886
- force: parsed.force,
1887
- json: parsed.json,
1888
- })
1889
- }
1890
-
1891
- fn doctor_args(args: &[String], cwd: &Path) -> DoctorArgs {
1892
- let parsed = parse_args(args);
1893
- DoctorArgs {
1894
- spec: parsed.positionals.first().map(PathBuf::from),
1895
- workspace: workspace(&parsed, cwd),
1896
- gate: doctor_gate(parsed.gate.as_deref()),
1897
- comms: parsed.comms,
1898
- team: parsed.team,
1899
- fix: parsed.fix,
1900
- fix_schema: parsed.fix_schema,
1901
- cleanup_orphans: parsed.cleanup_orphans,
1902
- confirm: parsed.confirm,
1903
- json: parsed.json,
1904
- }
1905
- }
1906
-
1907
- fn doctor_gate(raw: Option<&str>) -> Option<DoctorGate> {
1908
- match raw {
1909
- Some("orphans") => Some(DoctorGate::Orphans),
1910
- Some("comms") => Some(DoctorGate::Comms),
1911
- Some(other) => Some(DoctorGate::Unknown(other.to_string())),
1912
- None => None,
1913
- }
1914
- }
1915
-
1916
- fn leaders_args(args: &[String], _cwd: &Path) -> Result<LeadersArgs, CliError> {
1917
- let mut view = None;
1918
- let mut query = None;
1919
- let mut prune = false;
1920
- let mut dry_run = false;
1921
- let mut json = false;
1922
- let mut i = 0usize;
1923
- while i < args.len() {
1924
- let arg = &args[i];
1925
- match arg.as_str() {
1926
- "--json" => json = true,
1927
- "--all" => {
1928
- if view.replace(LeadersView::All).is_some() {
1929
- return Err(CliError::Usage(
1930
- "leaders accepts only one of --all or --stale".to_string(),
1931
- ));
1932
- }
1933
- }
1934
- "--stale" => {
1935
- if view.replace(LeadersView::Stale).is_some() {
1936
- return Err(CliError::Usage(
1937
- "leaders accepts only one of --all or --stale".to_string(),
1938
- ));
1939
- }
1940
- }
1941
- "--prune" => {
1942
- if prune {
1943
- return Err(CliError::Usage(
1944
- "leaders accepts --prune at most once".to_string(),
1945
- ));
1946
- }
1947
- prune = true;
1948
- }
1949
- "--dry-run" => dry_run = true,
1950
- "--search" => {
1951
- let Some(value) = args.get(i.saturating_add(1)) else {
1952
- return Err(CliError::Usage(
1953
- "leaders --search requires TEXT".to_string(),
1954
- ));
1955
- };
1956
- if value.starts_with('-') {
1957
- return Err(CliError::Usage(
1958
- "leaders --search requires TEXT".to_string(),
1959
- ));
1960
- }
1961
- i = i.saturating_add(1);
1962
- if query.replace(value.clone()).is_some() {
1963
- return Err(CliError::Usage(
1964
- "leaders accepts only one QUERY or --search TEXT".to_string(),
1965
- ));
1966
- }
1967
- }
1968
- value if value.starts_with("--search=") => {
1969
- let value = value.trim_start_matches("--search=").to_string();
1970
- if query.replace(value).is_some() {
1971
- return Err(CliError::Usage(
1972
- "leaders accepts only one QUERY or --search TEXT".to_string(),
1973
- ));
1974
- }
1975
- }
1976
- value if value.starts_with('-') => {
1977
- return Err(CliError::Usage(format!(
1978
- "unknown leaders argument: {value}"
1979
- )))
1980
- }
1981
- value => {
1982
- if query.replace(value.to_string()).is_some() {
1983
- return Err(CliError::Usage(
1984
- "leaders accepts only one QUERY or --search TEXT".to_string(),
1985
- ));
1986
- }
1987
- }
1988
- }
1989
- i = i.saturating_add(1);
1990
- }
1991
- if query
1992
- .as_deref()
1993
- .is_some_and(|value| value.trim().is_empty())
1994
- {
1995
- return Err(CliError::Usage("leaders QUERY cannot be blank".to_string()));
1996
- }
1997
- if prune && view.is_some() {
1998
- return Err(CliError::Usage(
1999
- "leaders --prune cannot be combined with --all or --stale".to_string(),
2000
- ));
2001
- }
2002
- if prune && query.is_some() {
2003
- return Err(CliError::Usage(
2004
- "leaders --prune cannot be combined with QUERY or --search".to_string(),
2005
- ));
2006
- }
2007
- if dry_run && !prune {
2008
- return Err(CliError::Usage(
2009
- "leaders --dry-run requires --prune".to_string(),
2010
- ));
2011
- }
2012
- Ok(LeadersArgs {
2013
- view: view.unwrap_or(LeadersView::Live),
2014
- query,
2015
- prune,
2016
- dry_run,
2017
- json,
2018
- })
2019
- }
2020
-
2021
- fn profile_args(args: &[String], cwd: &Path) -> Result<ProfileArgs, CliError> {
2022
- let parsed = parse_args(args);
2023
- let workspace = resolve_cli_path(cwd, &workspace(&parsed, cwd));
2024
- Ok(ProfileArgs {
2025
- command: required_pos(&parsed, 0, "profile command")?,
2026
- name: required_pos(&parsed, 1, "profile name")?,
2027
- workspace: resolve_path(&workspace),
2028
- team: parsed.team,
2029
- auth_mode: parsed.auth_mode,
2030
- proxy_mode: parsed.proxy_mode,
2031
- json: parsed.json,
2032
- })
2033
- }
2034
-
2035
- fn run_coordinator(args: &[String], cwd: &Path) -> Result<ExitCode, CliError> {
2036
- let parsed = parse_args(args);
2037
- let workspace = crate::coordinator::WorkspacePath::new(workspace(&parsed, cwd));
2038
- // 0.5.x Windows portability Batch 9 F8: pass `--team` through
2039
- // to the daemon so it doesn't have to derive from state at
2040
- // boot time. `parse_args` already recognizes `--team`; we just
2041
- // thread the value into `DaemonArgs::team_key`.
2042
- crate::coordinator::run_daemon(crate::coordinator::DaemonArgs {
2043
- workspace,
2044
- once: parsed.once,
2045
- tick_interval_sec: parsed.tick_interval,
2046
- team_key: parsed.team.clone(),
2047
- })
2048
- .map(|()| ExitCode::Ok)
2049
- .map_err(|e| CliError::Runtime(e.to_string()))
2050
- }
2051
-
2052
- fn human_value(value: &Value) -> String {
2053
- match value {
2054
- Value::Null => "None".to_string(),
2055
- Value::Bool(true) => "True".to_string(),
2056
- Value::Bool(false) => "False".to_string(),
2057
- Value::Number(n) => n.to_string(),
2058
- Value::String(s) => s.clone(),
2059
- Value::Array(_) | Value::Object(_) => json_dumps_like(value),
2060
- }
2061
- }
2062
-
2063
- fn json_dumps_like(value: &Value) -> String {
2064
- match value {
2065
- Value::Null => "null".to_string(),
2066
- Value::Bool(b) => b.to_string(),
2067
- Value::Number(n) => n.to_string(),
2068
- Value::String(s) => match serde_json::to_string(s) {
2069
- Ok(text) => text,
2070
- Err(_) => "\"\"".to_string(),
2071
- },
2072
- Value::Array(arr) => {
2073
- let inner = arr
2074
- .iter()
2075
- .map(json_dumps_like)
2076
- .collect::<Vec<_>>()
2077
- .join(", ");
2078
- format!("[{inner}]")
2079
- }
2080
- Value::Object(obj) => {
2081
- let inner = obj
2082
- .iter()
2083
- .map(|(k, v)| {
2084
- format!(
2085
- "{}: {}",
2086
- json_dumps_like(&Value::String(k.clone())),
2087
- json_dumps_like(v)
2088
- )
2089
- })
2090
- .collect::<Vec<_>>()
2091
- .join(", ");
2092
- format!("{{{inner}}}")
2093
- }
2094
- }
2095
- }
2096
-
2097
- #[cfg(test)]
2098
- mod tests {
2099
- #![allow(clippy::unwrap_used)]
2100
-
2101
- use super::*;
2102
-
2103
- fn tmp_workspace() -> PathBuf {
2104
- use std::sync::atomic::{AtomicU64, Ordering};
2105
- static CTR: AtomicU64 = AtomicU64::new(0);
2106
- let dir = std::env::temp_dir().join(format!(
2107
- "ta-cli-emit-test-{}-{}",
2108
- std::process::id(),
2109
- CTR.fetch_add(1, Ordering::Relaxed)
2110
- ));
2111
- std::fs::create_dir_all(&dir).unwrap();
2112
- dir
2113
- }
2114
-
2115
- fn cli_argv(items: &[&str]) -> Vec<String> {
2116
- items.iter().map(|s| (*s).to_string()).collect()
2117
- }
2118
-
2119
- fn visible_help_commands(help: &str) -> Vec<String> {
2120
- help.lines()
2121
- .filter_map(|line| {
2122
- let trimmed = line.strip_prefix(" ")?;
2123
- if trimmed.starts_with("team-agent ") || trimmed.starts_with(char::is_whitespace) {
2124
- return None;
2125
- }
2126
- let command = trimmed.split_whitespace().next()?;
2127
- (command.chars().next()?.is_ascii_lowercase()
2128
- && command
2129
- .chars()
2130
- .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-'))
2131
- .then(|| command.to_string())
2132
- })
2133
- .collect()
2134
- }
2135
-
2136
- #[test]
2137
- fn leaders_parser_supports_views_and_search() {
2138
- let parsed = leaders_args(
2139
- &cli_argv(&["--all", "--search", "Wiki", "--json"]),
2140
- Path::new("."),
2141
- )
2142
- .unwrap();
2143
- assert_eq!(parsed.view, LeadersView::All);
2144
- assert_eq!(parsed.query.as_deref(), Some("Wiki"));
2145
- assert!(!parsed.prune);
2146
- assert!(!parsed.dry_run);
2147
- assert!(parsed.json);
2148
- }
2149
-
2150
- #[test]
2151
- fn leaders_parser_rejects_invalid_search_and_prune_combinations() {
2152
- for args in [
2153
- cli_argv(&["one", "two"]),
2154
- cli_argv(&["one", "--search", "two"]),
2155
- cli_argv(&["--search", " "]),
2156
- cli_argv(&["--dry-run"]),
2157
- cli_argv(&["--prune", "--stale"]),
2158
- cli_argv(&["--prune", "--search", "x"]),
2159
- ] {
2160
- assert!(
2161
- leaders_args(&args, Path::new(".")).is_err(),
2162
- "args={args:?}"
2163
- );
2164
- }
2165
- }
2166
-
2167
- #[test]
2168
- fn command_specs_have_unique_names() {
2169
- let mut names = std::collections::BTreeSet::new();
2170
- for spec in COMMAND_SPECS {
2171
- assert!(
2172
- names.insert(spec.name),
2173
- "duplicate command spec `{}`",
2174
- spec.name
2175
- );
2176
- }
2177
- }
2178
-
2179
- #[test]
2180
- fn all_dispatch_kinds_have_exactly_one_spec() {
2181
- for kind in ALL_DISPATCH_KINDS {
2182
- let count = COMMAND_SPECS
2183
- .iter()
2184
- .filter(|spec| spec.kind == CommandKind::Dispatch(*kind))
2185
- .count();
2186
- assert_eq!(
2187
- count, 1,
2188
- "dispatch kind `{kind:?}` must appear in exactly one CommandSpec"
2189
- );
2190
- }
2191
- }
2192
-
2193
- #[test]
2194
- fn known_command_gate_uses_specs() {
2195
- for spec in COMMAND_SPECS.iter().filter(|spec| spec.command_help) {
2196
- assert!(
2197
- is_known_subcommand(spec.name),
2198
- "`{}` must be accepted by the known-command help gate",
2199
- spec.name
2200
- );
2201
- }
2202
- assert!(!is_known_subcommand("missing-c1-command"));
2203
- }
2204
-
2205
- #[test]
2206
- fn default_help_lists_only_default_help_specs() {
2207
- let top_help = command_help(None);
2208
- let visible = visible_help_commands(&top_help);
2209
- for command in &visible {
2210
- let spec = command_spec(command).expect("visible command must have a spec");
2211
- assert!(
2212
- spec.default_help,
2213
- "`{command}` appears in default help without default_help=true"
2214
- );
2215
- }
2216
- let expected: Vec<&str> = COMMAND_SPECS
2217
- .iter()
2218
- .filter(|spec| spec.default_help)
2219
- .map(|spec| spec.name)
2220
- .collect();
2221
- assert_eq!(
2222
- expected.len(),
2223
- 34,
2224
- "the public catalog adds the four canonical lifecycle surfaces and retires the Cursor launcher"
2225
- );
2226
- for spec_name in &expected {
2227
- assert!(
2228
- visible.iter().any(|command| command == spec_name),
2229
- "`{spec_name}` has default_help=true but is missing from top-level help"
2230
- );
2231
- }
2232
- let mut actual = visible.clone();
2233
- actual.sort();
2234
- let mut expected_sorted: Vec<String> =
2235
- expected.iter().map(|name| (*name).to_string()).collect();
2236
- expected_sorted.sort();
2237
- assert_eq!(
2238
- actual, expected_sorted,
2239
- "default help must match the exact public spec set, not a slack threshold; got {visible:?}"
2240
- );
2241
- assert!(
2242
- top_help.contains("copilot"),
2243
- "top-level leader passthrough help must list copilot"
2244
- );
2245
- }
2246
-
2247
- #[test]
2248
- fn hidden_commands_not_in_default_help() {
2249
- let top_help = command_help(None);
2250
- let visible = visible_help_commands(&top_help);
2251
- assert!(visible.iter().any(|command| command == "doctor"));
2252
- assert!(visible.iter().any(|command| command == "leaders"));
2253
- for command in [
2254
- "results",
2255
- "wait",
2256
- "attach-app-server-leader",
2257
- "identity",
2258
- "watch",
2259
- "sessions",
2260
- "validate",
2261
- "preflight",
2262
- "wait-ready",
2263
- "e2e",
2264
- "peek",
2265
- "coordinator",
2266
- ] {
2267
- assert!(
2268
- !visible.iter().any(|visible| visible == command),
2269
- "`{command}` must stay hidden from default help"
2270
- );
2271
- }
2272
- }
2273
-
2274
- #[test]
2275
- fn retired_commands_have_no_catalog_machine_or_help_gate() {
2276
- for command in [
2277
- "e2e",
2278
- "allow-peer-talk",
2279
- "results",
2280
- "validate",
2281
- "identity",
2282
- "sessions",
2283
- "watch",
2284
- "peek",
2285
- "wait-ready",
2286
- "preflight",
2287
- ] {
2288
- assert!(
2289
- command_spec(command).is_none(),
2290
- "retired catalog entry: {command}"
2291
- );
2292
- assert!(
2293
- !is_machine_command(command),
2294
- "retired Machine route: {command}"
2295
- );
2296
- assert!(
2297
- !is_known_subcommand(command),
2298
- "retired help gate: {command}"
2299
- );
2300
- }
2301
- }
2302
-
2303
- #[test]
2304
- fn leaders_help_publishes_selectors_and_prune() {
2305
- let help = command_help(Some("leaders"));
2306
- assert!(help.contains("--all"));
2307
- assert!(help.contains("--stale"));
2308
- assert!(help.contains("--search TEXT"));
2309
- assert!(help.contains("--prune"));
2310
- assert!(help.contains("--dry-run"));
2311
- }
2312
-
2313
- #[test]
2314
- fn observation_a_commands_have_terminal_tiers() {
2315
- for (command, tier) in [
2316
- ("approvals", CommandTier::Core),
2317
- ("profile", CommandTier::Core),
2318
- ("install-skill", CommandTier::Core),
2319
- ] {
2320
- assert_eq!(command_spec(command).map(|spec| spec.tier), Some(tier));
2321
- }
2322
- }
2323
-
2324
- #[test]
2325
- fn suggestion_index_excludes_hidden_commands() {
2326
- assert_eq!(nearest_subcommand("statu"), Some("status"));
2327
- assert_eq!(nearest_subcommand("leader"), Some("leaders"));
2328
- assert_eq!(nearest_subcommand("fallback-send-leade"), None);
2329
- assert_eq!(nearest_subcommand("coordinato"), None);
2330
- }
2331
-
2332
- #[test]
2333
- fn copilot_is_listed_as_leader_passthrough_candidate() {
2334
- assert!(command_help(None).contains("copilot"));
2335
- assert_eq!(nearest_subcommand("copliot"), Some("copilot"));
2336
- }
2337
-
2338
- #[test]
2339
- fn copilot_help_dispatches_as_leader_passthrough() {
2340
- let cwd = tmp_workspace();
2341
- assert_eq!(run(&cli_argv(&["copilot", "--help"]), &cwd), ExitCode::Ok);
2342
- }
2343
-
2344
- #[test]
2345
- fn t0_help_catalog_lists_command_flags() {
2346
- for (command, flags) in [
2347
- (
2348
- "quick-start",
2349
- &["--workspace", "--team-id", "--yes", "--json"][..],
2350
- ),
2351
- ("send", &["--workspace", "--team", "--json"][..]),
2352
- (
2353
- "status",
2354
- &["--workspace", "--team", "--summary", "--json", "--detail"][..],
2355
- ),
2356
- (
2357
- "shutdown",
2358
- &["--workspace", "--team", "--keep-logs", "--json"][..],
2359
- ),
2360
- (
2361
- "restart",
2362
- &[
2363
- "--team",
2364
- "--allow-fresh",
2365
- "--session-converge-deadline",
2366
- "--json",
2367
- ][..],
2368
- ),
2369
- (
2370
- "start-agent",
2371
- &[
2372
- "--model",
2373
- "--effort",
2374
- "--bypass",
2375
- "--prompt",
2376
- "--profile",
2377
- "--provider",
2378
- "--workspace",
2379
- "--team",
2380
- "--allow-fresh",
2381
- "--json",
2382
- ][..],
2383
- ),
2384
- (
2385
- "reset-agent",
2386
- &["--workspace", "--team", "--discard-session", "--json"][..],
2387
- ),
2388
- (
2389
- "add-agent",
2390
- &[
2391
- "--role-file",
2392
- "--provider",
2393
- "--bypass",
2394
- "--model",
2395
- "--effort",
2396
- "--prompt",
2397
- "--profile",
2398
- "--force",
2399
- "--workspace",
2400
- "--team",
2401
- "--json",
2402
- ][..],
2403
- ),
2404
- (
2405
- "fork-agent",
2406
- &["--as", "--label", "--workspace", "--team", "--json"][..],
2407
- ),
2408
- (
2409
- "remove-agent",
2410
- &[
2411
- "--workspace",
2412
- "--team",
2413
- "--from-spec",
2414
- "--confirm",
2415
- "--force",
2416
- "--json",
2417
- ][..],
2418
- ),
2419
- (
2420
- "doctor",
2421
- &[
2422
- "--workspace",
2423
- "--team",
2424
- "--gate",
2425
- "--fix-schema",
2426
- "--cleanup-orphans",
2427
- "--json",
2428
- ][..],
2429
- ),
2430
- (
2431
- "attach-leader",
2432
- &[
2433
- "--workspace",
2434
- "--team",
2435
- "--pane",
2436
- "--provider",
2437
- "--confirm",
2438
- "--json",
2439
- ][..],
2440
- ),
2441
- ("stop-agent", &["--workspace", "--team", "--json"][..]),
2442
- ("approvals", &["--workspace", "--team", "--json"][..]),
2443
- (
2444
- "inbox",
2445
- &["--workspace", "--team", "-n", "--limit", "--json"][..],
2446
- ),
2447
- ] {
2448
- let help = command_help(Some(command));
2449
- for flag in flags {
2450
- assert!(
2451
- help.contains(flag),
2452
- "`team-agent {command} --help` is missing {flag}"
2453
- );
2454
- }
2455
- }
2456
- let cwd = tmp_workspace();
2457
- for command in ["wait", "attach-app-server-leader", "coordinator"] {
2458
- assert_eq!(
2459
- run(&cli_argv(&[command, "--help"]), &cwd),
2460
- ExitCode::Usage,
2461
- "Machine help must be generic Usage2, not a private flag tutorial"
2462
- );
2463
- }
2464
- std::fs::remove_dir_all(cwd).unwrap();
2465
- assert!(
2466
- !command_help(Some("quick-start")).contains("--fresh"),
2467
- "quick-start help must not advertise removed reset semantics"
2468
- );
2469
- }
2470
-
2471
- #[test]
2472
- fn public_help_templates_and_cli_guidance_are_english() {
2473
- fn assert_english(text: &str) {
2474
- assert!(
2475
- !text.chars().any(|ch| matches!(ch, '\u{3400}'..='\u{9fff}')),
2476
- "unauthorized CJK CLI guidance: {text}"
2477
- );
2478
- }
2479
- assert_english(&default_help());
2480
- assert_eq!(TEAM_TEMPLATE.lines().nth(1), Some("name: current"));
2481
- for spec in COMMAND_SPECS {
2482
- assert_english(spec.summary);
2483
- assert_english(&command_help(Some(spec.name)));
2484
- }
2485
- for text in [
2486
- TEAM_TEMPLATE,
2487
- WORKER_TEMPLATE,
2488
- HUMAN_NAVIGATION,
2489
- crate::cli::route::HELP,
2490
- crate::cli::COMMS_BOUNDARY_TEXT,
2491
- crate::cli::QUICK_START_REMINDER,
2492
- crate::cli::SEND_REMINDER,
2493
- crate::cli::STATUS_REMINDER,
2494
- ] {
2495
- assert_english(text);
2496
- }
2497
- for command in ["quick-start", "restart", "send"] {
2498
- let payload = CliError::Runtime("fixture failure".to_string())
2499
- .to_payload(Path::new("/tmp/fixture.log"), command);
2500
- assert_english(&payload.action);
2501
- }
2502
- }
2503
-
2504
- #[test]
2505
- fn worker_lifecycle_help_uses_authoritative_spec_usage_and_summary() {
2506
- for name in ["start-agent", "add-agent"] {
2507
- let spec = command_spec(name).expect("registered worker lifecycle command");
2508
- let help = command_help(Some(name));
2509
- assert!(help.contains(spec.usage));
2510
- assert!(help.contains("Purpose:"));
2511
- for flag in [
2512
- "--model MODEL",
2513
- "--effort LEVEL",
2514
- "--bypass true|false",
2515
- "--prompt TEXT",
2516
- "--profile NAME",
2517
- "--provider TOOL",
2518
- ] {
2519
- assert!(help.contains(flag), "{name} help missing {flag}: {help}");
2520
- }
2521
- assert!(help.contains("Next Action") && help.contains("send"));
2522
- }
2523
- assert!(!command_help(Some("start-agent")).contains("--force"));
2524
- let add = command_help(Some("add-agent"));
2525
- assert!(add.contains("[--role-file FILE]"));
2526
- assert!(add.contains("provider") && add.contains("bypass") && add.contains("--role-file"));
2527
- assert!(add.contains("Conflicting") && add.contains("refused"));
2528
- }
2529
-
2530
- #[test]
2531
- fn status_help_describes_brief_projection_and_unknown_boundary() {
2532
- let help = command_help(Some("status"));
2533
- for marker in [
2534
- "name/provider/model/effort/runtime_status/activity/health/session_name/tmux_command",
2535
- "Use --json for structured output",
2536
- "unknown means insufficient evidence",
2537
- "tmux_command",
2538
- "do not add fields",
2539
- ] {
2540
- assert!(
2541
- help.contains(marker),
2542
- "status help missing {marker}: {help}"
2543
- );
2544
- }
2545
- assert!(!help.contains("error breakdown via status --summary"));
2546
- }
2547
-
2548
- #[test]
2549
- fn models_defaults_provider_and_accepts_one_query_form() {
2550
- let defaulted = models_args(&cli_argv(&["gpt", "5.6", "luna"])).unwrap();
2551
- assert_eq!(defaulted.provider, "pi");
2552
- assert_eq!(defaulted.search.as_deref(), Some("gpt 5.6 luna"));
2553
-
2554
- let cursor = models_args(&cli_argv(&[
2555
- "--provider",
2556
- "cursor",
2557
- "--search",
2558
- "GPT Luna",
2559
- ]))
2560
- .unwrap();
2561
- assert_eq!(cursor.provider, "cursor");
2562
- assert_eq!(cursor.search.as_deref(), Some("GPT Luna"));
2563
-
2564
- let both = models_args(&cli_argv(&["luna", "--search", "gpt"])).unwrap_err();
2565
- assert!(
2566
- matches!(both, CliError::Usage(message) if message.contains("either QUERY or --search TEXT"))
2567
- );
2568
- let blank = models_args(&cli_argv(&["--search", " "])).unwrap();
2569
- assert_eq!(blank.search, None);
2570
- }
2571
-
2572
- #[test]
2573
- fn send_pane_positionals_are_message_not_target() {
2574
- let cwd = tmp_workspace();
2575
- let args = send_args(&cli_argv(&["--pane", "%1596", "hello"]), &cwd).unwrap();
2576
- assert_eq!(args.pane.as_deref(), Some("%1596"));
2577
- assert_eq!(args.target, None);
2578
- assert_eq!(args.targets, None);
2579
- assert_eq!(args.message, vec!["hello".to_string()]);
2580
-
2581
- let args = send_args(
2582
- &cli_argv(&["--pane", "%1596", "multi", "word", "message"]),
2583
- &cwd,
2584
- )
2585
- .unwrap();
2586
- assert_eq!(args.target, None);
2587
- assert_eq!(
2588
- args.message,
2589
- vec![
2590
- "multi".to_string(),
2591
- "word".to_string(),
2592
- "message".to_string()
2593
- ]
2594
- );
2595
-
2596
- let _ = std::fs::remove_dir_all(&cwd);
2597
- }
2598
-
2599
- #[test]
2600
- fn send_mailbox_and_legacy_progress_map_to_the_one_bit_request() {
2601
- let cwd = tmp_workspace();
2602
- let mailbox = send_args(&cli_argv(&["leader", "progress", "--mailbox"]), &cwd).unwrap();
2603
- assert_eq!(
2604
- mailbox.presentation.sink,
2605
- crate::messaging::presentation::PresentationSink::Casefile
2606
- );
2607
-
2608
- let args = send_args(
2609
- &cli_argv(&[
2610
- "leader",
2611
- "progress",
2612
- "--presentation-sink",
2613
- "casefile",
2614
- "--message-class",
2615
- "progress",
2616
- "--case-id",
2617
- "case-9",
2618
- ]),
2619
- &cwd,
2620
- )
2621
- .unwrap();
2622
- assert_eq!(
2623
- args.presentation.sink,
2624
- crate::messaging::presentation::PresentationSink::Casefile
2625
- );
2626
- assert_eq!(
2627
- args.presentation.class,
2628
- crate::messaging::presentation::PresentationClass::Message
2629
- );
2630
- assert_eq!(args.presentation.case_id, None);
2631
- }
2632
-
2633
- #[test]
2634
- fn send_presentation_flags_fail_closed_when_incomplete() {
2635
- let cwd = tmp_workspace();
2636
- let error = send_args(
2637
- &cli_argv(&["leader", "progress", "--presentation-sink", "casefile"]),
2638
- &cwd,
2639
- )
2640
- .unwrap_err();
2641
- assert!(matches!(
2642
- error,
2643
- CliError::Usage(message) if message == "invalid send routing: missing_class"
2644
- ));
2645
- }
2646
-
2647
- #[test]
2648
- fn send_to_name_positionals_are_message_not_target() {
2649
- let cwd = tmp_workspace();
2650
- let args = send_args(&cli_argv(&["--to-name", "team-a/qa", "hello"]), &cwd).unwrap();
2651
- assert_eq!(args.to_name.as_deref(), Some("team-a/qa"));
2652
- assert_eq!(args.target, None);
2653
- assert_eq!(args.targets, None);
2654
- assert_eq!(args.message, vec!["hello".to_string()]);
2655
-
2656
- let args = send_args(
2657
- &cli_argv(&["--to-name=team-a/qa", "multi", "word", "message"]),
2658
- &cwd,
2659
- )
2660
- .unwrap();
2661
- assert_eq!(args.target, None);
2662
- assert_eq!(
2663
- args.message,
2664
- vec![
2665
- "multi".to_string(),
2666
- "word".to_string(),
2667
- "message".to_string()
2668
- ]
2669
- );
2670
-
2671
- let _ = std::fs::remove_dir_all(&cwd);
2672
- }
2673
-
2674
- #[test]
2675
- fn send_pane_still_rejects_to_and_empty_message() {
2676
- let cwd = tmp_workspace();
2677
- let err = send_args(
2678
- &cli_argv(&["--pane", "%1596", "--to", "worker", "hello"]),
2679
- &cwd,
2680
- ).unwrap_err();
2681
- assert!(matches!(err, CliError::Usage(ref message) if message.contains("one recipient addressing mode")));
2682
- // The public parser now refuses first; the typed handler must still
2683
- // reject the same conflict if a non-CLI caller constructs it directly.
2684
- let mut args = send_args(&cli_argv(&["--pane", "%1596", "hello"]), &cwd).unwrap();
2685
- args.targets = Some("worker".to_string());
2686
- let err = cmd_send(&args).unwrap_err();
2687
- assert!(
2688
- matches!(err, CliError::Usage(ref message) if message.contains("--pane") && message.contains("--to") && message.contains("cannot") && message.contains("combined")),
2689
- "expected --pane/--to mutual-exclusion usage error, got {err:?}"
2690
- );
2691
-
2692
- let args = send_args(&cli_argv(&["--pane", "%1596"]), &cwd).unwrap();
2693
- let err = cmd_send(&args).unwrap_err();
2694
- assert!(
2695
- matches!(err, CliError::Usage(ref message) if message.contains("--pane") && message.contains("cannot send an empty message")),
2696
- "expected empty-message usage error, got {err:?}"
2697
- );
2698
-
2699
- let _ = std::fs::remove_dir_all(&cwd);
2700
- }
2701
-
2702
- #[test]
2703
- fn ux_quick_start_workspace_resolves_relative_agents_dir_inside_workspace() {
2704
- let cwd = tmp_workspace();
2705
- let ws = tmp_workspace();
2706
- let args = quick_start_args(
2707
- &cli_argv(&[
2708
- "--workspace",
2709
- &ws.to_string_lossy(),
2710
- "agents",
2711
- "--yes",
2712
- "--json",
2713
- ]),
2714
- &cwd,
2715
- )
2716
- .unwrap();
2717
- assert_eq!(
2718
- args.agents_dir,
2719
- ws.join("agents"),
2720
- "quick-start --workspace <ws> agents must resolve the role-doc dir under <ws>, so team-in-team \
2721
- setup works from any caller cwd"
2722
- );
2723
- let _ = std::fs::remove_dir_all(&cwd);
2724
- let _ = std::fs::remove_dir_all(&ws);
2725
- }
2726
-
2727
- #[test]
2728
- fn ux_quick_start_positional_team_dir_is_standalone_workspace() {
2729
- let cwd = tmp_workspace();
2730
- let ws = tmp_workspace();
2731
- std::fs::write(ws.join("TEAM.md"), "# team\n").unwrap();
2732
- let args = quick_start_args(&cli_argv(&[&ws.to_string_lossy()]), &cwd).unwrap();
2733
- assert_eq!(args.workspace, ws);
2734
- assert_eq!(args.agents_dir, ws);
2735
- let _ = std::fs::remove_dir_all(&cwd);
2736
- let _ = std::fs::remove_dir_all(&ws);
2737
- }
2738
-
2739
- #[test]
2740
- fn ux_quick_start_team_dir_under_dot_team_uses_project_workspace() {
2741
- let cwd = tmp_workspace();
2742
- let team_dir = cwd.join(".team/current");
2743
- std::fs::create_dir_all(&team_dir).unwrap();
2744
- std::fs::write(team_dir.join("TEAM.md"), "# team\n").unwrap();
2745
- let args = quick_start_args(&cli_argv(&[".team/current"]), &cwd).unwrap();
2746
- assert_eq!(args.workspace, cwd);
2747
- assert_eq!(args.agents_dir, team_dir);
2748
- let _ = std::fs::remove_dir_all(&cwd);
2749
- }
2750
-
2751
- // ── E8 (N38): 未知子命令 → 最近似建议(additive,不破坏 golden invalid-choice 行) ──
2752
- #[test]
2753
- fn e8_unknown_subcommand_suggests_nearest_known_command() {
2754
- // 'statu' typo → status; 'add-agen' → add-agent.
2755
- assert_eq!(nearest_subcommand("statu"), Some("status"));
2756
- assert_eq!(nearest_subcommand("add-agen"), Some("add-agent"));
2757
- // Presentation migration: the new canonical short verb is now a
2758
- // prefix candidate in the unchanged shared similarity ranking.
2759
- assert_eq!(nearest_subcommand("start-agnet"), Some("start"));
2760
- }
2761
-
2762
- #[test]
2763
- fn e8_unknown_subcommand_no_suggestion_when_far() {
2764
- // 完全无关的串不应误配出任何建议。
2765
- assert_eq!(nearest_subcommand("zzzzzzzzzz"), None);
2766
- assert_eq!(nearest_subcommand("x"), None);
2767
- }
2768
-
2769
- #[test]
2770
- fn e8_levenshtein_basic() {
2771
- // 0.5.45 naming-addressing: distance function moved to
2772
- // `crate::model::name_similarity` (shared with --to-name typo
2773
- // suggestions). Same math, single source.
2774
- use crate::model::name_similarity::levenshtein;
2775
- assert_eq!(levenshtein("kitten", "sitting"), 3);
2776
- assert_eq!(levenshtein("status", "status"), 0);
2777
- assert_eq!(levenshtein("statu", "status"), 1);
2778
- }
2779
-
2780
- // ─── Stage 4: multi-team ambiguity refusal for destructive commands ───
2781
-
2782
- fn seed_two_alive_teams_in(ws: &std::path::Path) {
2783
- crate::state::persist::save_runtime_state(
2784
- ws,
2785
- &serde_json::json!({
2786
- "teams": {
2787
- "alpha": {"status": "alive"},
2788
- "beta": {"status": "alive"},
2789
- },
2790
- }),
2791
- )
2792
- .unwrap();
2793
- }
2794
-
2795
- #[test]
2796
- fn refuse_helper_passes_on_single_alive_team() {
2797
- let ws = tmp_workspace();
2798
- crate::state::persist::save_runtime_state(
2799
- &ws,
2800
- &serde_json::json!({"teams": {"alpha": {"status": "alive"}}}),
2801
- )
2802
- .unwrap();
2803
- assert!(
2804
- refuse_if_multi_alive_team_missing_scope("stuck-cancel", &ws, None).is_ok(),
2805
- "single-alive-team workspace must not trigger the ambiguity refusal"
2806
- );
2807
- }
2808
-
2809
- #[test]
2810
- fn shutdown_args_builder_refuses_on_multi_alive_team() {
2811
- let ws = tmp_workspace();
2812
- seed_two_alive_teams_in(&ws);
2813
- let argv = cli_argv(&["--workspace", &ws.to_string_lossy()]);
2814
- let err = shutdown_args(&argv, &ws).expect_err("must refuse");
2815
- assert!(
2816
- err.to_string().contains("multiple alive teams"),
2817
- "shutdown args builder must surface the refusal; got: {err}"
2818
- );
2819
- }
2820
-
2821
- #[test]
2822
- fn restart_args_builder_refuses_on_multi_alive_team() {
2823
- let ws = tmp_workspace();
2824
- seed_two_alive_teams_in(&ws);
2825
- let argv = cli_argv(&[&ws.to_string_lossy()]);
2826
- let err = restart_args(&argv, &ws).expect_err("must refuse");
2827
- assert!(
2828
- err.to_string().contains("multiple alive teams"),
2829
- "restart args builder must surface the refusal; got: {err}"
2830
- );
2831
- }
2832
-
2833
- #[test]
2834
- fn reset_agent_complete_input_refuses_multi_alive_team_before_agent_validation() {
2835
- let ws = tmp_workspace();
2836
- seed_two_alive_teams_in(&ws);
2837
- let argv = cli_argv(&[
2838
- "nonexistent-agent",
2839
- "--discard-session",
2840
- "--workspace",
2841
- &ws.to_string_lossy(),
2842
- ]);
2843
- let err = reset_agent_args(&argv, &ws).expect_err("must refuse");
2844
- assert!(
2845
- err.to_string().contains("multiple alive teams"),
2846
- "reset-agent args builder must surface the refusal; got: {err}"
2847
- );
2848
- }
2849
-
2850
- #[test]
2851
- fn remove_agent_complete_input_refuses_multi_alive_team_before_agent_validation() {
2852
- let ws = tmp_workspace();
2853
- seed_two_alive_teams_in(&ws);
2854
- let argv = cli_argv(&["nonexistent-agent", "--workspace", &ws.to_string_lossy()]);
2855
- let err = remove_agent_args(&argv, &ws).expect_err("must refuse");
2856
- assert!(
2857
- err.to_string().contains("multiple alive teams"),
2858
- "remove-agent args builder must surface the refusal; got: {err}"
2859
- );
2860
- }
2861
-
2862
- // ──────────── Stage QR: quick-start/restart separation ────────────
2863
- // Design doc: .team/artifacts/quickstart-restart-separation-design.md
2864
-
2865
- #[test]
2866
- fn quick_start_refuses_fresh_flag_with_restart_guidance() {
2867
- // QR contract: `--fresh` is gone from quick-start. The flag is
2868
- // not advertised or carried in QuickStartArgs, but scripts that
2869
- // still pass it get a clear redirect to restart --allow-fresh.
2870
- let ws = tmp_workspace();
2871
- let argv = cli_argv(&["--workspace", &ws.to_string_lossy(), "--fresh"]);
2872
- let err = quick_start_args(&argv, &ws).expect_err("must refuse --fresh");
2873
- let message = err.to_string();
2874
- assert!(
2875
- message.contains("no longer accepts --fresh"),
2876
- "QR: refusal must say --fresh is gone; got: {message}"
2877
- );
2878
- assert!(
2879
- message.contains("restart --allow-fresh"),
2880
- "QR: refusal must redirect to `restart --allow-fresh`; got: {message}"
2881
- );
2882
- }
2883
-
2884
- #[test]
2885
- fn quick_start_without_fresh_flag_still_builds_args() {
2886
- // Without --fresh, args build normally (the initial-creation path).
2887
- let ws = tmp_workspace();
2888
- let argv = cli_argv(&["--workspace", &ws.to_string_lossy()]);
2889
- let args = quick_start_args(&argv, &ws).expect("must build");
2890
- assert_eq!(args.workspace, ws);
2891
- // No `fresh` field anymore — the struct must compile and round-trip
2892
- // without it.
2893
- }
2894
- }
2895
-
2896
- #[cfg(test)]
2897
- #[path = "tests/parser_safety.rs"]
2898
- mod parser_safety_tests;