@team-agent/installer 0.5.128 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +1 -1
  3. package/package.json +4 -8
  4. package/skills/team-agent/SKILL.md +37 -20
  5. package/skills/team-agent/command-coverage.json +169 -183
  6. package/skills/team-agent/docs/reference/team-agent-operator.md +64 -30
  7. package/skills/team-agent/references/recovery-runbook.md +1 -1
  8. package/skills/team-agent/references/team-agent-operator.md +64 -30
  9. package/templates/team_state.md +1 -1
  10. package/Cargo.lock +0 -1063
  11. package/Cargo.toml +0 -36
  12. package/crates/team-agent/Cargo.toml +0 -69
  13. package/crates/team-agent/src/app_server_test_support.rs +0 -258
  14. package/crates/team-agent/src/cli/adapters.rs +0 -1288
  15. package/crates/team-agent/src/cli/arguments.rs +0 -405
  16. package/crates/team-agent/src/cli/attach_app_server_leader.rs +0 -98
  17. package/crates/team-agent/src/cli/diagnose.rs +0 -1721
  18. package/crates/team-agent/src/cli/emit.rs +0 -2930
  19. package/crates/team-agent/src/cli/grok_slot.rs +0 -384
  20. package/crates/team-agent/src/cli/helpers.rs +0 -91
  21. package/crates/team-agent/src/cli/intent/runtime.rs +0 -1216
  22. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -912
  23. package/crates/team-agent/src/cli/intent/tests.rs +0 -689
  24. package/crates/team-agent/src/cli/intent.rs +0 -664
  25. package/crates/team-agent/src/cli/leader.rs +0 -300
  26. package/crates/team-agent/src/cli/leader_prompt.rs +0 -261
  27. package/crates/team-agent/src/cli/leaders.rs +0 -418
  28. package/crates/team-agent/src/cli/mod.rs +0 -6545
  29. package/crates/team-agent/src/cli/models.rs +0 -1206
  30. package/crates/team-agent/src/cli/named_address.rs +0 -1651
  31. package/crates/team-agent/src/cli/profile.rs +0 -342
  32. package/crates/team-agent/src/cli/route.rs +0 -212
  33. package/crates/team-agent/src/cli/schedule.rs +0 -175
  34. package/crates/team-agent/src/cli/send/coordinator.rs +0 -164
  35. package/crates/team-agent/src/cli/send/mailbox.rs +0 -145
  36. package/crates/team-agent/src/cli/send/persist.rs +0 -156
  37. package/crates/team-agent/src/cli/send/presentation.rs +0 -370
  38. package/crates/team-agent/src/cli/send/resolve.rs +0 -573
  39. package/crates/team-agent/src/cli/send.rs +0 -199
  40. package/crates/team-agent/src/cli/shutdown_socket.rs +0 -288
  41. package/crates/team-agent/src/cli/spec.rs +0 -165
  42. package/crates/team-agent/src/cli/status.rs +0 -280
  43. package/crates/team-agent/src/cli/status_port/agents.rs +0 -358
  44. package/crates/team-agent/src/cli/status_port/approvals.rs +0 -79
  45. package/crates/team-agent/src/cli/status_port/brief.rs +0 -1981
  46. package/crates/team-agent/src/cli/status_port/compact.rs +0 -240
  47. package/crates/team-agent/src/cli/status_port/format.rs +0 -146
  48. package/crates/team-agent/src/cli/status_port/inbox.rs +0 -62
  49. package/crates/team-agent/src/cli/status_port/runtime.rs +0 -197
  50. package/crates/team-agent/src/cli/status_port/snapshot.rs +0 -208
  51. package/crates/team-agent/src/cli/status_port/store.rs +0 -416
  52. package/crates/team-agent/src/cli/status_port/tests.rs +0 -90
  53. package/crates/team-agent/src/cli/status_port.rs +0 -92
  54. package/crates/team-agent/src/cli/tests/base.rs +0 -885
  55. package/crates/team-agent/src/cli/tests/divergence.rs +0 -518
  56. package/crates/team-agent/src/cli/tests/lane_c.rs +0 -453
  57. package/crates/team-agent/src/cli/tests/leader_watch.rs +0 -322
  58. package/crates/team-agent/src/cli/tests/main_preserved.rs +0 -430
  59. package/crates/team-agent/src/cli/tests/missing_subcommands.rs +0 -336
  60. package/crates/team-agent/src/cli/tests/mod.rs +0 -137
  61. package/crates/team-agent/src/cli/tests/named_address.rs +0 -761
  62. package/crates/team-agent/src/cli/tests/parser_safety.rs +0 -383
  63. package/crates/team-agent/src/cli/tests/run_delegation.rs +0 -484
  64. package/crates/team-agent/src/cli/tests/shutdown_kill_plan.rs +0 -2179
  65. package/crates/team-agent/src/cli/tests/status_brief.rs +0 -1514
  66. package/crates/team-agent/src/cli/tests/status_send.rs +0 -888
  67. package/crates/team-agent/src/cli/tests/verb_install_skill.rs +0 -93
  68. package/crates/team-agent/src/cli/tests/verb_profile.rs +0 -392
  69. package/crates/team-agent/src/cli/triage.rs +0 -234
  70. package/crates/team-agent/src/cli/types.rs +0 -591
  71. package/crates/team-agent/src/codex_app_server.rs +0 -546
  72. package/crates/team-agent/src/communication_mode/mod.rs +0 -56
  73. package/crates/team-agent/src/compiler/tests.rs +0 -827
  74. package/crates/team-agent/src/compiler.rs +0 -890
  75. package/crates/team-agent/src/conpty/backend.rs +0 -829
  76. package/crates/team-agent/src/conpty/mod.rs +0 -33
  77. package/crates/team-agent/src/contract_runtime/backend.rs +0 -1744
  78. package/crates/team-agent/src/contract_runtime/commands.rs +0 -671
  79. package/crates/team-agent/src/contract_runtime/config.rs +0 -364
  80. package/crates/team-agent/src/contract_runtime/config_tests.rs +0 -76
  81. package/crates/team-agent/src/contract_runtime/discovery.rs +0 -449
  82. package/crates/team-agent/src/contract_runtime/fork.rs +0 -361
  83. package/crates/team-agent/src/contract_runtime/forward.rs +0 -288
  84. package/crates/team-agent/src/contract_runtime/framework.rs +0 -367
  85. package/crates/team-agent/src/contract_runtime/mcp.rs +0 -394
  86. package/crates/team-agent/src/contract_runtime/mod.rs +0 -17
  87. package/crates/team-agent/src/contract_runtime/prompt.rs +0 -216
  88. package/crates/team-agent/src/contract_runtime/pump.rs +0 -271
  89. package/crates/team-agent/src/contract_runtime/registry.rs +0 -553
  90. package/crates/team-agent/src/contract_runtime/workspace.rs +0 -228
  91. package/crates/team-agent/src/coordinator/backoff.rs +0 -741
  92. package/crates/team-agent/src/coordinator/conpty_shim.rs +0 -805
  93. package/crates/team-agent/src/coordinator/health.rs +0 -1185
  94. package/crates/team-agent/src/coordinator/mod.rs +0 -119
  95. package/crates/team-agent/src/coordinator/orphan.rs +0 -110
  96. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -798
  97. package/crates/team-agent/src/coordinator/runtime_observation.rs +0 -84
  98. package/crates/team-agent/src/coordinator/steps/abnormal.rs +0 -2309
  99. package/crates/team-agent/src/coordinator/steps/delivery.rs +0 -15
  100. package/crates/team-agent/src/coordinator/steps/health_sync.rs +0 -15
  101. package/crates/team-agent/src/coordinator/steps/mod.rs +0 -126
  102. package/crates/team-agent/src/coordinator/steps/persist.rs +0 -15
  103. package/crates/team-agent/src/coordinator/steps/runtime_prompts.rs +0 -15
  104. package/crates/team-agent/src/coordinator/steps/session_gate.rs +0 -16
  105. package/crates/team-agent/src/coordinator/tests/a0_lostupdate.rs +0 -158
  106. package/crates/team-agent/src/coordinator/tests/abnormal.rs +0 -312
  107. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +0 -300
  108. package/crates/team-agent/src/coordinator/tests/basics.rs +0 -211
  109. package/crates/team-agent/src/coordinator/tests/daemon.rs +0 -514
  110. package/crates/team-agent/src/coordinator/tests/energy.rs +0 -549
  111. package/crates/team-agent/src/coordinator/tests/health_sync.rs +0 -503
  112. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +0 -186
  113. package/crates/team-agent/src/coordinator/tests/mod.rs +0 -295
  114. package/crates/team-agent/src/coordinator/tests/s3_bounded.rs +0 -207
  115. package/crates/team-agent/src/coordinator/tests/spine.rs +0 -308
  116. package/crates/team-agent/src/coordinator/tests/takeover.rs +0 -286
  117. package/crates/team-agent/src/coordinator/tests/tick_core.rs +0 -237
  118. package/crates/team-agent/src/coordinator/tick.rs +0 -3024
  119. package/crates/team-agent/src/coordinator/types.rs +0 -540
  120. package/crates/team-agent/src/db/agent_health_capture.rs +0 -126
  121. package/crates/team-agent/src/db/message_store.rs +0 -1527
  122. package/crates/team-agent/src/db/migration.rs +0 -984
  123. package/crates/team-agent/src/db/mod.rs +0 -26
  124. package/crates/team-agent/src/db/schema.rs +0 -663
  125. package/crates/team-agent/src/diagnose/comms.rs +0 -242
  126. package/crates/team-agent/src/diagnose/mod.rs +0 -44
  127. package/crates/team-agent/src/diagnose/orphans.rs +0 -889
  128. package/crates/team-agent/src/direct_delivery.rs +0 -368
  129. package/crates/team-agent/src/event_log.rs +0 -502
  130. package/crates/team-agent/src/fake_worker.rs +0 -303
  131. package/crates/team-agent/src/inbox_store.rs +0 -169
  132. package/crates/team-agent/src/kill_audit.rs +0 -106
  133. package/crates/team-agent/src/layout/manager.rs +0 -248
  134. package/crates/team-agent/src/layout/mod.rs +0 -36
  135. package/crates/team-agent/src/layout/overlay.rs +0 -134
  136. package/crates/team-agent/src/layout/placement.rs +0 -52
  137. package/crates/team-agent/src/layout/recovery.rs +0 -106
  138. package/crates/team-agent/src/layout/runtime_sessions.rs +0 -317
  139. package/crates/team-agent/src/layout/sessions.rs +0 -294
  140. package/crates/team-agent/src/layout/tmux_endpoint.rs +0 -165
  141. package/crates/team-agent/src/layout/worker_env.rs +0 -721
  142. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -37
  143. package/crates/team-agent/src/leader/helpers.rs +0 -178
  144. package/crates/team-agent/src/leader/incident.rs +0 -6
  145. package/crates/team-agent/src/leader/lease.rs +0 -3356
  146. package/crates/team-agent/src/leader/mod.rs +0 -104
  147. package/crates/team-agent/src/leader/owner_bind.rs +0 -400
  148. package/crates/team-agent/src/leader/prompt.rs +0 -905
  149. package/crates/team-agent/src/leader/provider_attribution.rs +0 -247
  150. package/crates/team-agent/src/leader/rediscover/tests.rs +0 -689
  151. package/crates/team-agent/src/leader/rediscover.rs +0 -1192
  152. package/crates/team-agent/src/leader/registry.rs +0 -888
  153. package/crates/team-agent/src/leader/start.rs +0 -4501
  154. package/crates/team-agent/src/leader/takeover.rs +0 -65
  155. package/crates/team-agent/src/leader/tests/basics.rs +0 -337
  156. package/crates/team-agent/src/leader/tests/byte_findings.rs +0 -355
  157. package/crates/team-agent/src/leader/tests/claim_leader_mailbox_flush_contract.rs +0 -544
  158. package/crates/team-agent/src/leader/tests/historical_inventory_upgrade_gate_red.rs +0 -624
  159. package/crates/team-agent/src/leader/tests/identity.rs +0 -465
  160. package/crates/team-agent/src/leader/tests/identity_session_names.rs +0 -42
  161. package/crates/team-agent/src/leader/tests/idle.rs +0 -113
  162. package/crates/team-agent/src/leader/tests/lease_api.rs +0 -520
  163. package/crates/team-agent/src/leader/tests/lease_claim.rs +0 -629
  164. package/crates/team-agent/src/leader/tests/mod.rs +0 -106
  165. package/crates/team-agent/src/leader/tests/prompt_contract.rs +0 -268
  166. package/crates/team-agent/src/leader/tests/rediscover.rs +0 -403
  167. package/crates/team-agent/src/leader/tests/rehomed_env.rs +0 -83
  168. package/crates/team-agent/src/leader/tests/team_in_team_state_scope_red.rs +0 -1273
  169. package/crates/team-agent/src/leader/tests/terminal_and_replay_vs_rerender_invariants_red.rs +0 -417
  170. package/crates/team-agent/src/leader/tests/wake_start_owner.rs +0 -168
  171. package/crates/team-agent/src/leader/types.rs +0 -534
  172. package/crates/team-agent/src/lib.rs +0 -147
  173. package/crates/team-agent/src/lifecycle/helpers.rs +0 -212
  174. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +0 -881
  175. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +0 -598
  176. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -332
  177. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +0 -204
  178. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -107
  179. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +0 -144
  180. package/crates/team-agent/src/lifecycle/launch/identity.rs +0 -674
  181. package/crates/team-agent/src/lifecycle/launch/layout.rs +0 -350
  182. package/crates/team-agent/src/lifecycle/launch/leader_context.rs +0 -589
  183. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +0 -160
  184. package/crates/team-agent/src/lifecycle/launch/ownership.rs +0 -105
  185. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +0 -899
  186. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +0 -225
  187. package/crates/team-agent/src/lifecycle/launch/plan.rs +0 -269
  188. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +0 -5200
  189. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +0 -368
  190. package/crates/team-agent/src/lifecycle/launch/readiness.rs +0 -519
  191. package/crates/team-agent/src/lifecycle/launch/role_source.rs +0 -287
  192. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -473
  193. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -801
  194. package/crates/team-agent/src/lifecycle/launch/state_projection.rs +0 -624
  195. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -558
  196. package/crates/team-agent/src/lifecycle/launch.rs +0 -557
  197. package/crates/team-agent/src/lifecycle/lock.rs +0 -350
  198. package/crates/team-agent/src/lifecycle/mod.rs +0 -79
  199. package/crates/team-agent/src/lifecycle/pane_input_lock.rs +0 -239
  200. package/crates/team-agent/src/lifecycle/profile_launch.rs +0 -1067
  201. package/crates/team-agent/src/lifecycle/profile_smoke.rs +0 -557
  202. package/crates/team-agent/src/lifecycle/restart/agent.rs +0 -2199
  203. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1798
  204. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +0 -163
  205. package/crates/team-agent/src/lifecycle/restart/common.rs +0 -2362
  206. package/crates/team-agent/src/lifecycle/restart/orchestrator.rs +0 -65
  207. package/crates/team-agent/src/lifecycle/restart/preflight.rs +0 -113
  208. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +0 -5135
  209. package/crates/team-agent/src/lifecycle/restart/remove.rs +0 -1504
  210. package/crates/team-agent/src/lifecycle/restart/selection.rs +0 -559
  211. package/crates/team-agent/src/lifecycle/restart/team_state.rs +0 -329
  212. package/crates/team-agent/src/lifecycle/restart.rs +0 -227
  213. package/crates/team-agent/src/lifecycle/role_config.rs +0 -1230
  214. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +0 -1021
  215. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +0 -1205
  216. package/crates/team-agent/src/lifecycle/tests/b0_legacy_snapshot_nonauthority_contract.rs +0 -265
  217. package/crates/team-agent/src/lifecycle/tests/b0_reader_hideone_audit_contract.rs +0 -490
  218. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +0 -656
  219. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  220. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +0 -447
  221. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +0 -1638
  222. package/crates/team-agent/src/lifecycle/tests/clone_agent_preserves_source_tools.rs +0 -427
  223. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +0 -770
  224. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +0 -419
  225. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +0 -2035
  226. package/crates/team-agent/src/lifecycle/tests/core.rs +0 -1327
  227. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +0 -315
  228. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_g0.stdout.txt +0 -222
  229. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_list_models_spaced_ids.stdout.txt +0 -9
  230. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +0 -72
  231. package/crates/team-agent/src/lifecycle/tests/gate_fixtures.rs +0 -562
  232. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +0 -110
  233. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +0 -512
  234. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +0 -921
  235. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +0 -68
  236. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +0 -1851
  237. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +0 -3983
  238. package/crates/team-agent/src/lifecycle/tests/lifecycle_lock.rs +0 -339
  239. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +0 -596
  240. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +0 -513
  241. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +0 -69
  242. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +0 -824
  243. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +0 -723
  244. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +0 -164
  245. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +0 -200
  246. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  247. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +0 -527
  248. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +0 -1062
  249. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1419
  250. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +0 -98
  251. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +0 -550
  252. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +0 -226
  253. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +0 -332
  254. package/crates/team-agent/src/lifecycle/tests/realmachine_clusters_1_6_red.rs +0 -786
  255. package/crates/team-agent/src/lifecycle/tests/realmachine_residual_g1_g4_red.rs +0 -648
  256. package/crates/team-agent/src/lifecycle/tests/restart.rs +0 -185
  257. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +0 -1053
  258. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +0 -679
  259. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1126
  260. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +0 -153
  261. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +0 -427
  262. package/crates/team-agent/src/lifecycle/tests/stale_team_saveconflict_contract.rs +0 -431
  263. package/crates/team-agent/src/lifecycle/tests/startup_latency_contract.rs +0 -1066
  264. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +0 -876
  265. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +0 -1026
  266. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +0 -342
  267. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +0 -543
  268. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +0 -1103
  269. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +0 -1276
  270. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_roster_red.rs +0 -145
  271. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +0 -603
  272. package/crates/team-agent/src/lifecycle/tests/test_isolation_escape_contract.rs +0 -936
  273. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +0 -970
  274. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +0 -995
  275. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -836
  276. package/crates/team-agent/src/lifecycle/tests.rs +0 -105
  277. package/crates/team-agent/src/lifecycle/types.rs +0 -877
  278. package/crates/team-agent/src/lifecycle/worker_command_context.rs +0 -363
  279. package/crates/team-agent/src/main.rs +0 -52
  280. package/crates/team-agent/src/mcp_server/helpers.rs +0 -510
  281. package/crates/team-agent/src/mcp_server/lifecycle_tools/mod.rs +0 -6
  282. package/crates/team-agent/src/mcp_server/lifecycle_tools/state_status.rs +0 -43
  283. package/crates/team-agent/src/mcp_server/mod.rs +0 -119
  284. package/crates/team-agent/src/mcp_server/normalize.rs +0 -485
  285. package/crates/team-agent/src/mcp_server/readiness.rs +0 -527
  286. package/crates/team-agent/src/mcp_server/readiness_tests.rs +0 -348
  287. package/crates/team-agent/src/mcp_server/tests/golden.rs +0 -285
  288. package/crates/team-agent/src/mcp_server/tests/normalize.rs +0 -247
  289. package/crates/team-agent/src/mcp_server/tests/scoped.rs +0 -158
  290. package/crates/team-agent/src/mcp_server/tests/send.rs +0 -353
  291. package/crates/team-agent/src/mcp_server/tests/tools.rs +0 -341
  292. package/crates/team-agent/src/mcp_server/tests/wire.rs +0 -254
  293. package/crates/team-agent/src/mcp_server/tests.rs +0 -43
  294. package/crates/team-agent/src/mcp_server/tools.rs +0 -889
  295. package/crates/team-agent/src/mcp_server/types.rs +0 -396
  296. package/crates/team-agent/src/mcp_server/wire.rs +0 -867
  297. package/crates/team-agent/src/messaging/activity.rs +0 -461
  298. package/crates/team-agent/src/messaging/address.rs +0 -87
  299. package/crates/team-agent/src/messaging/delivery.rs +0 -3727
  300. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +0 -234
  301. package/crates/team-agent/src/messaging/enter_rescue.rs +0 -362
  302. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +0 -633
  303. package/crates/team-agent/src/messaging/helpers.rs +0 -336
  304. package/crates/team-agent/src/messaging/leader_channel.rs +0 -287
  305. package/crates/team-agent/src/messaging/leader_receiver.rs +0 -786
  306. package/crates/team-agent/src/messaging/mod.rs +0 -167
  307. package/crates/team-agent/src/messaging/persist.rs +0 -377
  308. package/crates/team-agent/src/messaging/presentation.rs +0 -417
  309. package/crates/team-agent/src/messaging/reminders.rs +0 -316
  310. package/crates/team-agent/src/messaging/results/collection_tests.rs +0 -719
  311. package/crates/team-agent/src/messaging/results.rs +0 -1415
  312. package/crates/team-agent/src/messaging/scheduler.rs +0 -223
  313. package/crates/team-agent/src/messaging/selftest.rs +0 -315
  314. package/crates/team-agent/src/messaging/send.rs +0 -981
  315. package/crates/team-agent/src/messaging/tests/basic.rs +0 -346
  316. package/crates/team-agent/src/messaging/tests/dup_inject.rs +0 -657
  317. package/crates/team-agent/src/messaging/tests/e23.rs +0 -49
  318. package/crates/team-agent/src/messaging/tests/leader_channel.rs +0 -169
  319. package/crates/team-agent/src/messaging/tests/leader_inject_acceptance.rs +0 -817
  320. package/crates/team-agent/src/messaging/tests/main_preserved.rs +0 -85
  321. package/crates/team-agent/src/messaging/tests/mod.rs +0 -306
  322. package/crates/team-agent/src/messaging/tests/runtime.rs +0 -3549
  323. package/crates/team-agent/src/messaging/tests/spine.rs +0 -853
  324. package/crates/team-agent/src/messaging/tests/wave2.rs +0 -381
  325. package/crates/team-agent/src/messaging/trust.rs +0 -215
  326. package/crates/team-agent/src/messaging/types.rs +0 -472
  327. package/crates/team-agent/src/messaging/wait.rs +0 -366
  328. package/crates/team-agent/src/messaging/watchers.rs +0 -916
  329. package/crates/team-agent/src/model/enums.rs +0 -356
  330. package/crates/team-agent/src/model/errors.rs +0 -18
  331. package/crates/team-agent/src/model/ids.rs +0 -165
  332. package/crates/team-agent/src/model/mod.rs +0 -29
  333. package/crates/team-agent/src/model/name_similarity.rs +0 -252
  334. package/crates/team-agent/src/model/pane_authority_refusal.rs +0 -359
  335. package/crates/team-agent/src/model/paths.rs +0 -257
  336. package/crates/team-agent/src/model/routing.rs +0 -387
  337. package/crates/team-agent/src/model/spec.rs +0 -1184
  338. package/crates/team-agent/src/model/task_graph.rs +0 -321
  339. package/crates/team-agent/src/model/testdata/fuzz.golden.yaml +0 -43
  340. package/crates/team-agent/src/model/testdata/fuzz.yaml +0 -43
  341. package/crates/team-agent/src/model/testdata/spec_invalid_a.yaml +0 -209
  342. package/crates/team-agent/src/model/testdata/team.spec.golden.yaml +0 -208
  343. package/crates/team-agent/src/model/testdata/team.spec.yaml +0 -208
  344. package/crates/team-agent/src/model/yaml/tests.rs +0 -188
  345. package/crates/team-agent/src/model/yaml.rs +0 -802
  346. package/crates/team-agent/src/os_probe.rs +0 -280
  347. package/crates/team-agent/src/packaging/install.rs +0 -219
  348. package/crates/team-agent/src/packaging/migrate.rs +0 -38
  349. package/crates/team-agent/src/packaging/mod.rs +0 -91
  350. package/crates/team-agent/src/packaging/repair.rs +0 -33
  351. package/crates/team-agent/src/packaging/tests.rs +0 -822
  352. package/crates/team-agent/src/packaging/types.rs +0 -417
  353. package/crates/team-agent/src/platform/argv.rs +0 -331
  354. package/crates/team-agent/src/platform/errors.rs +0 -104
  355. package/crates/team-agent/src/platform/file_lock.rs +0 -279
  356. package/crates/team-agent/src/platform/mod.rs +0 -5
  357. package/crates/team-agent/src/platform/process.rs +0 -545
  358. package/crates/team-agent/src/provider/adapter.rs +0 -1150
  359. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  360. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  361. package/crates/team-agent/src/provider/adapters/copilot.rs +0 -75
  362. package/crates/team-agent/src/provider/adapters/copilot_fork.rs +0 -307
  363. package/crates/team-agent/src/provider/adapters/fake.rs +0 -18
  364. package/crates/team-agent/src/provider/adapters/mod.rs +0 -30
  365. package/crates/team-agent/src/provider/adapters/pi.rs +0 -106
  366. package/crates/team-agent/src/provider/approvals/mod.rs +0 -3
  367. package/crates/team-agent/src/provider/approvals/parsing.rs +0 -586
  368. package/crates/team-agent/src/provider/approvals/runtime_prompts.rs +0 -205
  369. package/crates/team-agent/src/provider/argv_route.rs +0 -405
  370. package/crates/team-agent/src/provider/bypass_flags.rs +0 -116
  371. package/crates/team-agent/src/provider/classify.rs +0 -708
  372. package/crates/team-agent/src/provider/command_helpers.rs +0 -45
  373. package/crates/team-agent/src/provider/faults.rs +0 -165
  374. package/crates/team-agent/src/provider/helpers.rs +0 -52
  375. package/crates/team-agent/src/provider/mod.rs +0 -78
  376. package/crates/team-agent/src/provider/model_catalog.rs +0 -910
  377. package/crates/team-agent/src/provider/session/capture.rs +0 -2731
  378. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  379. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +0 -172
  380. package/crates/team-agent/src/provider/session/context_fork.rs +0 -396
  381. package/crates/team-agent/src/provider/session/mod.rs +0 -36
  382. package/crates/team-agent/src/provider/session/resume.rs +0 -269
  383. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  384. package/crates/team-agent/src/provider/session_scan/common/tests.rs +0 -316
  385. package/crates/team-agent/src/provider/session_scan/common.rs +0 -654
  386. package/crates/team-agent/src/provider/session_scan/copilot.rs +0 -280
  387. package/crates/team-agent/src/provider/session_scan/pi.rs +0 -185
  388. package/crates/team-agent/src/provider/session_scan.rs +0 -71
  389. package/crates/team-agent/src/provider/startup_prompt.rs +0 -757
  390. package/crates/team-agent/src/provider/submit_now.rs +0 -71
  391. package/crates/team-agent/src/provider/testdata/copilot-ready-marker.txt +0 -5
  392. package/crates/team-agent/src/provider/testdata/copilot-trust-prompt.txt +0 -19
  393. package/crates/team-agent/src/provider/testdata/grok-models-authenticated.stdout +0 -9
  394. package/crates/team-agent/src/provider/testdata/grok-models-unauthenticated.stdout +0 -7
  395. package/crates/team-agent/src/provider/tests/adapter.rs +0 -441
  396. package/crates/team-agent/src/provider/tests/classify.rs +0 -148
  397. package/crates/team-agent/src/provider/tests/command_helpers.rs +0 -35
  398. package/crates/team-agent/src/provider/tests/copilot_fork.rs +0 -191
  399. package/crates/team-agent/src/provider/tests/faults.rs +0 -200
  400. package/crates/team-agent/src/provider/tests/idle.rs +0 -177
  401. package/crates/team-agent/src/provider/tests/wire.rs +0 -213
  402. package/crates/team-agent/src/provider/tests.rs +0 -32
  403. package/crates/team-agent/src/provider/types.rs +0 -529
  404. package/crates/team-agent/src/provider/wire.rs +0 -394
  405. package/crates/team-agent/src/redaction.rs +0 -259
  406. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +0 -248
  407. package/crates/team-agent/src/state/abnormal_watch.rs +0 -144
  408. package/crates/team-agent/src/state/identity.rs +0 -914
  409. package/crates/team-agent/src/state/identity_keys.rs +0 -132
  410. package/crates/team-agent/src/state/mod.rs +0 -74
  411. package/crates/team-agent/src/state/owner_gate.rs +0 -482
  412. package/crates/team-agent/src/state/ownership.rs +0 -563
  413. package/crates/team-agent/src/state/paths.rs +0 -395
  414. package/crates/team-agent/src/state/persist.rs +0 -3811
  415. package/crates/team-agent/src/state/projection.rs +0 -1508
  416. package/crates/team-agent/src/state/repository/intent.rs +0 -14
  417. package/crates/team-agent/src/state/repository/tests.rs +0 -184
  418. package/crates/team-agent/src/state/repository.rs +0 -866
  419. package/crates/team-agent/src/state/selector.rs +0 -160
  420. package/crates/team-agent/src/state/testdata/state-rich.canonical.json +0 -133
  421. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
  422. package/crates/team-agent/src/tmux_backend/enter_rescue.rs +0 -325
  423. package/crates/team-agent/src/tmux_backend/enter_rescue_tests.rs +0 -432
  424. package/crates/team-agent/src/tmux_backend/native_input.rs +0 -513
  425. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +0 -742
  426. package/crates/team-agent/src/tmux_backend/tests.rs +0 -4103
  427. package/crates/team-agent/src/tmux_backend.rs +0 -4492
  428. package/crates/team-agent/src/topology.rs +0 -537
  429. package/crates/team-agent/src/transport/enter_rescue.rs +0 -166
  430. package/crates/team-agent/src/transport/native_input.rs +0 -491
  431. package/crates/team-agent/src/transport/test_support.rs +0 -743
  432. package/crates/team-agent/src/transport/tests/behavior.rs +0 -326
  433. package/crates/team-agent/src/transport/tests/mod.rs +0 -194
  434. package/crates/team-agent/src/transport/tests/wire.rs +0 -574
  435. package/crates/team-agent/src/transport.rs +0 -1655
  436. package/crates/team-agent/src/transport_factory.rs +0 -819
