@team-agent/installer 0.5.128 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +37 -20
  5. package/skills/team-agent/command-coverage.json +169 -183
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +64 -30
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +64 -30
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1288
  15. package/crates/team-agent/src/cli/arguments.rs +0 -405
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1721
  18. package/crates/team-agent/src/cli/emit.rs +0 -2930
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1216
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -912
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -689
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6545
  29. package/crates/team-agent/src/cli/models.rs +0 -1206
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/schedule.rs +0 -175
  34. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  35. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  36. package/crates/team-agent/src/cli/send/persist.rs +0 -156
  37. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  38. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  39. package/crates/team-agent/src/cli/send.rs +0 -199
  40. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  41. package/crates/team-agent/src/cli/spec.rs +0 -165
  42. package/crates/team-agent/src/cli/status.rs +0 -280
  43. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  44. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  45. package/crates/team-agent/src/cli/status_port/brief.rs +0 -1981
  46. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  47. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  48. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  49. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  50. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  51. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  52. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  53. package/crates/team-agent/src/cli/status_port.rs +0 -92
  54. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  55. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  56. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  57. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -322
  58. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  59. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  60. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  61. package/crates/team-agent/src/cli/tests/named_address.rs +0 -761
  62. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  63. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -484
  64. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  65. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  66. package/crates/team-agent/src/cli/tests/status_send.rs +0 -888
  67. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  68. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  69. package/crates/team-agent/src/cli/triage.rs +0 -234
  70. package/crates/team-agent/src/cli/types.rs +0 -591
  71. package/crates/team-agent/src/codex_app_server.rs +0 -546
  72. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  73. package/crates/team-agent/src/compiler/tests.rs +0 -827
  74. package/crates/team-agent/src/compiler.rs +0 -890
  75. package/crates/team-agent/src/conpty/backend.rs +0 -829
  76. package/crates/team-agent/src/conpty/mod.rs +0 -33
  77. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1744
  78. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  79. package/crates/team-agent/src/contract_runtime/config.rs +0 -364
  80. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -76
  81. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -449
  82. package/crates/team-agent/src/contract_runtime/fork.rs +0 -361
  83. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  84. package/crates/team-agent/src/contract_runtime/framework.rs +0 -367
  85. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -394
  86. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  87. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  88. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  89. package/crates/team-agent/src/contract_runtime/registry.rs +0 -553
  90. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  91. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  92. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  93. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  94. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  95. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  96. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  97. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  98. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  99. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  101. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  102. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  104. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  105. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  106. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  107. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -300
  108. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  109. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  110. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  111. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -503
  112. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  113. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  114. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  115. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  116. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  117. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  118. package/crates/team-agent/src/coordinator/tick.rs +0 -3024
  119. package/crates/team-agent/src/coordinator/types.rs +0 -540
  120. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  121. package/crates/team-agent/src/db/message_store.rs +0 -1527
  122. package/crates/team-agent/src/db/migration.rs +0 -984
  123. package/crates/team-agent/src/db/mod.rs +0 -26
  124. package/crates/team-agent/src/db/schema.rs +0 -663
  125. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  126. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  127. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  128. package/crates/team-agent/src/direct_delivery.rs +0 -368
  129. package/crates/team-agent/src/event_log.rs +0 -502
  130. package/crates/team-agent/src/fake_worker.rs +0 -303
  131. package/crates/team-agent/src/inbox_store.rs +0 -169
  132. package/crates/team-agent/src/kill_audit.rs +0 -106
  133. package/crates/team-agent/src/layout/manager.rs +0 -248
  134. package/crates/team-agent/src/layout/mod.rs +0 -36
  135. package/crates/team-agent/src/layout/overlay.rs +0 -134
  136. package/crates/team-agent/src/layout/placement.rs +0 -52
  137. package/crates/team-agent/src/layout/recovery.rs +0 -106
  138. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  139. package/crates/team-agent/src/layout/sessions.rs +0 -294
  140. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  141. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  142. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  143. package/crates/team-agent/src/leader/helpers.rs +0 -178
  144. package/crates/team-agent/src/leader/incident.rs +0 -6
  145. package/crates/team-agent/src/leader/lease.rs +0 -3356
  146. package/crates/team-agent/src/leader/mod.rs +0 -104
  147. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  148. package/crates/team-agent/src/leader/prompt.rs +0 -905
  149. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  150. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  151. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  152. package/crates/team-agent/src/leader/registry.rs +0 -888
  153. package/crates/team-agent/src/leader/start.rs +0 -4501
  154. package/crates/team-agent/src/leader/takeover.rs +0 -65
  155. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  156. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  157. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  158. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  159. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  160. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  161. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  162. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  163. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  164. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  165. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -268
  166. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  167. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  168. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  169. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  170. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  171. package/crates/team-agent/src/leader/types.rs +0 -534
  172. package/crates/team-agent/src/lib.rs +0 -147
  173. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  174. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -881
  175. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -598
  176. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  177. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -204
  178. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -107
  179. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -144
  180. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  181. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  182. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  183. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -160
  184. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  185. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -899
  186. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -225
  187. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  188. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5200
  189. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  190. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  191. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  192. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -473
  193. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  194. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  195. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  196. package/crates/team-agent/src/lifecycle/launch.rs +0 -557
  197. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  198. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  199. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  200. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -1067
  201. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  202. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2199
  203. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1798
  204. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +0 -163
  205. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2362
  206. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  207. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  208. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  209. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  210. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  211. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  212. package/crates/team-agent/src/lifecycle/restart.rs +0 -227
  213. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1230
  214. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  215. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  216. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  217. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  218. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  219. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  220. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -447
  221. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1638
  222. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  223. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -770
  224. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -419
  225. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2035
  226. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1327
  227. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  228. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  229. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  230. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -72
  231. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  232. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  233. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -512
  234. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  235. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  236. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  237. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3983
  238. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  239. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  240. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  241. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  242. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  243. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  244. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -164
  245. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -200
  246. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  247. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -527
  248. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -1062
  249. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1419
  250. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -98
  251. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -550
  252. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -226
  253. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -332
  254. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  255. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  256. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  257. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  258. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  259. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  260. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  261. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  262. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  263. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  264. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  265. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  266. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -342
  267. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  268. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  269. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  270. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  271. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  272. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  273. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  274. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -995
  275. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -836
  276. package/crates/team-agent/src/lifecycle/tests.rs +0 -105
  277. package/crates/team-agent/src/lifecycle/types.rs +0 -877
  278. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -363
  279. package/crates/team-agent/src/main.rs +0 -52
  280. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  281. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  282. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  283. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  284. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  285. package/crates/team-agent/src/mcp_server/readiness.rs +0 -527
  286. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -348
  287. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  288. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  289. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -158
  290. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -353
  291. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -341
  292. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  293. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  294. package/crates/team-agent/src/mcp_server/tools.rs +0 -889
  295. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  296. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  297. package/crates/team-agent/src/messaging/activity.rs +0 -461
  298. package/crates/team-agent/src/messaging/address.rs +0 -87
  299. package/crates/team-agent/src/messaging/delivery.rs +0 -3727
  300. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  301. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  302. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  303. package/crates/team-agent/src/messaging/helpers.rs +0 -336
  304. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  305. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  306. package/crates/team-agent/src/messaging/mod.rs +0 -167
  307. package/crates/team-agent/src/messaging/persist.rs +0 -377
  308. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  309. package/crates/team-agent/src/messaging/reminders.rs +0 -316
  310. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  311. package/crates/team-agent/src/messaging/results.rs +0 -1415
  312. package/crates/team-agent/src/messaging/scheduler.rs +0 -223
  313. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  314. package/crates/team-agent/src/messaging/send.rs +0 -981
  315. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  316. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -657
  317. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  318. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  319. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  320. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  321. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  322. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3549
  323. package/crates/team-agent/src/messaging/tests/spine.rs +0 -853
  324. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  325. package/crates/team-agent/src/messaging/trust.rs +0 -215
  326. package/crates/team-agent/src/messaging/types.rs +0 -472
  327. package/crates/team-agent/src/messaging/wait.rs +0 -366
  328. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  329. package/crates/team-agent/src/model/enums.rs +0 -356
  330. package/crates/team-agent/src/model/errors.rs +0 -18
  331. package/crates/team-agent/src/model/ids.rs +0 -165
  332. package/crates/team-agent/src/model/mod.rs +0 -29
  333. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  334. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  335. package/crates/team-agent/src/model/paths.rs +0 -257
  336. package/crates/team-agent/src/model/routing.rs +0 -387
  337. package/crates/team-agent/src/model/spec.rs +0 -1184
  338. package/crates/team-agent/src/model/task_graph.rs +0 -321
  339. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  340. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  341. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  342. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  343. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  344. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  345. package/crates/team-agent/src/model/yaml.rs +0 -802
  346. package/crates/team-agent/src/os_probe.rs +0 -280
  347. package/crates/team-agent/src/packaging/install.rs +0 -219
  348. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  349. package/crates/team-agent/src/packaging/mod.rs +0 -91
  350. package/crates/team-agent/src/packaging/repair.rs +0 -33
  351. package/crates/team-agent/src/packaging/tests.rs +0 -822
  352. package/crates/team-agent/src/packaging/types.rs +0 -417
  353. package/crates/team-agent/src/platform/argv.rs +0 -331
  354. package/crates/team-agent/src/platform/errors.rs +0 -104
  355. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  356. package/crates/team-agent/src/platform/mod.rs +0 -5
  357. package/crates/team-agent/src/platform/process.rs +0 -545
  358. package/crates/team-agent/src/provider/adapter.rs +0 -1150
  359. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  360. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  361. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  362. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  363. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  364. package/crates/team-agent/src/provider/adapters/mod.rs +0 -30
  365. package/crates/team-agent/src/provider/adapters/pi.rs +0 -106
  366. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  367. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  368. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  369. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  370. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  371. package/crates/team-agent/src/provider/classify.rs +0 -708
  372. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  373. package/crates/team-agent/src/provider/faults.rs +0 -165
  374. package/crates/team-agent/src/provider/helpers.rs +0 -52
  375. package/crates/team-agent/src/provider/mod.rs +0 -78
  376. package/crates/team-agent/src/provider/model_catalog.rs +0 -910
  377. package/crates/team-agent/src/provider/session/capture.rs +0 -2731
  378. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  379. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -172
  380. package/crates/team-agent/src/provider/session/context_fork.rs +0 -396
  381. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  382. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  383. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  384. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  385. package/crates/team-agent/src/provider/session_scan/common.rs +0 -654
  386. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  387. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -185
  388. package/crates/team-agent/src/provider/session_scan.rs +0 -71
  389. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  390. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  391. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  392. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  393. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  394. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  395. package/crates/team-agent/src/provider/tests/adapter.rs +0 -441
  396. package/crates/team-agent/src/provider/tests/classify.rs +0 -148
  397. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -35
  398. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  399. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  400. package/crates/team-agent/src/provider/tests/idle.rs +0 -177
  401. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  402. package/crates/team-agent/src/provider/tests.rs +0 -32
  403. package/crates/team-agent/src/provider/types.rs +0 -529
  404. package/crates/team-agent/src/provider/wire.rs +0 -394
  405. package/crates/team-agent/src/redaction.rs +0 -259
  406. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  407. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  408. package/crates/team-agent/src/state/identity.rs +0 -914
  409. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  410. package/crates/team-agent/src/state/mod.rs +0 -74
  411. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  412. package/crates/team-agent/src/state/ownership.rs +0 -563
  413. package/crates/team-agent/src/state/paths.rs +0 -395
  414. package/crates/team-agent/src/state/persist.rs +0 -3811
  415. package/crates/team-agent/src/state/projection.rs +0 -1508
  416. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  417. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  418. package/crates/team-agent/src/state/repository.rs +0 -866
  419. package/crates/team-agent/src/state/selector.rs +0 -160
  420. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  421. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
  422. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  423. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  424. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  425. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  426. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4103
  427. package/crates/team-agent/src/tmux_backend.rs +0 -4492
  428. package/crates/team-agent/src/topology.rs +0 -537
  429. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  430. package/crates/team-agent/src/transport/native_input.rs +0 -491
  431. package/crates/team-agent/src/transport/test_support.rs +0 -743
  432. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  433. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  434. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  435. package/crates/team-agent/src/transport.rs +0 -1655
  436. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,1230 +0,0 @@
