@team-agent/installer 0.5.122 → 0.5.124

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 (35) hide show
  1. package/Cargo.lock +8 -1
  2. package/Cargo.toml +1 -1
  3. package/crates/team-agent/src/cli/diagnose.rs +176 -10
  4. package/crates/team-agent/src/cli/intent/runtime.rs +103 -43
  5. package/crates/team-agent/src/cli/intent/runtime_tests.rs +198 -0
  6. package/crates/team-agent/src/cli/intent/tests.rs +37 -0
  7. package/crates/team-agent/src/cli/intent.rs +22 -0
  8. package/crates/team-agent/src/cli/models.rs +54 -10
  9. package/crates/team-agent/src/contract_runtime/backend.rs +498 -2
  10. package/crates/team-agent/src/contract_runtime/commands.rs +38 -24
  11. package/crates/team-agent/src/contract_runtime/discovery.rs +46 -56
  12. package/crates/team-agent/src/contract_runtime/forward.rs +59 -0
  13. package/crates/team-agent/src/contract_runtime/framework.rs +23 -17
  14. package/crates/team-agent/src/contract_runtime/registry.rs +41 -3
  15. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +19 -101
  16. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +6 -17
  17. package/crates/team-agent/src/lifecycle/launch/quick_start_transport.rs +26 -19
  18. package/crates/team-agent/src/lifecycle/launch/spawn.rs +19 -2
  19. package/crates/team-agent/src/lifecycle/restart/rebuild.rs +95 -31
  20. package/crates/team-agent/src/lifecycle/restart.rs +1 -0
  21. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +5 -6
  22. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +7 -5
  23. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +1 -3
  24. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +4 -16
  25. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +1 -3
  26. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +84 -53
  27. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +19 -1
  28. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +21 -0
  29. package/crates/team-agent/src/messaging/delivery.rs +5 -3
  30. package/crates/team-agent/src/provider/adapters/pi.rs +4 -4
  31. package/crates/team-agent/src/provider/session_scan/pi.rs +32 -19
  32. package/crates/team-agent/src/provider/tests/command_helpers.rs +2 -2
  33. package/crates/team-agent/src/provider/wire.rs +2 -1
  34. package/npm/install.mjs +56 -99
  35. package/package.json +4 -4
@@ -29,19 +29,11 @@ use crate::model::enums::{Provider, ProviderEffort};
29
29
  use crate::provider::adapters::pi::{build_pi_command_argv, PiCommandRequest, PiSessionSelector};
30
30
  use crate::provider::{CommandPlan, McpConfig, ProviderError, SessionId};
31
31
 
32
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
33
- pub(crate) enum PiExecutableFileType {
34
- Wrapper,
35
- Symlink,
36
- Binary,
37
- }
38
-
32
+ /// The first executable `pi` on PATH, exactly what the worker's bare `pi`
33
+ /// runs: a wrapper, npm symlink or plain binary alike. No inner binary is probed.
39
34
  #[derive(Debug, Clone, PartialEq, Eq)]
40
35
  pub(crate) struct PiExecutableChain {
41
36
  pub path_entry: PathBuf,
42
- pub path_entry_type: PiExecutableFileType,
43
- pub launch_executable: PathBuf,
44
- pub real_binary: PathBuf,
45
37
  pub pi_version: String,
46
38
  pub catalog_sha256: String,
47
39
  }
@@ -169,20 +161,13 @@ pub(crate) fn verify_started_pi_model(selected: &str, observed: &str) -> Result<
169
161
  }
170
162
 
171
163
  /// ---
172
- /// purpose: 校验 Pi launch/real path 与 live catalog;MCP 能力在实际 Pi context 验证
173
- /// returns: executable chain 与 catalog receipt 完整时成功
164
+ /// purpose: 校验 Pi PATH entry 与 live catalog;MCP 能力在实际 Pi context 验证
165
+ /// returns: PATH entry 与 catalog receipt 完整时成功
174
166
  /// errors: 缺路径或 catalog receipt 时返回 ProviderError