@@ -1,1798 +0,0 @@
1
- //! Pi 的锁内新席位 fork:稳定读取 source JSONL,写入独立 session backing 后精确 resume。
2
- use std::collections::{BTreeSet, HashSet};
3
- use std::fs::{self, OpenOptions};
4
- use std::io::{BufRead, Read, Seek, SeekFrom, Write};
5
- use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
6
- use std::path::{Component, Path, PathBuf};
7
-
8
- use serde_json::Value as JsonValue;
9
- use sha2::{Digest, Sha256};
10
-
11
- use crate::lifecycle::launch::add_agent_state::{
12
- fork_upsert_agent_state_from_role, inject_agent_into_spec,
13
- };
14
- use crate::lifecycle::launch::role_source::{
15
- materialize_latest_role, resolve_role_source, MaterializedRole,
16
- };
17
- use crate::lifecycle::launch::ForkCaptureSeed;
18
- use crate::lifecycle::{
19
- AgentActionEnvelope, ForkAgentReport, ForkBackingState, LifecycleError, PiForkDetails,
20
- StartMode,
21
- };
22
- use crate::model::ids::AgentId;
23
- use crate::model::yaml::{self, Value as YamlValue};
24
- use crate::provider::{CaptureVia, CapturedSession, Confidence, Provider, RolloutPath, SessionId};
25
- use crate::state::selector::SelectedTeam;
26
- use crate::transport::{BackendKind, SessionName, Transport, WindowName};
27
-
28
- use super::common::state_session_name;
29
-
30
- #[derive(Clone, Copy, Debug, PartialEq, Eq)]
31
- struct FileIdentity {
32
- device: u64,
33
- inode: u64,
34
- }
35
-
36
- #[derive(Clone)]
37
- struct SourceBinding {
38
- session_id: SessionId,
39
- backing_path: PathBuf,
40
- sessions_root: PathBuf,
41
- spawn_cwd: PathBuf,
42
- captured_at: String,
43
- captured_via: CaptureVia,
44
- spawned_at: String,
45
- spawn_epoch: Option<u64>,
46
- identity: FileIdentity,
47
- }
48
-
49
- struct SourceSnapshot {
50
- body: Vec<u8>,
51
- }
52
-
53
- struct StagedPiSession {
54
- seat_paths: crate::lifecycle::launch::pi_mcp::PiSeatPaths,
55
- backing_path: PathBuf,
56
- bytes: Vec<u8>,
57
- identity: FileIdentity,
58
- created_dirs: Vec<PathBuf>,
59
- wrapper_identity: Option<FileIdentity>,
60
- session_id: SessionId,
61
- captured_at: String,
62
- sha256: String,
63
- }
64
-
65
- struct SpecRegistration {
66
- path: PathBuf,
67
- previous_bytes: Option<Vec<u8>>,
68
- written_bytes: Vec<u8>,
69
- target_agent: YamlValue,
70
- identity: Option<FileIdentity>,
71
- }
72
-
73
- /// Called only while `fork_agent_with_transport` holds the selected team's lifecycle lock.
74
- pub(crate) fn fork_pi_new_seat_locked(
75
- selected: &SelectedTeam,
76
- source_agent_id: &AgentId,
77
- target_agent_id: &AgentId,
78
- label: Option<&str>,
79
- transport: &dyn Transport,
80
- ) -> Result<ForkAgentReport, LifecycleError> {
81
- let run_workspace = &selected.run_workspace;
82
- let team_key = selected.team_key.as_str();
83
- let mut phase = "p0_preflight";
84
- let mut staged = None;
85
- let mut role: Option<MaterializedRole> = None;
86
- let mut spec_registration: Option<SpecRegistration> = None;
87
- let mut state_registered = false;
88
- let mut spawn_attempted = false;
89
- let mut spawned = None;
90
- let mut panes_before = BTreeSet::new();
91
- let mut audit = serde_json::json!({
92
- "team": team_key,
93
- "source_agent_id": source_agent_id.as_str(),
94
- "target_agent_id": target_agent_id.as_str(),
95
- "source_session_id": null,
96
- "target_session_id": null,
97
- "source_backing_path": null,
98
- "backing_path": null,
99
- "snapshot_bytes": null,
100
- "snapshot_sha256": null,
101
- "target_pane_id": null,
102
- "tmux_endpoint": transport.tmux_endpoint(),
103
- });
104
-
105
- let operation = (|| -> Result<ForkAgentReport, LifecycleError> {
106
- validate_path_component(source_agent_id.as_str(), "source agent id")?;
107
- validate_path_component(target_agent_id.as_str(), "target agent id")?;
108
- validate_path_component(team_key, "team id")?;
109
- if source_agent_id == target_agent_id {
110
- return Err(LifecycleError::RequirementUnmet(
111
- "Pi fork target must differ from source".to_string(),
112
- ));
113
- }
114
- if transport.kind() != BackendKind::Tmux {
115
- return Err(LifecycleError::TeamSelect(
116
- "Pi fork requires the selected team's tmux transport".to_string(),
117
- ));
118
- }
119
- let expected_transport = super::common::lifecycle_worker_tmux_backend_selection_for_state(
120
- run_workspace,
121
- &selected.state,
122
- )?
123
- .backend;
124
- if transport.probes_real_tmux_socket_roots()
125
- && transport.tmux_endpoint() != expected_transport.tmux_endpoint()
126
- {
127
- return Err(LifecycleError::TeamSelect(
128
- "selected team tmux endpoint changed while fork was acquiring its lifecycle lock"
129
- .to_string(),
130
- ));
131
- }
132
- crate::lifecycle::launch::ensure_owner_allowed_for_state(
133
- &selected.state,
134
- Some(source_agent_id),
135
- )?;
136
- if selected
137
- .state
138
- .get("agents")
139
- .and_then(|agents| agents.get(target_agent_id.as_str()))
140
- .is_some()
141
- {
142
- return Err(LifecycleError::RequirementUnmet(format!(
143
- "target agent already exists in selected team: {target_agent_id}"
144
- )));
145
- }
146
- let session_name = state_session_name(&selected.state);
147
- if !state_has_session_name(&selected.state) {
148
- return Err(LifecycleError::TeamSelect(
149
- "selected team has no persisted tmux session name".to_string(),
150
- ));
151
- }
152
- let source_agent = selected
153
- .state
154
- .get("agents")
155
- .and_then(|agents| agents.get(source_agent_id.as_str()))
156
- .ok_or_else(|| {
157
- LifecycleError::RequirementUnmet(format!(
158
- "unknown worker agent id: {source_agent_id}"
159
- ))
160
- })?;
161
- if source_agent.get("provider").and_then(JsonValue::as_str) != Some("pi")
162
- || source_agent.get("auth_mode").and_then(JsonValue::as_str) != Some("subscription")
163
- {
164
- return Err(LifecycleError::Provider(
165
- "Pi session fork requires a Pi subscription source seat".to_string(),
166
- ));
167
- }
168
- let binding = source_binding(selected, source_agent_id)?;
169
- audit["source_session_id"] = serde_json::json!(binding.session_id.as_str());
170
- audit["source_backing_path"] =
171
- serde_json::json!(binding.backing_path.to_string_lossy().to_string());
172
- audit["source_captured_at"] = serde_json::json!(binding.captured_at.as_str());
173
- audit["source_captured_via"] = serde_json::json!(binding.captured_via);
174
- audit["source_attribution_confidence"] = serde_json::json!("high");
175
- audit["source_spawned_at"] = serde_json::json!(binding.spawned_at.as_str());
176
- audit["source_spawn_epoch"] = serde_json::json!(binding.spawn_epoch);
177
- let source_role_path = resolve_role_source(
178
- run_workspace,
179
- &selected.team_dir,
180
- &selected.state,
181
- source_agent_id,
182
- )?;
183
- let (source_role_meta, _) = crate::compiler::read_front_matter(&source_role_path)
184
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
185
- for field in ["working_directory", "cwd"] {
186
- if let Some(cwd) = source_role_meta.get(field).and_then(YamlValue::as_str) {
187
- if Path::new(cwd).canonicalize().ok().as_deref()
188
- != Some(binding.spawn_cwd.as_path())
189
- {
190
- return Err(LifecycleError::Compile(format!(
191
- "Pi source role {field} differs from the captured source cwd"
192
- )));
193
- }
194
- }
195
- }
196
- let team_meta = crate::compiler::read_front_matter(&selected.team_dir.join("TEAM.md"))
197
- .map(|(meta, _)| meta)
198
- .unwrap_or(YamlValue::Null);
199
- let workspace_text = run_workspace.to_string_lossy().to_string();
200
- let source_compiled =
201
- crate::compiler::compile_role_agent(&source_role_path, &team_meta, &workspace_text)
202
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
203
- if source_compiled.id != source_agent_id.as_str() {
204
- return Err(LifecycleError::Compile(
205
- "latest source role id does not match the source seat".to_string(),
206
- ));
207
- }
208
- if source_compiled
209
- .agent
210
- .get("provider")
211
- .and_then(YamlValue::as_str)
212
- != Some("pi")
213
- || source_compiled
214
- .agent
215
- .get("auth_mode")
216
- .and_then(YamlValue::as_str)
217
- != Some("subscription")
218
- {
219
- return Err(LifecycleError::Compile(
220
- "latest source role must resolve to Pi subscription".to_string(),
221
- ));
222
- }
223
-
224
- let mut base_spec = crate::compiler::compile_team(&selected.team_dir)
225
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
226
- crate::lifecycle::launch::spec_state::override_spec_workspace(
227
- &mut base_spec,
228
- run_workspace,
229
- );
230
- let spec_path = crate::model::paths::runtime_spec_path(run_workspace, team_key);
231
- ensure_no_symlink_components(&spec_path, true)?;
232
- let previous_spec_bytes = read_optional_bytes(&spec_path)?;
233
- let runtime_spec_has_target = match previous_spec_bytes.as_deref() {
234
- Some(bytes) => {
235
- let text = std::str::from_utf8(bytes)
236
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
237
- let spec = yaml::loads(text)
238
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
239
- spec_has_target(&spec, target_agent_id.as_str())
240
- }
241
- None => false,
242
- };
243
- if spec_has_target(&base_spec, target_agent_id.as_str()) || runtime_spec_has_target {
244
- return Err(LifecycleError::RequirementUnmet(format!(
245
- "target agent or route already exists in selected team spec: {target_agent_id}"
246
- )));
247
- }
248
- let managed_role_path = run_workspace
249
- .join(".team")
250
- .join("dynamic-role-files")
251
- .join(format!("{}.md", target_agent_id.as_str()));
252
- ensure_no_symlink_components(&managed_role_path, true)?;
253
- refuse_existing_path(&managed_role_path, "target managed role file")?;
254
- let target_paths = crate::lifecycle::launch::pi_mcp::pi_seat_paths(
255
- run_workspace,
256
- team_key,
257
- target_agent_id.as_str(),
258
- );
259
- ensure_no_symlink_components(&target_paths.runtime_root, true)?;
260
- refuse_existing_path(&target_paths.runtime_root, "target Pi runtime seat")?;
261
- let targets = transport
262
- .list_targets()
263
- .map_err(|error| LifecycleError::Transport(error.to_string()))?;
264
- if targets.iter().any(|pane| {
265
- pane.session.as_str() == session_name.as_str()
266
- && pane.window_name.as_ref().map(WindowName::as_str)
267
- == Some(target_agent_id.as_str())
268
- }) {
269
- return Err(LifecycleError::RequirementUnmet(format!(
270
- "target window already exists: {}:{}",
271
- session_name.as_str(),
272
- target_agent_id.as_str()
273
- )));
274
- }
275
- panes_before.extend(
276
- targets
277
- .into_iter()
278
- .map(|pane| pane.pane_id.as_str().to_string()),
279
- );
280
-
281
- phase = "p1_snapshot";
282
- let snapshot = read_stable_source_snapshot(&binding, run_workspace)?;
283
- revalidate_source_binding(selected, source_agent_id, &binding)?;
284
- let target_session_id = crate::lifecycle::launch::pi_mcp::new_pi_session_id();
285
- let full_state = crate::state::persist::load_runtime_state(run_workspace)
286
- .map_err(|error| LifecycleError::StatePersist(error.to_string()))?;
287
- if target_session_id == binding.session_id
288
- || session_id_in_use(&full_state, &target_session_id)
289
- {
290
- return Err(LifecycleError::RequirementUnmet(
291
- "generated Pi fork session id is not unique in selected team".to_string(),
292
- ));
293
- }
294
- let captured_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
295
- let staged_file = stage_pi_session(
296
- &target_paths,
297
- &target_session_id,
298
- &captured_at,
299
- &binding.spawn_cwd,
300
- &binding.backing_path,
301
- &snapshot.body,
302
- )?;
303
- audit["target_session_id"] = serde_json::json!(target_session_id.as_str());
304
- audit["backing_path"] =
305
- serde_json::json!(staged_file.backing_path.to_string_lossy().to_string());
306
- audit["snapshot_bytes"] = serde_json::json!(staged_file.bytes.len());
307
- audit["snapshot_sha256"] = serde_json::json!(staged_file.sha256.as_str());
308
- staged = Some(staged_file);
309
-
310
- let target_role = materialize_latest_role(
311
- run_workspace,
312
- &selected.team_dir,
313
- &selected.state,
314
- source_agent_id,
315
- target_agent_id,
316
- label,
317
- )?;
318
- role = Some(target_role);
319
- let target_role_path = role
320
- .as_ref()
321
- .ok_or_else(|| {
322
- LifecycleError::StatePersist("materialized role disappeared".to_string())
323
- })?
324
- .path()
325
- .to_path_buf();
326
- let (target_meta, _) = crate::compiler::read_front_matter(&target_role_path)
327
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
328
- for field in ["working_directory", "cwd"] {
329
- if let Some(cwd) = target_meta.get(field).and_then(YamlValue::as_str) {
330
- if Path::new(cwd).canonicalize().ok().as_deref()
331
- != Some(binding.spawn_cwd.as_path())
332
- {
333
- return Err(LifecycleError::Compile(format!(
334
- "Pi fork target role {field} differs from the source cohort cwd"
335
- )));
336
- }
337
- }
338
- }
339
- let compiled =
340
- crate::compiler::compile_role_agent(&target_role_path, &team_meta, &workspace_text)
341
- .map_err(|error| LifecycleError::Compile(error.to_string()))?;
342
- if compiled.id != target_agent_id.as_str() {
343
- return Err(LifecycleError::Compile(format!(
344
- "materialized role id '{}' does not match target '{}'",
345
- compiled.id, target_agent_id
346
- )));
347
- }
348
- let compiled_provider = compiled.agent.get("provider").and_then(YamlValue::as_str);
349
- let compiled_auth = compiled.agent.get("auth_mode").and_then(YamlValue::as_str);
350
- if compiled_provider != Some("pi") || compiled_auth != Some("subscription") {
351
- return Err(LifecycleError::Compile(
352
- "compiled target role must remain Pi subscription".to_string(),
353
- ));
354
- }
355
- let cwd = compiled
356
- .agent
357
- .get("working_directory")
358
- .and_then(YamlValue::as_str)
359
- .ok_or_else(|| {
360
- LifecycleError::Compile("Pi target role has no working_directory".to_string())
361
- })?;
362
- if Path::new(cwd).canonicalize().ok().as_deref() != Some(binding.spawn_cwd.as_path()) {
363
- return Err(LifecycleError::Compile(
364
- "Pi fork target role working_directory differs from the source cohort cwd"
365
- .to_string(),
366
- ));
367
- }
368
- let staged_file = staged.as_ref().ok_or_else(|| {
369
- LifecycleError::StatePersist("Pi fork snapshot staging was lost".to_string())
370
- })?;
371
- let seed = ForkCaptureSeed {
372
- source_agent_id: source_agent_id.clone(),
373
- captured: CapturedSession {
374
- session_id: Some(staged_file.session_id.clone()),
375
- rollout_path: Some(RolloutPath::new(staged_file.backing_path.clone())),
376
- captured_via: CaptureVia::ForkSnapshot,
377
- attribution_confidence: Confidence::High,
378
- spawn_cwd: binding.spawn_cwd.clone(),
379
- },
380
- captured_at: staged_file.captured_at.clone(),
381
- pi_sessions_root: target_paths.sessions.clone(),
382
- profile_dir: selected.team_dir.join("profiles"),
383
- };
384
-
385
- phase = "p2_register";
386
- revalidate_source_binding(selected, source_agent_id, &binding)?;
387
- ensure_no_symlink_components(&spec_path, true)?;
388
- let current_spec_bytes = read_optional_bytes(&spec_path)?;
389
- if previous_spec_bytes.is_some() && current_spec_bytes.is_none() {
390
- return Err(LifecycleError::RequirementUnmet(
391
- "runtime spec disappeared during Pi fork preparation".to_string(),
392
- ));
393
- }
394
- let mut latest_spec = match current_spec_bytes.as_deref() {
395
- Some(bytes) => yaml::loads(std::str::from_utf8(bytes).map_err(|error| {
396
- LifecycleError::Compile(format!("runtime spec is not UTF-8: {error}"))
397
- })?)
398
- .map_err(|error| LifecycleError::Compile(error.to_string()))?,
399
- None => base_spec,
400
- };
401
- if spec_has_target(&latest_spec, target_agent_id.as_str()) {
402
- return Err(LifecycleError::RequirementUnmet(format!(
403
- "target agent or route appeared in runtime spec during fork preparation: {target_agent_id}"
404
- )));
405
- }
406
- inject_agent_into_spec(
407
- &mut latest_spec,
408
- compiled.agent.clone(),
409
- target_agent_id.as_str(),
410
- )?;
411
- let written_bytes = yaml::dumps(&latest_spec).into_bytes();
412
- if read_optional_bytes(&spec_path)? != current_spec_bytes {
413
- return Err(LifecycleError::RequirementUnmet(
414
- "runtime spec changed while registering Pi fork target".to_string(),
415
- ));
416
- }
417
- spec_registration = Some(SpecRegistration {
418
- path: spec_path.clone(),
419
- previous_bytes: current_spec_bytes,
420
- written_bytes,
421
- target_agent: compiled.agent.clone(),
422
- identity: None,
423
- });
424
- crate::lifecycle::launch::spec_state::write_spec_atomic(&spec_path, &latest_spec)?;
425
- let spec_identity = file_identity(&spec_path).map_err(LifecycleError::StatePersist)?;
426
- if let Some(registration) = spec_registration.as_mut() {
427
- registration.identity = Some(spec_identity);
428
- }
429
- match fork_upsert_agent_state_from_role(
430
- run_workspace,
431
- team_key,
432
- target_agent_id,
433
- &target_meta,
434
- &compiled.agent,
435
- &target_role_path,
436
- &seed,
437
- ) {
438
- Ok(()) => state_registered = true,
439
- Err(error) => {
440
- state_registered = staged.as_ref().is_some_and(|staged| {
441
- fork_target_state_registered(
442
- run_workspace,
443
- team_key,
444
- target_agent_id,
445
- source_agent_id,
446
- &staged.session_id,
447
- &staged.backing_path,
448
- &target_role_path,
449
- )
450
- });
451
- return Err(error);
452
- }
453
- }
454
-
455
- phase = "p3_spawn";
456
- spawn_attempted = true;
457
- let latest_state =
458
- crate::state::projection::select_runtime_state(run_workspace, Some(team_key))
459
- .map_err(|error| LifecycleError::TeamSelect(error.to_string()))?;
460
- let target_row = latest_state
461
- .get("agents")
462
- .and_then(|agents| agents.get(target_agent_id.as_str()))
463
- .ok_or_else(|| {
464
- LifecycleError::StatePersist(
465
- "registered Pi fork target row disappeared".to_string(),
466
- )
467
- })?;
468
- let safety = crate::lifecycle::launch::effective_runtime_config_for_worker_spawn_json(
469
- target_row,
470
- Provider::Pi,
471
- )?;
472
- let spawn = super::common::spawn_agent_window(
473
- run_workspace,
474
- &session_name,
475
- target_agent_id,
476
- target_row,
477
- Some(
478
- &staged
479
- .as_ref()
480
- .ok_or_else(|| {
481
- LifecycleError::StatePersist(
482
- "Pi fork snapshot staging was lost".to_string(),
483
- )
484
- })?
485
- .session_id,
486
- ),
487
- true,
488
- transport,
489
- Some(&safety),
490
- None,
491
- Some(run_workspace),
492
- Some("fork-agent"),
493
- Some(team_key),
494
- );
495
- let spawn = match spawn {
496
- Ok(spawn) => spawn,
497
- Err(error) => {
498
- capture_target_wrapper_identity(staged.as_mut());
499
- return Err(error);
500
- }
501
- };
502
- capture_target_wrapper_identity(staged.as_mut());
503
- audit["target_pane_id"] = serde_json::json!(spawn.spawn.pane_id.as_str());
504
- spawned = Some(spawn);
505
- let spawned_ref = spawned.as_ref().ok_or_else(|| {
506
- LifecycleError::StatePersist("Pi fork spawn result disappeared".to_string())
507
- })?;
508
- super::agent::verify_spawned_pane_matches_target(
509
- transport,
510
- &spawned_ref.spawn.pane_id,
511
- &session_name,
512
- &WindowName::new(target_agent_id.as_str()),
513
- )?;
514
-
515
- phase = "p4_persist";
516
- let mut updated_state =
517
- crate::state::projection::select_runtime_state(run_workspace, Some(team_key))
518
- .map_err(|error| LifecycleError::TeamSelect(error.to_string()))?;
519
- super::agent::mark_agent_started(
520
- &mut updated_state,
521
- target_agent_id,
522
- target_agent_id.as_str(),
523
- spawned_ref,
524
- transport,
525
- &safety,
526
- StartMode::Resumed,
527
- )?;
528
- let updated_target = updated_state
529
- .get("agents")
530
- .and_then(|agents| agents.get(target_agent_id.as_str()))
531
- .cloned()
532
- .ok_or_else(|| {
533
- LifecycleError::StatePersist("started Pi fork target row disappeared".to_string())
534
- })?;
535
- crate::state::repository::StateRepository::new(run_workspace)
536
- .commit_fork_agent(
537
- crate::state::repository::StateWriteIntent::ForkAgent {
538
- team_key,
539
- agent_id: target_agent_id.as_str(),
540
- },
541
- &updated_target,
542
- )
543
- .map_err(|error| LifecycleError::StatePersist(error.to_string()))?;
544
- let _ = crate::db::agent_health_capture::clear_agent_health_observation(
545
- run_workspace,
546
- team_key,
547
- target_agent_id,
548
- );
549
- let coordinator =
550
- super::common::start_coordinator_for_workspace(run_workspace, Some(team_key))?;
551
- if !coordinator.ok {
552
- return Err(LifecycleError::StatePersist(format!(
553
- "coordinator did not become available after Pi fork: {}",
554
- coordinator.status
555
- )));
556
- }
557
-
558
- phase = "p5_receipt";
559
- let staged_file = staged.as_ref().ok_or_else(|| {
560
- LifecycleError::StatePersist("Pi fork snapshot staging was lost".to_string())
561
- })?;
562
- Ok(ForkAgentReport {
563
- source_agent_id: source_agent_id.clone(),
564
- new_agent_id: target_agent_id.clone(),
565
- env: AgentActionEnvelope {
566
- agent_id: target_agent_id.clone(),
567
- state_file: crate::state::persist::runtime_state_path(run_workspace),
568
- coordinator_started: coordinator.ok,
569
- },
570
- session_id: Some(staged_file.session_id.clone()),
571
- backing_state: ForkBackingState::Verified,
572
- pi_fork: Some(PiForkDetails {
573
- source_session_id: binding.session_id.clone(),
574
- session_id: staged_file.session_id.clone(),
575
- backing_path: RolloutPath::new(staged_file.backing_path.clone()),
576
- }),
577
- })
578
- })();
579
-
580
- match operation {
581
- Ok(report) => {
582
- if let Err(error) = write_fork_audit(
583
- run_workspace,
584
- &mut audit,
585
- "succeeded",
586
- "complete",
587
- "not_required",
588
- ) {
589
- let compensation = compensate_fork(
590
- run_workspace,
591
- team_key,
592
- target_agent_id,
593
- source_agent_id,
594
- transport,
595
- &session_name_for_audit(&selected.state),
596
- &panes_before,
597
- spawn_attempted,
598
- spawned.as_ref(),
599
- spec_registration.as_ref(),
600
- state_registered,
601
- staged.as_ref(),
602
- role.as_mut(),
603
- );
604
- return Err(LifecycleError::StatePersist(if compensation.is_empty() {
605
- format!("fork succeeded but audit receipt failed: {error}")
606
- } else {
607
- format!("fork succeeded but audit receipt failed: {error}; compensation incomplete: {compensation}")
608
- }));
609
- }
610
- if let Some(role) = role.as_mut() {
611
- role.keep();
612
- }
613
- Ok(report)
614
- }
615
- Err(error) => {
616
- let compensation = compensate_fork(
617
- run_workspace,
618
- team_key,
619
- target_agent_id,
620
- source_agent_id,
621
- transport,
622
- &session_name_for_audit(&selected.state),
623
- &panes_before,
624
- spawn_attempted,
625
- spawned.as_ref(),
626
- spec_registration.as_ref(),
627
- state_registered,
628
- staged.as_ref(),
629
- role.as_mut(),
630
- );
631
- let result = if compensation.is_empty() {
632
- "complete"
633
- } else {
634
- "incomplete"
635
- };
636
- audit["failure"] = serde_json::json!(phase);
637
- let audit_error =
638
- write_fork_audit(run_workspace, &mut audit, "failed", phase, result).err();
639
- let audit_detail = audit_error
640
- .map(|audit_error| format!("; failure receipt failed: {audit_error}"))
641
- .unwrap_or_default();
642
- if compensation.is_empty() && audit_detail.is_empty() {
643
- Err(error)
644
- } else if compensation.is_empty() {
645
- Err(LifecycleError::StatePersist(format!(
646
- "{error}{audit_detail}"
647
- )))
648
- } else {
649
- Err(LifecycleError::StatePersist(format!(
650
- "{error}; compensation incomplete: {compensation}{audit_detail}"
651
- )))
652
- }
653
- }
654
- }
655
- }
656
-
657
- fn source_binding(
658
- selected: &SelectedTeam,
659
- source_agent_id: &AgentId,
660
- ) -> Result<SourceBinding, LifecycleError> {
661
- let source = selected
662
- .state
663
- .get("agents")
664
- .and_then(|agents| agents.get(source_agent_id.as_str()))
665
- .ok_or_else(|| LifecycleError::RequirementUnmet("Pi source row disappeared".to_string()))?;
666
- if source.get("provider").and_then(JsonValue::as_str) != Some("pi")
667
- || source.get("auth_mode").and_then(JsonValue::as_str) != Some("subscription")
668
- || source.get("capture_state").and_then(JsonValue::as_str) != Some("captured")
669
- {
670
- return Err(LifecycleError::RequirementUnmet(
671
- "Pi source does not have a complete captured subscription session".to_string(),
672
- ));
673
- }
674
- if source
675
- .get("owner_team_id")
676
- .and_then(JsonValue::as_str)
677
- .is_some_and(|owner| owner != selected.team_key)
678
- {
679
- return Err(LifecycleError::TeamSelect(
680
- "Pi source owner does not match the selected team".to_string(),
681
- ));
682
- }
683
- let session_id = source
684
- .get("session_id")
685
- .and_then(JsonValue::as_str)
686
- .filter(|value| !value.is_empty())
687
- .map(SessionId::new)
688
- .ok_or_else(|| {
689
- LifecycleError::RequirementUnmet("Pi source session_id is missing".to_string())
690
- })?;
691
- let attribution_confidence = source
692
- .get("attribution_confidence")
693
- .and_then(JsonValue::as_str);
694
- if attribution_confidence.is_some_and(|confidence| confidence != "high")
695
- || source
696
- .get("attribution_ambiguous")
697
- .and_then(JsonValue::as_bool)
698
- == Some(true)
699
- {
700
- return Err(LifecycleError::RequirementUnmet(
701
- "Pi source capture attribution is explicitly low-confidence or ambiguous".to_string(),
702
- ));
703
- }
704
- let captured_at = required_state_string(source, "captured_at")?;
705
- let captured_via: CaptureVia = serde_json::from_value(serde_json::json!(
706
- required_state_string(source, "captured_via")?
707
- ))
708
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
709
- let spawned_at = required_state_string(source, "spawned_at")?;
710
- chrono::DateTime::parse_from_rfc3339(&captured_at)
711
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
712
- chrono::DateTime::parse_from_rfc3339(&spawned_at)
713
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
714
- let spawn_cwd = PathBuf::from(required_state_string(source, "spawn_cwd")?);
715
- if !spawn_cwd.is_absolute() {
716
- return Err(LifecycleError::RequirementUnmet(
717
- "Pi source spawn_cwd is not absolute".to_string(),
718
- ));
719
- }
720
- let canonical_cwd = fs::canonicalize(&spawn_cwd)
721
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
722
- let canonical_workspace = fs::canonicalize(&selected.run_workspace)
723
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
724
- if canonical_cwd != canonical_workspace {
725
- return Err(LifecycleError::RequirementUnmet(
726
- "Pi source spawn_cwd differs from the selected team workspace".to_string(),
727
- ));
728
- }
729
- for field in ["cwd", "working_directory"] {
730
- if let Some(cwd) = source.get(field).and_then(JsonValue::as_str) {
731
- if Path::new(cwd).canonicalize().ok().as_deref()
732
- != Some(selected.run_workspace.as_path())
733
- {
734
- return Err(LifecycleError::RequirementUnmet(format!(
735
- "Pi source {field} differs from the selected target working directory"
736
- )));
737
- }
738
- }
739
- }
740
- let backing_path = PathBuf::from(required_state_string(source, "rollout_path")?);
741
- if backing_path
742
- .extension()
743
- .and_then(|extension| extension.to_str())
744
- != Some("jsonl")
745
- {
746
- return Err(LifecycleError::RequirementUnmet(
747
- "Pi source backing is not a .jsonl session file".to_string(),
748
- ));
749
- }
750
- if !backing_path.is_absolute() {
751
- return Err(LifecycleError::RequirementUnmet(
752
- "Pi source rollout_path is not absolute".to_string(),
753
- ));
754
- }
755
- ensure_no_symlink_components(&backing_path, false)?;
756
- let canonical_backing = fs::canonicalize(&backing_path)
757
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
758
- if canonical_backing != backing_path {
759
- return Err(LifecycleError::RequirementUnmet(
760
- "Pi source rollout_path is not its canonical exact path".to_string(),
761
- ));
762
- }
763
- // Native cwd roots (and explicit --session-dir roots) are shared. Ownership
764
- // comes from the captured header UUID/cwd tuple, not a seat directory name.
765
- let recorded_root = PathBuf::from(required_state_string(source, "claude_projects_root")?);
766
- ensure_no_symlink_components(&recorded_root, false)?;
767
- let canonical_root = fs::canonicalize(&recorded_root)
768
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
769
- if !canonical_backing.starts_with(&canonical_root) {
770
- return Err(LifecycleError::RequirementUnmet(
771
- "Pi source backing is outside its recorded session root".to_string(),
772
- ));
773
- }
774
- let file = fs::File::open(&backing_path)
775
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
776
- let mut reader = std::io::BufReader::new(file).take(64 * 1024);
777
- let mut header_line = String::new();
778
- let header_bytes = reader
779
- .read_line(&mut header_line)
780
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
781
- if header_bytes == 0 || !header_line.ends_with('\n') {
782
- return Err(LifecycleError::RequirementUnmet(
783
- "Pi source session header is incomplete".to_string(),
784
- ));
785
- }
786
- let header: JsonValue = serde_json::from_str(header_line.trim_end())
787
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
788
- let header_cwd = header
789
- .get("cwd")
790
- .and_then(JsonValue::as_str)
791
- .map(PathBuf::from)
792
- .ok_or_else(|| {
793
- LifecycleError::RequirementUnmet("Pi source header cwd is missing".into())
794
- })?;
795
- let canonical_header_cwd = fs::canonicalize(&header_cwd)
796
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
797
- if canonical_header_cwd != canonical_cwd || canonical_header_cwd != canonical_workspace {
798
- return Err(LifecycleError::RequirementUnmet(
799
- "Pi source header cwd differs from its capture tuple or target workspace".into(),
800
- ));
801
- }
802
- crate::provider::session_scan::pi::validate_exact_backing(
803
- &backing_path,
804
- &session_id,
805
- &canonical_cwd,
806
- )
807
- .map_err(|error| LifecycleError::Provider(error.to_string()))?;
808
- let identity = file_identity(&backing_path).map_err(LifecycleError::RequirementUnmet)?;
809
- Ok(SourceBinding {
810
- session_id,
811
- backing_path,
812
- sessions_root: canonical_root,
813
- spawn_cwd: canonical_cwd,
814
- captured_at: captured_at.to_string(),
815
- captured_via,
816
- spawned_at: spawned_at.to_string(),
817
- spawn_epoch: source.get("spawn_epoch").and_then(JsonValue::as_u64),
818
- identity,
819
- })
820
- }
821
-
822
- fn revalidate_source_binding(
823
- selected: &SelectedTeam,
824
- source_agent_id: &AgentId,
825
- expected: &SourceBinding,
826
- ) -> Result<(), LifecycleError> {
827
- let current = crate::state::projection::select_runtime_state(
828
- &selected.run_workspace,
829
- Some(&selected.team_key),
830
- )
831
- .map_err(|error| LifecycleError::TeamSelect(error.to_string()))?;
832
- let latest = source_binding_from_state(&current, selected, source_agent_id)?;
833
- if latest.session_id != expected.session_id
834
- || latest.backing_path != expected.backing_path
835
- || latest.sessions_root != expected.sessions_root
836
- || latest.spawn_cwd != expected.spawn_cwd
837
- || latest.captured_at != expected.captured_at
838
- || latest.captured_via != expected.captured_via
839
- || latest.spawned_at != expected.spawned_at
840
- || latest.spawn_epoch != expected.spawn_epoch
841
- || latest.identity != expected.identity
842
- {
843
- return Err(LifecycleError::RequirementUnmet(
844
- "Pi source session cohort changed during fork preparation".to_string(),
845
- ));
846
- }
847
- Ok(())
848
- }
849
-
850
- fn source_binding_from_state(
851
- state: &JsonValue,
852
- selected: &SelectedTeam,
853
- source_agent_id: &AgentId,
854
- ) -> Result<SourceBinding, LifecycleError> {
855
- let mut snapshot = selected.clone();
856
- snapshot.state = state.clone();
857
- source_binding(&snapshot, source_agent_id)
858
- }
859
-
860
- fn read_stable_source_snapshot(
861
- binding: &SourceBinding,
862
- run_workspace: &Path,
863
- ) -> Result<SourceSnapshot, LifecycleError> {
864
- ensure_no_symlink_components(&binding.backing_path, false)?;
865
- let before_path = fs::symlink_metadata(&binding.backing_path)
866
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
867
- if !before_path.file_type().is_file()
868
- || identity_from_metadata(&before_path) != binding.identity
869
- {
870
- return Err(LifecycleError::RequirementUnmet(
871
- "Pi source backing is not the captured regular file".to_string(),
872
- ));
873
- }
874
- let mut file = OpenOptions::new()
875
- .read(true)
876
- .custom_flags(libc::O_NOFOLLOW)
877
- .open(&binding.backing_path)
878
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
879
- let open_before = file
880
- .metadata()
881
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
882
- if identity_from_metadata(&open_before) != binding.identity {
883
- return Err(LifecycleError::RequirementUnmet(
884
- "Pi source backing changed while opening".to_string(),
885
- ));
886
- }
887
- let mut first = Vec::new();
888
- file.read_to_end(&mut first)
889
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
890
- let middle = file
891
- .metadata()
892
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
893
- file.seek(SeekFrom::Start(0))
894
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
895
- let mut second = Vec::new();
896
- file.read_to_end(&mut second)
897
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
898
- let after = file
899
- .metadata()
900
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
901
- let after_path = fs::symlink_metadata(&binding.backing_path)
902
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
903
- if first != second
904
- || identity_from_metadata(&middle) != binding.identity
905
- || identity_from_metadata(&after) != binding.identity
906
- || identity_from_metadata(&after_path) != binding.identity
907
- || middle.len() != after.len()
908
- {
909
- return Err(LifecycleError::RequirementUnmet(
910
- "Pi source JSONL changed during stable snapshot read".to_string(),
911
- ));
912
- }
913
- let canonical_workspace = fs::canonicalize(run_workspace)
914
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
915
- if canonical_workspace != binding.spawn_cwd {
916
- return Err(LifecycleError::RequirementUnmet(
917
- "Pi source capture cwd differs from the selected target workspace".into(),
918
- ));
919
- }
920
- let body = validate_session_bytes(&first, &binding.session_id, &canonical_workspace, None)?;
921
- Ok(SourceSnapshot { body })
922
- }
923
-
924
- fn validate_session_bytes(
925
- bytes: &[u8],
926
- expected_id: &SessionId,
927
- expected_cwd: &Path,
928
- expected_parent: Option<&Path>,
929
- ) -> Result<Vec<u8>, LifecycleError> {
930
- let header_end = bytes
931
- .iter()
932
- .position(|byte| *byte == b'\n')
933
- .ok_or_else(|| {
934
- LifecycleError::RequirementUnmet("Pi session header is incomplete".to_string())
935
- })?;
936
- let header_line = trim_line_ending(&bytes[..header_end]);
937
- let header: JsonValue = serde_json::from_slice(header_line)
938
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
939
- if header.get("type").and_then(JsonValue::as_str) != Some("session")
940
- || header.get("version").and_then(JsonValue::as_u64) != Some(3)
941
- || header.get("id").and_then(JsonValue::as_str) != Some(expected_id.as_str())
942
- {
943
- return Err(LifecycleError::RequirementUnmet(
944
- "Pi session header type/version/id mismatch".to_string(),
945
- ));
946
- }
947
- let cwd = header
948
- .get("cwd")
949
- .and_then(JsonValue::as_str)
950
- .map(PathBuf::from)
951
- .ok_or_else(|| LifecycleError::RequirementUnmet("Pi session cwd is missing".to_string()))?;
952
- let canonical_cwd = fs::canonicalize(&cwd)
953
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
954
- let canonical_expected_cwd = fs::canonicalize(expected_cwd)
955
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
956
- if !cwd.is_absolute() || canonical_cwd != canonical_expected_cwd {
957
- return Err(LifecycleError::RequirementUnmet(
958
- "Pi session header cwd does not match the captured cohort".to_string(),
959
- ));
960
- }
961
- let timestamp = header
962
- .get("timestamp")
963
- .and_then(JsonValue::as_str)
964
- .ok_or_else(|| {
965
- LifecycleError::RequirementUnmet("Pi session timestamp is missing".to_string())
966
- })?;
967
- chrono::DateTime::parse_from_rfc3339(timestamp)
968
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
969
- if let Some(expected_parent) = expected_parent {
970
- if header
971
- .get("parentSession")
972
- .and_then(JsonValue::as_str)
973
- .map(PathBuf::from)
974
- .as_deref()
975
- != Some(expected_parent)
976
- {
977
- return Err(LifecycleError::RequirementUnmet(
978
- "Pi fork parentSession does not match the exact source backing".to_string(),
979
- ));
980
- }
981
- }
982
- let body = &bytes[header_end + 1..];
983
- if !body.is_empty() && !body.ends_with(b"\n") {
984
- return Err(LifecycleError::RequirementUnmet(
985
- "Pi session has an incomplete trailing JSONL record".to_string(),
986
- ));
987
- }
988
- let mut ids = HashSet::new();
989
- for record in body.split_inclusive(|byte| *byte == b'\n') {
990
- if record.is_empty() || !record.ends_with(b"\n") {
991
- return Err(LifecycleError::RequirementUnmet(
992
- "Pi session contains an incomplete JSONL record".to_string(),
993
- ));
994
- }
995
- let json: JsonValue = serde_json::from_slice(trim_line_ending(record))
996
- .map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
997
- if json
998
- .get("type")
999
- .and_then(JsonValue::as_str)
1000
- .is_none_or(|kind| kind.is_empty() || kind == "session")
1001
- {
1002
- return Err(LifecycleError::RequirementUnmet(
1003
- "Pi session entry type is missing or invalid".to_string(),
1004
- ));
1005
- }
1006
- let id = json
1007
- .get("id")
1008
- .and_then(JsonValue::as_str)
1009
- .filter(|id| !id.is_empty())
1010
- .ok_or_else(|| {
1011
- LifecycleError::RequirementUnmet("Pi session entry id is missing".to_string())
1012
- })?;
1013
- if ids.contains(id) {
1014
- return Err(LifecycleError::RequirementUnmet(format!(
1015
- "Pi session entry id is duplicated: {id}"
1016
- )));
1017
- }
1018
- let parent = json.get("parentId").ok_or_else(|| {
1019
- LifecycleError::RequirementUnmet("Pi session entry parentId is missing".to_string())
1020
- })?;
1021
- match parent {
1022
- JsonValue::Null => {}
1023
- JsonValue::String(parent) if ids.contains(parent) => {}
1024
- JsonValue::String(parent) => {
1025
- return Err(LifecycleError::RequirementUnmet(format!(
1026
- "Pi session parentId does not reference an earlier entry: {parent}"
1027
- )))
1028
- }
1029
- _ => {
1030
- return Err(LifecycleError::RequirementUnmet(
1031
- "Pi session parentId must be string or null".to_string(),
1032
- ))
1033
- }
1034
- }
1035
- ids.insert(id.to_string());
1036
- }
1037
- Ok(body.to_vec())
1038
- }
1039
-
1040
- fn trim_line_ending(line: &[u8]) -> &[u8] {
1041
- let line = line.strip_suffix(b"\n").unwrap_or(line);
1042
- line.strip_suffix(b"\r").unwrap_or(line)
1043
- }
1044
-
1045
- fn stage_pi_session(
1046
- paths: &crate::lifecycle::launch::pi_mcp::PiSeatPaths,
1047
- session_id: &SessionId,
1048
- timestamp: &str,
1049
- cwd: &Path,
1050
- parent_session: &Path,
1051
- body: &[u8],
1052
- ) -> Result<StagedPiSession, LifecycleError> {
1053
- let file_timestamp = timestamp.replace(':', "-").replace('.', "-");
1054
- let backing_path = paths
1055
- .sessions
1056
- .join(format!("{file_timestamp}_{}.jsonl", session_id.as_str()));
1057
- let header = serde_json::json!({
1058
- "type": "session",
1059
- "version": 3,
1060
- "id": session_id.as_str(),
1061
- "timestamp": timestamp,
1062
- "cwd": cwd.to_string_lossy(),
1063
- "parentSession": parent_session.to_string_lossy(),
1064
- });
1065
- let mut bytes = serde_json::to_vec(&header)
1066
- .map_err(|error| LifecycleError::StatePersist(error.to_string()))?;
1067
- bytes.push(b'\n');
1068
- bytes.extend_from_slice(body);
1069
- validate_session_bytes(&bytes, session_id, cwd, Some(parent_session))?;
1070
- let created_dirs = create_target_session_dirs(paths)?;
1071
- let mut file = match OpenOptions::new()
1072
- .write(true)
1073
- .create_new(true)
1074
- .mode(0o600)
1075
- .custom_flags(libc::O_NOFOLLOW)
1076
- .open(&backing_path)
1077
- {
1078
- Ok(file) => file,
1079
- Err(error) => {
1080
- cleanup_created_dirs(&created_dirs);
1081
- return Err(if error.kind() == std::io::ErrorKind::AlreadyExists {
1082
- LifecycleError::RequirementUnmet(format!(
1083
- "target Pi backing already exists: {}",
1084
- backing_path.display()
1085
- ))
1086
- } else {
1087
- LifecycleError::StatePersist(error.to_string())
1088
- });
1089
- }
1090
- };
1091
- if let Err(error) = file.write_all(&bytes).and_then(|_| file.sync_all()) {
1092
- drop(file);
1093
- let _ = fs::remove_file(&backing_path);
1094
- cleanup_created_dirs(&created_dirs);
1095
- return Err(LifecycleError::StatePersist(error.to_string()));
1096
- }
1097
- drop(file);
1098
- let stored = match fs::read(&backing_path) {
1099
- Ok(stored) => stored,
1100
- Err(error) => {
1101
- let _ = fs::remove_file(&backing_path);
1102
- cleanup_created_dirs(&created_dirs);
1103
- return Err(LifecycleError::StatePersist(error.to_string()));
1104
- }
1105
- };
1106
- if stored != bytes {
1107
- let _ = fs::remove_file(&backing_path);
1108
- cleanup_created_dirs(&created_dirs);
1109
- return Err(LifecycleError::RequirementUnmet(
1110
- "Pi fork backing changed before registration".to_string(),
1111
- ));
1112
- }
1113
- if let Err(error) = validate_session_bytes(&stored, session_id, cwd, Some(parent_session)) {
1114
- let _ = fs::remove_file(&backing_path);
1115
- cleanup_created_dirs(&created_dirs);
1116
- return Err(error);
1117
- }
1118
- let identity = match file_identity(&backing_path) {
1119
- Ok(identity) => identity,
1120
- Err(error) => {
1121
- let _ = fs::remove_file(&backing_path);
1122
- cleanup_created_dirs(&created_dirs);
1123
- return Err(LifecycleError::StatePersist(error));
1124
- }
1125
- };
1126
- let sha256 = format!("{:x}", Sha256::digest(&bytes));
1127
- Ok(StagedPiSession {
1128
- seat_paths: paths.clone(),
1129
- backing_path,
1130
- bytes,
1131
- identity,
1132
- created_dirs,
1133
- wrapper_identity: None,
1134
- session_id: session_id.clone(),
1135
- captured_at: timestamp.to_string(),
1136
- sha256,
1137
- })
1138
- }
1139
-
1140
- fn create_target_session_dirs(
1141
- paths: &crate::lifecycle::launch::pi_mcp::PiSeatPaths,
1142
- ) -> Result<Vec<PathBuf>, LifecycleError> {
1143
- let mut created = Vec::new();
1144
- // Wrapper metadata and native sessions have separate roots. Roll back only
1145
- // directories this attempt creates, never existing native session data.
1146
- for path in [&paths.runtime_root, &paths.sessions] {
1147
- let mut current = PathBuf::new();
1148
- if !path.is_absolute() {
1149
- cleanup_created_dirs(&created);
1150
- return Err(LifecycleError::StatePersist(
1151
- "Pi target path is not absolute".into(),
1152
- ));
1153
- }
1154
- for component in path.components() {
1155
- if component == Component::RootDir {
1156
- current.push(component);
1157
- continue;
1158
- }
1159
- let Component::Normal(name) = component else {
1160
- cleanup_created_dirs(&created);
1161
- return Err(LifecycleError::StatePersist(
1162
- "target Pi session root contains an invalid path component".to_string(),
1163
- ));
1164
- };
1165
- current.push(name);
1166
- match fs::symlink_metadata(&current) {
1167
- Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
1168
- cleanup_created_dirs(&created);
1169
- return Err(LifecycleError::RequirementUnmet(format!(
1170
- "target Pi session path is not a real directory: {}",
1171
- current.display()
1172
- )));
1173
- }
1174
- Ok(_) => {}
1175
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1176
- if let Err(error) = fs::create_dir(&current) {
1177
- cleanup_created_dirs(&created);
1178
- return Err(LifecycleError::StatePersist(error.to_string()));
1179
- }
1180
- created.push(current.clone());
1181
- if let Err(error) =
1182
- fs::set_permissions(&current, fs::Permissions::from_mode(0o700))
1183
- {
1184
- cleanup_created_dirs(&created);
1185
- return Err(LifecycleError::StatePersist(error.to_string()));
1186
- }
1187
- }
1188
- Err(error) => {
1189
- cleanup_created_dirs(&created);
1190
- return Err(LifecycleError::StatePersist(error.to_string()));
1191
- }
1192
- }
1193
- }
1194
- }
1195
- let canonical = match fs::canonicalize(&paths.sessions) {
1196
- Ok(canonical) => canonical,
1197
- Err(error) => {
1198
- cleanup_created_dirs(&created);
1199
- return Err(LifecycleError::StatePersist(error.to_string()));
1200
- }
1201
- };
1202
- if canonical != paths.sessions {
1203
- cleanup_created_dirs(&created);
1204
- return Err(LifecycleError::RequirementUnmet(
1205
- "target Pi session root resolves outside its managed path".to_string(),
1206
- ));
1207
- }
1208
- Ok(created)
1209
- }
1210
-
1211
- fn session_id_in_use(state: &JsonValue, session_id: &SessionId) -> bool {
1212
- match state {
1213
- JsonValue::Object(values) => values.iter().any(|(key, value)| {
1214
- (matches!(key.as_str(), "session_id" | "_pending_session_id")
1215
- && value.as_str() == Some(session_id.as_str()))
1216
- || session_id_in_use(value, session_id)
1217
- }),
1218
- JsonValue::Array(values) => values
1219
- .iter()
1220
- .any(|value| session_id_in_use(value, session_id)),
1221
- _ => false,
1222
- }
1223
- }
1224
-
1225
- fn required_state_string<'a>(state: &'a JsonValue, key: &str) -> Result<&'a str, LifecycleError> {
1226
- state
1227
- .get(key)
1228
- .and_then(JsonValue::as_str)
1229
- .filter(|value| !value.is_empty())
1230
- .ok_or_else(|| LifecycleError::RequirementUnmet(format!("Pi source {key} is missing")))
1231
- }
1232
-
1233
- fn file_identity(path: &Path) -> Result<FileIdentity, String> {
1234
- let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
1235
- if !metadata.file_type().is_file() {
1236
- return Err(format!("not a regular file: {}", path.display()));
1237
- }
1238
- Ok(identity_from_metadata(&metadata))
1239
- }
1240
-
1241
- fn identity_from_metadata(metadata: &fs::Metadata) -> FileIdentity {
1242
- FileIdentity {
1243
- device: metadata.dev(),
1244
- inode: metadata.ino(),
1245
- }
1246
- }
1247
-
1248
- fn validate_path_component(value: &str, label: &str) -> Result<(), LifecycleError> {
1249
- let mut components = Path::new(value).components();
1250
- if value.is_empty()
1251
- || value
1252
- .chars()
1253
- .any(|character| matches!(character, '/' | '\\' | '\0'))
1254
- || !matches!(components.next(), Some(Component::Normal(_)))
1255
- || components.next().is_some()
1256
- {
1257
- return Err(LifecycleError::RequirementUnmet(format!(
1258
- "{label} is not a safe path component"
1259
- )));
1260
- }
1261
- Ok(())
1262
- }
1263
-
1264
- fn ensure_no_symlink_components(path: &Path, allow_missing: bool) -> Result<(), LifecycleError> {
1265
- if !path.is_absolute()
1266
- || path
1267
- .components()
1268
- .any(|component| matches!(component, Component::ParentDir))
1269
- {
1270
- return Err(LifecycleError::RequirementUnmet(format!(
1271
- "path is not a normalized absolute path: {}",
1272
- path.display()
1273
- )));
1274
- }
1275
- let mut current = PathBuf::new();
1276
- for component in path.components() {
1277
- current.push(component.as_os_str());
1278
- match fs::symlink_metadata(&current) {
1279
- Ok(metadata) if metadata.file_type().is_symlink() => {
1280
- return Err(LifecycleError::RequirementUnmet(format!(
1281
- "symlink path component is not allowed: {}",
1282
- current.display()
1283
- )))
1284
- }
1285
- Ok(_) => {}
1286
- Err(error) if allow_missing && error.kind() == std::io::ErrorKind::NotFound => {
1287
- return Ok(())
1288
- }
1289
- Err(error) => return Err(LifecycleError::RequirementUnmet(error.to_string())),
1290
- }
1291
- }
1292
- Ok(())
1293
- }
1294
-
1295
- fn refuse_existing_path(path: &Path, label: &str) -> Result<(), LifecycleError> {
1296
- match fs::symlink_metadata(path) {
1297
- Ok(_) => Err(LifecycleError::RequirementUnmet(format!(
1298
- "{label} already exists: {}",
1299
- path.display()
1300
- ))),
1301
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1302
- Err(error) => Err(LifecycleError::StatePersist(error.to_string())),
1303
- }
1304
- }
1305
-
1306
- fn read_optional_bytes(path: &Path) -> Result<Option<Vec<u8>>, LifecycleError> {
1307
- match fs::read(path) {
1308
- Ok(bytes) => Ok(Some(bytes)),
1309
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1310
- Err(error) => Err(LifecycleError::StatePersist(error.to_string())),
1311
- }
1312
- }
1313
-
1314
- fn spec_has_target(spec: &YamlValue, target: &str) -> bool {
1315
- if !spec.is_map() {
1316
- return true;
1317
- }
1318
- if spec
1319
- .get("agents")
1320
- .and_then(YamlValue::as_list)
1321
- .is_some_and(|agents| {
1322
- agents
1323
- .iter()
1324
- .any(|agent| yaml_agent_id(agent) == Some(target))
1325
- })
1326
- {
1327
- return true;
1328
- }
1329
- spec.get("routing")
1330
- .and_then(|routing| routing.get("rules"))
1331
- .and_then(YamlValue::as_list)
1332
- .is_some_and(|rules| rules.iter().any(|rule| yaml_route_mentions(rule, target)))
1333
- }
1334
-
1335
- fn yaml_agent_id(agent: &YamlValue) -> Option<&str> {
1336
- agent.get("id").and_then(YamlValue::as_str)
1337
- }
1338
-
1339
- fn yaml_route_mentions(rule: &YamlValue, target: &str) -> bool {
1340
- rule.get("assign_to").and_then(YamlValue::as_str) == Some(target)
1341
- || rule
1342
- .get("match")
1343
- .and_then(|matcher| matcher.get("assignee"))
1344
- .and_then(YamlValue::as_list)
1345
- .is_some_and(|assignees| {
1346
- assignees
1347
- .iter()
1348
- .any(|assignee| assignee.as_str() == Some(target))
1349
- })
1350
- }
1351
-
1352
- fn compensate_fork(
1353
- workspace: &Path,
1354
- team_key: &str,
1355
- target: &AgentId,
1356
- source: &AgentId,
1357
- transport: &dyn Transport,
1358
- session: &SessionName,
1359
- panes_before: &BTreeSet<String>,
1360
- spawn_attempted: bool,
1361
- spawned: Option<&super::common::SpawnedAgentWindow>,
1362
- spec_registration: Option<&SpecRegistration>,
1363
- state_registered: bool,
1364
- staged: Option<&StagedPiSession>,
1365
- role: Option<&mut MaterializedRole>,
1366
- ) -> String {
1367
- if let Some(staged) = staged {
1368
- if let Err(error) = verify_no_target_writer(
1369
- transport,
1370
- session,
1371
- target,
1372
- panes_before,
1373
- spawn_attempted,
1374
- spawned,
1375
- ) {
1376
- if let Some(role) = role {
1377
- role.keep();
1378
- }
1379
- return error;
1380
- }
1381
- match read_optional_bytes(&staged.backing_path) {
1382
- Ok(Some(bytes)) if bytes == staged.bytes => {}
1383
- Ok(Some(_)) => {
1384
- if let Some(role) = role {
1385
- role.keep();
1386
- }
1387
- return format!(
1388
- "target Pi session has post-snapshot records; preserved {}",
1389
- staged.backing_path.display()
1390
- );
1391
- }
1392
- Ok(None) => {}
1393
- Err(error) => {
1394
- if let Some(role) = role {
1395
- role.keep();
1396
- }
1397
- return format!("cannot verify target Pi backing before cleanup: {error}");
1398
- }
1399
- }
1400
- } else if spawn_attempted {
1401
- if let Err(error) = verify_no_target_writer(
1402
- transport,
1403
- session,
1404
- target,
1405
- panes_before,
1406
- spawn_attempted,
1407
- spawned,
1408
- ) {
1409
- if let Some(role) = role {
1410
- role.keep();
1411
- }
1412
- return error;
1413
- }
1414
- }
1415
-
1416
- if state_registered {
1417
- let Some((staged, role_ref)) = staged.zip(role.as_deref()) else {
1418
- if let Some(role) = role {
1419
- role.keep();
1420
- }
1421
- return "fork state identity is unavailable; resources preserved".to_string();
1422
- };
1423
- if let Err(error) = rollback_fork_state(
1424
- workspace,
1425
- team_key,
1426
- target,
1427
- source,
1428
- &staged.session_id,
1429
- &staged.backing_path,
1430
- role_ref.path(),
1431
- ) {
1432
- if let Some(role) = role {
1433
- role.keep();
1434
- }
1435
- return format!("state rollback failed: {error}");
1436
- }
1437
- }
1438
- if let Some(registration) = spec_registration {
1439
- if let Err(error) = rollback_fork_spec(registration, target.as_str()) {
1440
- if let Some(role) = role {
1441
- role.keep();
1442
- }
1443
- return format!("spec rollback failed: {error}");
1444
- }
1445
- }
1446
- if let Some(staged) = staged {
1447
- if let Err(error) = remove_staged_session(staged, spawn_attempted) {
1448
- if let Some(role) = role {
1449
- role.keep();
1450
- }
1451
- return error;
1452
- }
1453
- }
1454
- String::new()
1455
- }
1456
-
1457
- fn verify_no_target_writer(
1458
- transport: &dyn Transport,
1459
- session: &SessionName,
1460
- target: &AgentId,
1461
- panes_before: &BTreeSet<String>,
1462
- spawn_attempted: bool,
1463
- spawned: Option<&super::common::SpawnedAgentWindow>,
1464
- ) -> Result<(), String> {
1465
- let pane_id = if let Some(spawned) = spawned {
1466
- spawned.spawn.pane_id.clone()
1467
- } else if spawn_attempted {
1468
- let targets = transport
1469
- .list_targets()
1470
- .map_err(|error| error.to_string())?;
1471
- let new_panes: Vec<_> = targets
1472
- .iter()
1473
- .filter(|pane| !panes_before.contains(pane.pane_id.as_str()))
1474
- .collect();
1475
- match new_panes.as_slice() {
1476
- [] => return Ok(()),
1477
- [pane]
1478
- if pane.session.as_str() == session.as_str()
1479
- && pane.window_name.as_ref().map(WindowName::as_str)
1480
- == Some(target.as_str()) =>
1481
- {
1482
- pane.pane_id.clone()
1483
- }
1484
- _ => return Err("new pane ownership is ambiguous; resources preserved".to_string()),
1485
- }
1486
- } else {
1487
- return Ok(());
1488
- };
1489
- let targets = transport
1490
- .list_targets()
1491
- .map_err(|error| error.to_string())?;
1492
- let exact = targets.iter().any(|pane| {
1493
- pane.pane_id == pane_id
1494
- && pane.session.as_str() == session.as_str()
1495
- && pane.window_name.as_ref().map(WindowName::as_str) == Some(target.as_str())
1496
- });
1497
- if !exact {
1498
- let still_present = targets.iter().any(|pane| pane.pane_id == pane_id);
1499
- if !panes_before.contains(pane_id.as_str()) {
1500
- transport
1501
- .kill_pane(&pane_id)
1502
- .map_err(|error| format!("could not stop newly spawned pane: {error}"))?;
1503
- let remaining = transport
1504
- .list_targets()
1505
- .map_err(|error| error.to_string())?;
1506
- if remaining.iter().any(|pane| pane.pane_id == pane_id) {
1507
- return Err(
1508
- "newly spawned pane remains after kill; resources preserved".to_string()
1509
- );
1510
- }
1511
- return Ok(());
1512
- }
1513
- if still_present {
1514
- return Err(
1515
- "spawned pane is not owned by the target window; resources preserved".to_string(),
1516
- );
1517
- }
1518
- return Ok(());
1519
- }
1520
- transport
1521
- .kill_pane(&pane_id)
1522
- .map_err(|error| format!("could not stop exact target pane: {error}"))?;
1523
- let remaining = transport
1524
- .list_targets()
1525
- .map_err(|error| error.to_string())?;
1526
- if remaining.iter().any(|pane| pane.pane_id == pane_id) {
1527
- return Err("exact target pane remains after kill; resources preserved".to_string());
1528
- }
1529
- Ok(())
1530
- }
1531
-
1532
- fn fork_target_state_registered(
1533
- workspace: &Path,
1534
- team_key: &str,
1535
- target: &AgentId,
1536
- source: &AgentId,
1537
- session_id: &SessionId,
1538
- backing_path: &Path,
1539
- role_path: &Path,
1540
- ) -> bool {
1541
- let Ok(state) = crate::state::projection::select_runtime_state(workspace, Some(team_key))
1542
- else {
1543
- return false;
1544
- };
1545
- let Some(agent) = state
1546
- .get("agents")
1547
- .and_then(|agents| agents.get(target.as_str()))
1548
- else {
1549
- return false;
1550
- };
1551
- let backing_text = backing_path.to_string_lossy().to_string();
1552
- let role_text = role_path.to_string_lossy().to_string();
1553
- agent.get("owner_team_id").and_then(JsonValue::as_str) == Some(team_key)
1554
- && agent.get("forked_from").and_then(JsonValue::as_str) == Some(source.as_str())
1555
- && agent.get("session_id").and_then(JsonValue::as_str) == Some(session_id.as_str())
1556
- && agent.get("rollout_path").and_then(JsonValue::as_str) == Some(backing_text.as_str())
1557
- && agent.get("dynamic_role_file").and_then(JsonValue::as_str) == Some(role_text.as_str())
1558
- && agent.get("captured_via").and_then(JsonValue::as_str) == Some("fork_snapshot")
1559
- && agent.get("capture_state").and_then(JsonValue::as_str) == Some("captured")
1560
- }
1561
-
1562
- fn rollback_fork_state(
1563
- workspace: &Path,
1564
- team_key: &str,
1565
- target: &AgentId,
1566
- source: &AgentId,
1567
- session_id: &SessionId,
1568
- backing_path: &Path,
1569
- role_path: &Path,
1570
- ) -> Result<(), String> {
1571
- let mut state = crate::state::projection::select_runtime_state(workspace, Some(team_key))
1572
- .map_err(|error| error.to_string())?;
1573
- let agent = state
1574
- .get("agents")
1575
- .and_then(|agents| agents.get(target.as_str()))
1576
- .ok_or_else(|| "fork target row disappeared before rollback".to_string())?;
1577
- let backing_text = backing_path.to_string_lossy().to_string();
1578
- let role_text = role_path.to_string_lossy().to_string();
1579
- if agent.get("owner_team_id").and_then(JsonValue::as_str) != Some(team_key)
1580
- || agent.get("forked_from").and_then(JsonValue::as_str) != Some(source.as_str())
1581
- || agent.get("session_id").and_then(JsonValue::as_str) != Some(session_id.as_str())
1582
- || agent.get("rollout_path").and_then(JsonValue::as_str) != Some(backing_text.as_str())
1583
- || agent.get("dynamic_role_file").and_then(JsonValue::as_str) != Some(role_text.as_str())
1584
- {
1585
- return Err("fork target row identity changed; left untouched".to_string());
1586
- }
1587
- state
1588
- .get_mut("agents")
1589
- .and_then(JsonValue::as_object_mut)
1590
- .ok_or_else(|| "runtime agents map is missing".to_string())?
1591
- .remove(target.as_str());
1592
- crate::state::repository::StateRepository::new(workspace)
1593
- .save(
1594
- crate::state::repository::StateWriteIntent::AgentRollback {
1595
- team_key: Some(team_key),
1596
- agent_id: target.as_str(),
1597
- },
1598
- &state,
1599
- )
1600
- .map_err(|error| error.to_string())
1601
- }
1602
-
1603
- fn rollback_fork_spec(registration: &SpecRegistration, target: &str) -> Result<(), String> {
1604
- ensure_no_symlink_components(&registration.path, true).map_err(|error| error.to_string())?;
1605
- let current = read_optional_bytes(&registration.path).map_err(|error| error.to_string())?;
1606
- if current.as_deref() == registration.previous_bytes.as_deref() {
1607
- return Ok(());
1608
- }
1609
- if current.as_deref() == Some(registration.written_bytes.as_slice())
1610
- && registration.identity.is_some()
1611
- && file_identity(&registration.path).ok() == registration.identity
1612
- {
1613
- return match &registration.previous_bytes {
1614
- Some(bytes) => write_bytes_atomic(&registration.path, bytes),
1615
- None => fs::remove_file(&registration.path).map_err(|error| error.to_string()),
1616
- };
1617
- }
1618
- let Some(bytes) = current else {
1619
- return if registration.previous_bytes.is_none() {
1620
- Ok(())
1621
- } else {
1622
- Err("runtime spec disappeared during rollback".to_string())
1623
- };
1624
- };
1625
- let text = std::str::from_utf8(&bytes).map_err(|error| error.to_string())?;
1626
- let mut spec = yaml::loads(text).map_err(|error| error.to_string())?;
1627
- remove_target_from_spec(&mut spec, target, &registration.target_agent);
1628
- if spec_has_target(&spec, target) {
1629
- return Err("runtime spec target changed during operation; left untouched".to_string());
1630
- }
1631
- let bytes = yaml::dumps(&spec).into_bytes();
1632
- write_bytes_atomic(&registration.path, &bytes)
1633
- }
1634
-
1635
- fn remove_target_from_spec(spec: &mut YamlValue, target: &str, expected_agent: &YamlValue) {
1636
- let YamlValue::Map(root) = spec else {
1637
- return;
1638
- };
1639
- if let Some((_, YamlValue::List(agents))) = root.iter_mut().find(|(key, _)| key == "agents") {
1640
- agents.retain(|agent| yaml_agent_id(agent) != Some(target) || agent != expected_agent);
1641
- }
1642
- if let Some((_, YamlValue::Map(fields))) = root.iter_mut().find(|(key, _)| key == "routing") {
1643
- if let Some((_, YamlValue::List(rules))) = fields.iter_mut().find(|(key, _)| key == "rules")
1644
- {
1645
- let route_id = format!("route-{target}");
1646
- let expected_route = YamlValue::Map(vec![
1647
- ("id".to_string(), YamlValue::Str(route_id.clone())),
1648
- (
1649
- "match".to_string(),
1650
- YamlValue::Map(vec![(
1651
- "assignee".to_string(),
1652
- YamlValue::List(vec![YamlValue::Str(target.to_string())]),
1653
- )]),
1654
- ),
1655
- ("assign_to".to_string(), YamlValue::Str(target.to_string())),
1656
- ("priority".to_string(), YamlValue::Int(10)),
1657
- ]);
1658
- rules.retain(|rule| {
1659
- !(rule.get("id").and_then(YamlValue::as_str) == Some(route_id.as_str())
1660
- && rule.get("assign_to").and_then(YamlValue::as_str) == Some(target)
1661
- && rule == &expected_route)
1662
- });
1663
- }
1664
- }
1665
- }
1666
-
1667
- fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
1668
- let parent = path
1669
- .parent()
1670
- .ok_or_else(|| "runtime spec path has no parent".to_string())?;
1671
- let nonce = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
1672
- let temp = parent.join(format!(
1673
- ".fork-spec-rollback-{}-{nonce}",
1674
- std::process::id()
1675
- ));
1676
- let mut file = OpenOptions::new()
1677
- .write(true)
1678
- .create_new(true)
1679
- .mode(0o600)
1680
- .open(&temp)
1681
- .map_err(|error| error.to_string())?;
1682
- if let Err(error) = file.write_all(bytes).and_then(|_| file.sync_all()) {
1683
- drop(file);
1684
- let _ = fs::remove_file(&temp);
1685
- return Err(error.to_string());
1686
- }
1687
- drop(file);
1688
- if let Err(error) = fs::rename(&temp, path) {
1689
- let _ = fs::remove_file(&temp);
1690
- return Err(error.to_string());
1691
- }
1692
- Ok(())
1693
- }
1694
-
1695
- fn capture_target_wrapper_identity(staged: Option<&mut StagedPiSession>) {
1696
- if let Some(staged) = staged {
1697
- staged.wrapper_identity = ensure_no_symlink_components(&staged.seat_paths.wrapper, false)
1698
- .ok()
1699
- .and_then(|_| file_identity(&staged.seat_paths.wrapper).ok());
1700
- }
1701
- }
1702
-
1703
- fn remove_staged_session(staged: &StagedPiSession, remove_wrapper: bool) -> Result<(), String> {
1704
- ensure_no_symlink_components(&staged.backing_path, true).map_err(|error| error.to_string())?;
1705
- match fs::symlink_metadata(&staged.backing_path) {
1706
- Ok(_) => {
1707
- if file_identity(&staged.backing_path).ok() != Some(staged.identity)
1708
- || read_optional_bytes(&staged.backing_path)
1709
- .map_err(|error| error.to_string())?
1710
- .as_deref()
1711
- != Some(staged.bytes.as_slice())
1712
- {
1713
- return Err(format!(
1714
- "target Pi backing is no longer the staged file; preserved {}",
1715
- staged.backing_path.display()
1716
- ));
1717
- }
1718
- fs::remove_file(&staged.backing_path).map_err(|error| error.to_string())?;
1719
- }
1720
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1721
- Err(error) => return Err(error.to_string()),
1722
- }
1723
- if remove_wrapper {
1724
- ensure_no_symlink_components(&staged.seat_paths.runtime_root, false)
1725
- .map_err(|error| error.to_string())?;
1726
- match fs::symlink_metadata(&staged.seat_paths.wrapper) {
1727
- Ok(metadata)
1728
- if metadata.file_type().is_file()
1729
- && staged.wrapper_identity == Some(identity_from_metadata(&metadata)) =>
1730
- {
1731
- fs::remove_file(&staged.seat_paths.wrapper).map_err(|error| error.to_string())?;
1732
- }
1733
- Ok(_) => return Err("target Pi wrapper is not a regular file; preserved".to_string()),
1734
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1735
- Err(error) => return Err(error.to_string()),
1736
- }
1737
- }
1738
- cleanup_created_dirs_checked(&staged.created_dirs)
1739
- }
1740
-
1741
- fn cleanup_created_dirs(dirs: &[PathBuf]) {
1742
- for dir in dirs.iter().rev() {
1743
- let _ = fs::remove_dir(dir);
1744
- }
1745
- }
1746
-
1747
- fn cleanup_created_dirs_checked(dirs: &[PathBuf]) -> Result<(), String> {
1748
- for dir in dirs.iter().rev() {
1749
- match fs::remove_dir(dir) {
1750
- Ok(()) => {}
1751
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1752
- Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => {
1753
- return Err(format!(
1754
- "target Pi runtime directory is not empty; preserved {}",
1755
- dir.display()
1756
- ))
1757
- }
1758
- Err(error) => return Err(error.to_string()),
1759
- }
1760
- }
1761
- Ok(())
1762
- }
1763
-
1764
- fn write_fork_audit(
1765
- workspace: &Path,
1766
- fields: &mut JsonValue,
1767
- outcome: &str,
1768
- failure_stage: &str,
1769
- compensation: &str,
1770
- ) -> Result<(), String> {
1771
- fields["outcome"] = serde_json::json!(outcome);
1772
- fields["failure_stage"] = if outcome == "succeeded" {
1773
- JsonValue::Null
1774
- } else {
1775
- serde_json::json!(failure_stage)
1776
- };
1777
- fields["compensation"] = serde_json::json!(compensation);
1778
- crate::event_log::EventLog::new(workspace)
1779
- .write(crate::lifecycle::event_names::CONTEXT_FORK, fields.clone())
1780
- .map(|_| ())
1781
- .map_err(|error| error.to_string())
1782
- }
1783
-
1784
- fn state_has_session_name(state: &JsonValue) -> bool {
1785
- state
1786
- .get("session_name")
1787
- .and_then(JsonValue::as_str)
1788
- .is_some_and(|value| !value.is_empty())
1789
- || state
1790
- .get("leader_receiver")
1791
- .and_then(|receiver| receiver.get("session_name"))
1792
- .and_then(JsonValue::as_str)
1793
- .is_some_and(|value| !value.is_empty())
1794
- }
1795
-
1796
- fn session_name_for_audit(state: &JsonValue) -> SessionName {
1797
- state_session_name(state)
1798
- }