@team-agent/installer 0.5.126 → 0.5.128

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 (187) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +11 -0
  4. package/crates/team-agent/src/cli/adapters.rs +3 -13
  5. package/crates/team-agent/src/cli/arguments.rs +4 -0
  6. package/crates/team-agent/src/cli/diagnose.rs +68 -91
  7. package/crates/team-agent/src/cli/emit.rs +61 -28
  8. package/crates/team-agent/src/cli/grok_slot.rs +88 -3
  9. package/crates/team-agent/src/cli/intent/runtime.rs +38 -9
  10. package/crates/team-agent/src/cli/intent/runtime_tests.rs +147 -11
  11. package/crates/team-agent/src/cli/intent/tests.rs +10 -12
  12. package/crates/team-agent/src/cli/intent.rs +1 -1
  13. package/crates/team-agent/src/cli/mod.rs +38 -9
  14. package/crates/team-agent/src/cli/models.rs +789 -186
  15. package/crates/team-agent/src/cli/schedule.rs +175 -0
  16. package/crates/team-agent/src/cli/send/persist.rs +0 -36
  17. package/crates/team-agent/src/cli/send/presentation.rs +1 -1
  18. package/crates/team-agent/src/cli/send.rs +108 -110
  19. package/crates/team-agent/src/cli/spec.rs +6 -0
  20. package/crates/team-agent/src/cli/status_port/brief.rs +5 -67
  21. package/crates/team-agent/src/cli/tests/leader_watch.rs +12 -62
  22. package/crates/team-agent/src/cli/tests/mod.rs +3 -3
  23. package/crates/team-agent/src/cli/tests/named_address.rs +11 -10
  24. package/crates/team-agent/src/cli/tests/run_delegation.rs +12 -9
  25. package/crates/team-agent/src/cli/tests/status_send.rs +70 -273
  26. package/crates/team-agent/src/compiler/tests.rs +39 -27
  27. package/crates/team-agent/src/compiler.rs +206 -6
  28. package/crates/team-agent/src/contract_runtime/backend.rs +181 -11
  29. package/crates/team-agent/src/contract_runtime/commands.rs +338 -7
  30. package/crates/team-agent/src/contract_runtime/config.rs +30 -19
  31. package/crates/team-agent/src/contract_runtime/config_tests.rs +24 -4
  32. package/crates/team-agent/src/contract_runtime/discovery.rs +12 -1
  33. package/crates/team-agent/src/contract_runtime/fork.rs +3 -10
  34. package/crates/team-agent/src/contract_runtime/framework.rs +28 -14
  35. package/crates/team-agent/src/contract_runtime/mcp.rs +19 -24
  36. package/crates/team-agent/src/contract_runtime/prompt.rs +2 -2
  37. package/crates/team-agent/src/contract_runtime/registry.rs +93 -130
  38. package/crates/team-agent/src/coordinator/steps/abnormal.rs +45 -5
  39. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +8 -29
  40. package/crates/team-agent/src/coordinator/tests/energy.rs +4 -4
  41. package/crates/team-agent/src/coordinator/tests/health_sync.rs +44 -2
  42. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +2 -2
  43. package/crates/team-agent/src/coordinator/tests/spine.rs +1 -1
  44. package/crates/team-agent/src/coordinator/tests/takeover.rs +3 -3
  45. package/crates/team-agent/src/coordinator/tick.rs +1 -89
  46. package/crates/team-agent/src/db/message_store.rs +7 -65
  47. package/crates/team-agent/src/direct_delivery.rs +368 -0
  48. package/crates/team-agent/src/inbox_store.rs +169 -0
  49. package/crates/team-agent/src/leader/registry.rs +5 -0
  50. package/crates/team-agent/src/leader/start.rs +2 -1
  51. package/crates/team-agent/src/leader/tests/lease_api.rs +2 -2
  52. package/crates/team-agent/src/leader/tests/prompt_contract.rs +1 -0
  53. package/crates/team-agent/src/lib.rs +2 -0
  54. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +33 -0
  55. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +206 -1
  56. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +28 -2
  57. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +36 -179
  58. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +87 -6
  59. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +13 -488
  60. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +351 -81
  61. package/crates/team-agent/src/lifecycle/launch/pi_mcp_extension.js +3 -4
  62. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +26 -2
  63. package/crates/team-agent/src/lifecycle/launch/spawn.rs +41 -31
  64. package/crates/team-agent/src/lifecycle/launch.rs +27 -12
  65. package/crates/team-agent/src/lifecycle/profile_launch.rs +318 -64
  66. package/crates/team-agent/src/lifecycle/restart/agent.rs +1 -0
  67. package/crates/team-agent/src/lifecycle/restart/avatar.rs +1798 -0
  68. package/crates/team-agent/src/lifecycle/restart/claude_fork.rs +163 -0
  69. package/crates/team-agent/src/lifecycle/restart/common.rs +298 -133
  70. package/crates/team-agent/src/lifecycle/restart/remove.rs +129 -0
  71. package/crates/team-agent/src/lifecycle/restart/selection.rs +5 -5
  72. package/crates/team-agent/src/lifecycle/restart.rs +4 -0
  73. package/crates/team-agent/src/lifecycle/role_config.rs +79 -27
  74. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +1 -1
  75. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +8 -12
  76. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +37 -240
  77. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +325 -0
  78. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +320 -8
  79. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +329 -70
  80. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +378 -4
  81. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +25 -39
  82. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +7 -11
  83. package/crates/team-agent/src/lifecycle/tests/core.rs +39 -36
  84. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +22 -8
  85. package/crates/team-agent/src/lifecycle/tests/fixtures/pi_native_mcp_host.mjs +2 -1
  86. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +15 -133
  87. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +60 -20
  88. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +30 -67
  89. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +3 -31
  90. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +194 -169
  91. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +164 -282
  92. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +15 -78
  93. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +7 -7
  94. package/crates/team-agent/src/lifecycle/tests/mcp_tool_name_format_red.rs +6 -6
  95. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +75 -69
  96. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +2 -10
  97. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +18 -6
  98. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +70 -52
  99. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +210 -0
  100. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +157 -4
  101. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +526 -10
  102. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +1419 -0
  103. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +68 -1
  104. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +34 -12
  105. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +94 -2
  106. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +14 -15
  107. package/crates/team-agent/src/lifecycle/tests/restart.rs +12 -153
  108. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +27 -5
  109. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +59 -10
  110. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +47 -6
  111. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +3 -1374
  112. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +27 -10
  113. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +7 -7
  114. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +67 -313
  115. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +254 -2
  116. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +2 -2
  117. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +1 -1
  118. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +2 -2
  119. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +4 -4
  120. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +74 -19
  121. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +38 -39
  122. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +51 -88
  123. package/crates/team-agent/src/lifecycle/tests.rs +3 -4
  124. package/crates/team-agent/src/lifecycle/types.rs +18 -5
  125. package/crates/team-agent/src/lifecycle/worker_command_context.rs +43 -50
  126. package/crates/team-agent/src/mcp_server/readiness.rs +130 -149
  127. package/crates/team-agent/src/mcp_server/readiness_tests.rs +86 -109
  128. package/crates/team-agent/src/mcp_server/tests/scoped.rs +21 -31
  129. package/crates/team-agent/src/mcp_server/tests/send.rs +72 -107
  130. package/crates/team-agent/src/mcp_server/tests/tools.rs +10 -12
  131. package/crates/team-agent/src/mcp_server/tools.rs +70 -196
  132. package/crates/team-agent/src/messaging/delivery.rs +143 -253
  133. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +5 -5
  134. package/crates/team-agent/src/messaging/helpers.rs +1 -19
  135. package/crates/team-agent/src/messaging/mod.rs +1 -0
  136. package/crates/team-agent/src/messaging/reminders.rs +316 -0
  137. package/crates/team-agent/src/messaging/scheduler.rs +7 -1
  138. package/crates/team-agent/src/messaging/tests/dup_inject.rs +255 -150
  139. package/crates/team-agent/src/messaging/tests/main_preserved.rs +2 -2
  140. package/crates/team-agent/src/messaging/tests/runtime.rs +9 -115
  141. package/crates/team-agent/src/messaging/tests/spine.rs +44 -24
  142. package/crates/team-agent/src/messaging/tests/wave2.rs +13 -20
  143. package/crates/team-agent/src/messaging/types.rs +1 -0
  144. package/crates/team-agent/src/provider/adapter.rs +208 -254
  145. package/crates/team-agent/src/provider/adapters/claude.rs +78 -0
  146. package/crates/team-agent/src/provider/adapters/claude_fork.rs +131 -0
  147. package/crates/team-agent/src/provider/adapters/mod.rs +7 -7
  148. package/crates/team-agent/src/provider/adapters/pi.rs +106 -0
  149. package/crates/team-agent/src/provider/classify.rs +1 -66
  150. package/crates/team-agent/src/provider/model_catalog.rs +201 -13
  151. package/crates/team-agent/src/provider/session/capture.rs +111 -111
  152. package/crates/team-agent/src/provider/session/context_fork/claude.rs +123 -0
  153. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +10 -18
  154. package/crates/team-agent/src/provider/session/context_fork.rs +87 -74
  155. package/crates/team-agent/src/provider/session/mod.rs +2 -3
  156. package/crates/team-agent/src/provider/session_scan/claude.rs +523 -0
  157. package/crates/team-agent/src/provider/session_scan/common.rs +47 -47
  158. package/crates/team-agent/src/provider/session_scan/pi.rs +34 -1
  159. package/crates/team-agent/src/provider/session_scan.rs +13 -13
  160. package/crates/team-agent/src/provider/tests/adapter.rs +127 -121
  161. package/crates/team-agent/src/provider/tests/classify.rs +0 -53
  162. package/crates/team-agent/src/provider/tests/command_helpers.rs +11 -19
  163. package/crates/team-agent/src/provider/tests/idle.rs +13 -19
  164. package/crates/team-agent/src/provider/types.rs +0 -4
  165. package/crates/team-agent/src/provider/wire.rs +34 -20
  166. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +1 -1
  167. package/crates/team-agent/src/state/persist.rs +6 -6
  168. package/crates/team-agent/src/state/projection.rs +1 -1
  169. package/crates/team-agent/src/state/repository/tests.rs +2 -2
  170. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +144 -0
  171. package/crates/team-agent/src/tmux_backend/tests.rs +0 -151
  172. package/crates/team-agent/src/tmux_backend.rs +9 -43
  173. package/package.json +4 -4
  174. package/skills/team-agent/SKILL.md +7 -8
  175. package/skills/team-agent/command-coverage.json +15 -1
  176. package/skills/team-agent/docs/reference/team-agent-operator.md +5 -3
  177. package/skills/team-agent/references/team-agent-operator.md +5 -3
  178. package/crates/team-agent/src/lifecycle/launch/grok_per_seat.rs +0 -260
  179. package/crates/team-agent/src/lifecycle/tests/codex_weak_window_attribution_red.rs +0 -683
  180. package/crates/team-agent/src/lifecycle/tests/grok_effort_argv_red.rs +0 -247
  181. package/crates/team-agent/src/lifecycle/tests/grok_mcp_overlay_red.rs +0 -507
  182. package/crates/team-agent/src/lifecycle/tests/grok_restart_resume_red.rs +0 -300
  183. package/crates/team-agent/src/provider/adapters/codex.rs +0 -101
  184. package/crates/team-agent/src/provider/adapters/grok.rs +0 -67
  185. package/crates/team-agent/src/provider/session/context_fork/codex.rs +0 -514
  186. package/crates/team-agent/src/provider/session_scan/codex.rs +0 -326
  187. package/crates/team-agent/src/provider/session_scan/grok.rs +0 -288
