@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
@@ -0,0 +1,368 @@
1
+ //! Generic contract-native seat fork (avatar): one pipeline for every leaf.
2
+ //! The descriptor's fork facet selects the admitted mode, the leaf's H2/H7
3
+ //! supply native argv and stage intent, and the shared `Lifecycle::fork` runs
4
+ //! F0-F5 with its own compensation. Only the registry dispatches per leaf; a
5
+ //! refused provider leaves no role, spec, state, pane or native file behind.
6
+ use std::path::{Path, PathBuf};
7
+
8
+ use serde_json::{json, Value};
9
+ use team_agent_contract::contract::{
10
+ fork::{resolve_fork, select_new_seat_mode, ForkMode, ForkRequest},
11
+ plan::{resolve_launch, validate_launch_plan},
12
+ types::{ContractError, Operation, OperationId, SeatId},
13
+ };
14
+ use team_agent_contract::host::{clock::RealClock, command::RealCommandRunner, materialize::ScopedMaterializer};
15
+ use team_agent_contract::orchestration::{
16
+ lifecycle::{Adapter, Lifecycle, Routing},
17
+ physical::{PhysicalRuntime, Registration},
18
+ store::{OperationRecord, Outcome, SeatStatus},
19
+ Error,
20
+ };
21
+
22
+ use crate::cli::CliError;
23
+ use crate::lifecycle::launch::add_agent_state::{inject_agent_into_spec, rollback_add_agent_atomic, upsert_agent_entry};
24
+ use crate::model::ids::AgentId;
25
+ use crate::model::yaml::Value as Yaml;
26
+ use crate::state::selector::SelectedTeam;
27
+
28
+ use super::{
29
+ backend::{self, Backend, BackendError},
30
+ commands,
31
+ config::{MemberRoute, RoleConfig},
32
+ discovery, framework, registry,
33
+ };
34
+
35
+ fn error(error: impl std::fmt::Display) -> CliError {
36
+ CliError::Runtime(error.to_string())
37
+ }
38
+
39
+ fn refused(provider: &str, refusal: ContractError) -> CliError {
40
+ CliError::Runtime(format!(
41
+ "{provider} does not support session forking: {refusal}; no seat, pane or file was created"
42
+ ))
43
+ }
44
+
45
+ /// `fork-agent <source> --as <target>` for a contract seat. None: the source
46
+ /// is not a contract seat and keeps its own runtime's fork path.
47
+ pub fn fork_agent(
48
+ workspace: &Path,
49
+ team: Option<&str>,
50
+ source: &str,
51
+ target: &str,
52
+ label: Option<&str>,
53
+ ) -> Result<Option<Value>, CliError> {
54
+ commands::with_agent(workspace, team, source, "fork-agent", |selected, source_id| {
55
+ fork_locked(selected, source_id, target, label)
56
+ })
57
+ }
58
+
59
+ /// Called under the source's lifecycle lock (`with_agent`).
60
+ fn fork_locked(
61
+ selected: &SelectedTeam,
62
+ source_id: &SeatId,
63
+ target: &str,
64
+ label: Option<&str>,
65
+ ) -> Result<Value, CliError> {
66
+ let workspace = selected.run_workspace.as_path();
67
+ let team = selected.team_key.as_str();
68
+ // F0 is read-only: nothing below writes until the role file.
69
+ let parent = Backend::open_readonly(workspace, team).map_err(error)?
70
+ .store.seat(source_id).map_err(error)?
71
+ .ok_or_else(|| error("contract source seat is not in its native store"))?;
72
+ let provider = parent.provider.as_str().to_owned();
73
+ let descriptor = registry::provider(&provider).map_err(error)?.descriptor();
74
+ if target == source_id.as_str() {
75
+ // The same seat can only branch in place, and only when admitted.
76
+ descriptor.fork.in_window.require("in-window branch").map_err(|refusal| refused(&provider, refusal))?;
77
+ return Err(error("contract_capability_unverified: in-window branch dispatch is not wired; no key was sent"));
78
+ }
79
+ if select_new_seat_mode(descriptor).map_err(|refusal| refused(&provider, refusal))? != ForkMode::NativeNewSeat {
80
+ return Err(error(format!(
81
+ "contract_capability_unverified: {provider} full-snapshot staging is not wired; no seat was created"
82
+ )));
83
+ }
84
+ let target_id = SeatId::new(target).map_err(|_| error(format!("invalid fork target id: {target}")))?;
85
+ if target == "leader" {
86
+ return Err(error("fork target id `leader` is reserved"));
87
+ }
88
+ let source_session = parent.session.as_ref()
89
+ .filter(|_| parent.status != SeatStatus::Unknown)
90
+ .map(|session| session.native_session.as_str().to_owned())
91
+ .ok_or_else(|| error("contract source seat has no captured native session to fork"))?;
92
+ if selected.state.get("agents").and_then(|agents| agents.get(target)).is_some() {
93
+ return Err(error(format!("agent id already exists: {target}")));
94
+ }
95
+ let role_path = selected.team_dir.join("agents").join(format!("{target}.md"));
96
+ if std::fs::symlink_metadata(&role_path).is_ok() {
97
+ return Err(error(format!("role file already exists: {}", role_path.display())));
98
+ }
99
+ let config = framework::team_config(workspace, &selected.team_dir, team).map_err(error)?
100
+ .ok_or_else(|| error("contract team configuration is unavailable"))?;
101
+ let source_role = config.roles.iter().find(|role| &role.id == source_id)
102
+ .ok_or_else(|| error("contract source role is no longer configured"))?;
103
+ if source_role.provider != parent.provider {
104
+ return Err(error("contract source role now declares another provider; a fork keeps the parent's"));
105
+ }
106
+ let role_text = fork_role_text(&std::fs::read_to_string(&source_role.source).map_err(error)?, target, label);
107
+ let spec_path = crate::model::paths::runtime_spec_path(workspace, team);
108
+ let pre_spec = match std::fs::read_to_string(&spec_path) {
109
+ Ok(text) => Some(text),
110
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
111
+ Err(e) => return Err(error(e)),
112
+ };
113
+ write_new(&role_path, role_text.as_bytes()).map_err(error)?;
114
+ let undo = Undo {
115
+ workspace: workspace.to_path_buf(), team: team.to_owned(), target: target_id.clone(),
116
+ role_path: role_path.clone(), role_bytes: role_text.into_bytes(), spec_path: spec_path.clone(), pre_spec,
117
+ };
118
+ let result = (|| -> Result<Value, CliError> {
119
+ let config = framework::team_config(workspace, &selected.team_dir, team).map_err(error)?
120
+ .ok_or_else(|| error("contract team configuration is unavailable"))?;
121
+ let role = config.roles.iter().find(|role| role.id == target_id)
122
+ .ok_or_else(|| error("forked contract role was not configured"))?;
123
+ if role.paused || role.provider != parent.provider {
124
+ return Err(error("forked contract role is paused or changed provider; nothing was started"));
125
+ }
126
+ register_spec(selected, &role_path, target, &spec_path, undo.pre_spec.as_deref())?;
127
+ let record = native_fork(workspace, team, source_id, role, &config.members).map_err(error)?;
128
+ if record.outcome != Outcome::Committed {
129
+ return Err(error(BackendError::Shutdown {
130
+ operation: record.id, phase: record.phase, outcome: record.outcome, failure: record.failure,
131
+ }));
132
+ }
133
+ // The roster row appears only once the native seat has committed: a
134
+ // half-built target never enters the coordinator tick's projection.
135
+ upsert_agent_entry(workspace, team, &AgentId::new(target), json!({
136
+ "agent_id": target, "provider": role.provider.as_str(), "runtime_family": "contract",
137
+ "status": "starting", "contract_instance": null, "pane_id": null, "forked_from": source_id.as_str(),
138
+ })).map_err(error)?;
139
+ let projection = commands::publish_at(workspace, team, &target_id, true)?;
140
+ let coordinator = crate::coordinator::start_coordinator_with_team(
141
+ &crate::coordinator::WorkspacePath::new(workspace.to_path_buf()), Some(team),
142
+ ).map_err(error)?;
143
+ Ok(json!({"ok":coordinator.ok,"status":"forked","runtime":"contract","mode":"native_new_seat",
144
+ "provider":provider,"source_agent_id":source_id.as_str(),"new_agent_id":target,"target":target,
145
+ "agent_id":target,"operation":record.id,"source_session_id":source_session,
146
+ "session_id":projection.get("session_id"),"new_session_id":projection.get("session_id"),
147
+ "generation":projection.get("generation"),"backing_state":"verified",
148
+ "coordinator":crate::lifecycle::coordinator_start_summary_value(
149
+ &crate::lifecycle::CoordinatorStartSummary::from_start_report(&coordinator))}))
150
+ })();
151
+ result.map_err(|failure| undo.run(failure))
152
+ }
153
+
154
+ /// The provider-neutral F1-F5: H2 plans the native fork argv for the target,
155
+ /// H7 states the intent, and `Lifecycle::fork` registers, spawns, captures the
156
+ /// child binding and commits, compensating its own effects on failure.
157
+ fn native_fork(
158
+ workspace: &Path,
159
+ team: &str,
160
+ source: &SeatId,
161
+ role: &RoleConfig,
162
+ members: &[MemberRoute],
163
+ ) -> Result<OperationRecord, BackendError> {
164
+ let mut backend = Backend::open(workspace, team)?;
165
+ backend::require_candidate(&backend.binding)?;
166
+ if !backend::seat_unclaimed(&backend, &role.id)? {
167
+ return Err(Error::Conflict.into());
168
+ }
169
+ let parent = backend.store.seat(source)?.ok_or(Error::Invalid("unknown native seat"))?;
170
+ let session = parent.session.clone().ok_or(ContractError::Invalid("native fork source session"))?;
171
+ if parent.status == SeatStatus::Unknown || parent.provider != role.provider {
172
+ return Err(Error::Fence.into());
173
+ }
174
+ let selected = registry::provider(role.provider.as_str())?;
175
+ let descriptor = selected.descriptor();
176
+ let discovered = discovery::discover_runtime(&role.provider, workspace)?;
177
+ if let Some(path) = selected.native_fork_source(discovered.runtime.as_ref(), &session)? {
178
+ // The exact parent backing the native CLI reads must exist before any effect.
179
+ let metadata = std::fs::symlink_metadata(&path)?;
180
+ if !metadata.is_file() || metadata.len() == 0 {
181
+ return Err(ContractError::Invalid("native fork parent backing").into());
182
+ }
183
+ }
184
+ backend::publish_framework_routes(&mut backend, members)?;
185
+ let identity = backend.store.propose_identity(&role.id)?;
186
+ let server_key = selected.server_key_for(&identity)?;
187
+ backend::write_role(&backend.binding, &identity, role)?;
188
+ let adapter = backend::launch_adapter(&backend.binding, &identity, &role.provider, &discovered)?;
189
+ let hooks = adapter.hooks();
190
+ let mut launch = backend::request(&backend.binding, role, identity, &discovered)?;
191
+ launch.operation = Operation::NativeNewSeat;
192
+ if !descriptor.workspace.shared_cwd {
193
+ launch.paths.cwd = super::workspace::prepare(&backend.binding, &role.id)?;
194
+ }
195
+ backend::require_private_primary(selected, &launch.paths.cwd)?;
196
+ backend::preassign_session(selected, &mut launch, &discovered)?;
197
+ let operation = OperationId::new(format!("fork-{}", launch.identity.instance.as_str()))?;
198
+ let request = ForkRequest {
199
+ mode: ForkMode::NativeNewSeat,
200
+ auth: launch.auth,
201
+ source: session,
202
+ expected_source: parent.identity.clone(),
203
+ target: launch.identity.clone(),
204
+ target_native_session: None,
205
+ target_backing: None,
206
+ channel: launch.channel,
207
+ input_profile: launch.input_profile.clone(),
208
+ cwd: launch.paths.cwd.clone(),
209
+ native: launch.native.clone(),
210
+ evidence_kind: launch.evidence_kind,
211
+ selected_turn: None,
212
+ operation_id: operation.clone(),
213
+ };
214
+ launch.fork = Some(Box::new(resolve_fork(descriptor, &hooks, &request)?));
215
+ let resolved = resolve_launch(descriptor, &hooks, &launch, Some(&discovered.catalog))?;
216
+ let plan = adapter.plan(&resolved)?;
217
+ validate_launch_plan(descriptor, &resolved, &plan)?;
218
+ let (workspace_topology, _, _) = backend::workspace_tmux(&backend.binding, &role.id, None)?;
219
+ let mut io = ScopedMaterializer::new(descriptor, &resolved, &plan, operation.clone(), RealCommandRunner::default())?;
220
+ let clock = RealClock::new();
221
+ let mut physical = PhysicalRuntime::new(
222
+ Registration {
223
+ descriptor,
224
+ hooks: &hooks,
225
+ controls: selected.controls(),
226
+ startup: selected.startup(),
227
+ session_panel: selected.session_panel(),
228
+ },
229
+ backend::settings(&backend.binding, selected),
230
+ operation.clone(),
231
+ &clock,
232
+ )?;
233
+ physical.evidence = backend::policy_evidence(&role.provider, &launch.native, backend.binding.candidate_sha256)?;
234
+ physical.workspace_tmux = Some(workspace_topology);
235
+ let routing = Routing {
236
+ pane: "unpublished".into(),
237
+ binding_key: format!("binding-{}", launch.identity.instance.as_str()),
238
+ server_key,
239
+ };
240
+ let record = Lifecycle { store: &mut backend.store, host: &mut physical, io: &mut io }.fork(
241
+ &Adapter { descriptor, hooks: &hooks, catalog: Some(&discovered.catalog) },
242
+ &request,
243
+ Some((&launch, routing)),
244
+ )?;
245
+ Ok(record)
246
+ }
247
+
248
+ /// The target's runtime spec entry and route, compiled exactly as add-agent does.
249
+ fn register_spec(
250
+ selected: &SelectedTeam,
251
+ role_path: &Path,
252
+ target: &str,
253
+ spec_path: &Path,
254
+ pre_spec: Option<&str>,
255
+ ) -> Result<(), CliError> {
256
+ let mut spec = crate::compiler::compile_team(&selected.team_dir).map_err(error)?;
257
+ crate::lifecycle::launch::spec_state::override_spec_workspace(&mut spec, &selected.run_workspace);
258
+ let workspace_text = spec.get("team").and_then(|team| team.get("workspace")).and_then(Yaml::as_str)
259
+ .map(str::to_owned)
260
+ .unwrap_or_else(|| selected.run_workspace.to_string_lossy().into_owned());
261
+ let team_meta = crate::compiler::read_front_matter(&selected.team_dir.join("TEAM.md"))
262
+ .map(|(meta, _)| meta)
263
+ .unwrap_or(Yaml::Null);
264
+ let compiled = crate::compiler::compile_role_agent(role_path, &team_meta, &workspace_text).map_err(error)?;
265
+ if compiled.id != target {
266
+ return Err(error(format!("forked role compiles to '{}', not '{target}'", compiled.id)));
267
+ }
268
+ let mut latest = pre_spec.and_then(|text| crate::model::yaml::loads(text).ok()).unwrap_or(spec);
269
+ inject_agent_into_spec(&mut latest, compiled.agent, &compiled.id).map_err(error)?;
270
+ crate::lifecycle::launch::spec_state::write_spec_atomic(spec_path, &latest).map_err(error)
271
+ }
272
+
273
+ /// The parent's role document under the target's identity: its own name, the
274
+ /// optional label as role, every other field and the body unchanged.
275
+ fn fork_role_text(source: &str, target: &str, label: Option<&str>) -> String {
276
+ let (mut meta, body) = crate::compiler::split_front_matter(source);
277
+ if let Yaml::Map(pairs) = &mut meta {
278
+ pairs.retain(|(key, _)| key != "agent_id");
279
+ set_field(pairs, "name", target);
280
+ if let Some(label) = label.map(str::trim).filter(|label| !label.is_empty()) {
281
+ set_field(pairs, "role", label);
282
+ }
283
+ }
284
+ format!("---\n{}---\n\n{}", crate::lifecycle::launch::role_source::dump_role_frontmatter(&meta), body)
285
+ }
286
+
287
+ fn set_field(pairs: &mut Vec<(String, Yaml)>, key: &str, value: &str) {
288
+ match pairs.iter_mut().find(|(name, _)| name == key) {
289
+ Some((_, old)) => *old = Yaml::Str(value.to_owned()),
290
+ None => pairs.push((key.to_owned(), Yaml::Str(value.to_owned()))),
291
+ }
292
+ }
293
+
294
+ fn write_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
295
+ use std::io::Write;
296
+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(path)?;
297
+ file.write_all(bytes)?;
298
+ file.sync_all()
299
+ }
300
+
301
+ /// Compensation for this fork's own registration. A started but unpublished
302
+ /// native seat is stopped first; if that fails, the role/spec/state stay so
303
+ /// status and stop can still reach the live seat.
304
+ struct Undo {
305
+ workspace: PathBuf,
306
+ team: String,
307
+ target: SeatId,
308
+ role_path: PathBuf,
309
+ role_bytes: Vec<u8>,
310
+ spec_path: PathBuf,
311
+ pre_spec: Option<String>,
312
+ }
313
+
314
+ impl Undo {
315
+ fn run(&self, failure: CliError) -> CliError {
316
+ let started = Backend::open_readonly(&self.workspace, &self.team)
317
+ .ok()
318
+ .and_then(|backend| backend.store.seat(&self.target).ok().flatten())
319
+ .is_some_and(|seat| seat.status != SeatStatus::Stopped && seat.physical.is_some());
320
+ if started {
321
+ if let Err(stop) = backend::stop(&self.workspace, &self.team, &self.target) {
322
+ return error(format!(
323
+ "{failure}; stopping the forked native seat failed: {stop}; its role, spec and state were kept"
324
+ ));
325
+ }
326
+ }
327
+ rollback_add_agent_atomic(
328
+ &self.workspace, &self.spec_path, self.pre_spec.as_deref(), None,
329
+ Some(self.team.as_str()), &AgentId::new(self.target.as_str()), "fork_agent_failed",
330
+ );
331
+ let residual = match std::fs::read(&self.role_path) {
332
+ Ok(bytes) if bytes == self.role_bytes => std::fs::remove_file(&self.role_path)
333
+ .err()
334
+ .map(|e| format!("role file {}: {e}", self.role_path.display())),
335
+ Ok(_) => Some(format!("role file {} changed; preserved", self.role_path.display())),
336
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
337
+ Err(e) => Some(format!("role file {}: {e}", self.role_path.display())),
338
+ };
339
+ match residual {
340
+ None => failure,
341
+ Some(residual) => error(format!("{failure}; compensation incomplete: {residual}")),
342
+ }
343
+ }
344
+ }
345
+
346
+ #[cfg(test)]
347
+ mod tests {
348
+ use super::fork_role_text;
349
+ use crate::model::yaml::Value;
350
+
351
+ #[test]
352
+ fn forked_role_keeps_its_body_and_takes_the_target_identity() {
353
+ let source = "---\nname: opus-architect\nagent_id: opus-architect\nprovider: claude\nmodel: claude-opus-5-5\n---\n\nYou design the system.\n";
354
+ let forked = fork_role_text(source, "opus-fork", Some(" avatar "));
355
+ let (meta, body) = crate::compiler::split_front_matter(&forked);
356
+ assert_eq!(meta.get("name").and_then(Value::as_str), Some("opus-fork"));
357
+ assert!(meta.get("agent_id").is_none());
358
+ assert_eq!(meta.get("role").and_then(Value::as_str), Some("avatar"));
359
+ assert_eq!(meta.get("provider").and_then(Value::as_str), Some("claude"));
360
+ assert_eq!(meta.get("model").and_then(Value::as_str), Some("claude-opus-5-5"));
361
+ assert_eq!(body.trim(), "You design the system.");
362
+ let unlabeled = fork_role_text("plain body\n", "opus-fork", None);
363
+ let (meta, body) = crate::compiler::split_front_matter(&unlabeled);
364
+ assert_eq!(meta.get("name").and_then(Value::as_str), Some("opus-fork"));
365
+ assert!(meta.get("role").is_none());
366
+ assert_eq!(body.trim(), "plain body");
367
+ }
368
+ }
@@ -55,16 +55,15 @@ pub fn require_legacy_lifecycle(
55
55
  return Ok(());
56
56
  };
