@team-agent/installer 0.5.125 → 0.5.127

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