@@ -348,6 +348,114 @@ pub struct CompiledRole {
348
348
  pub agent: Value,
349
349
  }
350
350
 
351
+ #[derive(Debug, Clone, PartialEq, Eq)]
352
+ pub struct PiModelPreflightError {
353
+ pub requested: String,
354
+ pub candidates: Vec<String>,
355
+ pub action: String,
356
+ pub not_ready: bool,
357
+ }
358
+
359
+ impl std::fmt::Display for PiModelPreflightError {
360
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361
+ write!(
362
+ formatter,
363
+ "Pi role model {:?} is not a qualified exact model",
364
+ self.requested
365
+ )
366
+ }
367
+ }
368
+
369
+ /// Shared admission gate: omitted and qualified models pass; only an
370
+ /// unqualified present model causes one bounded catalog observation.
371
+ pub fn preflight_pi_role_model(meta: &Value) -> Result<(), PiModelPreflightError> {
372
+ preflight_pi_role_model_with(meta, |requested| {
373
+ crate::lifecycle::launch::pi_mcp::pi_model_candidates(requested).map_err(|_| ())
374
+ })
375
+ }
376
+
377
+ pub fn preflight_pi_role_model_with<F>(
378
+ meta: &Value,
379
+ mut discover: F,
380
+ ) -> Result<(), PiModelPreflightError>
381
+ where
382
+ F: FnMut(&str) -> Result<Vec<String>, ()>,
383
+ {
384
+ if parse_canonical_provider(meta.get("provider").and_then(Value::as_str).unwrap_or(""))
385
+ != Some(Provider::Pi)
386
+ {
387
+ return Ok(());
388
+ }
389
+ let Some(model) = string_field(meta, "model").filter(|value| !value.trim().is_empty()) else {
390
+ return Ok(());
391
+ };
392
+ let requested = model.trim().to_string();
393
+ if requested.split_once('/').is_some_and(|(provider, name)| {
394
+ !provider.is_empty() && !name.is_empty() && !requested.contains('*')
395
+ }) {
396
+ return Ok(());
397
+ }
398
+ let (candidates, not_ready) = match discover(&requested) {
399
+ Ok(candidates) => (candidates, false),
400
+ Err(()) => (Vec::new(), true),
401
+ };
402
+ let action = if candidates.is_empty() {
403
+ format!("run `team-agent models --provider pi --search {requested}`")
404
+ } else {
405
+ format!("copy a candidate into the role, or run `team-agent models --provider pi --search {requested}`")
406
+ };
407
+ Err(PiModelPreflightError {
408
+ requested,
409
+ candidates,
410
+ action,
411
+ not_ready,
412
+ })
413
+ }
414
+
415
+ pub fn preflight_pi_models_in_team(team_dir: &Path) -> Result<(), PiModelPreflightError> {
416
+ preflight_pi_models_in_team_with(team_dir, |requested| {
417
+ crate::lifecycle::launch::pi_mcp::pi_model_candidates(requested).map_err(|_| ())
418
+ })
419
+ }
420
+
421
+ pub fn preflight_pi_models_in_team_with<F>(
422
+ team_dir: &Path,
423
+ mut discover: F,
424
+ ) -> Result<(), PiModelPreflightError>
425
+ where
426
+ F: FnMut(&str) -> Result<Vec<String>, ()>,
427
+ {
428
+ let agents_dir = team_dir.join("agents");
429
+ let entries = match std::fs::read_dir(&agents_dir) {
430
+ Ok(entries) => entries,
431
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
432
+ Err(_) => {
433
+ return Err(PiModelPreflightError {
434
+ requested: "<role directory>".into(),
435
+ candidates: Vec::new(),
436
+ action: "repair the role directory and retry".into(),
437
+ not_ready: true,
438
+ })
439
+ }
440
+ };
441
+ let mut paths = entries
442
+ .filter_map(Result::ok)
443
+ .map(|entry| entry.path())
444
+ .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("md"))
445
+ .collect::<Vec<_>>();
446
+ paths.sort();
447
+ for path in paths {
448
+ let (meta, _) = read_front_matter(&path).map_err(|_| PiModelPreflightError {
449
+ requested: path.display().to_string(),
450
+ candidates: Vec::new(),
451
+ action: "repair the role document and retry".into(),
452
+ not_ready: true,
453
+ })?;
454
+ preflight_pi_role_model_with(&meta, &mut discover)?;
455
+ }
456
+ Ok(())
457
+ }
458
+
351
459
  /// 把一份 role 文档编译成 agent spec 条目。`team_meta` 供 model/auth_mode 继承;
