@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,1409 +0,0 @@
1
- //! Independent R01–R12 contracts for Pi `fork-agent` session inheritance.
2
- //!
3
- //! These tests exercise the public lifecycle port and existing lifecycle/state
4
- //! surfaces only. No implementation-only fork helper is assumed by the baseline.
5
- //! The frozen baseline is expected to fail R01 at its current Pi native-fork
6
- //! refusal, after the fixture has independently proved a valid source tuple.
7
-
8
- #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
9
-
10
- #[path = "../../../tests/support/hermetic.rs"]
11
- mod hermetic_guard;
12
- #[allow(dead_code)]
13
- fn _hermetic_boundary_marker(_: &hermetic_guard::HermeticTestEnv) {}
14
-
15
- use std::fs;
16
- #[cfg(unix)]
17
- use std::os::unix::fs::PermissionsExt;
18
- use std::path::{Path, PathBuf};
19
- use std::time::{Duration, Instant};
20
-
21
- use crate as team_agent;
22
- use serde_json::{Value, json};
23
- use serial_test::serial;
24
- use team_agent::lifecycle::launch::{fork_agent_with_transport, pi_mcp::pi_seat_paths};
25
- use team_agent::model::ids::AgentId;
26
- use team_agent::provider::{AuthMode, Provider, SessionId, get_adapter};
27
- use team_agent::state::persist::{load_runtime_state, runtime_state_path};
28
- use team_agent::transport::test_support::OfflineTransport;
29
-
30
- const SOURCE: &str = "implementer";
31
- const TARGET: &str = "variant";
32
- const SESSION_A: &str = "652756ea-aaee-4437-a30f-40c5606826d5";
33
- const CAPTURED_AT: &str = "2026-09-12T10:00:02Z";
34
- const SESSION_TIMESTAMP: &str = "2025-01-02T03:04:05.000Z";
35
- const PROPERTY_SEED: u64 = 0x5eed_f0a7_1209_2026;
36
-
37
- const ROLE_DOC: &str = "---\nname: implementer\nrole: Session inheritance fixture\nprovider: pi\nmodel: team-agent/qwen3.8-27b\nauth_mode: subscription\neffort: high\ndangerously_skip_permissions: false\ntools:\n - mcp_team\ncommunication_mode: orchestrated\n---\n\nKeep the complete role body: 雪だるま 🛰️.\n";
38
- const SOURCE_ROLE: &str = "---\nname: implementer\nrole: Dynamic source role\nprovider: pi\nmodel: team-agent/qwen3.8-27b\nauth_mode: subscription\neffort: high\ndangerously_skip_permissions: false\ntools:\n - mcp_team\ncommunication_mode: orchestrated\nprofile: research\n---\n\nDynamic body stays exact: use Δ, 雪, and the captured tool result.\n";
39
-
40
- #[cfg(unix)]
41
- struct PathEnvGuard {
42
- previous: Option<std::ffi::OsString>,
43
- }
44
-
45
- #[cfg(unix)]
46
- impl PathEnvGuard {
47
- fn with_fake_pi(root: &Path) -> Self {
48
- let wrapper_bin = root.join("bin/wrapper");
49
- let real_bin = root.join("bin/real");
50
- fs::create_dir_all(&wrapper_bin).expect("create fake wrapper bin");
51
- fs::create_dir_all(&real_bin).expect("create fake real bin");
52
- let wrapper = wrapper_bin.join("pi");
53
- let wrapper_script = "#!/bin/sh\ncase \"$1\" in\n--version) echo 0.87.1 ;;\n--list-models) printf 'provider model\\nteam-agent qwen3.8-27b\\n' ;;\nlist) exit 64 ;;\nesac\nexit 0\n";
54
- fs::write(&wrapper, wrapper_script).expect("write offline Pi wrapper");
55
- let real = real_bin.join("pi");
56
- fs::write(&real, "#!/bin/sh\necho 0.87.1\nexit 0\n")
57
- .expect("write offline Pi real-binary stand-in");
58
- for pi in [&wrapper, &real] {
59
- let mut permissions = fs::metadata(pi).expect("fake Pi metadata").permissions();
60
- permissions.set_mode(0o755);
61
- fs::set_permissions(pi, permissions).expect("make fake Pi executable");
62
- }
63
- let previous = std::env::var_os("PATH");
64
- let mut paths = vec![wrapper_bin, real_bin];
65
- if let Some(existing) = previous.as_deref() {
66
- paths.extend(std::env::split_paths(existing));
67
- }
68
- let path = std::env::join_paths(paths).expect("join fixture PATH");
69
- unsafe { std::env::set_var("PATH", path) };
70
- let version = std::process::Command::new("pi")
71
- .arg("--version")
72
- .output()
73
- .expect("fake Pi must resolve through fixture PATH");
74
- assert!(version.status.success(), "fake Pi must be executable");
75
- Self { previous }
76
- }
77
- }
78
-
79
- #[cfg(unix)]
80
- impl Drop for PathEnvGuard {
81
- fn drop(&mut self) {
82
- if let Some(path) = self.previous.take() {
83
- unsafe { std::env::set_var("PATH", path) };
84
- } else {
85
- unsafe { std::env::remove_var("PATH") };
86
- }
87
- }
88
- }
89
-
90
- struct Fixture {
91
- #[cfg(unix)]
92
- _path_guard: PathEnvGuard,
93
- _caller: hermetic_guard::HermeticTestEnv,
94
- root: PathBuf,
95
- team_dir: PathBuf,
96
- run_workspace: PathBuf,
97
- team_key: String,
98
- state_path: PathBuf,
99
- source_paths: team_agent::lifecycle::launch::pi_mcp::PiSeatPaths,
100
- source_file: PathBuf,
101
- source_body: Vec<u8>,
102
- dynamic_role: PathBuf,
103
- }
104
-
105
- impl Fixture {
106
- fn new() -> Self {
107
- let caller = hermetic_guard::HermeticTestEnv::enter_with_leader("pi-fork-owned-caller");
108
- let root = super::temp_ws();
109
- #[cfg(unix)]
110
- let path_guard = PathEnvGuard::with_fake_pi(&root);
111
- let team_dir = root.join("teamdir");
112
- fs::create_dir_all(team_dir.join("agents")).expect("create team roles");
113
- fs::create_dir_all(team_dir.join("profiles")).expect("create role profiles");
114
- fs::write(
115
- team_dir.join("TEAM.md"),
116
- "---\nname: fork-contract-team\nobjective: Session inheritance fixture.\nprovider: codex\n---\n\nTeam fixture.\n",
117
- )
118
- .expect("write team definition");
119
- fs::write(team_dir.join("agents").join("implementer.md"), ROLE_DOC)
120
- .expect("write source role");
121
- fs::write(
122
- team_dir.join("profiles").join("research.yaml"),
123
- "temperature: 0.25\n",
124
- )
125
- .expect("write referenced profile");
126
-
127
- super::launch_spawn::seed_healthy_coordinator(&root);
128
- let setup = team_agent::lifecycle::launch::quick_start_with_transport(
129
- &team_dir,
130
- None,
131
- true,
132
- None,
133
- &OfflineTransport::new(),
134
- )
135
- .expect("valid Pi team fixture must quick-start");
136
- assert!(
137
- matches!(setup, team_agent::lifecycle::QuickStartReport::Ready { .. }),
138
- "fixture must be a started/selectable team, not a failed quick-start: {setup:?}"
139
- );
140
- let selected = team_agent::state::selector::resolve_active_team(
141
- &team_dir,
142
- None,
143
- team_agent::state::selector::SelectorMode::RequireSpec,
144
- )
145
- .expect("quick-start must create a selectable team with a spec");
146
- let run_workspace = selected.run_workspace.clone();
147
- let team_key = selected.team_key.clone();
148
- let state_path = runtime_state_path(&run_workspace);
149
- let source_paths = pi_seat_paths(&run_workspace, &team_key, SOURCE);
150
- let source_file = source_paths.sessions.join("2025/01/02/session-A.jsonl");
151
- fs::create_dir_all(source_file.parent().expect("source file parent"))
152
- .expect("create source session tree");
153
- let source_body = valid_v3_body();
154
- write_session(
155
- &source_file,
156
- SESSION_A,
157
- &run_workspace,
158
- SESSION_TIMESTAMP,
159
- &source_body,
160
- );
161
-
162
- let dynamic_role = run_workspace
163
- .join(".team/runtime/dynamic-role-files")
164
- .join(&team_key)
165
- .join("implementer.md");
166
- fs::create_dir_all(dynamic_role.parent().expect("dynamic role parent"))
167
- .expect("create dynamic role directory");
168
- fs::write(&dynamic_role, SOURCE_ROLE).expect("write current dynamic role");
169
-
170
- let mut state = selected.state.clone();
171
- if !state.get("agents").is_some_and(Value::is_object) {
172
- state["agents"] = json!({});
173
- }
174
- if !state["agents"][SOURCE].is_object() {
175
- state["agents"][SOURCE] = json!({});
176
- }
177
- let source = state["agents"][SOURCE]
178
- .as_object_mut()
179
- .expect("source row is an object");
180
- source.insert("provider".to_string(), json!("pi"));
181
- source.insert("auth_mode".to_string(), json!("subscription"));
182
- source.insert(
183
- "spawn_cwd".to_string(),
184
- json!(run_workspace.to_string_lossy().to_string()),
185
- );
186
- source.insert("session_id".to_string(), json!(SESSION_A));
187
- source.insert(
188
- "rollout_path".to_string(),
189
- json!(source_file.to_string_lossy().to_string()),
190
- );
191
- source.insert("captured_at".to_string(), json!(CAPTURED_AT));
192
- source.insert("captured_via".to_string(), json!("session_scan"));
193
- source.insert("capture_state".to_string(), json!("captured"));
194
- source.insert(
195
- "dynamic_role_file".to_string(),
196
- json!(dynamic_role.to_string_lossy().to_string()),
197
- );
198
- team_agent::state::projection::save_team_scoped_state(&run_workspace, &state)
199
- .expect("persist valid Pi source tuple");
200
-
201
- let fixture = Self {
202
- #[cfg(unix)]
203
- _path_guard: path_guard,
204
- _caller: caller,
205
- root,
206
- team_dir,
207
- run_workspace,
208
- team_key,
209
- state_path,
210
- source_paths,
211
- source_file,
212
- source_body,
213
- dynamic_role,
214
- };
215
- fixture.assert_valid_source_fixture();
216
- fixture
217
- }
218
-
219
- fn assert_valid_source_fixture(&self) {
220
- let state = self.state();
221
- let source = &state["agents"][SOURCE];
222
- assert_eq!(source["provider"], "pi", "fixture source must be Pi");
223
- assert_eq!(source["auth_mode"], "subscription");
224
- assert_eq!(source["session_id"], SESSION_A);
225
- assert_eq!(
226
- source["rollout_path"].as_str(),
227
- Some(self.source_file.to_string_lossy().as_ref())
228
- );
229
- assert!(
230
- self.source_file.is_file(),
231
- "source backing must be a regular file"
232
- );
233
- let header = read_header(&self.source_file);
234
- assert_eq!(header["version"], 3, "source fixture must be a v3 session");
235
- assert_eq!(header["id"], SESSION_A);
236
- assert_eq!(header["cwd"], self.run_workspace.to_string_lossy().as_ref());
237
- assert_eq!(header["timestamp"], SESSION_TIMESTAMP);
238
- let spawned_at = source["spawned_at"]
239
- .as_str()
240
- .expect("source spawn generation");
241
- assert!(header["timestamp"].as_str().unwrap() < spawned_at);
242
- assert_valid_entry_tree(&body_bytes(&self.source_file));
243
- assert!(!self.dynamic_role.as_os_str().is_empty());
244
- }
245
-
246
- fn state(&self) -> Value {
247
- let full = load_runtime_state(&self.run_workspace).expect("load fixture runtime state");
248
- team_agent::state::projection::project_top_level_view(&full, &self.team_key)
249
- }
250
-
251
- fn save_state(&self, state: &Value) {
252
- team_agent::state::projection::save_team_scoped_state(&self.run_workspace, state)
253
- .expect("save fixture runtime state");
254
- }
255
-
256
- fn target_paths(&self, target: &str) -> team_agent::lifecycle::launch::pi_mcp::PiSeatPaths {
257
- pi_seat_paths(&self.run_workspace, &self.team_key, target)
258
- }
259
-
260
- fn transport(&self) -> OfflineTransport {
261
- OfflineTransport::new()
262
- .with_session_present(true)
263
- .with_windows(vec![team_agent::transport::WindowName::new(SOURCE)])
264
- }
265
-
266
- fn fork(
267
- &self,
268
- target: &str,
269
- label: Option<&str>,
270
- transport: &dyn team_agent::transport::Transport,
271
- ) -> Result<team_agent::lifecycle::ForkAgentReport, team_agent::lifecycle::LifecycleError> {
272
- self.fork_from(SOURCE, target, label, transport)
273
- }
274
-
275
- fn fork_from(
276
- &self,
277
- source: &str,
278
- target: &str,
279
- label: Option<&str>,
280
- transport: &dyn team_agent::transport::Transport,
281
- ) -> Result<team_agent::lifecycle::ForkAgentReport, team_agent::lifecycle::LifecycleError> {
282
- fork_agent_with_transport(
283
- &self.team_dir,
284
- &AgentId::new(source),
285
- &AgentId::new(target),
286
- label,
287
- false,
288
- Some(&self.team_key),
289
- transport,
290
- )
291
- }
292
-
293
- fn assert_no_target(&self, target: &str, transport: &OfflineTransport) {
294
- let state = self.state();
295
- assert!(
296
- !state["agents"].get(target).is_some(),
297
- "rejected fork must not register a usable target; state={state}"
298
- );
299
- let paths = self.target_paths(target);
300
- assert!(
301
- !paths.wrapper.exists(),
302
- "rejected fork must not leave a usable wrapper"
303
- );
304
- assert!(
305
- !transport
306
- .spawn_records()
307
- .iter()
308
- .any(|(_, argv)| argv.iter().any(|arg| arg.contains(target))),
309
- "rejected fork must not spawn a target pane"
310
- );
311
- }
312
- }
313
-
314
- impl Drop for Fixture {
315
- fn drop(&mut self) {
316
- let _ = fs::remove_dir_all(&self.root);
317
- }
318
- }
319
-
320
- fn append_session_entry(path: &Path, entry: Value) {
321
- let mut bytes = fs::read(path).expect("read session before append");
322
- bytes.extend_from_slice(entry.to_string().as_bytes());
323
- bytes.push(b'\n');
324
- fs::write(path, bytes).expect("append independent session entry");
325
- }
326
-
327
- #[cfg(unix)]
328
- fn inode(path: &Path) -> u64 {
329
- std::os::unix::fs::MetadataExt::ino(&fs::metadata(path).expect("file metadata"))
330
- }
331
-
332
- fn valid_v3_body() -> Vec<u8> {
333
- // Stable one-seed generated branch keeps property inputs reproducible.
334
- let branch_id = format!(
335
- "branch-{:016x}",
336
- PROPERTY_SEED ^ PROPERTY_SEED.rotate_left(17)
337
- );
338
- let entries = [
339
- json!({
340
- "type": "message", "id": "entry-user", "parentId": null,
341
- "timestamp": "2025-01-02T03:04:06.000Z",
342
- "message": {"role": "user", "content": [
343
- {"type": "text", "text": "共同历史:雪だるま 🛰️; session A is ordinary body text."},
344
- {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
345
- ]}
346
- }),
347
- json!({
348
- "type": "message", "id": "entry-tool-call", "parentId": "entry-user",
349
- "timestamp": "2025-01-02T03:04:07.000Z",
350
- "message": {"role": "assistant", "content": [
351
- {"type": "text", "text": "Inspect the captured fixture."},
352
- {"type": "toolCall", "id": "tool-1", "name": "read_file", "arguments": {"path": "notes/Δ.md"}}
353
- ], "provider": "fixture-provider", "opaqueSignature": "signed/東京/🔒"}
354
- }),
355
- json!({
356
- "type": "tool_execution_start", "id": "entry-tool-start", "parentId": "entry-tool-call",
357
- "timestamp": "2025-01-02T03:04:08.000Z", "toolCallId": "tool-1",
358
- "toolName": "read_file", "args": {"path": "notes/Δ.md"}
359
- }),
360
- json!({
361
- "type": "tool_execution_end", "id": "entry-tool-result", "parentId": "entry-tool-start",
362
- "timestamp": "2025-01-02T03:04:09.000Z", "toolCallId": "tool-1",
363
- "toolName": "read_file", "result": [{"type": "text", "text": "result: preserve me exactly"}],
364
- "isError": false
365
- }),
366
- json!({
367
- "type": "message", "id": "entry-system-patch", "parentId": "entry-tool-result",
368
- "timestamp": "2025-01-02T03:04:10.000Z",
369
- "message": {"role": "system", "content": [{"type": "text", "text": "System patch: retain role-body and profile context."}]}
370
- }),
371
- json!({
372
- "type": "custom", "id": "entry-custom", "parentId": "entry-system-patch",
373
- "timestamp": "2025-01-02T03:04:11.000Z", "customType": "context_edit",
374
- "data": {"text": "custom context edit: 東京", "signed": "do-not-rewrite-A"}
375
- }),
376
- json!({
377
- "type": "compaction", "id": "entry-compaction", "parentId": "entry-custom",
378
- "timestamp": "2025-01-02T03:04:12.000Z", "summary": "Keep the complete branch ancestry.",
379
- "firstKeptEntryId": "entry-system-patch", "tokensBefore": 1234
380
- }),
381
- json!({
382
- "type": "message", "id": branch_id, "parentId": "entry-system-patch",
383
- "timestamp": "2025-01-02T03:04:13.000Z",
384
- "message": {"role": "assistant", "content": [{"type": "text", "text": "alternate branch answer"}]}
385
- }),
386
- ];
387
- let mut body = Vec::new();
388
- for entry in entries {
389
- body.extend_from_slice(entry.to_string().as_bytes());
390
- body.push(b'\n');
391
- }
392
- body
393
- }
394
-
395
- fn write_session(path: &Path, id: &str, cwd: &Path, timestamp: &str, body: &[u8]) {
396
- fs::create_dir_all(path.parent().expect("session file parent")).expect("create session parent");
397
- let header = json!({
398
- "type": "session", "version": 3, "id": id,
399
- "timestamp": timestamp, "cwd": cwd.to_string_lossy()
400
- });
401
- let mut bytes = header.to_string().into_bytes();
402
- bytes.push(b'\n');
403
- bytes.extend_from_slice(body);
404
- fs::write(path, bytes).expect("write session fixture");
405
- }
406
-
407
- fn read_header(path: &Path) -> Value {
408
- let bytes = fs::read(path).expect("read session file");
409
- let first_line_end = bytes
410
- .iter()
411
- .position(|byte| *byte == b'\n')
412
- .expect("header newline");
413
- serde_json::from_slice(&bytes[..first_line_end]).expect("valid session header JSON")
414
- }
415
-
416
- fn body_bytes(path: &Path) -> Vec<u8> {
417
- let bytes = fs::read(path).expect("read session file");
418
- let first_line_end = bytes
419
- .iter()
420
- .position(|byte| *byte == b'\n')
421
- .expect("header newline");
422
- bytes[first_line_end + 1..].to_vec()
423
- }
424
-
425
- fn assert_valid_entry_tree(body: &[u8]) {
426
- let mut ids = std::collections::BTreeSet::new();
427
- for (index, line) in body
428
- .split(|byte| *byte == b'\n')
429
- .filter(|line| !line.is_empty())
430
- .enumerate()
431
- {
432
- let entry: Value = serde_json::from_slice(line).expect("entry must be valid JSON");
433
- let id = entry["id"].as_str().expect("entry id");
434
- assert!(ids.insert(id.to_string()), "entry ids must be unique: {id}");
435
- if !entry["parentId"].is_null() {
436
- let parent = entry["parentId"].as_str().expect("parent id string");
437
- assert!(
438
- ids.contains(parent),
439
- "entry {index} parent must precede it: {parent}"
440
- );
441
- }
442
- }
443
- assert!(
444
- ids.len() >= 8,
445
- "v3 fixture includes messages, tool results, and branches"
446
- );
447
- }
448
-
449
- fn role_field<'a>(role: &'a str, key: &str) -> Option<&'a str> {
450
- let mut in_front_matter = false;
451
- for line in role.lines() {
452
- if line.trim() == "---" {
453
- if in_front_matter {
454
- break;
455
- }
456
- in_front_matter = true;
457
- continue;
458
- }
459
- if in_front_matter {
460
- if let Some((field, value)) = line.split_once(':') {
461
- if field.trim() == key {
462
- return Some(value.trim());
463
- }
464
- }
465
- }
466
- }
467
- None
468
- }
469
-
470
- fn role_body(role: &str) -> &str {
471
- let first = role.find("---").expect("role front matter opener") + 3;
472
- let second = role[first..].find("---").expect("role front matter closer") + first + 3;
473
- role[second..].trim_start_matches(&['\r', '\n'][..])
474
- }
475
-
476
- fn forked_target_file(fixture: &Fixture, state: &Value, target: &str) -> PathBuf {
477
- let path = state["agents"][target]["rollout_path"]
478
- .as_str()
479
- .expect("successful fork registers target rollout_path");
480
- PathBuf::from(path)
481
- }
482
-
483
- #[test]
484
- #[serial(env)]
485
- fn r01_public_lifecycle_port_pi_fork_must_create_a_distinct_seat() {
486
- let fixture = Fixture::new();
487
- let source = fixture.state()["agents"][SOURCE].clone();
488
- assert_eq!(source["provider"], "pi");
489
- assert_eq!(source["session_id"], SESSION_A);
490
- assert!(fixture.source_file.is_file());
491
- assert_valid_entry_tree(&fixture.source_body);
492
-
493
- let response = team_agent::cli::lifecycle_port::fork_agent(
494
- &fixture.team_dir,
495
- SOURCE,
496
- TARGET,
497
- None,
498
- Some(&fixture.team_key),
499
- )
500
- .expect("public lifecycle port returns its JSON result");
501
- assert_eq!(
502
- response["ok"], true,
503
- "R01: valid Pi fork-agent SOURCE --as TARGET must create a managed new seat through the public lifecycle port; baseline currently refuses Pi native session fork. response={response}"
504
- );
505
- assert_eq!(response["source_agent_id"], SOURCE);
506
- assert_eq!(response["new_agent_id"], TARGET);
507
- assert_ne!(response["session_id"], SESSION_A);
508
- let after = fixture.state();
509
- assert!(
510
- after["agents"].get(TARGET).is_some(),
511
- "public fork must register TARGET"
512
- );
513
- }
514
-
515
- #[test]
516
- #[serial(env)]
517
- fn r02_r03_fork_is_an_independent_identity_with_the_exact_complete_v3_tree() {
518
- let fixture = Fixture::new();
519
- let transport = fixture.transport();
520
- let source_before = fs::read(&fixture.source_file).expect("source backing before fork");
521
- #[cfg(unix)]
522
- let source_inode = inode(&fixture.source_file);
523
- let report = fixture
524
- .fork(TARGET, None, &transport)
525
- .expect("R02/R03: valid Pi session must fork instead of injecting into SOURCE");
526
- assert_eq!(report.source_agent_id.as_str(), SOURCE);
527
- assert_eq!(report.new_agent_id.as_str(), TARGET);
528
- let new_session_id = report
529
- .session_id
530
- .as_ref()
531
- .expect("fork session id")
532
- .as_str();
533
- assert_ne!(
534
- new_session_id, SESSION_A,
535
- "TARGET gets a fresh session UUID"
536
- );
537
- assert_eq!(
538
- report.backing_state,
539
- team_agent::lifecycle::ForkBackingState::Verified
540
- );
541
-
542
- let state = fixture.state();
543
- let source = &state["agents"][SOURCE];
544
- let target = &state["agents"][TARGET];
545
- assert_eq!(
546
- source["session_id"], SESSION_A,
547
- "SOURCE tuple remains untouched"
548
- );
549
- assert_eq!(
550
- source["rollout_path"],
551
- fixture.source_file.to_string_lossy().as_ref()
552
- );
553
- assert_eq!(target["session_id"], new_session_id);
554
- assert_eq!(target["provider"], "pi");
555
- assert!(target["pane_id"].as_str().is_some());
556
- assert_ne!(
557
- target["pane_id"], source["pane_id"],
558
- "new seat has its own pane"
559
- );
560
-
561
- let target_paths = fixture.target_paths(TARGET);
562
- assert_ne!(
563
- fs::canonicalize(&fixture.source_paths.runtime_root).expect("canonical source root"),
564
- fs::canonicalize(&target_paths.runtime_root).expect("canonical target root"),
565
- "source and target canonical seat roots differ"
566
- );
567
- let target_file = forked_target_file(&fixture, &state, TARGET);
568
- assert!(target_file.starts_with(&target_paths.sessions));
569
- assert_ne!(
570
- fs::canonicalize(&fixture.source_file).expect("canonical source file"),
571
- fs::canonicalize(&target_file).expect("canonical target file"),
572
- "source and target backing paths differ"
573
- );
574
- #[cfg(unix)]
575
- assert_ne!(
576
- source_inode,
577
- inode(&target_file),
578
- "target backing must be a distinct inode, not a hard link"
579
- );
580
- assert_eq!(
581
- fs::read(&fixture.source_file).expect("source remains"),
582
- source_before
583
- );
584
- let header = read_header(&target_file);
585
- assert_eq!(header["type"], "session");
586
- assert_eq!(header["version"], 3);
587
- assert_eq!(header["id"], new_session_id);
588
- assert_ne!(header["id"], SESSION_A);
589
- assert_eq!(
590
- header["parentSession"],
591
- fixture.source_file.to_string_lossy().as_ref(),
592
- "new Pi header records the exact source backing as parentSession"
593
- );
594
- assert_eq!(
595
- body_bytes(&target_file),
596
- fixture.source_body,
597
- "non-header bytes are exact"
598
- );
599
- assert_valid_entry_tree(&body_bytes(&target_file));
600
-
601
- let entries: Vec<Value> = body_bytes(&target_file)
602
- .split(|byte| *byte == b'\n')
603
- .filter(|line| !line.is_empty())
604
- .map(|line| serde_json::from_slice(line).expect("copied entry JSON"))
605
- .collect();
606
- assert!(
607
- entries
608
- .iter()
609
- .any(|entry| entry["type"] == "tool_execution_end")
610
- );
611
- assert!(
612
- entries
613
- .iter()
614
- .any(|entry| entry["customType"] == "context_edit")
615
- );
616
- assert!(entries.iter().any(|entry| entry["type"] == "compaction"));
617
- let spawn_args = transport
618
- .spawn_records()
619
- .into_iter()
620
- .flat_map(|(_, argv)| argv)
621
- .collect::<Vec<_>>();
622
- assert!(
623
- spawn_args
624
- .iter()
625
- .any(|arg| arg.contains(target_file.to_string_lossy().as_ref())),
626
- "new pane resumes only the new backing G; argv={spawn_args:?}"
627
- );
628
- assert!(
629
- !spawn_args
630
- .iter()
631
- .any(|arg| arg.contains(fixture.source_file.to_string_lossy().as_ref())),
632
- "new pane must not resume SOURCE backing F"
633
- );
634
- let source_pane = source["pane_id"].as_str().unwrap_or("");
635
- assert!(
636
- transport.inject_targets().iter().all(|target| {
637
- source_pane.is_empty() || !format!("{target:?}").contains(source_pane)
638
- }),
639
- "SOURCE must not receive injected commands"
640
- );
641
- assert!(
642
- !transport
643
- .calls()
644
- .iter()
645
- .any(|call| call.contains("kill") || call.contains("restart")),
646
- "SOURCE must not receive kill/restart during fork"
647
- );
648
- assert!(
649
- target_paths.wrapper.is_file(),
650
- "TARGET owns a fresh Pi wrapper"
651
- );
652
- let wrapper = fs::read_to_string(&target_paths.wrapper).expect("read target wrapper");
653
- assert!(
654
- wrapper.contains(TARGET),
655
- "wrapper identity belongs to TARGET"
656
- );
657
- assert!(
658
- source_pane.is_empty() || !wrapper.contains(source_pane),
659
- "wrapper must not inherit SOURCE pane identity"
660
- );
661
- }
662
-
663
- #[test]
664
- #[serial(env)]
665
- fn r04_target_materializes_the_latest_role_changing_only_identity_and_label() {
666
- let fixture = Fixture::new();
667
- let transport = fixture.transport();
668
- fixture
669
- .fork(TARGET, Some("Variant Researcher"), &transport)
670
- .expect("R04: valid Pi source role must materialize on fork");
671
- let state = fixture.state();
672
- let source_path = PathBuf::from(
673
- state["agents"][SOURCE]["dynamic_role_file"]
674
- .as_str()
675
- .unwrap(),
676
- );
677
- let target_path = PathBuf::from(
678
- state["agents"][TARGET]["dynamic_role_file"]
679
- .as_str()
680
- .unwrap(),
681
- );
682
- let source_role = fs::read_to_string(source_path).expect("read latest source role");
683
- let target_role = fs::read_to_string(target_path).expect("read materialized target role");
684
- assert_eq!(role_field(&target_role, "name"), Some(TARGET));
685
- assert_eq!(role_field(&target_role, "role"), Some("Variant Researcher"));
686
- for field in [
687
- "provider",
688
- "model",
689
- "auth_mode",
690
- "effort",
691
- "dangerously_skip_permissions",
692
- "communication_mode",
693
- "profile",
694
- ] {
695
- assert_eq!(
696
- role_field(&target_role, field),
697
- role_field(&source_role, field),
698
- "role field {field} is inherited"
699
- );
700
- }
701
- assert!(
702
- target_role.contains("mcp_team"),
703
- "tools and permissions are preserved"
704
- );
705
- assert_eq!(
706
- role_body(&target_role),
707
- role_body(&source_role),
708
- "role body bytes stay intact"
709
- );
710
- assert_eq!(state["agents"][TARGET]["provider"], "pi");
711
- }
712
-
713
- #[test]
714
- #[serial(env)]
715
- fn r05_bad_source_tuples_and_jsonl_fail_closed_without_a_fresh_target() {
716
- let fixture = Fixture::new();
717
- let original_state = fixture.state();
718
- let original_bytes = fs::read(&fixture.source_file).expect("source bytes");
719
- let outside = fixture.root.join("outside.jsonl");
720
- write_session(
721
- &outside,
722
- SESSION_A,
723
- &fixture.run_workspace,
724
- SESSION_TIMESTAMP,
725
- &fixture.source_body,
726
- );
727
-
728
- let mut cases = vec![
729
- "missing-tuple",
730
- "wrong-header-id",
731
- "wrong-cwd",
732
- "wrong-version",
733
- "wrong-timestamp",
734
- "bad-json",
735
- "broken-parent",
736
- "truncated",
737
- "truncated-json",
738
- "outside-root",
739
- ];
740
- #[cfg(unix)]
741
- cases.push("symlink");
742
- for case in cases {
743
- let mut state = original_state.clone();
744
- let source = state["agents"][SOURCE].as_object_mut().expect("source row");
745
- let mut bytes = original_bytes.clone();
746
- match case {
747
- "missing-tuple" => {
748
- source.remove("rollout_path");
749
- }
750
- "wrong-header-id" => {
751
- write_session(
752
- &fixture.source_file,
753
- "cc09d133-878f-4241-920f-f7ebfefc2a9e",
754
- &fixture.run_workspace,
755
- SESSION_TIMESTAMP,
756
- &fixture.source_body,
757
- );
758
- }
759
- "wrong-cwd" => {
760
- let wrong_cwd = fixture.root.join("wrong-cwd");
761
- write_session(
762
- &fixture.source_file,
763
- SESSION_A,
764
- &wrong_cwd,
765
- SESSION_TIMESTAMP,
766
- &fixture.source_body,
767
- );
768
- }
769
- "wrong-version" => {
770
- let header = json!({"type":"session","version":2,"id":SESSION_A,"timestamp":SESSION_TIMESTAMP,"cwd":fixture.run_workspace.to_string_lossy()});
771
- bytes = [header.to_string().as_bytes(), b"\n", &fixture.source_body].concat();
772
- fs::write(&fixture.source_file, &bytes).expect("write wrong-version session");
773
- }
774
- "wrong-timestamp" => {
775
- let header = json!({"type":"session","version":3,"id":SESSION_A,"timestamp":"not-a-timestamp","cwd":fixture.run_workspace.to_string_lossy()});
776
- bytes = [header.to_string().as_bytes(), b"\n", &fixture.source_body].concat();
777
- fs::write(&fixture.source_file, &bytes).expect("write invalid-timestamp session");
778
- }
779
- "bad-json" => {
780
- bytes = [b"{not-json}\n".as_slice(), &fixture.source_body].concat();
781
- fs::write(&fixture.source_file, &bytes).expect("write malformed source");
782
- }
783
- "broken-parent" => {
784
- let invalid = json!({"type":"message","id":"orphan","parentId":"missing-entry","message":{"role":"user","content":[]}}).to_string();
785
- bytes = [serde_json::to_string(&json!({"type":"session","version":3,"id":SESSION_A,"timestamp":SESSION_TIMESTAMP,"cwd":fixture.run_workspace.to_string_lossy()})).unwrap().as_bytes(), b"\n", invalid.as_bytes(), b"\n"].concat();
786
- fs::write(&fixture.source_file, &bytes).expect("write invalid entry tree");
787
- }
788
- "truncated" => {
789
- bytes.pop();
790
- fs::write(&fixture.source_file, &bytes).expect("truncate final JSONL newline");
791
- }
792
- "truncated-json" => {
793
- let last_line = bytes[..bytes.len() - 1]
794
- .iter()
795
- .rposition(|byte| *byte == b'\n')
796
- .expect("last entry begins after a newline")
797
- + 1;
798
- bytes.truncate(last_line + 3);
799
- fs::write(&fixture.source_file, &bytes).expect("truncate inside final JSON entry");
800
- }
801
- "outside-root" => {
802
- source.insert(
803
- "rollout_path".to_string(),
804
- json!(outside.to_string_lossy().to_string()),
805
- );
806
- }
807
- #[cfg(unix)]
808
- "symlink" => {
809
- fs::remove_file(&fixture.source_file).expect("remove source for symlink case");
810
- std::os::unix::fs::symlink(&outside, &fixture.source_file)
811
- .expect("create source symlink");
812
- }
813
- _ => unreachable!(),
814
- }
815
- if case == "missing-tuple" {
816
- // An ordinary save backfills the latest complete tuple (stale-writer
817
- // protection), so only a capture-backfill-skipping writer can drop it.
818
- team_agent::state::projection::save_team_scoped_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
819
- &fixture.run_workspace,
820
- &state,
821
- &fixture.team_key,
822
- &[SOURCE],
823
- &[],
824
- )
825
- .expect("persist the incomplete source tuple");
826
- } else {
827
- fixture.save_state(&state);
828
- }
829
- assert_eq!(
830
- fixture.state()["agents"][SOURCE]["rollout_path"],
831
- state["agents"][SOURCE]["rollout_path"],
832
- "R05 ({case}): the adversarial source row must be what fork reads"
833
- );
834
- let transport = fixture.transport();
835
- let result = fixture.fork(TARGET, None, &transport);
836
- assert!(
837
- result.is_err(),
838
- "R05 ({case}): invalid source must refuse, never fresh-fork; result={result:?}"
839
- );
840
- fixture.assert_no_target(TARGET, &transport);
841
- let after = fixture.state();
842
- assert!(
843
- after["agents"].get(TARGET).is_none(),
844
- "R05 ({case}): no target roster row"
845
- );
846
- if case != "missing-tuple" && case != "outside-root" {
847
- let source_after = &after["agents"][SOURCE];
848
- assert_eq!(
849
- source_after["session_id"], SESSION_A,
850
- "source identity remains unchanged"
851
- );
852
- }
853
- if case == "symlink" {
854
- fs::remove_file(&fixture.source_file).expect("remove source symlink");
855
- }
856
- fs::write(&fixture.source_file, &original_bytes)
857
- .expect("restore valid source between adversarial cases");
858
- }
859
- fixture.save_state(&original_state);
860
- fixture.assert_valid_source_fixture();
861
- }
862
-
863
- #[test]
864
- #[serial(env)]
865
- fn r06_target_collisions_preserve_existing_roster_spec_and_resource_bytes() {
866
- let fixture = Fixture::new();
867
- let mut state = fixture.state();
868
- state["agents"][TARGET] = json!({"status":"stopped","provider":"pi","sentinel":"must-survive"});
869
- fixture.save_state(&state);
870
- let roster_before = fs::read(&fixture.state_path).expect("persisted roster bytes");
871
- let selected = team_agent::state::selector::resolve_active_team(
872
- &fixture.team_dir,
873
- Some(&fixture.team_key),
874
- team_agent::state::selector::SelectorMode::RequireSpec,
875
- )
876
- .expect("selected team");
877
- let spec_path = selected.spec_path.expect("compiled spec path");
878
- let spec_before = fs::read(&spec_path).expect("spec bytes");
879
- let target_paths = fixture.target_paths(TARGET);
880
- fs::create_dir_all(&target_paths.sessions).expect("pre-existing target resource");
881
- let sentinel = target_paths.sessions.join("keep.jsonl");
882
- fs::write(&sentinel, b"collision bytes\n").expect("write collision sentinel");
883
- let transport = fixture.transport();
884
- assert!(
885
- fixture.fork(TARGET, None, &transport).is_err(),
886
- "R06 duplicate target must refuse"
887
- );
888
- assert_eq!(
889
- fs::read(&fixture.state_path).unwrap(),
890
- roster_before,
891
- "roster bytes stay unchanged"
892
- );
893
- assert_eq!(
894
- fs::read(&spec_path).unwrap(),
895
- spec_before,
896
- "compiled spec bytes stay unchanged"
897
- );
898
- assert_eq!(
899
- fs::read(sentinel).unwrap(),
900
- b"collision bytes\n",
901
- "existing target bytes are never overwritten"
902
- );
903
- assert!(
904
- transport.spawn_records().is_empty(),
905
- "collision must not spawn a second target"
906
- );
907
- }
908
-
909
- #[test]
910
- #[serial(env)]
911
- fn r07_capture_observation_does_not_replace_the_inherited_target_tuple() {
912
- let fixture = Fixture::new();
913
- let transport = fixture.transport();
914
- fixture.fork(TARGET, None, &transport).expect(
915
- "R07: source header predates spawn, but the captured source tuple is authoritative",
916
- );
917
- let mut state = fixture.state();
918
- let target_before = state["agents"][TARGET].clone();
919
- let mut adapter_for = |provider| get_adapter(provider);
920
- let report = team_agent::provider::session::capture::capture_missing_provider_sessions_once(
921
- &mut state,
922
- &mut adapter_for,
923
- true,
924
- 1,
925
- )
926
- .expect("coordinator observation merge");
927
- assert!(
928
- report.assigned.is_empty(),
929
- "complete inherited tuples are not recaptured: {report:?}"
930
- );
931
- assert_eq!(
932
- state["agents"][TARGET]["session_id"],
933
- target_before["session_id"]
934
- );
935
- assert_eq!(
936
- state["agents"][TARGET]["rollout_path"],
937
- target_before["rollout_path"]
938
- );
939
- fixture.save_state(&state);
940
- let reloaded = fixture.state();
941
- assert_eq!(
942
- reloaded["agents"][TARGET]["session_id"], target_before["session_id"],
943
- "persisted observation merge keeps inherited session B"
944
- );
945
- assert_eq!(
946
- reloaded["agents"][TARGET]["rollout_path"], target_before["rollout_path"],
947
- "persisted observation merge keeps backing G"
948
- );
949
- assert_eq!(reloaded["agents"][SOURCE]["session_id"], SESSION_A);
950
- assert_eq!(
951
- reloaded["agents"][SOURCE]["rollout_path"],
952
- fixture.source_file.to_string_lossy().as_ref()
953
- );
954
- }
955
-
956
- #[test]
957
- #[serial(env)]
958
- fn r08_sibling_observation_racing_with_target_spawn_is_not_lost() {
959
- let fixture = Fixture::new();
960
- let mut observed = fixture.state();
961
- observed["agents"]["sibling"] = json!({
962
- "provider":"pi", "status":"running", "session_id":"sibling-session",
963
- "rollout_path":"/sibling/only.jsonl", "captured_at":"2026-09-12T10:01:00Z",
964
- "captured_via":"session_scan", "observation_generation":"concurrent-observation-17"
965
- });
966
- let transport = fixture.transport();
967
- let observed_transport = transport.clone();
968
- let run_workspace = fixture.run_workspace.clone();
969
- let updater = std::thread::spawn(move || {
970
- let deadline = Instant::now() + Duration::from_secs(5);
971
- while !observed_transport
972
- .calls()
973
- .iter()
974
- .any(|call| call.starts_with("spawn"))
975
- {
976
- if Instant::now() >= deadline {
977
- return Err("valid Pi fork never reached target spawn".to_string());
978
- }
979
- std::thread::yield_now();
980
- }
981
- team_agent::state::projection::save_team_scoped_state(&run_workspace, &observed)
982
- .map_err(|error| format!("persist concurrent sibling observation: {error}"))
983
- });
984
- let fork_result = fixture.fork(TARGET, None, &transport);
985
- let update_result = updater.join().expect("sibling observation thread");
986
- assert!(
987
- update_result.is_ok(),
988
- "R08 concurrent state update must commit while target spawn is in flight; fork={fork_result:?} update={update_result:?}"
989
- );
990
- let fork_report =
991
- fork_result.expect("R08 Pi fork must complete after the concurrent sibling observation");
992
- assert_eq!(fork_report.new_agent_id.as_str(), TARGET);
993
- let after = fixture.state();
994
- assert_eq!(
995
- after["agents"]["sibling"]["observation_generation"], "concurrent-observation-17",
996
- "fork must merge its target row, not roll back an observation concurrent with target spawn"
997
- );
998
- assert_eq!(after["agents"][SOURCE]["session_id"], SESSION_A);
999
- assert!(after["agents"].get(TARGET).is_some());
1000
- }
1001
-
1002
- #[test]
1003
- #[serial(env)]
1004
- fn r09_spawn_failure_is_compensated_without_an_alive_target_on_deleted_backing() {
1005
- let fixture = Fixture::new();
1006
- let transport = fixture
1007
- .transport()
1008
- .with_spawn_failure(TARGET, "R09 injected target spawn failure");
1009
- let result = fixture.fork(TARGET, None, &transport);
1010
- assert!(
1011
- result.is_err(),
1012
- "R09 injected spawn failure must be reported: {result:?}"
1013
- );
1014
- assert!(
1015
- transport.calls().iter().any(|call| call.contains("spawn")),
1016
- "R09 setup must reach the existing transport spawn fault-injection seam; calls={:?}",
1017
- transport.calls()
1018
- );
1019
- let state = fixture.state();
1020
- assert!(
1021
- !state["agents"]
1022
- .get(TARGET)
1023
- .is_some_and(|target| target["status"] == "running"),
1024
- "failed target spawn cannot be reported as alive; state={state}"
1025
- );
1026
- let target_paths = fixture.target_paths(TARGET);
1027
- if !target_paths.sessions.exists() {
1028
- assert!(
1029
- !target_paths.wrapper.exists(),
1030
- "fully rolled-back failure leaves no wrapper"
1031
- );
1032
- }
1033
- assert_eq!(state["agents"][SOURCE]["session_id"], SESSION_A);
1034
- assert_eq!(
1035
- state["agents"][SOURCE]["rollout_path"],
1036
- fixture.source_file.to_string_lossy().as_ref()
1037
- );
1038
- }
1039
-
1040
- #[test]
1041
- #[serial(env)]
1042
- fn r09_pane_verification_failure_compensates_the_new_target() {
1043
- let fixture = Fixture::new();
1044
- let transport = fixture.transport().with_spawned_panes_addressable(false);
1045
- let result = fixture.fork(TARGET, None, &transport);
1046
- assert!(
1047
- result.is_err(),
1048
- "R09 pane verification failure must be reported: {result:?}"
1049
- );
1050
- assert!(
1051
- transport
1052
- .calls()
1053
- .iter()
1054
- .any(|call| call.starts_with("spawn")),
1055
- "R09 setup must reach the transport spawn seam before pane verification; calls={:?}",
1056
- transport.calls()
1057
- );
1058
- assert!(
1059
- transport.calls().contains(&"kill_pane"),
1060
- "R09 must compensate the spawned target pane after verification fails; calls={:?}",
1061
- transport.calls()
1062
- );
1063
- let state = fixture.state();
1064
- assert!(
1065
- !state["agents"]
1066
- .get(TARGET)
1067
- .is_some_and(|target| target["status"] == "running"),
1068
- "unverified target cannot remain alive in runtime state; state={state}"
1069
- );
1070
- let target_paths = fixture.target_paths(TARGET);
1071
- assert!(
1072
- !target_paths.wrapper.exists(),
1073
- "failed target must not retain a runnable Pi wrapper"
1074
- );
1075
- assert_eq!(state["agents"][SOURCE]["session_id"], SESSION_A);
1076
- assert_eq!(
1077
- state["agents"][SOURCE]["rollout_path"],
1078
- fixture.source_file.to_string_lossy().as_ref()
1079
- );
1080
- }
1081
-
1082
- #[test]
1083
- #[serial(env)]
1084
- fn r10_messages_remain_team_scoped_and_target_messages_name_only_target() {
1085
- let fixture = Fixture::new();
1086
- let store = team_agent::db::message_store::MessageStore::open(&fixture.run_workspace)
1087
- .expect("open selected team's message database");
1088
- let source_marker = store
1089
- .create_message_with_id(
1090
- "msg_fork_source_keep",
1091
- None,
1092
- "caller",
1093
- SOURCE,
1094
- "source-only",
1095
- None,
1096
- false,
1097
- Some(&fixture.team_key),
1098
- )
1099
- .expect("seed source message marker");
1100
- let sibling_marker = store
1101
- .create_message_with_id(
1102
- "msg_fork_sibling_keep",
1103
- None,
1104
- "caller",
1105
- "sibling",
1106
- "sibling-only",
1107
- None,
1108
- false,
1109
- Some("sibling-team"),
1110
- )
1111
- .expect("seed sibling-team message marker");
1112
- let transport = fixture.transport();
1113
- fixture
1114
- .fork(TARGET, None, &transport)
1115
- .expect("R10 database ownership checks require a successfully registered target");
1116
- let target_marker = store
1117
- .create_message_with_id(
1118
- "msg_fork_target_owner",
1119
- None,
1120
- SOURCE,
1121
- TARGET,
1122
- "target-only",
1123
- None,
1124
- false,
1125
- Some(&fixture.team_key),
1126
- )
1127
- .expect("target message is stored in selected team DB");
1128
- let connection = team_agent::db::schema::open_db(store.db_path()).expect("read team DB");
1129
- for (id, owner, recipient) in [
1130
- (&source_marker, fixture.team_key.as_str(), SOURCE),
1131
- (&sibling_marker, "sibling-team", "sibling"),
1132
- (&target_marker, fixture.team_key.as_str(), TARGET),
1133
- ] {
1134
- let actual: (Option<String>, String) = connection
1135
- .query_row(
1136
- "select owner_team_id, recipient from messages where message_id=?1",
1137
- [id],
1138
- |row| Ok((row.get(0)?, row.get(1)?)),
1139
- )
1140
- .expect("message row exists");
1141
- assert_eq!(
1142
- actual.0.as_deref(),
1143
- Some(owner),
1144
- "message {id} has its owner team"
1145
- );
1146
- assert_eq!(
1147
- actual.1, recipient,
1148
- "message {id} remains attributed to its recipient"
1149
- );
1150
- }
1151
- }
1152
-
1153
- #[test]
1154
- #[serial(env)]
1155
- fn r11_source_and_target_backings_remain_independently_loadable() {
1156
- let fixture = Fixture::new();
1157
- let transport = fixture.transport();
1158
- fixture
1159
- .fork(TARGET, None, &transport)
1160
- .expect("R11 independent lifecycle requires a successful fork");
1161
- let state = fixture.state();
1162
- let target_file = forked_target_file(&fixture, &state, TARGET);
1163
- append_session_entry(
1164
- &fixture.source_file,
1165
- json!({
1166
- "type":"message", "id":"entry-source-live", "parentId":"entry-user",
1167
- "timestamp":"2026-09-12T10:02:00Z",
1168
- "message":{"role":"assistant","content":[{"type":"text","text":"SOURCE-only follow-up"}]}
1169
- }),
1170
- );
1171
- append_session_entry(
1172
- &target_file,
1173
- json!({
1174
- "type":"message", "id":"entry-target-live", "parentId":"entry-user",
1175
- "timestamp":"2026-09-12T10:03:00Z",
1176
- "message":{"role":"assistant","content":[{"type":"text","text":"TARGET-only follow-up"}]}
1177
- }),
1178
- );
1179
- let target_before =
1180
- fs::read(&target_file).expect("target backing bytes after target-only append");
1181
- let source_before =
1182
- fs::read(&fixture.source_file).expect("source backing after source-only append");
1183
- assert!(
1184
- source_before
1185
- .windows(b"SOURCE-only follow-up".len())
1186
- .any(|bytes| bytes == b"SOURCE-only follow-up")
1187
- );
1188
- assert!(
1189
- !source_before
1190
- .windows(b"TARGET-only follow-up".len())
1191
- .any(|bytes| bytes == b"TARGET-only follow-up")
1192
- );
1193
- assert!(
1194
- target_before
1195
- .windows(b"TARGET-only follow-up".len())
1196
- .any(|bytes| bytes == b"TARGET-only follow-up")
1197
- );
1198
- assert!(
1199
- !target_before
1200
- .windows(b"SOURCE-only follow-up".len())
1201
- .any(|bytes| bytes == b"SOURCE-only follow-up")
1202
- );
1203
- assert_valid_entry_tree(&body_bytes(&fixture.source_file));
1204
- assert_valid_entry_tree(&body_bytes(&target_file));
1205
- fs::remove_file(&fixture.source_file).expect("simulate SOURCE backing retirement");
1206
- assert_eq!(
1207
- fs::read(&target_file).expect("TARGET remains offline-loadable"),
1208
- target_before
1209
- );
1210
- fs::write(&fixture.source_file, &source_before).expect("restore independent SOURCE backing");
1211
- fs::remove_file(&target_file).expect("simulate TARGET backing retirement");
1212
- assert!(
1213
- fixture.source_file.is_file(),
1214
- "removing TARGET backing must not remove SOURCE backing"
1215
- );
1216
- assert_eq!(fs::read(&fixture.source_file).unwrap(), source_before);
1217
- }
1218
-
1219
- #[test]
1220
- #[serial(env)]
1221
- fn r12_pi_clone_and_non_pi_in_window_fork_compatibility_are_preserved() {
1222
- let workspace = Path::new("/workspace/pi-fork-contract");
1223
- let source_paths = pi_seat_paths(workspace, "team-a", SOURCE);
1224
- let clone_paths = pi_seat_paths(workspace, "team-a", TARGET);
1225
- assert_ne!(source_paths.runtime_root, clone_paths.runtime_root);
1226
- assert_ne!(source_paths.wrapper, clone_paths.wrapper);
1227
- assert_ne!(source_paths.sessions, clone_paths.sessions);
1228
- assert!(
1229
- matches!(
1230
- get_adapter(Provider::Pi).fork(
1231
- Some(&SessionId::new(SESSION_A)),
1232
- AuthMode::Subscription,
1233
- None
1234
- ),
1235
- Err(team_agent::provider::ProviderError::CapabilityUnsupported(
1236
- _
1237
- ))
1238
- ),
1239
- "managed fork must not be faked by changing the provider's unsupported native-fork capability"
1240
- );
1241
- assert_eq!(
1242
- team_agent::lifecycle::launch::in_window_fork(Provider::Grok, AuthMode::Subscription)
1243
- .map(|spec| spec.command),
1244
- Some("/fork"),
1245
- "non-Pi Grok subscription keeps its verified in-window command"
1246
- );
1247
- assert_eq!(
1248
- team_agent::lifecycle::launch::in_window_fork(Provider::ClaudeCode, AuthMode::Subscription)
1249
- .map(|spec| spec.command),
1250
- Some("/branch"),
1251
- "non-Pi Claude subscription keeps its verified in-window command"
1252
- );
1253
- assert!(
1254
- team_agent::lifecycle::launch::in_window_fork(Provider::Pi, AuthMode::Subscription)
1255
- .is_none(),
1256
- "Pi must use managed new-seat inheritance, never an in-window slash alias"
1257
- );
1258
- let fixture = Fixture::new();
1259
- let state = fixture.state();
1260
- assert_eq!(state["agents"][SOURCE]["session_id"], SESSION_A);
1261
- assert!(
1262
- fixture
1263
- .source_paths
1264
- .sessions
1265
- .starts_with(&fixture.source_paths.runtime_root)
1266
- );
1267
- }
1268
-
1269
- #[test]
1270
- #[serial(env)]
1271
- fn r13_cascading_fork_inherits_variant1_hello_and_reply_without_aliasing_any_seat() {
1272
- const VARIANT1: &str = "variant1";
1273
- const VARIANT2: &str = "variant2";
1274
-
1275
- let fixture = Fixture::new();
1276
- let author_before = fs::read(&fixture.source_file).expect("author session before forks");
1277
- let transport = fixture.transport().with_windows(vec![
1278
- team_agent::transport::WindowName::new(SOURCE),
1279
- team_agent::transport::WindowName::new(VARIANT1),
1280
- team_agent::transport::WindowName::new(VARIANT2),
1281
- ]);
1282
-
1283
- let first_report = fixture
1284
- .fork_from(SOURCE, VARIANT1, None, &transport)
1285
- .expect("R13 first generation fork creates variant1");
1286
- let after_first = fixture.state();
1287
- let session_b = after_first["agents"][VARIANT1]["session_id"]
1288
- .as_str()
1289
- .expect("variant1 session B")
1290
- .to_string();
1291
- assert_eq!(
1292
- first_report.session_id.as_ref().map(SessionId::as_str),
1293
- Some(session_b.as_str())
1294
- );
1295
- assert_ne!(session_b, SESSION_A);
1296
- let variant1_file = forked_target_file(&fixture, &after_first, VARIANT1);
1297
- assert_eq!(read_header(&variant1_file)["id"], session_b);
1298
- assert_eq!(
1299
- read_header(&variant1_file)["parentSession"],
1300
- fixture.source_file.to_string_lossy().as_ref()
1301
- );
1302
- assert_eq!(body_bytes(&variant1_file), fixture.source_body);
1303
-
1304
- append_session_entry(
1305
- &variant1_file,
1306
- json!({
1307
- "type":"message", "id":"entry-variant1-hello", "parentId":"entry-user",
1308
- "timestamp":"2026-09-12T10:10:00Z",
1309
- "message":{"role":"user","content":[{"type":"text","text":"HELLO"}]}
1310
- }),
1311
- );
1312
- append_session_entry(
1313
- &variant1_file,
1314
- json!({
1315
- "type":"message", "id":"entry-variant1-reply", "parentId":"entry-variant1-hello",
1316
- "timestamp":"2026-09-12T10:10:01Z",
1317
- "message":{"role":"assistant","content":[{"type":"text","text":"HELLO acknowledged by variant1"}]}
1318
- }),
1319
- );
1320
- let variant1_history = body_bytes(&variant1_file);
1321
- assert!(variant1_history.starts_with(&fixture.source_body));
1322
- assert!(
1323
- variant1_history
1324
- .windows(b"HELLO".len())
1325
- .any(|bytes| bytes == b"HELLO")
1326
- );
1327
- assert!(
1328
- variant1_history
1329
- .windows(b"HELLO acknowledged by variant1".len())
1330
- .any(|bytes| bytes == b"HELLO acknowledged by variant1")
1331
- );
1332
- assert_valid_entry_tree(&variant1_history);
1333
- let variant1_before_second_fork =
1334
- fs::read(&variant1_file).expect("variant1 session with its new dialogue");
1335
-
1336
- let second_report = fixture
1337
- .fork_from(VARIANT1, VARIANT2, None, &transport)
1338
- .expect("R13 second generation fork creates variant2 from variant1");
1339
- let after_second = fixture.state();
1340
- let session_c = after_second["agents"][VARIANT2]["session_id"]
1341
- .as_str()
1342
- .expect("variant2 session C");
1343
- assert_ne!(session_c, SESSION_A);
1344
- assert_ne!(session_c, session_b);
1345
- assert_eq!(
1346
- second_report.session_id.as_ref().map(SessionId::as_str),
1347
- Some(session_c)
1348
- );
1349
- assert_eq!(after_second["agents"][SOURCE]["session_id"], SESSION_A);
1350
- assert_eq!(after_second["agents"][VARIANT1]["session_id"], session_b);
1351
-
1352
- let variant2_file = forked_target_file(&fixture, &after_second, VARIANT2);
1353
- let variant1_header = read_header(&variant1_file);
1354
- let variant2_header = read_header(&variant2_file);
1355
- assert_eq!(variant1_header["id"], session_b);
1356
- assert_eq!(variant2_header["id"], session_c);
1357
- assert_eq!(
1358
- variant2_header["parentSession"],
1359
- variant1_file.to_string_lossy().as_ref(),
1360
- "variant2 parentSession must identify its immediate source, variant1"
1361
- );
1362
- assert_eq!(
1363
- body_bytes(&variant2_file),
1364
- variant1_history,
1365
- "variant2 keeps the complete original history and variant1's HELLO/reply bytes"
1366
- );
1367
- assert_eq!(
1368
- fs::read(&fixture.source_file).expect("author history remains unchanged"),
1369
- author_before
1370
- );
1371
- assert_eq!(
1372
- fs::read(&variant1_file).expect("variant1 history remains unchanged by second fork"),
1373
- variant1_before_second_fork
1374
- );
1375
- assert_valid_entry_tree(&body_bytes(&variant2_file));
1376
-
1377
- let variant1_paths = fixture.target_paths(VARIANT1);
1378
- let variant2_paths = fixture.target_paths(VARIANT2);
1379
- let seat_roots = [
1380
- fs::canonicalize(&fixture.source_paths.runtime_root).expect("author seat root"),
1381
- fs::canonicalize(&variant1_paths.runtime_root).expect("variant1 seat root"),
1382
- fs::canonicalize(&variant2_paths.runtime_root).expect("variant2 seat root"),
1383
- ];
1384
- assert_ne!(seat_roots[0], seat_roots[1]);
1385
- assert_ne!(seat_roots[0], seat_roots[2]);
1386
- assert_ne!(seat_roots[1], seat_roots[2]);
1387
- let session_paths = [
1388
- fs::canonicalize(&fixture.source_file).expect("author session path"),
1389
- fs::canonicalize(&variant1_file).expect("variant1 session path"),
1390
- fs::canonicalize(&variant2_file).expect("variant2 session path"),
1391
- ];
1392
- assert_ne!(session_paths[0], session_paths[1]);
1393
- assert_ne!(session_paths[0], session_paths[2]);
1394
- assert_ne!(session_paths[1], session_paths[2]);
1395
- #[cfg(unix)]
1396
- {
1397
- let inodes = [
1398
- inode(&fixture.source_file),
1399
- inode(&variant1_file),
1400
- inode(&variant2_file),
1401
- ];
1402
- assert_ne!(inodes[0], inodes[1]);
1403
- assert_ne!(inodes[0], inodes[2]);
1404
- assert_ne!(inodes[1], inodes[2]);
1405
- }
1406
- assert_ne!(variant1_paths.wrapper, variant2_paths.wrapper);
1407
- assert!(variant1_paths.wrapper.is_file());
1408
- assert!(variant2_paths.wrapper.is_file());
1409
- }