57
57
  let row = agent.and_then(|id| selected.state.get("agents").and_then(|agents| agents.get(id)));
58
- // A pre-upgrade legacy Cursor seat has no engine left; only teardown is admitted.
58
+ // A pre-upgrade legacy Cursor, Claude, Codex, Grok or Pi seat has no engine left; only teardown is admitted.
59
59
  let teardown = matches!(operation, "stop-agent" | "remove-agent");
60
- if !teardown
61
- && row
62
- .and_then(|row| row.get("provider"))
63
- .and_then(Value::as_str)
64
- .is_some_and(crate::provider::wire::is_retired_provider)
60
+ if let Some(retired) = row
61
+ .and_then(|row| row.get("provider"))
62
+ .and_then(Value::as_str)
63
+ .filter(|provider| !teardown && crate::provider::wire::is_retired_provider(provider))
65
64
  {
66
65
  return Err(crate::cli::CliError::Runtime(
67
- crate::provider::wire::RETIRED_PROVIDER_ERROR.into(),
66
+ crate::provider::wire::retired_provider_error(retired).into(),
68
67
  ));
69
68
  }
70
69
  let selected_native = match agent {
@@ -115,12 +114,8 @@ pub fn declares_contract(path: Option<&Path>, provider: Option<&str>) -> bool {
115
114
  .and_then(crate::model::yaml::Value::as_str)
116
115
  .map(str::to_owned)
117
116
  });
118
- let opted_in = meta.as_ref().is_some_and(|meta| {
119
- matches!(meta.get("contract_runtime"), Some(crate::model::yaml::Value::Bool(true)))
120
- });
121
- provider
122
- .or(declared.as_deref())
123
- .is_some_and(|provider| super::registry::recognizes(provider, opted_in))
117
+ // An omitted provider is the default `pi`, which declares the Pi leaf.
118
+ super::registry::recognizes(provider.or(declared.as_deref()).unwrap_or("pi"))
124
119
  }
125
120
  pub fn team_config(
126
121
  workspace: &Path,
@@ -7,6 +7,7 @@ pub mod backend;
7
7
  pub mod commands;
8
8
  pub mod config;
9
9
  pub mod discovery;
10
+ pub mod fork;
10
11
  pub mod forward;
11
12
  pub mod framework;
12
13
  pub mod mcp;