1
- //! CLI convenience is a role-document transaction, not a provider override.
2
- //! Existing file compilation and process/session lifecycle remain authoritative.
3
-
4
- use std::fs::{self, OpenOptions};
5
- use std::io::Write;
6
- use std::path::{Path, PathBuf};
7
- use std::sync::atomic::{AtomicU64, Ordering};
8
-
9
- use crate::model::ids::AgentId;
10
- use crate::model::yaml::{self, Value};
11
- use crate::state::repository::{StateRepository, StateWriteIntent};
12
- use crate::state::selector::{SelectedTeam, SelectorMode};
13
- use crate::transport::Transport;
14
-
15
- use super::lock::{acquire_agent_lifecycle_lock, LifecycleLockRequest};
16
- use super::{AddAgentReport, LifecycleError, StartAgentOutcome};
17
-
18
- #[derive(Debug, Clone, Default, PartialEq, Eq)]
19
- pub struct RoleConfigPatch {
20
- pub provider: Option<String>,
21
- pub model: Option<String>,
22
- pub effort: Option<String>,
23
- pub bypass: Option<bool>,
24
- pub prompt: Option<String>,
25
- pub profile: Option<String>,
26
- }
27
-
28
- pub fn add_agent_from_role(
29
- workspace: &Path,
30
- agent_id: &AgentId,
31
- source: Option<&Path>,
32
- patch: &RoleConfigPatch,
33
- force: bool,
34
- team: Option<&str>,
35
- ) -> Result<AddAgentReport, LifecycleError> {
36
- if let Some(path) = source {
37
- if !path.is_file() {
38
- return Err(LifecycleError::Compile(format!(
39
- "role file not found: {}",
40
- path.display()
41
- )));
42
- }
43
- }
44
- let selected = select(workspace, team)?;
45
- with_selected(&selected, agent_id, |selected| {
46
- let transport = super::restart::lifecycle_worker_tmux_backend_selection_for_state(
47
- &selected.run_workspace,
48
- &selected.state,
49
- )?
50
- .backend;
51
- add_at_selected(selected, agent_id, source, patch, force, &transport)
52
- })
53
- }
54
-
55
- #[cfg(test)]
56
- pub(crate) fn add_agent_from_role_with_transport(
57
- workspace: &Path,
58
- agent_id: &AgentId,
59
- source: Option<&Path>,
60
- patch: &RoleConfigPatch,
61
- force: bool,
62
- transport: &dyn Transport,
63
- ) -> Result<AddAgentReport, LifecycleError> {
64
- with_selected(&select(workspace, None)?, agent_id, |selected| {
65
- add_at_selected(selected, agent_id, source, patch, force, transport)
66
- })
67
- }
68
-
69
- pub fn start_agent_from_role(
70
- workspace: &Path,
71
- agent_id: &AgentId,
72
- patch: &RoleConfigPatch,
73
- allow_fresh: bool,
74
- team: Option<&str>,
75
- ) -> Result<StartAgentOutcome, LifecycleError> {
76
- let selected = select(workspace, team)?;
77
- with_selected(&selected, agent_id, |selected| {
78
- let transport = super::restart::lifecycle_worker_tmux_backend_selection_for_state(
79
- &selected.run_workspace,
80
- &selected.state,
81
- )?
82
- .backend;
83
- start_at_selected(selected, agent_id, patch, allow_fresh, &transport)
84
- })
85
- }
86
-
87
- fn select(workspace: &Path, team: Option<&str>) -> Result<SelectedTeam, LifecycleError> {
88
- crate::state::selector::resolve_active_team_readonly(workspace, team, SelectorMode::RuntimeOnly)
89
- .map_err(|error| LifecycleError::TeamSelect(error.to_string()))
90
- }
91
-
92
- fn with_selected<T>(
93
- selected: &SelectedTeam,
94
- agent_id: &AgentId,
95
- operation: impl FnOnce(&SelectedTeam) -> Result<T, LifecycleError>,
96
- ) -> Result<T, LifecycleError> {
97
- validate_id(agent_id)?;
98
- let _lock = acquire_agent_lifecycle_lock(LifecycleLockRequest {
99
- workspace: &selected.run_workspace,
100
- operation: "role-config",
101
- team: Some(&selected.team_key),
102
- agent_id: Some(agent_id),
103
- })?;
104
- let latest = select(&selected.run_workspace, Some(&selected.team_key))?;
105
- super::launch::ensure_owner_allowed_for_state(&latest.state, Some(agent_id))?;
106
- operation(&latest)
107
- }
108
-
109
- fn add_at_selected(
110
- selected: &SelectedTeam,
111
- agent_id: &AgentId,
112
- source: Option<&Path>,
113
- patch: &RoleConfigPatch,
114
- force: bool,
115
- transport: &dyn Transport,
116
- ) -> Result<AddAgentReport, LifecycleError> {
117
- let recreate = admit_add(&selected.state, agent_id, force, transport)?;
118
- let spec = read_spec(selected)?;
119
- if !recreate && spec_has_agent(&spec, agent_id) {
120
- return Err(LifecycleError::RequirementUnmet(format!(
121
- "agent id already exists: {agent_id}"
122
- )));
123
- }
124
- let role_path = role_path(selected, agent_id);
125
- // --force re-adopts the role file a removed seat left behind (#391): CLI
126
- // values override its frontmatter and its body is kept.
127
- let adopted = !recreate
128
- && force
129
- && source.is_none()
130
- && fs::symlink_metadata(&role_path).is_ok_and(|meta| meta.is_file());
131
- if !recreate && !adopted {
132
- check_destination(&role_path, source)?;
133
- }
134
- let text = match source {
135
- Some(path) => read_text(path)?,
136
- None if adopted => patched_role(&read_text(&role_path)?, agent_id, patch, false)?,
137
- None => String::new(),
138
- };
139
- let generated = source.is_none() && !adopted;
140
- #[allow(unused_mut)]
141
- let mut reconciled = reconcile_creation(&text, patch)?;
142
- // A generated legacy role falls back to its id as instructions at compile
143
- // time; a contract role requires a body, so give it a neutral default.
144
- #[cfg(unix)]
145
- if generated
146
- && reconciled.prompt.is_none()
147
- && crate::contract_runtime::framework::declares_contract(
148
- None,
149
- reconciled.provider.as_deref(),
150
- )
151
- {
152
- reconciled.prompt = Some(format!(
153
- "You are {agent_id}. Complete the tasks assigned by the leader.\n"
154
- ));
155
- }
156
- let next = patched_role(&text, agent_id, &reconciled, generated)?;
157
- let snapshot = RoleSnapshot::capture(selected, &role_path)?;
158
- let result = (|| {
159
- if snapshot.role.bytes.as_deref() != Some(next.as_bytes()) {
160
- atomic_write(&role_path, next.as_bytes())?;
161
- }
162
- // Reuse existing lifecycle transactions; force never admits a live seat.
163
- let add = if recreate {
164
- super::launch::force_recreate_with_transport_locked
165
- } else {
166
- super::launch::add_agent_with_transport_at_paths_locked
167
- };
168
- add(
169
- &selected.run_workspace,
170
- &selected.team_dir,
171
- agent_id,
172
- &role_path,
173
- true,
174
- Some(&selected.team_key),
175
- transport,
176
- )
177
- })();
178
- match result {
179
- Ok(report) => Ok(report),
180
- Err(error) => Err(snapshot.rollback(selected, agent_id, error)),
181
- }
182
- }
183
-
184
- // Disaster recovery is opt-in and requires positive death of a recorded pane.
185
- // An absent/unknown pane binding is not permission to replace an existing seat.
186
- fn admit_add(
187
- state: &serde_json::Value,
188
- agent_id: &AgentId,
189
- force: bool,
190
- transport: &dyn Transport,
191
- ) -> Result<bool, LifecycleError> {
192
- let Some(agent) = state
193
- .get("agents")
194
- .and_then(|agents| agents.get(agent_id.as_str()))
195
- else {
196
- return Ok(false);
197
- };
198
- let duplicate =
199
- || LifecycleError::RequirementUnmet(format!("agent id already exists: {agent_id}"));
200
- if !force {
201
- return Err(duplicate());
202
- }
203
- super::restart::ensure_agent_not_running(state, agent_id, transport)?;
204
- let Some(pane) = agent
205
- .get("pane_id")
206
- .and_then(serde_json::Value::as_str)
207
- .filter(|value| !value.is_empty())
208
- else {
209
- return Err(duplicate());
210
- };
211
- let pane = crate::transport::PaneId::new(pane);
212
- let dead = match transport.has_pane(&pane) {
213
- Ok(Some(present)) => !present,
214
- Ok(None) | Err(_) => matches!(
215
- transport.liveness(&pane),
216
- Ok(crate::model::enums::PaneLiveness::Dead)
217
- ),
218
- };
219
- if dead {
220
- Ok(true)
221
- } else {
222
- Err(duplicate())
223
- }
224
- }
225
-
226
- fn start_at_selected(
227
- selected: &SelectedTeam,
228
- agent_id: &AgentId,
229
- patch: &RoleConfigPatch,
230
- allow_fresh: bool,
231
- transport: &dyn Transport,
232
- ) -> Result<StartAgentOutcome, LifecycleError> {
233
- let old_agent = selected
234
- .state
235
- .get("agents")
236
- .and_then(|agents| agents.get(agent_id.as_str()))
237
- .ok_or_else(|| LifecycleError::RequirementUnmet(format!("agent {agent_id} not found")))?;
238
- super::restart::ensure_agent_not_running(&selected.state, agent_id, transport)?;
239
- if old_agent.get("paused").and_then(serde_json::Value::as_bool) == Some(true) {
240
- return Err(LifecycleError::RequirementUnmet(format!(
241
- "agent {agent_id} is paused"
242
- )));
243
- }
244
- let source = super::launch::role_source::resolve_role_source(
245
- &selected.run_workspace,
246
- &selected.team_dir,
247
- &selected.state,
248
- agent_id,
249
- )?;
250
- let role_path = role_path(selected, agent_id);
251
- check_destination(&role_path, Some(&source))?;
252
- let text = read_text(&source)?;
253
- let next = patched_role(&text, agent_id, patch, false)?;
254
- // Compare to the established engine, never to a freshly edited spec or model name.
255
- let old_provider = old_agent
256
- .get("provider")
257
- .and_then(serde_json::Value::as_str)
258
- .and_then(crate::provider::wire::parse_provider)
259
- .ok_or_else(|| {
260
- LifecycleError::RequirementUnmet("established provider is unknown".into())
261
- })?;
262
- let meta = crate::compiler::read_front_matter(&source)
263
- .map_err(|error| LifecycleError::Compile(error.to_string()))?
264
- .0;
265
- // Preserve the traditional compiler's interpretation of omitted metadata.
266
- let provider = patch
267
- .provider
268
- .as_deref()
269
- .or_else(|| meta.get("provider").and_then(Value::as_str))
270
- .filter(|value| !value.trim().is_empty())
271
- .unwrap_or("pi");
272
- let provider = crate::provider::wire::parse_provider(provider)
273
- .ok_or_else(|| LifecycleError::Compile("unknown role provider".into()))?;
274
- if provider != old_provider {
275
- return Err(LifecycleError::RequirementUnmet(format!(
276
- "provider change is not allowed for agent {agent_id}: {} -> {}",
277
- crate::provider::wire::provider_wire(old_provider),
278
- crate::provider::wire::provider_wire(provider),
279
- )));
280
- }
281
- let snapshot = RoleSnapshot::capture(selected, &role_path)?;
282
- let result = (|| {
283
- if snapshot.role.bytes.as_deref() != Some(next.as_bytes()) {
284
- atomic_write(&role_path, next.as_bytes())?;
285
- }
286
- let team_meta = crate::compiler::read_front_matter(&selected.team_dir.join("TEAM.md"))
287
- .map_err(|error| LifecycleError::Compile(error.to_string()))?
288
- .0;
289
- let compiled = crate::compiler::compile_role_agent(
290
- &role_path,
291
- &team_meta,
292
- &selected.run_workspace.to_string_lossy(),
293
- )
294
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
295
- if compiled.id != agent_id.as_str() {
296
- return Err(LifecycleError::Compile(
297
- "role identity does not match agent id".into(),
298
- ));
299
- }
300
- if compiled
301
- .agent
302
- .get("provider")
303
- .and_then(Value::as_str)
304
- .and_then(crate::provider::wire::parse_provider)
305
- != Some(old_provider)
306
- {
307
- return Err(LifecycleError::RequirementUnmet(
308
- "compiled provider does not match established provider".into(),
309
- ));
310
- }
311
- let mut spec = read_spec(selected)?;
312
- replace_spec_agent(&mut spec, agent_id, &compiled.agent)?;
313
- crate::model::spec::validate_spec(&spec, &selected.run_workspace)
314
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
315
- atomic_write(&snapshot.spec.path, yaml::dumps(&spec).as_bytes())?;
316
- update_agent_config(selected, agent_id, &compiled.agent, &role_path)?;
317
- let outcome = super::restart::start_agent_at_paths(
318
- &selected.run_workspace,
319
- snapshot.spec.path.parent().unwrap_or(&selected.team_dir),
320
- agent_id,
321
- false,
322
- true,
323
- allow_fresh,
324
- Some(&selected.team_key),
325
- transport,
326
- )?;
327
- match outcome {
328
- StartAgentOutcome::Running { .. } => Ok(outcome),
329
- StartAgentOutcome::Noop { .. } => Err(LifecycleError::RequirementUnmet(format!(
330
- "agent {agent_id} is already running; use stop-agent first"
331
- ))),
332
- StartAgentOutcome::Paused { .. } => Err(LifecycleError::RequirementUnmet(format!(
333
- "agent {agent_id} is paused"
334
- ))),
335
- }
336
- })();
337
- match result {
338
- Ok(outcome) => Ok(outcome),
339
- Err(error) => Err(snapshot.rollback(selected, agent_id, error)),
340
- }
341
- }
342
-
343
- // Keep role-file values authoritative except for explicit CLI bypass intent.
344
- // Equal supplied values are omitted from the patch to preserve existing file bytes.
345
- fn reconcile_creation(
346
- text: &str,
347
- patch: &RoleConfigPatch,
348
- ) -> Result<RoleConfigPatch, LifecycleError> {
349
- let (meta, body) = role_parts(text)?;
350
- for field in ["provider", "model", "effort", "profile"] {
351
- if meta
352
- .get(field)
353
- .is_some_and(|value| !matches!(value, Value::Null | Value::Str(_)))
354
- {
355
- return Err(LifecycleError::Compile(format!(
356
- "role {field} must be a string"
357
- )));
358
- }
359
- }
360
- let mut next = patch.clone();
361
- let conflict = |field: &str| {
362
- LifecycleError::RequirementUnmet(format!(
363
- "conflicting {field}: --role-file and CLI values differ"
364
- ))
365
- };
366
- let file_provider = meta
367
- .get("provider")
368
- .and_then(Value::as_str)
369
- .filter(|value| !value.trim().is_empty());
370
- if let Some(file_provider) = file_provider {
371
- let file_provider = declared_provider(file_provider)
372
- .ok_or_else(|| LifecycleError::Compile("unknown role provider".into()))?;
373
- if let Some(provider) = &next.provider {
374
- if declared_provider(provider) != Some(file_provider) {
375
- return Err(conflict("provider"));
376
- }
377
- next.provider = None;
378
- }
379
- } else if next.provider.is_none() {
380
- return Err(LifecycleError::RequirementUnmet(
381
- "add-agent requires provider in --role-file or --provider <name>".into(),
382
- ));
383
- }
384
- match meta.get("dangerously_skip_permissions") {
385
- Some(Value::Bool(value)) => {
386
- if next.bypass == Some(*value) {
387
- next.bypass = None;
388
- }
389
- }
390
- Some(_) => {
391
- return Err(LifecycleError::Compile(
392
- "role dangerously_skip_permissions must be a boolean".into(),
393
- ))
394
- }
395
- None => {}
396
- }
397
- for (field, supplied) in [
398
- ("model", &mut next.model),
399
- ("effort", &mut next.effort),
400
- ("profile", &mut next.profile),
401
- ] {
402
- if let Some(file_value) = meta
403
- .get(field)
404
- .and_then(Value::as_str)
405
- .filter(|value| !value.trim().is_empty())
406
- {
407
- if let Some(value) = supplied.as_ref() {
408
- let equal = if field == "effort" {
409
- crate::model::enums::ProviderEffort::parse(file_value)
410
- == crate::model::enums::ProviderEffort::parse(value)
411
- } else {
412
- value == file_value
413
- };
414
- if !equal {
415
- return Err(conflict(field));
416
- }
417
- *supplied = None;
418
- }
419
- }
420
- }
421
- if let Some(prompt) = &next.prompt {
422
- if !body.trim().is_empty() {
423
- if prompt.trim() != body.trim() {
424
- return Err(conflict("prompt"));
425
- }
426
- next.prompt = None;
427
- }
428
- }
429
- Ok(next)
430
- }
431
-
432
- /// One identity per declared provider: its contract leaf id, else its legacy
433
- /// wire form, so `agent` in a role file and `--provider cursor` agree.
434
- fn declared_provider(value: &str) -> Option<&'static str> {
435
- #[cfg(unix)]
436
- if let Some(descriptor) = crate::contract_runtime::registry::declared(value) {
437
- return Some(descriptor.identity.id);
438
- }
439
- crate::provider::wire::parse_provider(value).map(crate::provider::wire::provider_wire)
440
- }
441
-
442
- fn role_path(selected: &SelectedTeam, agent_id: &AgentId) -> PathBuf {
443
- selected
444
- .team_dir
445
- .join("agents")
446
- .join(format!("{agent_id}.md"))
447
- }
448
-
449
- fn validate_id(agent_id: &AgentId) -> Result<(), LifecycleError> {
450
- let id = agent_id.as_str();
451
- if id.is_empty() || id == "." || id == ".." || id.contains(['/', '\\', '\0']) {
452
- return Err(LifecycleError::RequirementUnmet("invalid agent id".into()));
453
- }
454
- Ok(())
455
- }
456
-
457
- fn check_destination(path: &Path, source: Option<&Path>) -> Result<(), LifecycleError> {
458
- if fs::symlink_metadata(path).is_ok() {
459
- if !source.is_some_and(|source| {
460
- fs::canonicalize(source)
461
- .ok()
462
- .zip(fs::canonicalize(path).ok())
463
- .is_some_and(|(source, target)| source == target)
464
- }) {
465
- return Err(LifecycleError::RequirementUnmet(format!(
466
- "role file already exists: {}{}",
467
- path.display(),
468
- if source.is_none() {
469
- "; reuse it with --role-file or re-adopt it with --force"
470
- } else {
471
- ""
472
- }
473
- )));
474
- }
475
- }
476
- Ok(())
477
- }
478
-
479
- fn read_text(path: &Path) -> Result<String, LifecycleError> {
480
- fs::read_to_string(path)
481
- .map_err(|error| LifecycleError::Compile(format!("{}: {error}", path.display())))
482
- }
483
-
484
- // Unlike read_front_matter, this returns the unnormalised body slice, including blank lines.
485
- fn role_parts(text: &str) -> Result<(Value, &str), LifecycleError> {
486
- let (end, opening) = raw_line_end(text, 0);
487
- if &text[..end] != "---" || end == opening {
488
- return Ok((Value::Map(Vec::new()), text));
489
- }
490
- let mut offset = opening;
491
- while offset < text.len() {
492
- let (end, next) = raw_line_end(text, offset);
493
- if &text[offset..end] == "---" {
494
- let header = text[opening..offset]
495
- .replace("\r\n", "\n")
496
- .replace('\r', "\n");
497
- let meta = if header.trim().is_empty() {
498
- Value::Map(Vec::new())
499
- } else {
500
- yaml::loads(&header).map_err(|error| LifecycleError::Compile(error.to_string()))?
501
- };
502
- if !meta.is_map() {
503
- return Err(LifecycleError::Compile(
504
- "role frontmatter must be a map".into(),
505
- ));
506
- }
507
- return Ok((meta, &text[next..]));
508
- }
509
- offset = next;
510
- }
511
- Err(LifecycleError::Compile(
512
- "unterminated role frontmatter".into(),
513
- ))
514
- }
515
-
516
- fn raw_line_end(text: &str, start: usize) -> (usize, usize) {
517
- match text[start..].find(['\r', '\n']) {
518
- Some(relative) => {
519
- let end = start + relative;
520
- (
521
- end,
522
- end + if text[end..].starts_with("\r\n") {
523
- 2
524
- } else {
525
- 1
526
- },
527
- )
528
- }
529
- None => (text.len(), text.len()),
530
- }
531
- }
532
-
533
- pub(crate) fn patched_role(
534
- text: &str,
535
- agent_id: &AgentId,
536
- patch: &RoleConfigPatch,
537
- generated: bool,
538
- ) -> Result<String, LifecycleError> {
539
- if !generated && patch == &RoleConfigPatch::default() {
540
- return Ok(text.to_string());
541
- }
542
- let (mut meta, body) = role_parts(text)?;
543
- for key in ["agent_id", "name"] {
544
- if meta
545
- .get(key)
546
- .and_then(Value::as_str)
547
- .is_some_and(|id| id != agent_id.as_str())
548
- {
549
- return Err(LifecycleError::Compile(format!(
550
- "role {key} does not match {agent_id}"
551
- )));
552
- }
553
- }
554
- let before = meta.clone();
555
- if generated {
556
- set(&mut meta, "name", Value::Str(agent_id.as_str().into()))?;
557
- }
558
- for (key, value) in [
559
- ("provider", patch.provider.as_ref()),
560
- ("model", patch.model.as_ref()),
561
- ("effort", patch.effort.as_ref()),
562
- ("profile", patch.profile.as_ref()),
563
- ] {
564
- if let Some(value) = value {
565
- set(&mut meta, key, Value::Str(value.clone()))?;
566
- }
567
- }
568
- if let Some(value) = patch.bypass {
569
- set(
570
- &mut meta,
571
- "dangerously_skip_permissions",
572
- Value::Bool(value),
573
- )?;
574
- }
575
- if before == meta && patch.prompt.is_none() && !generated {
576
- return Ok(text.to_string());
577
- }
578
- let body = patch.prompt.as_deref().unwrap_or(body);
579
- Ok(format!(
580
- "---\n{}---\n{}",
581
- super::launch::role_source::dump_role_frontmatter(&meta),
582
- body
583
- ))
584
- }
585
-
586
- fn set(map: &mut Value, key: &str, value: Value) -> Result<(), LifecycleError> {
587
- let Value::Map(pairs) = map else {
588
- return Err(LifecycleError::Compile("expected map".into()));
589
- };
590
- if pairs.iter().filter(|(name, _)| name == key).count() > 1 {
591
- return Err(LifecycleError::Compile(format!(
592
- "duplicate role field: {key}"
593
- )));
594
- }
595
- if let Some((_, old)) = pairs.iter_mut().find(|(name, _)| name == key) {
596
- *old = value;
597
- } else {
598
- pairs.push((key.into(), value));
599
- }
600
- Ok(())
601
- }
602
-
603
- fn read_spec(selected: &SelectedTeam) -> Result<Value, LifecycleError> {
604
- let path = selected
605
- .spec_path
606
- .as_ref()
607
- .ok_or_else(|| LifecycleError::Compile("missing spec".into()))?;
608
- yaml::loads(&read_text(path)?).map_err(|error| LifecycleError::Compile(error.to_string()))
609
- }
610
-
611
- fn spec_has_agent(spec: &Value, agent_id: &AgentId) -> bool {
612
- spec.get("agents")
613
- .and_then(Value::as_list)
614
- .is_some_and(|agents| {
615
- agents
616
- .iter()
617
- .any(|agent| agent.get("id").and_then(Value::as_str) == Some(agent_id.as_str()))
618
- })
619
- }
620
-
621
- fn replace_spec_agent(
622
- spec: &mut Value,
623
- agent_id: &AgentId,
624
- next: &Value,
625
- ) -> Result<(), LifecycleError> {
626
- let Value::Map(fields) = spec else {
627
- return Err(LifecycleError::Compile("invalid spec".into()));
628
- };
629
- let Some((_, Value::List(agents))) = fields.iter_mut().find(|(key, _)| key == "agents") else {
630
- return Err(LifecycleError::Compile("spec agents missing".into()));
631
- };
632
- let target = agents
633
- .iter_mut()
634
- .find(|agent| agent.get("id").and_then(Value::as_str) == Some(agent_id.as_str()))
635
- .ok_or_else(|| LifecycleError::Compile("agent missing from spec".into()))?;
636
- *target = next.clone();
637
- Ok(())
638
- }
639
-
640
- fn to_json(value: &Value) -> serde_json::Value {
641
- match value {
642
- Value::Null => serde_json::Value::Null,
643
- Value::Bool(value) => (*value).into(),
644
- Value::Int(value) => (*value).into(),
645
- Value::Float(value) => serde_json::json!(value),
646
- Value::Str(value) => value.clone().into(),
647
- Value::List(values) => values.iter().map(to_json).collect(),
648
- Value::Map(values) => values
649
- .iter()
650
- .map(|(key, value)| (key.clone(), to_json(value)))
651
- .collect(),
652
- }
653
- }
654
-
655
- fn update_agent_config(
656
- selected: &SelectedTeam,
657
- agent_id: &AgentId,
658
- compiled: &Value,
659
- role: &Path,
660
- ) -> Result<(), LifecycleError> {
661
- StateRepository::new(&selected.run_workspace)
662
- .commit(
663
- StateWriteIntent::StartAgent {
664
- team_key: &selected.team_key,
665
- agent_id: agent_id.as_str(),
666
- },
667
- |state| {
668
- if let Some(agent) = state
669
- .get_mut("agents")
670
- .and_then(|agents| agents.get_mut(agent_id.as_str()))
671
- .and_then(serde_json::Value::as_object_mut)
672
- {
673
- for field in [
674
- "provider",
675
- "model",
676
- "role",
677
- "system_prompt",
678
- "output_contract",
679
- "auth_mode",
680
- "effort",
681
- "profile",
682
- "dangerously_skip_permissions",
683
- "communication_mode",
684
- ] {
685
- if let Some(value) = compiled.get(field) {
686
- agent.insert(field.into(), to_json(value));
687
- } else {
688
- agent.remove(field);
689
- }
690
- }
691
- agent.insert(
692
- "dynamic_role_file".into(),
693
- role.to_string_lossy().to_string().into(),
694
- );
695
- agent.insert("role_source_ownership".into(), "external".into());
696
- agent.insert(
697
- "model_source".into(),
698
- if compiled.get("model").and_then(Value::as_str).is_some() {
699
- "role".into()
700
- } else {
701
- "default".into()
702
- },
703
- );
704
- // Imported roles are self-contained in this Team, including
705
- // profile lookup; never retain an external credential root.
706
- if compiled.get("profile").and_then(Value::as_str).is_some() {
707
- agent.insert(
708
- "_profile_dir".into(),
709
- selected
710
- .team_dir
711
- .join("profiles")
712
- .to_string_lossy()
713
- .to_string()
714
- .into(),
715
- );
716
- } else {
717
- agent.remove("_profile_dir");
718
- }
719
- }
720
- },
721
- )
722
- .map(|_| ())
723
- .map_err(|error| LifecycleError::StatePersist(error.to_string()))
724
- }
725
-
726
- struct FileSnapshot {
727
- path: PathBuf,
728
- bytes: Option<Vec<u8>>,
729
- }
730
- impl FileSnapshot {
731
- fn capture(path: PathBuf) -> Result<Self, LifecycleError> {
732
- let bytes = match fs::read(&path) {
733
- Ok(bytes) => Some(bytes),
734
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
735
- Err(error) => return Err(LifecycleError::StatePersist(error.to_string())),
736
- };
737
- Ok(Self { path, bytes })
738
- }
739
- fn restore(&self) -> Result<(), LifecycleError> {
740
- if self.bytes.is_some() && fs::read(&self.path).ok().as_ref() == self.bytes.as_ref() {
741
- return Ok(());
742
- }
743
- match self.bytes.as_ref() {
744
- Some(bytes) => atomic_write(&self.path, bytes),
745
- None => fs::remove_file(&self.path)
746
- .or_else(|error| {
747
- if error.kind() == std::io::ErrorKind::NotFound {
748
- Ok(())
749
- } else {
750
- Err(error)
751
- }
752
- })
753
- .map_err(|error| LifecycleError::StatePersist(error.to_string())),
754
- }
755
- }
756
- }
757
-
758
- struct RoleSnapshot {
759
- role: FileSnapshot,
760
- spec: FileSnapshot,
761
- }
762
- impl RoleSnapshot {
763
- fn capture(selected: &SelectedTeam, role: &Path) -> Result<Self, LifecycleError> {
764
- Ok(Self {
765
- role: FileSnapshot::capture(role.to_path_buf())?,
766
- spec: FileSnapshot::capture(crate::model::paths::runtime_spec_path(
767
- &selected.run_workspace,
768
- &selected.team_key,
769
- ))?,
770
- })
771
- }
772
- fn rollback(
773
- &self,
774
- selected: &SelectedTeam,
775
- agent_id: &AgentId,
776
- error: LifecycleError,
777
- ) -> LifecycleError {
778
- let mut failures = Vec::new();
779
- for snapshot in [&self.role, &self.spec] {
780
- if let Err(error) = snapshot.restore() {
781
- failures.push(error.to_string());
782
- }
783
- }
784
- let restored = StateRepository::new(&selected.run_workspace).commit(
785
- StateWriteIntent::StartAgent {
786
- team_key: &selected.team_key,
787
- agent_id: agent_id.as_str(),
788
- },
789
- |state| {
790
- for field in ["agents", "agent_lifecycle"] {
791
- if let Some(rows) = state
792
- .get_mut(field)
793
- .and_then(serde_json::Value::as_object_mut)
794
- {
795
- if let Some(old) = selected
796
- .state
797
- .get(field)
798
- .and_then(|rows| rows.get(agent_id.as_str()))
799
- {
800
- rows.insert(agent_id.as_str().into(), old.clone());
801
- } else {
802
- rows.remove(agent_id.as_str());
803
- }
804
- }
805
- }
806
- },
807
- );
808
- if let Err(error) = restored {
809
- failures.push(error.to_string());
810
- }
811
- if failures.is_empty() {
812
- error
813
- } else {
814
- LifecycleError::StatePersist(format!(
815
- "{error}; rollback failed: {}",
816
- failures.join("; ")
817
- ))
818
- }
819
- }
820
- }
821
-
822
- /// Compare-and-replace a role only after its complete native plan is admitted.
823
- /// No rollback of a live/uncertain native generation is implied by this write.
824
- pub(crate) fn commit_contract_role(
825
- path: &Path,
826
- expected: &str,
827
- replacement: &str,
828
- ) -> Result<(), LifecycleError> {
829
- if read_text(path)? != expected {
830
- return Err(LifecycleError::RequirementUnmet("role source changed during admission".into()));
831
- }
832
- if expected != replacement {
833
- atomic_write(path, replacement.as_bytes())?;
834
- }
835
- Ok(())
836
- }
837
-
838
- fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), LifecycleError> {
839
- static NEXT: AtomicU64 = AtomicU64::new(0);
840
- if let Some(parent) = path.parent() {
841
- fs::create_dir_all(parent).map_err(persist_error)?;
842
- }
843
- if fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) {
844
- return Err(LifecycleError::StatePersist(format!(
845
- "refusing to replace symlink: {}",
846
- path.display()
847
- )));
848
- }
849
- let temp = path.with_extension(format!(
850
- "tmp-{}-{}",
851
- std::process::id(),
852
- NEXT.fetch_add(1, Ordering::Relaxed)
853
- ));
854
- let mut created = false;
855
- let result = (|| {
856
- let mut file = OpenOptions::new()
857
- .write(true)
858
- .create_new(true)
859
- .open(&temp)?;
860
- created = true;
861
- if let Ok(meta) = fs::metadata(path) {
862
- file.set_permissions(meta.permissions())?;
863
- }
864
- file.write_all(bytes)?;
865
- file.sync_all()?;
866
- drop(file);
867
- fs::rename(&temp, path)
868
- })();
869
- if result.is_err() && created {
870
- let _ = fs::remove_file(&temp);
871
- }
872
- result.map_err(persist_error)
873
- }
874
-
875
- fn persist_error(error: std::io::Error) -> LifecycleError {
876
- LifecycleError::StatePersist(error.to_string())
877
- }
878
-
879
- #[cfg(test)]
880
- mod tests {
881
- #![allow(clippy::unwrap_used, clippy::expect_used)]
882
- use super::*;
883
-
884
- fn pane(id: &str, session: &str, window: &str) -> crate::transport::PaneInfo {
885
- crate::transport::PaneInfo {
886
- pane_id: crate::transport::PaneId::new(id),
887
- session: crate::transport::SessionName::new(session),
888
- window_name: Some(crate::transport::WindowName::new(window)),
889
- window_index: None,
890
- pane_index: None,
891
- tty: None,
892
- current_command: None,
893
- current_path: None,
894
- active: true,
895
- pane_pid: None,
896
- leader_env: Default::default(),
897
- }
898
- }
899
-
900
- #[test]
901
- fn live_guard_does_not_borrow_a_peer_pane_or_ignore_own_live_cohort() {
902
- use crate::transport::test_support::OfflineTransport;
903
- let state = serde_json::json!({"session_name": "s", "agents": {
904
- "a": {"pane_id": "%b", "window": "a", "status": "running"},
905
- "b": {"pane_id": "%b", "window": "b", "status": "running"}
906
- }});
907
- let id = AgentId::new("a");
908
- let transport = OfflineTransport::new()
909
- .with_targets(vec![pane("%b", "s", "b")])
910
- .with_pane_presence("%b", true);
911
- super::super::restart::ensure_agent_not_running(&state, &id, &transport).unwrap();
912
- let transport = transport
913
- .with_targets(vec![pane("%a", "s", "a"), pane("%b", "s", "b")])
914
- .with_pane_presence("%a", true);
915
- let error = super::super::restart::ensure_agent_not_running(&state, &id, &transport)
916
- .unwrap_err()
917
- .to_string();
918
- assert!(error.contains("already running") && error.contains("cohort proof"));
919
- assert!(error.contains("window=a pane=%a"));
920
- assert!(!error.contains("pane=%b"));
921
- let transport = transport.with_pane_presence("%a", false);
922
- super::super::restart::ensure_agent_not_running(&state, &id, &transport).unwrap();
923
- }
924
-
925
- #[test]
926
- fn force_admission_requires_positive_death_and_never_replaces_a_live_seat() {
927
- use crate::transport::test_support::OfflineTransport;
928
- let state = serde_json::json!({"session_name": "s", "agents": {
929
- "a": {"pane_id": "%a", "window": "a", "status": "running"}
930
- }});
931
- let id = AgentId::new("a");
932
- let dead = OfflineTransport::new()
933
- .with_targets(vec![pane("%other", "other-team", "a")])
934
- .with_pane_presence("%a", false)
935
- .with_pane_presence("%other", true);
936
- assert!(admit_add(&state, &id, false, &dead)
937
- .unwrap_err()
938
- .to_string()
939
- .contains("agent id already exists"));
940
- assert!(admit_add(&state, &id, true, &dead).unwrap());
941
- let live = OfflineTransport::new()
942
- .with_targets(vec![pane("%a", "s", "a")])
943
- .with_pane_presence("%a", true);
944
- assert!(admit_add(&state, &id, true, &live)
945
- .unwrap_err()
946
- .to_string()
947
- .contains("already running"));
948
- assert!(admit_add(&state, &id, true, &OfflineTransport::new()).is_err());
949
- let absent_binding = serde_json::json!({"agents": {"a": {"status": "stopped"}}});
950
- assert!(admit_add(&absent_binding, &id, true, &dead).is_err());
951
- assert!(!admit_add(&serde_json::json!({"agents": {}}), &id, true, &dead).unwrap());
952
- assert!(admit_add(
953
- &state,
954
- &id,
955
- true,
956
- &dead.with_list_targets_error("unknown topology")
957
- )
958
- .is_err());
959
- }
960
-
961
- #[test]
962
- fn file_decisions_need_no_repeated_flags_and_conflicts_fail_closed() {
963
- let text = "---\nprovider: codex\ndangerously_skip_permissions: false\nmodel: native-model\neffort: ultra\nprofile: local\n---\n\nrole body\n";
964
- assert_eq!(
965
- reconcile_creation(text, &RoleConfigPatch::default()).unwrap(),
966
- RoleConfigPatch::default()
967
- );
968
- let same = RoleConfigPatch {
969
- provider: Some("codex".into()),
970
- bypass: Some(false),
971
- model: Some("native-model".into()),
972
- effort: Some("ultra".into()),
973
- profile: Some("local".into()),
974
- prompt: Some("role body".into()),
975
- };
976
- assert_eq!(
977
- reconcile_creation(text, &same).unwrap(),
978
- RoleConfigPatch::default()
979
- );
980
- for different in [
981
- RoleConfigPatch {
982
- provider: Some("pi".into()),
983
- ..Default::default()
984
- },
985
- RoleConfigPatch {
986
- model: Some("other".into()),
987
- ..Default::default()
988
- },
989
- RoleConfigPatch {
990
- effort: Some("high".into()),
991
- ..Default::default()
992
- },
993
- RoleConfigPatch {
994
- prompt: Some("other".into()),
995
- ..Default::default()
996
- },
997
- RoleConfigPatch {
998
- profile: Some("other".into()),
999
- ..Default::default()
1000
- },
1001
- ] {
1002
- assert!(reconcile_creation(text, &different).is_err());
1003
- }
1004
- let supplied = RoleConfigPatch {
1005
- provider: Some("pi".into()),
1006
- bypass: Some(false),
1007
- ..Default::default()
1008
- };
1009
- assert_eq!(reconcile_creation("body", &supplied).unwrap(), supplied);
1010
- assert!(reconcile_creation("body", &RoleConfigPatch::default()).is_err());
1011
- // An invalid existing declaration is not a missing field to overwrite.
1012
- for field in ["provider", "model", "effort", "profile"] {
1013
- let text =
1014
- format!("---\n{field}: true\ndangerously_skip_permissions: false\n---\nbody");
1015
- assert!(reconcile_creation(&text, &supplied).is_err());
1016
- }
1017
- }
1018
-
1019
- #[cfg(unix)]
1020
- #[test]
1021
- fn cursor_names_in_a_role_file_and_cli_are_one_provider() {
1022
- for file in ["cursor", "cursor-agent", "agent", "cursor_agent"] {
1023
- let text = format!("---\nprovider: {file}\ndangerously_skip_permissions: true\n---\nbody");
1024
- for cli in ["cursor", "agent"] {
1025
- let patch = RoleConfigPatch { provider: Some(cli.into()), ..Default::default() };
1026
- assert_eq!(reconcile_creation(&text, &patch).unwrap(), RoleConfigPatch::default(), "{file}/{cli}");
1027
- }
1028
- let pi = RoleConfigPatch { provider: Some("pi".into()), ..Default::default() };
1029
- assert!(reconcile_creation(&text, &pi).is_err(), "{file}");
1030
- }
1031
- }
1032
-
1033
- #[test]
1034
- fn explicit_bypass_overrides_role_file_in_both_directions() {
1035
- for &provider in crate::provider::wire::all_providers() {
1036
- let provider = crate::provider::wire::provider_wire(provider);
1037
- for declared in [true, false] {
1038
- let text = format!("---\nprovider: {provider}\ndangerously_skip_permissions: {declared}\n---\nbody");
1039
- let patch = RoleConfigPatch {
1040
- bypass: Some(!declared),
1041
- ..Default::default()
1042
- };
1043
- let reconciled = reconcile_creation(&text, &patch).unwrap();
1044
- let next = patched_role(&text, &AgentId::new("w"), &reconciled, false).unwrap();
1045
- assert_eq!(
1046
- role_parts(&next).unwrap().0.get("dangerously_skip_permissions"),
1047
- Some(&Value::Bool(!declared))
1048
- );
1049
- }
1050
- }
1051
- }
1052
-
1053
- #[test]
1054
- fn omitted_bypass_preserves_native_default_and_invalid_boolean_is_rejected() {
1055
- let patch = RoleConfigPatch {
1056
- provider: Some("pi".into()),
1057
- ..Default::default()
1058
- };
1059
- assert_eq!(reconcile_creation("", &patch).unwrap().bypass, None);
1060
- assert_eq!(
1061
- reconcile_creation("---\nprovider: pi\n---\n", &RoleConfigPatch::default())
1062
- .unwrap().bypass,
1063
- None
1064
- );
1065
- assert!(reconcile_creation(
1066
- "---\nprovider: pi\ndangerously_skip_permissions: yes\n---\n", &patch
1067
- ).is_err());
1068
- }
1069
-
1070
- #[test]
1071
- fn legacy_cr_only_header_does_not_change_engine_when_patched() {
1072
- let text = "---\rprovider: codex\ndangerously_skip_permissions: false\r---\r\rbody\r";
1073
- let patch = RoleConfigPatch {
1074
- effort: Some("ultra".into()),
1075
- ..Default::default()
1076
- };
1077
- let next = patched_role(text, &AgentId::new("w"), &patch, false).unwrap();
1078
- let (meta, body) = role_parts(&next).unwrap();
1079
- assert_eq!(meta.get("provider"), Some(&Value::Str("codex".into())));
1080
- assert_eq!(body, "\rbody\r");
1081
- assert!(reconcile_creation(text, &RoleConfigPatch::default()).is_ok());
1082
- }
1083
-
1084
- #[test]
1085
- fn partial_patch_preserves_body_and_false_presence() {
1086
- let body = "\r\n\r\n中文\r\n```yaml\r\nx: y\r\n```\r\n";
1087
- let original = format!("---\r\nname: worker\r\nprovider: pi\r\ncustom: kept\r\neffort: max\r\ndangerously_skip_permissions: true\r\n---\r\n{body}");
1088
- let patch = RoleConfigPatch {
1089
- effort: Some("high".into()),
1090
- bypass: Some(false),
1091
- ..Default::default()
1092
- };
1093
- let next = patched_role(&original, &AgentId::new("worker"), &patch, false).unwrap();
1094
- let (meta, actual_body) = role_parts(&next).unwrap();
1095
- assert_eq!(actual_body, body);
1096
- assert_eq!(meta.get("custom"), Some(&Value::Str("kept".into())));
1097
- assert_eq!(meta.get("effort"), Some(&Value::Str("high".into())));
1098
- assert_eq!(
1099
- meta.get("dangerously_skip_permissions"),
1100
- Some(&Value::Bool(false))
1101
- );
1102
- }
1103
-
1104
- #[test]
1105
- fn equal_patch_is_byte_identical() {
1106
- let text = "---\n# keep formatting\nprovider: pi\ndangerously_skip_permissions: false\n---\n\nbody\n";
1107
- let patch = RoleConfigPatch {
1108
- provider: Some("pi".into()),
1109
- bypass: Some(false),
1110
- ..Default::default()
1111
- };
1112
- assert_eq!(
1113
- patched_role(text, &AgentId::new("w"), &patch, false).unwrap(),
1114
- text
1115
- );
1116
- }
1117
-
1118
- #[test]
1119
- fn prompt_replaces_instead_of_appending() {
1120
- let patch = RoleConfigPatch {
1121
- prompt: Some("new\n---\nbody".into()),
1122
- ..Default::default()
1123
- };
1124
- let text = "---\nprovider: codex\n---\nold body";
1125
- let next = patched_role(text, &AgentId::new("w"), &patch, false).unwrap();
1126
- assert_eq!(role_parts(&next).unwrap().1, "new\n---\nbody");
1127
- assert!(!next.contains("old body"));
1128
- }
1129
-
1130
- #[test]
1131
- fn traditional_plain_and_empty_header_remain_supported() {
1132
- for text in ["plain\r\nrole", "---\n---\n\nbody"] {
1133
- assert_eq!(
1134
- patched_role(text, &AgentId::new("w"), &RoleConfigPatch::default(), false).unwrap(),
1135
- text
1136
- );
1137
- }
1138
- }
1139
-
1140
- #[test]
1141
- fn imported_profile_is_team_local_and_failed_update_restores_target_only() {
1142
- let nonce = std::time::SystemTime::now()
1143
- .duration_since(std::time::UNIX_EPOCH)
1144
- .unwrap()
1145
- .as_nanos();
1146
- let root =
1147
- std::env::temp_dir().join(format!("role-projection-{}-{nonce}", std::process::id()));
1148
- let team_dir = root.join("roles");
1149
- let old = serde_json::json!({
1150
- "provider": "codex", "model": "old", "effort": "high",
1151
- "profile": "local", "_profile_dir": "/external/profiles",
1152
- "session_id": "preserved-session", "status": "stopped"
1153
- });
1154
- let sibling = serde_json::json!({"provider": "pi", "model": "keep"});
1155
- let selected_state = serde_json::json!({"agents": {"w": old.clone()}});
1156
- crate::state::persist::save_runtime_state(
1157
- &root,
1158
- &serde_json::json!({
1159
- "teams": {
1160
- "t1": selected_state.clone(),
1161
- "t2": {"agents": {"w": sibling.clone()}}
1162
- }
1163
- }),
1164
- )
1165
- .unwrap();
1166
- let spec_path = crate::model::paths::runtime_spec_path(&root, "t1");
1167
- atomic_write(&spec_path, b"old spec\r\n").unwrap();
1168
- let selected = SelectedTeam {
1169
- run_workspace: root.clone(),
1170
- team_key: "t1".into(),
1171
- state: selected_state,
1172
- team_dir: team_dir.clone(),
1173
- spec_workspace: spec_path.parent().map(Path::to_path_buf),
1174
- spec_path: Some(spec_path.clone()),
1175
- };
1176
- let id = AgentId::new("w");
1177
- let role = role_path(&selected, &id);
1178
- let snapshot = RoleSnapshot::capture(&selected, &role).unwrap();
1179
- let compiled = yaml::loads("provider: codex\nmodel: new\neffort: ultra\nprofile: local\ndangerously_skip_permissions: false\nsystem_prompt: new instructions\n").unwrap();
1180
- atomic_write(&role, b"new role").unwrap();
1181
- atomic_write(&spec_path, b"new spec").unwrap();
1182
- update_agent_config(&selected, &id, &compiled, &role).unwrap();
1183
- let updated = crate::state::persist::load_runtime_state(&root).unwrap();
1184
- let target = &updated["teams"]["t1"]["agents"]["w"];
1185
- assert_eq!(target["model"], "new");
1186
- assert_eq!(target["effort"], "ultra");
1187
- assert_eq!(target["system_prompt"], "new instructions");
1188
- assert_eq!(target["dangerously_skip_permissions"], false);
1189
- assert_eq!(target["session_id"], "preserved-session");
1190
- assert_eq!(
1191
- target["_profile_dir"],
1192
- team_dir.join("profiles").to_string_lossy().as_ref()
1193
- );
1194
- assert_eq!(updated["teams"]["t2"]["agents"]["w"], sibling);
1195
- let error = snapshot.rollback(
1196
- &selected,
1197
- &id,
1198
- LifecycleError::RequirementUnmet("injected failure".into()),
1199
- );
1200
- assert!(error.to_string().contains("injected failure"));
1201
- assert!(!error.to_string().contains("rollback failed"));
1202
- assert!(!role.exists());
1203
- assert_eq!(fs::read(&spec_path).unwrap(), b"old spec\r\n");
1204
- let restored = crate::state::persist::load_runtime_state(&root).unwrap();
1205
- assert_eq!(restored["teams"]["t1"]["agents"]["w"], old);
1206
- assert_eq!(restored["teams"]["t2"]["agents"]["w"], sibling);
1207
- fs::remove_dir_all(root).unwrap();
1208
- }
1209
-
1210
- #[test]
1211
- fn file_snapshot_restores_original_bytes_and_absence() {
1212
- let nonce = std::time::SystemTime::now()
1213
- .duration_since(std::time::UNIX_EPOCH)
1214
- .unwrap()
1215
- .as_nanos();
1216
- let root = std::env::temp_dir().join(format!("role-config-{}-{nonce}", std::process::id()));
1217
- fs::create_dir_all(&root).unwrap();
1218
- let path = root.join("role.md");
1219
- let absent = FileSnapshot::capture(path.clone()).unwrap();
1220
- atomic_write(&path, b"old\r\n\n").unwrap();
1221
- let existing = FileSnapshot::capture(path.clone()).unwrap();
1222
- atomic_write(&path, b"new").unwrap();
1223
- existing.restore().unwrap();
1224
- assert_eq!(fs::read(&path).unwrap(), b"old\r\n\n");
1225
- absent.restore().unwrap();
1226
- assert!(!path.exists());
1227
- assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
1228
- fs::remove_dir(&root).unwrap();
1229
- }
1230
- }