175
167
  /// ---
176
168
  pub(crate) fn validate_pi_executable_chain(chain: &PiExecutableChain) -> Result<(), ProviderError> {
177
169
  if !chain.path_entry.is_absolute()
178
- || !chain.launch_executable.is_absolute()
179
- || !chain.real_binary.is_absolute()
180
- || !matches!(
181
- chain.path_entry_type,
182
- PiExecutableFileType::Wrapper | PiExecutableFileType::Symlink
183
- )
184
- || chain.launch_executable != chain.path_entry
185
- || chain.real_binary == chain.launch_executable
170
+ || chain.path_entry.file_name().is_none_or(|name| name != "pi")
186
171
  || chain.catalog_sha256.len() != 64
187
172
  || !chain
188
173
  .catalog_sha256
@@ -479,21 +464,6 @@ fn sha256(bytes: &[u8]) -> String {
479
464
  format!("{:x}", Sha256::digest(bytes))
480
465
  }
481
466
 
482
- fn executable_file_type(path: &Path) -> Result<PiExecutableFileType, ProviderError> {
483
- let metadata = std::fs::symlink_metadata(path)
484
- .map_err(|error| ProviderError::Io(format!("{}: {error}", path.display())))?;
485
- if metadata.file_type().is_symlink() {
486
- return Ok(PiExecutableFileType::Symlink);
487
- }
488
- let bytes = std::fs::read(path)
489
- .map_err(|error| ProviderError::Io(format!("{}: {error}", path.display())))?;
490
- if bytes.starts_with(b"#!") {
491
- Ok(PiExecutableFileType::Wrapper)
492
- } else {
493
- Ok(PiExecutableFileType::Binary)
494
- }
495
- }
496
-
497
467
  #[cfg(test)]
498
468
  #[derive(Debug, Default)]
499
469
  pub(crate) struct PiCatalogTestObservation {
@@ -610,12 +580,7 @@ impl crate::provider::model_catalog::CatalogObserver for PiCatalogObserver {
610
580
  }
611
581
 
612
582
  pub(crate) fn pi_model_candidates(requested: &str) -> Result<Vec<String>, ProviderError> {
613
- let path = std::env::var_os("PATH")
614
- .ok_or_else(|| ProviderError::Command("PATH is not set".to_string()))?;
615
- let executable = std::env::split_paths(&path)
616
- .map(|directory| directory.join("pi"))
617
- .find(|candidate| candidate.is_file())
618
- .ok_or_else(|| ProviderError::Command("Pi executable not found on PATH".to_string()))?;
583
+ let executable = pi_path_entry()?;
619
584
  let catalog = run_pi_catalog(&executable, Duration::from_secs(10), 1024 * 1024)
620
585
  .map_err(ProviderError::Command)?;
621
586
  let models = parse_pi_list_models_table(&catalog)?;
@@ -629,21 +594,13 @@ pub(crate) fn pi_model_candidates(requested: &str) -> Result<Vec<String>, Provid
629
594
  .collect())
630
595
  }
631
596
 
632
- fn pi_path_entries() -> Result<Vec<PathBuf>, ProviderError> {
597
+ /// The shell's own PATH choice: the first executable `pi`, kept as found.
598
+ fn pi_path_entry() -> Result<PathBuf, ProviderError> {
633
599
  let path = std::env::var_os("PATH")
634
600
  .ok_or_else(|| ProviderError::Command("PATH is not set".to_string()))?;
635
- let mut seen = BTreeSet::new();
636
- let entries = std::env::split_paths(&path)
637
- .map(|directory| directory.join("pi"))
638
- .filter(|candidate| candidate.is_file())
639
- .filter(|candidate| seen.insert(candidate.clone()))
640
- .collect::<Vec<_>>();
641
- if entries.is_empty() {
642
- return Err(ProviderError::Command(
643
- "Pi executable not found on PATH".to_string(),
644
- ));
645
- }
646
- Ok(entries)
601
+ team_agent_contract::host::command::PublicCommand::resolve("pi", &path)
602
+ .map(|command| command.entry)
603
+ .map_err(|_| ProviderError::Command("Pi executable not found on PATH".to_string()))
647
604
  }
648
605
 
649
606
  fn command_stdout(executable: &Path, args: &[&str]) -> Result<Vec<u8>, ProviderError> {
@@ -675,53 +632,17 @@ fn command_stdout(executable: &Path, args: &[&str]) -> Result<Vec<u8>, ProviderE
675
632
  /// ---
676
633
  pub(crate) fn resolve_pi_executable_chain(
677
634
  ) -> Result<(PiExecutableChain, Vec<String>), ProviderError> {
678
- let path_entries = pi_path_entries()?;
679
- let path_entry = path_entries[0].clone();
680
- let path_entry_type = executable_file_type(&path_entry)?;
681
- if !matches!(
682
- path_entry_type,
683
- PiExecutableFileType::Wrapper | PiExecutableFileType::Symlink
684
- ) {
685
- return Err(ProviderError::Command(
686
- "the direct Pi PATH entry is not a verified wrapper or npm symlink".to_string(),
687
- ));
688
- }
635
+ // Probe through the PATH entry itself so a user wrapper sees every probe.
636
+ let path_entry = pi_path_entry()?;
689
637
  let version =
690
638
  String::from_utf8(command_stdout(&path_entry, &["--version"])?).map_err(|error| {
691
639
  ProviderError::Command(format!("Pi version output is not UTF-8: {error}"))
692
640
  })?;
693
- let version = version.trim().to_string();
694
- let launch_identity = std::fs::canonicalize(&path_entry)
695
- .map_err(|error| ProviderError::Io(format!("{}: {error}", path_entry.display())))?;
696
- let real_binary = if path_entry_type == PiExecutableFileType::Symlink {
697
- launch_identity
698
- } else {
699
- path_entries
700
- .iter()
701
- .find_map(|candidate| {
702
- let real = std::fs::canonicalize(candidate).ok()?;
703
- (real != launch_identity).then_some(real)
704
- })
705
- .ok_or_else(|| {
706
- ProviderError::Command(
707
- "Pi PATH wrapper has no independently resolved real executable".to_string(),
708
- )
709
- })?
710
- };
711
- let _real_version =
712
- String::from_utf8(command_stdout(&real_binary, &["--version"])?).map_err(|error| {
713
- ProviderError::Command(format!(
714
- "Pi real binary version output is not UTF-8: {error}"
715
- ))
716
- })?;
717
641
  let catalog = command_stdout(&path_entry, &["--list-models"])?;
718
642
  let models = parse_pi_list_models_table(&catalog)?;
719
643
  let chain = PiExecutableChain {
720
- path_entry: path_entry.clone(),
721
- path_entry_type,
722
- launch_executable: path_entry,
723
- real_binary,
724
- pi_version: version,
644
+ path_entry,
645
+ pi_version: version.trim().to_string(),
725
646
  catalog_sha256: sha256(&catalog),
726
647
  };
727
648
  validate_pi_executable_chain(&chain)?;
@@ -762,8 +683,8 @@ pub(crate) struct PiMaterializeRequest<'a> {
762
683
  }
763
684
 
764
685
  /// ---
765
- /// purpose: 共享物化 Pi leader 与 TeamMate 的 wrapper、UUID 和 CommandPlan
766
- /// returns: fresh Pi CommandPlan;isolated seats carry their session root, while the
686
+ /// purpose: 共享物化 Pi leader 与 TeamMate 的 wrapper 和 CommandPlan
687
+ /// returns: fresh Pi CommandPlan 不传 --session-id;isolated seats carry their session root, while the
767
688
  /// interactive leader preserves Pi's native default root
768
689
  /// errors: resolver、exact model、wrapper 或 argv 构造失败时返回 ProviderError
769
690
  /// ---
@@ -858,19 +779,16 @@ fn materialize_pi_plan_with_session(
858
779
  })?;
859
780
  (argv, None)
860
781
  } else {
861
- let session_id = new_pi_session_id();
862
782
  let argv = build_pi_command_argv(PiCommandRequest {
863
783
  extension: &wrapper,
864
784
  model: model.as_deref(),
865
785
  effort: request.effort,
866
786
  system_prompt: request.system_prompt,
867
787
  session_dir,
868
- session: PiSessionSelector::Fresh {
869
- session_id: session_id.as_str(),
870
- },
788
+ session: PiSessionSelector::Fresh,
871
789
  agent_id: request.agent_id,
872
790
  })?;
873
- (argv, Some(session_id))
791
+ (argv, None)
874
792
  };
875
793
  Ok(CommandPlan {
876
794
  argv,
@@ -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"`.
@@ -840,18 +840,17 @@ fn a09_resume_retains_session_metadata_while_routes_change() {
840
840
  let f = Fixture::new("argv-resume");
841
841
  f.start_team("pi", &["worker"]);
842
842
  let selected = crate::state::projection::select_runtime_state(&f.ws, Some("argvteam")).unwrap();
843
- let pending = selected["agents"]["worker"]["_pending_session_id"]
844
- .as_str()
845
- .unwrap()
846
- .to_string();
843
+ // Fresh Pi assigns its own session id; capture records it afterwards.
844
+ assert!(selected["agents"]["worker"]["_pending_session_id"].is_null());
845
+ let session_id = "8d6c1f2e-4a5b-4c7d-9e0f-a09000000001";
847
846
  let session = crate::lifecycle::launch::pi_mcp::pi_seat_paths(&f.ws, "argvteam", "worker")
848
847
  .sessions
849
848
  .join("valid.jsonl");
850
849
  fs::create_dir_all(session.parent().unwrap()).unwrap();
851
- fs::write(&session, format!("{}\n{}\n", json!({"type":"session","version":3,"id":pending,"cwd":f.ws,"timestamp":"2026-01-01T00:00:00Z"}), json!({"type":"message","id":"a","parentId":null,"timestamp":"2026-01-01T00:00:01Z","message":{"role":"user","content":[{"type":"text","text":"seed"}]}}))).unwrap();
850
+ fs::write(&session, format!("{}\n{}\n", json!({"type":"session","version":3,"id":session_id,"cwd":f.ws,"timestamp":"2026-01-01T00:00:00Z"}), json!({"type":"message","id":"a","parentId":null,"timestamp":"2026-01-01T00:00:01Z","message":{"role":"user","content":[{"type":"text","text":"seed"}]}}))).unwrap();
852
851
  f.mutate_agent("worker", |a| {
853
852
  a["status"] = json!("stopped");
854
- a["session_id"] = json!(pending);
853
+ a["session_id"] = json!(session_id);
855
854
  a["rollout_path"] = json!(session);
856
855
  a["captured_at"] = json!("2026-01-01T00:00:01Z");
857
856
  a["captured_via"] = json!("session_scan");
@@ -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));
@@ -92,9 +92,7 @@ fn command_for_model(model: &str) -> Vec<String> {
92
92
  effort: Some(ProviderEffort::Medium),
93
93
  system_prompt: "worker contract",
94
94
  session_dir: Some(Path::new("/workspace/.team/runtime/pi/t1/w1/sessions")),
95
- session: PiSessionSelector::Fresh {
96
- session_id: "716ba0cb-c491-4471-b41a-43c8d5e1f05a",
97
- },
95
+ session: PiSessionSelector::Fresh,
98
96
  agent_id: "w1",
99
97
  })
100
98
  .expect("catalog member must build a semantic Pi argv")