@team-agent/installer 0.5.122 → 0.5.123

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.
@@ -5,7 +5,6 @@ use std::path::Path;
5
5
  use serde_json::{json, Value};
6
6
  use team_agent_contract::contract::types::SeatId;
7
7
  use team_agent_contract::orchestration::store::{Outcome, SeatStatus};
8
- use team_agent_contract::host::process::{sample_process, ProcessState};
9
8
 
10
9
  use crate::cli::CliError;
11
10
  use crate::lifecycle::lock::{acquire_agent_lifecycle_lock, LifecycleLockRequest};
@@ -21,7 +20,7 @@ fn error(error: impl std::fmt::Display) -> CliError {
21
20
 
22
21
  /// None delegates only a non-contract selection. Once selected, any identity,
23
22
  /// ownership, state or physical error stays on this route and cannot fall back.
24
- fn with_agent(
23
+ pub(super) fn with_agent(
25
24
  workspace: &Path,
26
25
  team: Option<&str>,
27
26
  agent: &str,
@@ -51,10 +50,7 @@ fn with_agent(
51
50
  apply(&latest, &SeatId::new(agent).map_err(error)?).map(Some)
52
51
  }
53
52
 
54
- fn publish(selected: &SelectedTeam, id: &SeatId, clear_stop: bool) -> Result<Value, CliError> {
55
- publish_at(&selected.run_workspace, &selected.team_key, id, clear_stop)
56
- }
57
- fn publish_at(workspace: &Path, team: &str, id: &SeatId, clear_stop: bool) -> Result<Value, CliError> {
53
+ pub(super) fn publish_at(workspace: &Path, team: &str, id: &SeatId, clear_stop: bool) -> Result<Value, CliError> {
58
54
  let projected = framework::project_seat(workspace, team, id.as_str()).map_err(error)?;
59
55
  StateRepository::new(workspace).commit(
60
56
  StateWriteIntent::StartAgent { team_key: team, agent_id: id.as_str() },
@@ -70,6 +66,9 @@ fn publish_at(workspace: &Path, team: &str, id: &SeatId, clear_stop: bool) -> Re
70
66
  }
71
67
  },
72
68
  ).map_err(error)?;
69
+ // Fresh, explicit resume and team restart share this one publication path.
70
+ // Only the exact live receipt may claim a session it actually created.
71
+ backend::bind_workspace_session(workspace, team, id).map_err(error)?;
73
72
  Ok(projected)
74
73
  }
75
74
 
@@ -121,34 +120,32 @@ pub fn start_agent(
121
120
  return Ok(json!({"ok":false,"agent_id":agent,"status":"paused","reason":"agent_paused"}));
122
121
  }
123
122
  let unstarted = framework::is_paused_unstarted(row);
124
- let prepared = if unstarted {
123
+ if unstarted {
125
124
  // Full pure team admission precedes native allocation or role writes.
126
125
  backend::preflight(&config).map_err(error)?;
127
- None
128
- } else {
129
- let backend = Backend::open_readonly(&selected.run_workspace, &selected.team_key).map_err(error)?;
130
- let seat = backend.store.seat(id).map_err(error)?.ok_or(BackendError::Metadata).map_err(error)?;
131
- if seat.status == SeatStatus::Unknown {
132
- return Err(error("native seat state is unknown; explicit reconciliation required"));
133
- }
134
- if seat.status != SeatStatus::Stopped && seat.physical.as_ref().is_some_and(|target| sample_process(&target.process) == ProcessState::Alive) {
135
- return Err(error("native seat is already running; use stop-agent first"));
136
- }
137
- Some(backend::prepare_resume(&selected.run_workspace, &selected.team_key, id, Some(role)).map_err(error)?)
126
+ } else if backend::preflight_start_role(&selected.run_workspace, &selected.team_key, role).map_err(error)? {
127
+ backend::preflight(&config).map_err(error)?;
128
+ }
129
+ let before = if unstarted { None } else {
130
+ Backend::open_readonly(&selected.run_workspace, &selected.team_key).map_err(error)?
131
+ .store.creation_receipt(id, None).map_err(error)?
138
132
  };
139
133
  crate::lifecycle::role_config::commit_contract_role(&source, &previous, &next).map_err(error)?;
140
- let receipt = match prepared {
141
- Some(prepared) => backend::resume(prepared).map_err(error)?,
142
- None => backend::start(&selected.run_workspace, &selected.team_key, role, &config.members).map_err(error)?.1,
143
- };
134
+ let receipt = backend::start(&selected.run_workspace, &selected.team_key, role, &config.members).map_err(error)?.1;
144
135
  // An uncertain operation never rolls the authoritative native store back
145
136
  // to the old generation. The receipt remains available for recovery.
146
- let projection = checked_projection(&receipt, || publish(selected, id, true))?;
137
+ let projection = checked_projection(&receipt, || publish_at(&selected.run_workspace, &selected.team_key, id, true))?;
147
138
  let coordinator = crate::coordinator::start_coordinator_with_team(
148
139
  &crate::coordinator::WorkspacePath::new(selected.run_workspace.clone()), Some(&selected.team_key),
149
140
  ).map_err(error)?;
150
141
  Ok(json!({"ok":coordinator.ok,"agent_id":agent,"status":"running","runtime":"contract",
151
- "start_mode":if unstarted {"fresh"} else {"resumed"}, "operation":receipt.id,
142
+ "start_mode":match before {
143
+ None => "fresh",
144
+ Some(ref original) if original.outcome == Outcome::Compensated => "fresh",
145
+ Some(ref original) if original.id == receipt.id && original.outcome != Outcome::Committed => "receipt_completed",
146
+ Some(ref original) if original.id == receipt.id => "reused",
147
+ Some(_) => "resumed",
148
+ }, "operation":receipt.id,
152
149
  "session_id":projection.get("session_id"),"generation":projection.get("generation"),
153
150
  "coordinator":crate::lifecycle::coordinator_start_summary_value(
154
151
  &crate::lifecycle::CoordinatorStartSummary::from_start_report(&coordinator))}))
@@ -259,6 +256,23 @@ pub fn stop_agent(
259
256
 
260
257
  #[cfg(test)]
261
258
  mod tests {
259
+ // Assembly guard, not a substitute for the real shared-session restart/
260
+ // shutdown RED→GREEN journey. All start callers must use this common path.
261
+ #[test]
262
+ fn shared_owner_claim_follows_common_projection_commit_including_team_restart() {
263
+ let source = include_str!("commands.rs");
264
+ let body = source.split_once("pub(super) fn publish_at").unwrap().1
265
+ .split_once("fn check_record").unwrap().0;
266
+ let persisted = body.find("StateRepository::new(workspace).commit").unwrap();
267
+ let claimed = body.find("backend::bind_workspace_session(workspace, team, id)").unwrap();
268
+ let returned = body.find("Ok(projected)").unwrap();
269
+ assert!(persisted < claimed && claimed < returned);
270
+ let restart = source.split_once("pub(crate) fn restart_prepared").unwrap().1
271
+ .split_once("pub fn restart(").unwrap().0;
272
+ assert!(restart.contains("publish_at(workspace, team, &id, false)"));
273
+ assert!(!include_str!("framework.rs").contains("backend::bind_workspace_session"));
274
+ }
275
+
262
276
  use super::*;
263
277
  use team_agent_contract::contract::{delivery::DeliveryEffect, session::CwdIdentity, types::*};
264
278
  use team_agent_contract::orchestration::store::{OperationRecord, Phase, SeatRecord, TransactionKind};
@@ -208,10 +208,69 @@ pub fn drain(
208
208
  Ok(completed)
209
209
  }
210
210
 
211
+ /// Explicit operator egress only: reuse committed native receipts, never run a
212
+ /// coordinator tick, provider admission, input delivery, or candidate migration.
213
+ /// The original runtime binding remains authoritative even when this helper was
214
+ /// built from a newer revision. Pending forwards retain their exact source IDs.
215
+ pub fn drain_scoped_pending_egress(
216
+ workspace: &std::path::Path,
217
+ team: &str,
218
+ expected_scope: &str,
219
+ apply: bool,
220
+ ) -> Result<Value, String> {
221
+ if !workspace.is_absolute() || team.is_empty() || team.trim() != team {
222
+ return Err("egress requires an absolute workspace and exact explicit team".into());
223
+ }
224
+ ScopeId::new(expected_scope).map_err(|error| error.to_string())?;
225
+ let selected = crate::state::selector::resolve_active_team_readonly(
226
+ workspace, Some(team), crate::state::selector::SelectorMode::RuntimeOnly,
227
+ ).map_err(|error| error.to_string())?;
228
+ crate::lifecycle::launch::ensure_owner_allowed_for_state(&selected.state, None)
229
+ .map_err(|error| error.to_string())?;
230
+ let original = super::backend::Backend::open_readonly(&selected.run_workspace, &selected.team_key)
231
+ .map_err(|error| error.to_string())?;
232
+ if original.binding.scope.as_str() != expected_scope || original.binding.team != team {
233
+ return Err("egress scope/binding mismatch".into());
234
+ }
235
+ let binding = serde_json::to_value(&original.binding).map_err(|error| error.to_string())?;
236
+ let before: Vec<_> = original.store.pending_forwards(32).map_err(|error| error.to_string())?
237
+ .into_iter().map(|intent| intent.id).collect();
238
+ drop(original);
239
+ let processed = if apply {
240
+ let mut backend = super::backend::Backend::open(&selected.run_workspace, &selected.team_key)
241
+ .map_err(|error| error.to_string())?;
242
+ if serde_json::to_value(&backend.binding).map_err(|error| error.to_string())? != binding {
243
+ return Err("egress binding changed before claim".into());
244
+ }
245
+ drain(&backend.binding.framework(), &mut backend.store, 32).map_err(|error| error.to_string())?
246
+ } else { 0 };
247
+ let after = super::backend::Backend::open_readonly(&selected.run_workspace, &selected.team_key)
248
+ .map_err(|error| error.to_string())?;
249
+ if serde_json::to_value(&after.binding).map_err(|error| error.to_string())? != binding {
250
+ return Err("egress binding changed during forwarding".into());
251
+ }
252
+ let pending: Vec<_> = after.store.pending_forwards(32).map_err(|error| error.to_string())?
253
+ .into_iter().map(|intent| intent.id).collect();
254
+ Ok(json!({"scope":expected_scope,"team":team,"apply":apply,"processed":processed,
255
+ "pending_before":before,"pending_after":pending,"binding_unchanged":true,
256
+ "native_input":"not_invoked","coordinator_lifecycle":"not_invoked",
257
+ "leader_consumption":"requires actual natural receipt"}))
258
+ }
259
+
211
260
  #[cfg(test)]
212
261
  mod tests {
213
262
  use super::*;
214
263
  #[test]
264
+ fn egress_operator_refuses_implicit_workspace_team_and_invalid_scope_before_io() {
265
+ for (workspace, team, scope) in [
266
+ ("relative", "team", "scope"), ("/", "", "scope"),
267
+ ("/", " team", "scope"), ("/", "team", ""), ("/", "team", "bad/scope"),
268
+ ] {
269
+ assert!(drain_scoped_pending_egress(std::path::Path::new(workspace), team, scope, false).is_err());
270
+ assert!(drain_scoped_pending_egress(std::path::Path::new(workspace), team, scope, true).is_err());
271
+ }
272
+ }
273
+ #[test]
215
274
  fn compact_native_result_becomes_the_existing_framework_business_schema() {
216
275
  let compact = json!({"schema_version":1,"agent_id":"worker","task_id":"msg-bound","status":"completed","summary":"5535"});
217
276
  let result = framework_result("result-fixed", "worker", &compact).unwrap();
@@ -127,23 +127,29 @@ pub fn start_role(
127
127
  team: &str,
128
128
  id: &str,
129
129
  ) -> Result<(), crate::lifecycle::LifecycleError> {
130
- let error = |error: String| crate::lifecycle::LifecycleError::Provider(error);
131
- let config = team_config(workspace, directory, team)
132
- .map_err(|e| error(e.to_string()))?
133
- .ok_or_else(|| error("contract role no longer configured".into()))?;
134
- let role = config
135
- .roles
136
- .iter()
137
- .find(|role| role.id.as_str() == id)
138
- .ok_or_else(|| error("contract role not found".into()))?;
139
- let (_, record) =
140
- backend::start(workspace, team, role, &config.members).map_err(|e| error(e.to_string()))?;
141
- if record.outcome != Outcome::Committed {
142
- return Err(error(format!(
143
- "native startup {:?}: {}",
144
- record.outcome,
145
- record.failure.unwrap_or_default()
146
- )));
130
+ let result = super::commands::with_agent(workspace, Some(team), id, "start-role", |selected, seat| {
131
+ let error = |error: String| crate::cli::CliError::Runtime(error);
132
+ if directory.canonicalize()? != selected.team_dir.canonicalize()? {
133
+ return Err(error("native role source changed while acquiring lifecycle ownership".into()));
134
+ }
135
+ let config = team_config(&selected.run_workspace, &selected.team_dir, &selected.team_key)
136
+ .map_err(|e| error(e.to_string()))?
137
+ .ok_or_else(|| error("contract role no longer configured".into()))?;
138
+ let role = config.roles.iter().find(|role| &role.id == seat)
139
+ .ok_or_else(|| error("contract role not found".into()))?;
140
+ let (_, record) = backend::start(&selected.run_workspace, &selected.team_key, role, &config.members)
141
+ .map_err(|e| error(e.to_string()))?;
142
+ if record.outcome != Outcome::Committed {
143
+ return Err(error(format!("native startup seat={id} operation={:?} phase={:?} outcome={:?}: {}",
144
+ record.id, record.phase, record.outcome, record.failure.unwrap_or_default())));
145
+ }
146
+ // Preserve each committed seat before a later discovery/spawn can fail.
147
+ // A whole-batch error must never hide this generation's physical effects.
148
+ let projected = super::commands::publish_at(&selected.run_workspace, &selected.team_key, seat, true)?;
149
+ Ok(projected)
150
+ }).map_err(|e| crate::lifecycle::LifecycleError::Provider(e.to_string()))?;
151
+ if result.is_none() {
152
+ return Err(crate::lifecycle::LifecycleError::Provider("native startup scope/seat is not addressable; no legacy fallback".into()));
147
153
  }
148
154
  Ok(())
149
155
  }
@@ -1579,15 +1579,10 @@ pub(crate) fn quick_start_with_transport_in_workspace_pi_preflight(
1579
1579
  crate::lifecycle::restart::LifecyclePhase::ReadinessWait,
1580
1580
  );
1581
1581
  let worker_readiness = quick_start_worker_readiness(&workspace, &state_team_key);
1582
- let attach_windows = load_runtime_state(&workspace)
1583
- .ok()
1584
- .map(|state| {
1585
- attach_window_names_with_managed_leader(
1586
- &state,
1587
- started_attach_window_names(&launch.started),
1588
- )
1589
- })
1590
- .unwrap_or_else(|| started_attach_window_names(&launch.started));
1582
+ // The selected server is the display surface. Do not invent a leader
1583
+ // window or omit native windows merely because they are not legacy starts.
1584
+ let attach_windows = transport.list_windows(&session_name).unwrap_or_default()
1585
+ .into_iter().map(|window| window.as_str().to_owned()).collect::<Vec<_>>();
1591
1586
  let attach_commands = attach_commands_for_runtime_windows(
1592
1587
  launch.tmux_endpoint.as_deref(),
1593
1588
  &workspace,
@@ -1597,15 +1592,9 @@ pub(crate) fn quick_start_with_transport_in_workspace_pi_preflight(
1597
1592
  let mut next_actions = vec![format!(
1598
1593
  "team compiled; real spawn is behind the transport/provider boundary; {coordinator_action}"
1599
1594
  )];
1600
- // Stage QR (design doc
1601
- // .team/artifacts/quickstart-restart-separation-design.md):
1602
- // quick-start is initial-creation-only. After success, remind the
1603
- // operator that subsequent starts must go through restart so the
1604
- // user's context (sessions, ownership, tasks) survives.
1605
1595
  next_actions.push(
1606
- "quick-start initialized this team; for all subsequent starts use \
1607
- `team-agent restart` to resume context (quick-start refuses on \
1608
- already-initialised teams)"
1596
+ "team initialized; use `team-agent start` for idempotent activation, or \
1597
+ `team-agent team restart` for an intentional restart; quick-start is a compatibility creation command"
1609
1598
  .to_string(),
1610
1599
  );
1611
1600
  if should_emit_workspace_socket_missing_hint(
@@ -239,25 +239,10 @@ pub(super) fn attach_commands_for_runtime_windows<'a>(
239
239
  ) -> Vec<String> {
240
240
  let windows = window_names.into_iter().collect::<Vec<_>>();
241
241
  let attach = if let Some(endpoint) = endpoint.filter(|endpoint| !endpoint.is_empty()) {
242
- if Path::new(endpoint).is_absolute() {
243
- windows
244
- .iter()
245
- .map(|window_name| {
246
- format!(
247
- "tmux -S {} attach -t {}:{}",
248
- endpoint,
249
- session_name.as_str(),
250
- window_name
251
- )
252
- })
253
- .collect::<Vec<_>>()
254
- } else {
255
- crate::tmux_backend::attach_commands_for_windows(
256
- workspace,
257
- session_name,
258
- windows.iter().copied(),
259
- )
260
- }
242
+ let address = serde_json::json!({"tmux_endpoint":endpoint});
243
+ windows.iter().filter_map(|window| crate::tmux_backend::attach_command_for_runtime_state_or_workspace(
244
+ workspace, Some(&address), session_name, window,
245
+ )).collect::<Vec<_>>()
261
246
  } else {
262
247
  crate::tmux_backend::attach_commands_for_windows(
263
248
  workspace,
@@ -359,3 +344,25 @@ pub(super) fn attach_window_names_with_managed_leader(
359
344
  pub(super) fn state_uses_managed_leader(state: &serde_json::Value) -> bool {
360
345
  crate::state::projection::state_is_managed_leader(state)
361
346
  }
347
+
348
+ #[cfg(test)]
349
+ mod workspace_attach_tests {
350
+ use super::*;
351
+
352
+ #[test]
353
+ fn explicit_shared_endpoint_is_not_replaced_by_workspace_hash() {
354
+ let session = SessionName::new("team-native");
355
+ assert_eq!(attach_commands_for_runtime_windows(Some("authorized-workspace"),
356
+ Path::new("/not-the-selected-socket"), &session, ["grok-worker"]),
357
+ ["tmux -L authorized-workspace attach -t team-native:grok-worker"]);
358
+ assert_eq!(attach_commands_for_runtime_windows(Some("/private/tmp/owned/tmux.sock"),
359
+ Path::new("/not-the-selected-socket"), &session, ["grok-worker"]),
360
+ ["tmux -S /private/tmp/owned/tmux.sock attach -t team-native:grok-worker"]);
361
+ assert!(attach_commands_for_runtime_windows(Some("authorized-workspace"),
362
+ Path::new("/not-the-selected-socket"), &session, std::iter::empty()).is_empty());
363
+ assert_eq!(attach_commands_for_runtime_windows(Some("authorized-workspace"),
364
+ Path::new("/not-the-selected-socket"), &session, ["leader", "grok-worker"]),
365
+ ["tmux -L authorized-workspace attach -t team-native:leader",
366
+ "tmux -L authorized-workspace attach -t team-native:grok-worker"]);
367
+ }
368
+ }
@@ -78,7 +78,13 @@ pub(super) fn spawn_agents(
78
78
  let mut contract_started = Vec::new();
79
79
  #[cfg(not(unix))]
80
80
  let contract_started = Vec::new();
81
- for agent in spec_agent_values(spec) {
81
+ let agents = spec_agent_values(spec);
82
+ #[cfg(unix)]
83
+ let has_contract = agents.iter().any(|agent| agent.get("provider").and_then(Value::as_str)
84
+ .is_some_and(|provider| crate::contract_runtime::registry::descriptor(provider).is_some()));
85
+ #[cfg(not(unix))]
86
+ let has_contract = false;
87
+ for agent in agents {
82
88
  let Some(agent_id_raw) = agent.get("id").and_then(Value::as_str) else {
83
89
  continue;
84
90
  };
@@ -406,7 +412,7 @@ pub(super) fn spawn_agents(
406
412
  }
407
413
  // One independent tmux window per worker; no GUI/display layout.
408
414
  let window = WindowName::new(agent_id_raw);
409
- let spawn = if started.is_empty() {
415
+ let spawn = if started.is_empty() && contract_started.is_empty() {
410
416
  transport.spawn_first_with_env_unset(
411
417
  session_name,
412
418
  &window,
@@ -455,6 +461,17 @@ pub(super) fn spawn_agents(
455
461
  .or_else(|| profile_launch.claude_projects_root.clone()),
456
462
  managed_mcp_config: plan.managed_mcp_config || profile_launch.managed_mcp_config,
457
463
  });
464
+ if has_contract && contract_started.is_empty() && started.len() == 1 {
465
+ // A native seat following the first legacy seat must be able to
466
+ // verify the same session before borrowing it, not after the batch.
467
+ let selected = crate::state::selector::resolve_active_team_readonly(workspace,
468
+ Some(&mcp_team_id), crate::state::selector::SelectorMode::RuntimeOnly)
469
+ .map_err(|e| LifecycleError::TeamSelect(e.to_string()))?;
470
+ let generation = crate::state::projection::session_generation(&selected.state)
471
+ .unwrap_or(session_name.as_str());
472
+ transport.set_session_owner_with_generation(session_name, workspace, &mcp_team_id, generation)
473
+ .map_err(|e| LifecycleError::Transport(e.to_string()))?;
474
+ }
458
475
  }
459
476
  Ok((started, contract_started))
460
477
  }
@@ -320,27 +320,15 @@ pub(crate) fn restart_with_transport_with_session_convergence_deadline(
320
320
  crate::model::paths::runtime_dir(&resolved_ws).display()
321
321
  )));
322
322
  }
323
- // RED-2(P0)修:存在性门下移到 resolve 之后,用 selected.spec_path(读序 B:runtime 优先、
324
- // legacy 用户目录回落)判,而非 resolve 前自拼 workspace/team.spec.yaml(spec-demote 后 spec
325
- // 不在用户目录 → 旧门误报缺)。resolve_active_team(RequireSpec) 内部已按 spec_path 校验存在性,
326
- // 故直接交给它;失败信息(含真实 expected runtime spec 路径)即正确的 N38。
327
- let selected = crate::state::selector::resolve_active_team(
323
+ // The spec is derived. Select runtime identity first; the locked owner/source
324
+ // admission below rebuilds it before any teardown. Requiring it here made
325
+ // the advertised missing-spec recovery command reject its own prerequisite.
326
+ let selected = crate::state::selector::resolve_active_team_readonly(
328
327
  workspace,
329
328
  team,
330
- crate::state::selector::SelectorMode::RequireSpec,
329
+ crate::state::selector::SelectorMode::RuntimeOnly,
331
330
  )
332
331
  .map_err(|e| LifecycleError::TeamSelect(e.to_string()))?;
333
- // 显式存在性门(下移后):selected.spec_path 经读序 B 已定位 runtime/legacy spec。
334
- // 缺(空目录 restart 等)→ 报真实期望路径,不误导去用户目录找。
335
- if !selected.spec_path.as_ref().is_some_and(|p| p.exists()) {
336
- let expected = selected.spec_path.clone().unwrap_or_else(|| {
337
- crate::model::paths::runtime_spec_path(&selected.run_workspace, &selected.team_key)
338
- });
339
- return Err(LifecycleError::TeamSelect(format!(
340
- "missing spec for restart: {} (run `team-agent quick-start <teamdir>` first, or restore the team's role docs)",
341
- expected.display()
342
- )));
343
- }
344
332
  restart_with_selected_team_and_transport(
345
333
  selected,
346
334
  allow_fresh,
@@ -373,10 +361,10 @@ fn restart_with_selected_team_and_transport(
373
361
  })?;
374
362
  // Selection happened before the lifecycle lock. A stop-agent that won the
375
363
  // lock must not be undone by the old running snapshot used by restart.
376
- let mut state = crate::state::selector::resolve_active_team(
364
+ let mut state = crate::state::selector::resolve_active_team_readonly(
377
365
  &selected.run_workspace,
378
366
  Some(selected.team_key.as_str()),
379
- crate::state::selector::SelectorMode::RequireSpec,
367
+ crate::state::selector::SelectorMode::RuntimeOnly,
380
368
  )
381
369
  .map_err(|error| LifecycleError::TeamSelect(error.to_string()))?
382
370
  .state;
@@ -581,9 +569,18 @@ fn restart_with_selected_team_and_transport(
581
569
  // no authoritative live agents, the previous behavior (pre-spawn
582
570
  // teardown of a stale empty session) is preserved so tests that
583
571
  // seed a fake-live session without live agent rows still work.
572
+ #[cfg(unix)]
573
+ let shared_native_windows = crate::contract_runtime::backend::has_shared_windows(
574
+ &selected.run_workspace, &selected.team_key,
575
+ ).map_err(|error| LifecycleError::RequirementUnmet(error.to_string()))?;
576
+ #[cfg(not(unix))]
577
+ let shared_native_windows = false;
578
+ // Canonical windows share this session but are NOT legacy restart targets.
579
+ // Keep the session, and retire only each successful legacy replacement's
580
+ // exact old pane through the existing build-before-destroy path.
584
581
  let live_worker_session_deferred_teardown =
585
582
  session_live_or_default(transport, &session_name, false)
586
- && !collect_live_agents_from_state(&state).is_empty();
583
+ && (shared_native_windows || !collect_live_agents_from_state(&state).is_empty());
587
584
  let inherited_generation =
588
585
  crate::state::projection::session_generation(&state).map(str::to_string);
589
586
  let same_role_cohort_targets =
@@ -598,8 +595,8 @@ fn restart_with_selected_team_and_transport(
598
595
  } else {
599
596
  std::collections::BTreeSet::new()
600
597
  };
601
- if session_live_or_default(transport, &session_name, false)
602
- && !live_worker_session_deferred_teardown
598
+ if destroy_stale_worker_session(session_live_or_default(transport, &session_name, false),
599
+ live_worker_session_deferred_teardown, shared_native_windows)
603
600
  {
604
601
  eprintln!(
605
602
  "team_agent::layout restart_precondition_warning worker_session=`{}` action=killing \
@@ -3698,6 +3695,26 @@ fn rebuild_runtime_spec_from_roles(
3698
3695
  run_workspace: &Path,
3699
3696
  team_key: &str,
3700
3697
  state: &serde_json::Value,
3698
+ ) -> Result<YamlValue, LifecycleError> {
3699
+ let spec = compile_runtime_spec_from_roles(run_workspace, team_key, state)?;
3700
+ let spec_path = crate::model::paths::runtime_spec_path(run_workspace, team_key);
3701
+ crate::lifecycle::launch::write_spec_atomic(&spec_path, &spec)?;
3702
+ let team_dir = state.get("team_dir").and_then(serde_json::Value::as_str)
3703
+ .filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
3704
+ .unwrap_or_else(|| run_workspace.to_path_buf());
3705
+ let legacy_spec = team_dir.join("team.spec.yaml");
3706
+ if legacy_spec.exists() && legacy_spec != spec_path {
3707
+ let _ = std::fs::remove_file(&legacy_spec);
3708
+ }
3709
+ Ok(spec)
3710
+ }
3711
+
3712
+ /// Read-only counterpart of restart's existing compiler. It preserves dynamic
3713
+ /// role sources, retired-seat filtering and the established session override.
3714
+ pub(crate) fn compile_runtime_spec_from_roles(
3715
+ run_workspace: &Path,
3716
+ team_key: &str,
3717
+ state: &serde_json::Value,
3701
3718
  ) -> Result<YamlValue, LifecycleError> {
3702
3719
  // team_dir(角色定义源)优先取 state.team_dir;缺则回落 run_workspace(自含 team-dir 布局,
3703
3720
  // run_workspace 本身即角色目录)。两者都无角色定义则下面的齐全性检查会显式拒。
@@ -3758,18 +3775,52 @@ fn rebuild_runtime_spec_from_roles(
3758
3775
  // 三行式,不静默 prune 已 live 的 helper(persist SaveConflict 保护继续生效)。
3759
3776
  merge_state_dynamic_role_files(&mut spec, run_workspace, &team_dir, team_key, state)?;
3760
3777
  filter_retired_agents_from_spec(&mut spec, &retired_agent_ids(state));
3761
- // 写 runtime spec(覆盖,原子 tmp+rename;Bug2)。
3762
- let spec_path = crate::model::paths::runtime_spec_path(run_workspace, team_key);
3763
- crate::lifecycle::launch::write_spec_atomic(&spec_path, &spec)?;
3764
- // RC-A6a:重建成功后清理用户目录的 legacy spec(中间产物不该留在角色目录)。
3765
- // 仅删 team_dir 下的 team.spec.yaml(角色定义 TEAM.md/agents 不动);失败不致命(best-effort)。
3766
- let legacy_spec = team_dir.join("team.spec.yaml");
3767
- if legacy_spec.exists() && legacy_spec != spec_path {
3768
- let _ = std::fs::remove_file(&legacy_spec);
3769
- }
3770
3778
  Ok(spec)
3771
3779
  }
3772
3780
 
3781
+ /// Repair only derived metadata. The caller's readonly plan is checked again
3782
+ /// under lifecycle ownership; no process/session/control action is performed.
3783
+ pub(crate) fn restore_missing_runtime_spec(
3784
+ workspace: &Path,
3785
+ team: &str,
3786
+ expected: &YamlValue,
3787
+ ) -> Result<std::path::PathBuf, LifecycleError> {
3788
+ let run_workspace = crate::model::paths::canonical_run_workspace(workspace)
3789
+ .map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
3790
+ let _lock = acquire_agent_lifecycle_lock(LifecycleLockRequest {
3791
+ workspace: &run_workspace, operation: "restore-runtime-spec", team: Some(team), agent_id: None,
3792
+ })?;
3793
+ let selected = crate::state::selector::resolve_active_team_readonly(
3794
+ &run_workspace, Some(team), crate::state::selector::SelectorMode::RuntimeOnly,
3795
+ ).map_err(|e| LifecycleError::TeamSelect(e.to_string()))?;
3796
+ crate::lifecycle::launch::ensure_owner_allowed_for_state(&selected.state, None)?;
3797
+ if selected.run_workspace != run_workspace || selected.team_key != team {
3798
+ return Err(LifecycleError::TeamSelect("runtime spec repair scope changed".into()));
3799
+ }
3800
+ let spec_path = crate::model::paths::runtime_spec_path(&run_workspace, team);
3801
+ let current = compile_runtime_spec_from_roles(&run_workspace, team, &selected.state)?;
3802
+ if &current != expected {
3803
+ return Err(LifecycleError::TeamSelect("role/source changed since runtime spec repair planning".into()));
3804
+ }
3805
+ if spec_path.exists() {
3806
+ let text = std::fs::read_to_string(&spec_path)
3807
+ .map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
3808
+ if yaml::loads(&text).map_err(|e| LifecycleError::Compile(e.to_string()))? != current {
3809
+ return Err(LifecycleError::TeamSelect("runtime spec changed since repair planning".into()));
3810
+ }
3811
+ } else {
3812
+ crate::lifecycle::launch::write_spec_atomic(&spec_path, &current)?;
3813
+ }
3814
+ let mut state = selected.state;
3815
+ state["spec_path"] = serde_json::json!(spec_path);
3816
+ crate::state::repository::StateRepository::new(&run_workspace).save(
3817
+ crate::state::repository::StateWriteIntent::RestartTeam {
3818
+ team_key: team, topology_authority_agent_ids: &[], skip_capture_backfill_agent_ids: &[],
3819
+ }, &state,
3820
+ ).map_err(|e| LifecycleError::StatePersist(e.to_string()))?;
3821
+ Ok(spec_path)
3822
+ }
3823
+
3773
3824
  fn filter_retired_agents_from_spec(
3774
3825
  spec: &mut YamlValue,
3775
3826
  retired: &std::collections::BTreeSet<String>,
@@ -3969,8 +4020,21 @@ fn restart_candidate_has_context(state: &serde_json::Value) -> bool {
3969
4020
  })
3970
4021
  }
3971
4022
 
4023
+ // Never let a legacy session-wide kill bypass canonical native teardown.
4024
+ fn destroy_stale_worker_session(live: bool, deferred: bool, shared_native: bool) -> bool {
4025
+ live && !deferred && !shared_native
4026
+ }
4027
+
3972
4028
  #[cfg(test)]
3973
4029
  mod tests {
4030
+ #[test]
4031
+ fn startup_shared_session_never_bulk_kills_contract_windows() {
4032
+ assert!(!super::destroy_stale_worker_session(true, false, true));
4033
+ assert!(!super::destroy_stale_worker_session(true, true, true));
4034
+ assert!(super::destroy_stale_worker_session(true, false, false));
4035
+ assert!(!super::destroy_stale_worker_session(false, false, false));
4036
+ }
4037
+
3974
4038
  use super::*;
3975
4039
  use std::collections::BTreeMap;
3976
4040
  use std::path::Path;
@@ -96,6 +96,7 @@ pub(crate) use common::{
96
96
  };
97
97
  pub(crate) use orchestrator::{halt_plan, plan_status};
98
98
  pub(crate) use rebuild::restart_with_transport_with_session_convergence_deadline;
99
+ pub(crate) use rebuild::{compile_runtime_spec_from_roles, restore_missing_runtime_spec};
99
100
  // 0.5.38 (`.team/artifacts/startup-latency-locate.md` §5): expose the phase
100
101
  // timer + worker timing writer so `lifecycle::launch::launch_with_transport_in_workspace`
101
102
  // can emit the same instrumentation event family with `source="launch"`.
@@ -1546,9 +1546,10 @@ fn quick_start_persists_selected_tmux_endpoint_and_attach_commands() {
1546
1546
  "attach commands must use the selected socket endpoint: {attach_commands:?}"
1547
1547
  );
1548
1548
  assert!(
1549
- attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1550
- "fresh managed quick-start must include the leader window attach command: {attach_commands:?}"
1549
+ !attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1550
+ "managed metadata does not prove an unreported leader window exists: {attach_commands:?}"
1551
1551
  );
1552
+ assert!(attach_commands.iter().any(|cmd| cmd.ends_with(":implementer")));
1552
1553
  let (_raw, state) = raw_runtime_state(workspace);
1553
1554
  assert_eq!(state["tmux_endpoint"], json!(endpoint));
1554
1555
  assert_eq!(state["tmux_socket"], json!(endpoint));
@@ -1583,7 +1584,7 @@ fn annotate_runtime_tmux_endpoint_persists_workspace_socket_as_full_path() {
1583
1584
 
1584
1585
  #[test]
1585
1586
  #[serial(env)]
1586
- fn quick_start_preserves_managed_leader_topology_and_emits_leader_attach_command() {
1587
+ fn quick_start_preserves_managed_leader_topology_without_inventing_a_leader_window() {
1587
1588
  let hermetic = hermetic_guard::HermeticTestEnv::enter_with_leader("launch-spawn-managed-leader");
1588
1589
  let workspace = hermetic.root();
1589
1590
  let team = workspace.join("teamdir");
@@ -1641,9 +1642,10 @@ fn quick_start_preserves_managed_leader_topology_and_emits_leader_attach_command
1641
1642
  };
1642
1643
 
1643
1644
  assert!(
1644
- attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1645
- "managed topology quick-start output must include the leader window attach command: {attach_commands:?}"
1645
+ !attach_commands.iter().any(|cmd| cmd.contains(":leader")),
1646
+ "managed ownership must survive, but a missing physical leader window is not an attach target: {attach_commands:?}"
1646
1647
  );
1648
+ assert!(attach_commands.iter().any(|cmd| cmd.ends_with(":implementer")));
1647
1649
  let (_raw, state) = raw_runtime_state(workspace);
1648
1650
  assert_eq!(state["is_external_leader"], json!(false));
1649
1651
  assert_eq!(state["leader_client"]["diagnostic_only"], json!(true));
@@ -116,7 +116,8 @@ pub(crate) fn aliases(provider: Provider) -> &'static [&'static str] {
116
116
  /// Executable name we exec for the worker. `Claude` and `ClaudeCode` both
117
117
  /// resolve to `claude` — the distinction is in state semantics
118
118
  /// (`ClaudeCode` is the canonical CLI; `Claude` is a legacy alias kept for
119
- /// older specs).
119
+ /// older specs). Spawn this public name. Do not replace it with a
120
+ /// canonicalized deep binary; that skips the user's wrapper.
120
121
  pub(crate) fn command_name(provider: Provider) -> &'static str {
121
122
  match provider {
122
123
  Provider::Claude | Provider::ClaudeCode => "claude",