352
460
  /// `workspace_s` 是 working_directory。**纯读 `role_path`,无任何文件落地。**
353
461
  pub fn compile_role_agent(
@@ -386,7 +494,9 @@ fn compile_role_agent_with_mode(
386
494
  let provider = string_field(&meta, "provider")
387
495
  .filter(|provider| !provider.trim().is_empty())
388
496
  .unwrap_or_else(|| "pi".to_string());
389
- // An exact boolean opt-in; a bare shared key (codex) keeps its legacy meaning.
497
+ let is_pi = parse_canonical_provider(&provider) == Some(Provider::Pi);
498
+ // An exact boolean; every contract name (codex, grok, cursor, ...) selects
499
+ // its leaf without it, `true` only insists on a contract leaf.
390
500
  let contract_runtime = match meta.get("contract_runtime") {
391
501
  None => false,
392
502
  Some(Value::Bool(value)) => *value,
@@ -398,7 +508,7 @@ fn compile_role_agent_with_mode(
398
508
  }
399
509
  };
400
510
  #[cfg(unix)]
401
- let contract = crate::contract_runtime::registry::declared(&provider, contract_runtime);
511
+ let contract = crate::contract_runtime::registry::declared(&provider);
402
512
  #[cfg(not(unix))]
403
513
  let contract: Option<()> = None;
404
514
  if contract_runtime && contract.is_none() {
@@ -420,6 +530,7 @@ fn compile_role_agent_with_mode(
420
530
  contract.is_some_and(|descriptor| !descriptor.effort.inherit_team_default);
421
531
  #[cfg(not(unix))]
422
532
  let skip_team_effort = false;
533
+ validate_pi_role_fields(&meta, role_path, &provider)?;
423
534
  let model = string_field(&meta, "model")
424
535
  .filter(|value| !value.trim().is_empty())
425
536
  .map(Value::Str)
@@ -427,6 +538,12 @@ fn compile_role_agent_with_mode(
427
538
  let auth_mode = string_field(&meta, "auth_mode")
428
539
  .or_else(|| string_field(team_meta, "default_auth_mode"))
429
540
  .unwrap_or_else(|| "subscription".to_string());
541
+ if is_pi && auth_mode != "subscription" {
542
+ return Err(ModelError::Validation(format!(
543
+ "{}: Pi roles support subscription auth_mode only",
544
+ role_path.display()
545
+ )));
546
+ }
430
547
  if auth_mode != "subscription" && meta.get("profile").is_none() {
431
548
  return Err(ModelError::Validation(format!(
432
549
  "{}: profile is required when auth_mode is '{auth_mode}'",
@@ -472,9 +589,8 @@ fn compile_role_agent_with_mode(
472
589
  if let Some(profile) = string_field(&meta, "profile") {
473
590
  agent_items.push(("profile", Value::Str(profile)));
474
591
  }
475
- // Role effort wins; a contract leaf that does not inherit the team default
476
- // uses only an explicit role value. Legacy providers may inherit TEAM
477
- // provider_effort for Issue #238 compatibility.
592
+ // Role effort wins; Pi uses only an explicit role value. Other providers may
593
+ // inherit TEAM provider_effort for Issue #238 compatibility.
478
594
  let role_effort = match string_field(&meta, "effort") {
479
595
  Some(raw) if !raw.trim().is_empty() => {
480
596
  let value = raw.trim();
@@ -492,7 +608,7 @@ fn compile_role_agent_with_mode(
492
608
  Some(raw) if !raw.trim().is_empty() => ProviderEffort::parse(raw.trim()),
493
609
  _ => None,
494
610
  };
495
- let resolved_effort = if skip_team_effort {
611
+ let resolved_effort = if is_pi || skip_team_effort {
496
612
  role_effort
497
613
  } else {
498
614
  role_effort.or(team_effort)
@@ -590,6 +706,27 @@ fn string_field(meta: &Value, key: &str) -> Option<String> {
590
706
  .map(ToString::to_string)
591
707
  }
592
708
 
709
+ fn validate_pi_role_fields(meta: &Value, path: &Path, provider: &str) -> Result<(), ModelError> {
710
+ if parse_canonical_provider(provider) != Some(Provider::Pi) {
711
+ return Ok(());
712
+ }
713
+ if let Some(model) = string_field(meta, "model").filter(|value| !value.trim().is_empty()) {
714
+ let (catalog, name) = model.trim().split_once('/').ok_or_else(|| {
715
+ ModelError::Validation(format!(
716
+ "{}: Pi roles require a qualified exact model such as provider/model",
717
+ path.display()
718
+ ))
719
+ })?;
720
+ if catalog.is_empty() || name.is_empty() || model.contains('*') {
721
+ return Err(ModelError::Validation(format!(
722
+ "{}: Pi roles require a qualified exact model",
723
+ path.display()
724
+ )));
725
+ }
726
+ }
727
+ Ok(())
728
+ }
729
+
593
730
  fn optional_dangerously_skip_permissions(meta: &Value) -> bool {
594
731
  match meta.get("dangerously_skip_permissions") {
595
732
  Some(Value::Bool(value)) => *value,
@@ -618,6 +755,69 @@ fn int_field(meta: &Value, key: &str, default: i64) -> Value {
618
755
  }
619
756
  }
620
757
 
758
+ #[cfg(test)]
759
+ mod pi_preflight_tests {
760
+ use super::*;
761
+ use std::cell::Cell;
762
+
763
+ fn role(provider: &str, model: Option<&str>) -> Value {
764
+ let mut fields = vec![("provider".to_string(), Value::Str(provider.into()))];
765
+ if let Some(model) = model {
766
+ fields.push(("model".to_string(), Value::Str(model.into())));
767
+ }
768
+ Value::Map(fields)
769
+ }
770
+
771
+ #[test]
772
+ fn omitted_qualified_and_non_pi_do_not_discover() {
773
+ for meta in [
774
+ role("pi", None),
775
+ role("pi", Some("openai/gpt-5")),
776
+ role("codex", Some("gpt-5")),
777
+ ] {
778
+ let calls = Cell::new(0);
779
+ assert!(preflight_pi_role_model_with(&meta, |_| {
780
+ calls.set(calls.get() + 1);
781
+ Ok(vec![])
782
+ })
783
+ .is_ok());
784
+ assert_eq!(calls.get(), 0);
785
+ }
786
+ }
787
+
788
+ #[test]
789
+ fn unqualified_discovers_once_and_projects_candidates() {
790
+ let calls = Cell::new(0);
791
+ let error = preflight_pi_role_model_with(&role("pi", Some("gpt-5.6-sol")), |requested| {
792
+ calls.set(calls.get() + 1);
793
+ assert_eq!(requested, "gpt-5.6-sol");
794
+ Ok(vec![
795
+ "openai-codex/gpt-5.6-sol".into(),
796
+ "azure/gpt-5.6-sol".into(),
797
+ ])
798
+ })
799
+ .expect_err("unqualified model must fail closed");
800
+ assert_eq!(calls.get(), 1);
801
+ assert_eq!(
802
+ error.candidates,
803
+ vec!["openai-codex/gpt-5.6-sol", "azure/gpt-5.6-sol"]
804
+ );
805
+ assert!(!error.not_ready);
806
+ assert!(error
807
+ .action
808
+ .contains("team-agent models --provider pi --search gpt-5.6-sol"));
809
+ }
810
+
811
+ #[test]
812
+ fn catalog_failure_is_not_ready_without_partial_candidates() {
813
+ let error = preflight_pi_role_model_with(&role("pi", Some("gpt-5.6-sol")), |_| Err(()))
814
+ .expect_err("catalog failure must reject");
815
+ assert!(error.not_ready);
816
+ assert!(error.candidates.is_empty());
817
+ assert!(!error.to_string().contains("stderr"));
818
+ }
819
+ }
820
+
621
821
  fn py_int_value(value: &Value) -> Option<i64> {
622
822
  match value {
623
823
  Value::Bool(b) => Some(if *b { 1 } else { 0 }),
@@ -470,7 +470,7 @@ fn preflight_request(
470
470
  discovered: &Discovery,
471
471
  ) -> Result<LaunchRequest, BackendError> {
472
472
  let mut request = request(binding, role, identity, discovered)?;
473
- if matches!(registry::provider(role.provider.as_str())?, registry::NativeProvider::GrokBuild | registry::NativeProvider::Codex | registry::NativeProvider::Pi | registry::NativeProvider::Claude) {
473
+ if matches!(registry::provider(role.provider.as_str())?, registry::NativeProvider::Codex) {
474
474
  // Pure H2 only: this is a proposed private path, not a filesystem receipt.
475
475
  request.paths.cwd = team_agent_contract::contract::session::CwdIdentity {
476
476
  path: binding.transport_root.join("workspaces").join(role.id.as_str()),
@@ -487,11 +487,8 @@ pub(super) fn require_private_primary(
487
487
  cwd: &team_agent_contract::contract::session::CwdIdentity,
488
488
  ) -> Result<(), BackendError> {
489
489
  match selected {
490
- registry::NativeProvider::GrokBuild => team_agent_contract::providers::grok_build::native::require_private_primary(cwd)?,
491
490
  registry::NativeProvider::Codex => team_agent_contract::providers::codex::launcher::require_private_primary(cwd)?,
492
- registry::NativeProvider::Pi => team_agent_contract::providers::pi::launcher::require_private_primary(cwd)?,
493
- registry::NativeProvider::Claude => team_agent_contract::providers::claude::launcher::require_private_primary(cwd)?,
494
- registry::NativeProvider::Kiro | registry::NativeProvider::Cursor => {}
491
+ registry::NativeProvider::GrokBuild | registry::NativeProvider::Kiro | registry::NativeProvider::Cursor | registry::NativeProvider::Pi | registry::NativeProvider::Claude => {}
495
492
  }
496
493
  Ok(())
497
494
  }
@@ -577,6 +574,8 @@ fn existing_start(backend: &Backend, seat: &SeatId) -> Result<Option<ExistingSta
577
574
  return match backend.store.creation_receipt(seat, None)? {
578
575
  None => Ok(None),
579
576
  Some(record) if record.outcome == Outcome::Compensated => Ok(None),
577
+ // remove/reset ended this identity explicitly; the next start is fresh.
578
+ Some(record) if backend.store.retired(&record.target.identity)? => Ok(None),
580
579
  Some(_) => Err(Error::Fence.into()),
581
580
  };
582
581
  };
@@ -596,6 +595,49 @@ pub(super) fn require_candidate(binding: &Binding) -> Result<(), BackendError> {
596
595
  Ok(())
597
596
  }
598
597
 
598
+ /// Explicit discard-session may adopt an upgraded binary at the SAME installed
599
+ /// path, but only while every native seat is stopped and all operations ended.
600
+ /// Ordinary start/resume/MCP calls retain the exact candidate fingerprint fence.
601
+ pub(super) fn refresh_quiescent_candidate(workspace: &Path, team: &str, seat: &SeatId) -> Result<(), BackendError> {
602
+ use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
603
+ let mut backend = Backend::open(workspace, team)?;
604
+ let candidate = std::env::current_exe()?.canonicalize()?;
605
+ if candidate != backend.binding.candidate { return Err(Error::Fence.into()); }
606
+ let fingerprint = fingerprint_file(&candidate, 1024 * 1024 * 1024, Duration::from_secs(10))?;
607
+ if fingerprint == backend.binding.candidate_sha256 { return Ok(()); }
608
+ let root = root_for(workspace, &backend.binding.scope);
609
+ if root.canonicalize()? != root { return Err(Error::Fence.into()); }
610
+ let directory = std::fs::File::open(&root)?;
611
+ if !crate::platform::file_lock::try_lock_once_nonblocking(&directory)? { return Err(Error::Conflict.into()); }
612
+ if !backend.store.unfinished()?.is_empty() { return Err(Error::Conflict.into()); }
613
+ for current in backend.store.seats()? {
614
+ if current.status != SeatStatus::Stopped || backend.store.leased(&current.identity.seat)?
615
+ || current.physical.as_ref().is_some_and(|target| !matches!(
616
+ team_agent_contract::host::process::sample_process(&target.process),
617
+ team_agent_contract::host::process::ProcessState::Exited | team_agent_contract::host::process::ProcessState::Replaced)) {
618
+ return Err(Error::Invalid("stop the native cohort before upgrading its candidate binding").into());
619
+ }
620
+ }
621
+ let path = root.join("framework-binding.json");
622
+ let metadata = std::fs::symlink_metadata(&path)?;
623
+ if !metadata.is_file() || metadata.uid() != unsafe { libc::geteuid() }
624
+ || metadata.nlink() != 1 || metadata.mode() & 0o022 != 0 { return Err(Error::Fence.into()); }
625
+ let before = std::fs::read(&path)?;
626
+ backend.binding.candidate_sha256 = fingerprint;
627
+ let temporary = root.join(format!("binding-{}.tmp", backend.store.propose_identity(seat)?.instance.as_str()));
628
+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(metadata.mode() & 0o777).open(&temporary)?;
629
+ let result = (|| -> Result<(), BackendError> {
630
+ file.write_all(&serde_json::to_vec(&backend.binding).map_err(|_| BackendError::Metadata)?)?;
631
+ file.sync_all()?;
632
+ if std::fs::read(&path)? != before { return Err(Error::Fence.into()); }
633
+ std::fs::rename(&temporary, &path)?;
634
+ directory.sync_all()?;
635
+ Ok(())
636
+ })();
637
+ if result.is_err() { let _ = std::fs::remove_file(&temporary); }
638
+ result
639
+ }
640
+
599
641
  fn validate_existing(backend: &Backend, role: &RoleConfig, record: &OperationRecord) -> Result<SeatRecord, BackendError> {
600
642
  let current = backend.store.assert_current(&record.target.identity)?;
601
643
  if current.evidence_kind != EvidenceKind::Native || current.provider != role.provider
@@ -626,7 +668,7 @@ pub(crate) fn start_needs_reconciliation(workspace: &Path, team: &str, seat: &Se
626
668
  require_candidate(&backend.binding)?;
627
669
  let class = existing_start(&backend, seat)?;
628
670
  let current = backend.store.seat(seat)?;
629
- if current.as_ref().is_some_and(|seat| row.get("provider").and_then(serde_json::Value::as_str) != Some(seat.provider.as_str())) {
671
+ if current.as_ref().is_some_and(|seat| !registry::same_provider(row.get("provider").and_then(serde_json::Value::as_str).unwrap_or(""), seat.provider.as_str())) {
630
672
  return Err(Error::Fence.into());
631
673
  }
632
674
  let matches = |identity: &InstanceIdentity| {
@@ -726,12 +768,10 @@ pub(super) fn publish_framework_routes(backend: &mut Backend, members: &[MemberR
726
768
  /// The native session ID a launch names before spawn, for the leaves whose
727
769
  /// fresh session is `Preassigned`. Shared by fresh start and a native fork's child.
728
770
  pub(super) fn preassign_session(
729
- selected: registry::NativeProvider,
730
771
  request: &mut LaunchRequest,
731
772
  discovered: &Discovery,
732
773
  ) -> Result<(), BackendError> {
733
- if selected == registry::NativeProvider::Claude {
734
- // `--session-id` names the new session; derived from this proposed instance.
774
+ if matches!(&discovered.runtime, Some(registry::NativeRuntime::Claude(_))) {
735
775
  request.preassigned_session = Some(team_agent_contract::providers::claude::session_id(&request.identity));
736
776
  }
737
777
  if let Some(registry::NativeRuntime::Cursor(runtime)) = &discovered.runtime {
@@ -846,7 +886,7 @@ pub fn start(
846
886
  request.paths.cwd = super::workspace::prepare(&backend.binding, &role.id)?;
847
887
  }
848
888
  require_private_primary(selected, &request.paths.cwd)?;
849
- preassign_session(selected, &mut request, &discovered)?;
889
+ preassign_session(&mut request, &discovered)?;
850
890
  let resolved = resolve_launch(
851
891
  descriptor,
852
892
  &hooks,
@@ -923,7 +963,7 @@ pub(crate) fn prepare_restart(
923
963
  directory: &Path,
924
964
  state: &serde_json::Value,
925
965
  ) -> Result<Vec<PreparedResume>, BackendError> {
926
- let config = super::framework::team_config(workspace, directory, team)?.ok_or(BackendError::Metadata)?;
966
+ let config = super::framework::team_config(workspace, directory, team, None)?.ok_or(BackendError::Metadata)?;
927
967
  let mut prepared = Vec::new();
928
968
  let agents = state.get("agents").and_then(serde_json::Value::as_object).ok_or(BackendError::Metadata)?;
929
969
  for (id, _) in agents.iter().filter(|(_, row)| {
@@ -1178,6 +1218,16 @@ impl OwnedIo for NoNewIo {
1178
1218
  }
1179
1219
  }
1180
1220
 
1221
+ /// Retire a stopped seat's current identity. None: the store holds no seat
1222
+ /// for this ID (never started, or already retired).
1223
+ pub(crate) fn retire(workspace: &Path, team: &str, seat: &SeatId) -> Result<Option<SeatRecord>, BackendError> {
1224
+ let mut backend = Backend::open(workspace, team)?;
1225
+ let Some(current) = backend.store.seat(seat)? else {
1226
+ return Ok(None);
1227
+ };
1228
+ Ok(Some(backend.store.retire(&current.identity)?))
1229
+ }
1230
+
1181
1231
  pub fn stop(workspace: &Path, team: &str, seat: &SeatId) -> Result<OperationRecord, BackendError> {
1182
1232
  let mut backend = Backend::open(workspace, team)?;
1183
1233
  let target = backend
@@ -1222,6 +1272,7 @@ mod tests {
1222
1272
  let root = std::env::temp_dir().join(format!("contract-role-{}-{}", std::process::id(),
1223
1273
  std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
1224
1274
  std::fs::DirBuilder::new().mode(0o700).create(&root).unwrap();
1275
+ let root = root.canonicalize().unwrap();
1225
1276
  let cwd = resolve_cwd(&root).unwrap();
1226
1277
  let scope = scope_for(&cwd, "test").unwrap();
1227
1278
  std::fs::create_dir_all(root_for(&cwd.path, &scope)).unwrap();
@@ -1377,6 +1428,30 @@ mod tests {
1377
1428
  }
1378
1429
  }
1379
1430
 
1431
+ #[test]
1432
+ fn retired_identity_lets_its_seat_id_start_fresh_and_a_live_seat_never_retires() {
1433
+ {
1434
+ let mut fixture = RoleFixture::new();
1435
+ let backend = fixture.canonical(SeatStatus::Ready, Phase::F5Receipt, Outcome::Committed, None);
1436
+ let mut writer = ContractStore::open(&fixture.binding.transport_root,
1437
+ fixture.binding.scope.clone(), &fixture.binding.endpoint).unwrap();
1438
+ assert!(writer.retire(&fixture.identity).is_err());
1439
+ assert!(matches!(existing_start(&backend, &fixture.identity.seat).unwrap(),
1440
+ Some(ExistingStart::Committed(_))));
1441
+ }
1442
+ let mut fixture = RoleFixture::new();
1443
+ let backend = fixture.canonical(SeatStatus::Stopped, Phase::F5Receipt, Outcome::Committed, None);
1444
+ assert!(matches!(existing_start(&backend, &fixture.identity.seat).unwrap(),
1445
+ Some(ExistingStart::Resume(_))));
1446
+ let mut writer = ContractStore::open(&fixture.binding.transport_root,
1447
+ fixture.binding.scope.clone(), &fixture.binding.endpoint).unwrap();
1448
+ assert_eq!(writer.retire(&fixture.identity).unwrap().identity, fixture.identity);
1449
+ // Never a resume of the retired session, and never the missing-seat fence.
1450
+ assert!(existing_start(&backend, &fixture.identity.seat).unwrap().is_none());
1451
+ assert!(seat_unclaimed(&backend, &fixture.identity.seat).unwrap());
1452
+ assert_eq!(backend.store.propose_identity(&fixture.identity.seat).unwrap().generation, Generation(2));
1453
+ }
1454
+
1380
1455
  #[test]
1381
1456
  fn startup_receipt_lookup_refuses_cross_scope_and_generation_fallback() {
1382
1457
  let mut fixture = RoleFixture::new();
@@ -1429,6 +1504,101 @@ mod tests {
1429
1504
  }
1430
1505
  }
1431
1506
 
1507
+ #[test]
1508
+ fn explicit_discard_can_refresh_only_a_quiescent_same_path_candidate() {
1509
+ for status in [SeatStatus::Ready, SeatStatus::Stopped] {
1510
+ let mut fixture = RoleFixture::new();
1511
+ fixture.binding.candidate = std::env::current_exe().unwrap().canonicalize().unwrap();
1512
+ fixture.binding.candidate_sha256 = Digest([0; 32]);
1513
+ let _backend = fixture.canonical(status, Phase::F5Receipt, Outcome::Committed, None);
1514
+ let path = root_for(&fixture.root, &fixture.binding.scope).join("framework-binding.json");
1515
+ let before = std::fs::read(&path).unwrap();
1516
+ assert!(require_candidate(&fixture.binding).is_err());
1517
+ let result = refresh_quiescent_candidate(&fixture.root, "test", &fixture.identity.seat);
1518
+ if status == SeatStatus::Ready {
1519
+ assert!(result.is_err());
1520
+ assert_eq!(std::fs::read(&path).unwrap(), before);
1521
+ } else {
1522
+ result.unwrap();
1523
+ require_candidate(&Backend::open_readonly(&fixture.root, "test").unwrap().binding).unwrap();
1524
+ fixture.binding.candidate = fixture.root.join("foreign-candidate");
1525
+ std::fs::write(&path, serde_json::to_vec(&fixture.binding).unwrap()).unwrap();
1526
+ assert!(refresh_quiescent_candidate(&fixture.root, "test", &fixture.identity.seat).is_err());
1527
+ }
1528
+ }
1529
+ }
1530
+
1531
+ #[test]
1532
+ fn native_business_tools_use_independent_inbox_without_submitted_tasks() {
1533
+ use team_agent_contract::orchestration::mcp::CallContext;
1534
+ let mut fixture = RoleFixture::new();
1535
+ fixture.role.provider = ProviderId::new("grok_build").unwrap();
1536
+ let _backend = fixture.canonical(SeatStatus::Ready, Phase::F5Receipt, Outcome::Committed, None);
1537
+ let mut backend = Backend::open(&fixture.root, "test").unwrap();
1538
+ let state = serde_json::json!({"active_team_key":"test", "teams":{"test":{
1539
+ "team_key":"test", "team_dir":fixture.root, "agents":{"worker":{"provider":"grok","status":"running"}}
1540
+ }}});
1541
+ let state_file = crate::state::persist::runtime_state_path(&fixture.root);
1542
+ std::fs::write(state_file, serde_json::to_vec(&state).unwrap()).unwrap();
1543
+ let tools = crate::mcp_server::TeamOrchestratorTools::with_identity(
1544
+ &fixture.root, Some(crate::model::ids::AgentId::new("worker")),
1545
+ Some(crate::model::ids::TeamKey::new("test")));
1546
+ let context = CallContext { identity: fixture.identity.clone(), binding_key:"controlled".into(),
1547
+ connection_id:InstanceId::new("direct-callback").unwrap(), task_id:String::new() };
1548
+ assert!(backend.store.submitted_task(&fixture.identity).unwrap().is_none());
1549
+ for (id, name, arguments) in [
1550
+ (1, "send_message", serde_json::json!({"to":"leader","content":"unbound native callback","mailbox":true})),
1551
+ (2, "get_team_status", serde_json::json!({})),
1552
+ (3, "report_result", serde_json::json!({"summary":"independent native result"})),
1553
+ ] {
1554
+ let request = serde_json::json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":arguments}});
1555
+ let result = super::super::mcp::direct_request(&mut backend.store, &context, &request, &tools).unwrap().unwrap();
1556
+ assert_eq!(result["result"]["isError"], false, "{result}");
1557
+ }
1558
+ let inbox = crate::inbox_store::read(&fixture.root, "leader", 10, Some("test")).unwrap();
1559
+ assert_eq!(inbox["messages"].as_array().unwrap().len(), 2);
1560
+ let db = rusqlite::Connection::open(fixture.binding.transport_root.join("contract.db")).unwrap();
1561
+ let outbox: i64 = db.query_row("select count(*) from contract_outbox", [], |row| row.get(0)).unwrap();
1562
+ assert_eq!(outbox, 0, "no synthetic task or message-delivery ledger row");
1563
+ let mut foreign = context.clone(); foreign.identity.generation = Generation(2);
1564
+ let request = serde_json::json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"send_message","arguments":{"to":"leader","content":"must not arrive","mailbox":true}}});
1565
+ assert!(super::super::mcp::direct_request(&mut backend.store, &foreign, &request, &tools).is_err());
1566
+ }
1567
+
1568
+ #[test]
1569
+ fn grok_projection_exposes_public_provider_and_keeps_internal_contract_id() {
1570
+ let mut fixture = RoleFixture::new();
1571
+ fixture.role.provider = ProviderId::new("grok_build").unwrap();
1572
+ let _backend = fixture.canonical(SeatStatus::Ready, Phase::F5Receipt, Outcome::Committed, None);
1573
+ write_role(&fixture.binding, &fixture.identity, &fixture.role).unwrap();
1574
+ let projected = super::super::framework::project_seat(&fixture.root, "test", fixture.identity.seat.as_str()).unwrap();
1575
+ assert_eq!(projected["provider"], "grok");
1576
+ assert_eq!(projected["contract_provider"], "grok_build");
1577
+ }
1578
+
1579
+ #[test]
1580
+ fn native_snapshot_publishes_the_private_pane_endpoint_pair() {
1581
+ let mut fixture = RoleFixture::new();
1582
+ fixture.role.provider = ProviderId::new("pi_tui").unwrap();
1583
+ let _backend = fixture.canonical(SeatStatus::Ready, Phase::F5Receipt, Outcome::Committed, None);
1584
+ let db = rusqlite::Connection::open(fixture.binding.transport_root.join("contract.db")).unwrap();
1585
+ db.execute("update contract_operations set record=json_set(record, '$.failure', ?1)",
1586
+ ["session observation deferred: capture-failed; tmux capture: Deadline"]).unwrap();
1587
+ write_role(&fixture.binding, &fixture.identity, &fixture.role).unwrap();
1588
+ let state = super::super::framework::project_seat(
1589
+ &fixture.binding.workspace.path, "test", "worker",
1590
+ ).unwrap();
1591
+ assert_eq!(state["pane_id"], "%1");
1592
+ assert_eq!(state["pane_id"], state["native_pane"]);
1593
+ assert_eq!(state["tmux_endpoint"], fixture.binding.endpoint);
1594
+ assert_eq!(state["tmux_endpoint"], state["native_endpoint"]);
1595
+ assert!(state["session_name"].is_null());
1596
+ assert!(state["session_id"].is_null());
1597
+ assert_eq!(state["session_observation"], "unobserved");
1598
+ assert_eq!(state["session_warning"], "session observation deferred: capture-failed; tmux capture: Deadline");
1599
+ assert_eq!(state["mcp_binding"], "unverified");
1600
+ }
1601
+
1432
1602
  #[test]
1433
1603
  fn role_snapshots_are_instance_scoped_and_exclusive() {
1434
1604
  let fixture = RoleFixture::new();