@team-agent/installer 0.5.125 → 0.5.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/crates/team-agent/src/cli/diagnose.rs +0 -137
  4. package/crates/team-agent/src/cli/emit.rs +13 -8
  5. package/crates/team-agent/src/cli/grok_slot.rs +88 -3
  6. package/crates/team-agent/src/cli/intent/runtime.rs +6 -4
  7. package/crates/team-agent/src/cli/intent/runtime_tests.rs +55 -10
  8. package/crates/team-agent/src/cli/mod.rs +35 -29
  9. package/crates/team-agent/src/cli/models.rs +33 -944
  10. package/crates/team-agent/src/cli/tests/leader_watch.rs +1 -1
  11. package/crates/team-agent/src/cli/tests/mod.rs +3 -3
  12. package/crates/team-agent/src/cli/tests/run_delegation.rs +8 -7
  13. package/crates/team-agent/src/cli/tests/status_send.rs +2 -2
  14. package/crates/team-agent/src/compiler/tests.rs +54 -12
  15. package/crates/team-agent/src/compiler.rs +7 -205
  16. package/crates/team-agent/src/contract_runtime/backend.rs +97 -38
  17. package/crates/team-agent/src/contract_runtime/commands.rs +335 -4
  18. package/crates/team-agent/src/contract_runtime/config.rs +12 -8
  19. package/crates/team-agent/src/contract_runtime/fork.rs +368 -0
  20. package/crates/team-agent/src/contract_runtime/framework.rs +8 -13
  21. package/crates/team-agent/src/contract_runtime/mod.rs +1 -0
  22. package/crates/team-agent/src/contract_runtime/registry.rs +100 -60
  23. package/crates/team-agent/src/coordinator/steps/abnormal.rs +45 -5
  24. package/crates/team-agent/src/coordinator/tests/api_error_recovery.rs +54 -16
  25. package/crates/team-agent/src/coordinator/tests/energy.rs +4 -4
  26. package/crates/team-agent/src/coordinator/tests/health_sync.rs +2 -44
  27. package/crates/team-agent/src/coordinator/tests/main_preserved.rs +2 -2
  28. package/crates/team-agent/src/coordinator/tests/spine.rs +1 -1
  29. package/crates/team-agent/src/coordinator/tests/takeover.rs +3 -3
  30. package/crates/team-agent/src/leader/start.rs +1 -1
  31. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +2 -195
  32. package/crates/team-agent/src/lifecycle/launch/clone_agent.rs +11 -27
  33. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +22 -200
  34. package/crates/team-agent/src/lifecycle/launch/fork_entry.rs +6 -87
  35. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +5 -496
  36. package/crates/team-agent/src/lifecycle/launch/pi_mcp.rs +74 -244
  37. package/crates/team-agent/src/lifecycle/launch/quick_start.rs +2 -26
  38. package/crates/team-agent/src/lifecycle/launch/role_source.rs +5 -0
  39. package/crates/team-agent/src/lifecycle/launch/spawn.rs +26 -51
  40. package/crates/team-agent/src/lifecycle/launch.rs +3 -34
  41. package/crates/team-agent/src/lifecycle/profile_launch.rs +18 -373
  42. package/crates/team-agent/src/lifecycle/restart/common.rs +45 -463
  43. package/crates/team-agent/src/lifecycle/restart/remove.rs +129 -0
  44. package/crates/team-agent/src/lifecycle/restart/selection.rs +5 -5
  45. package/crates/team-agent/src/lifecycle/restart.rs +0 -2
  46. package/crates/team-agent/src/lifecycle/role_config.rs +40 -13
  47. package/crates/team-agent/src/lifecycle/tests/acceptance_b_batch_red.rs +1 -1
  48. package/crates/team-agent/src/lifecycle/tests/agent_ops.rs +8 -12
  49. package/crates/team-agent/src/lifecycle/tests/behavioral_diff_264_red.rs +38 -236
  50. package/crates/team-agent/src/lifecycle/tests/claude_profile_launch_red.rs +8 -320
  51. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +106 -186
  52. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +4 -334
  53. package/crates/team-agent/src/lifecycle/tests/communication_mode_runtime_contract_red.rs +19 -15
  54. package/crates/team-agent/src/lifecycle/tests/copilot_provider_red.rs +2 -2
  55. package/crates/team-agent/src/lifecycle/tests/core.rs +33 -58
  56. package/crates/team-agent/src/lifecycle/tests/f032_startup_prompt_best_effort_red.rs +22 -8
  57. package/crates/team-agent/src/lifecycle/tests/grok_require_explicit_model_red.rs +15 -133
  58. package/crates/team-agent/src/lifecycle/tests/harvest2_a_batch_red.rs +3 -51
  59. package/crates/team-agent/src/lifecycle/tests/host_cotenant_death_p0_contract.rs +30 -67
  60. package/crates/team-agent/src/lifecycle/tests/issue238_codex_effort_contract.rs +3 -31
  61. package/crates/team-agent/src/lifecycle/tests/lane_ops.rs +194 -169
  62. package/crates/team-agent/src/lifecycle/tests/launch_spawn.rs +162 -284
  63. package/crates/team-agent/src/lifecycle/tests/lifecycle_rollback_red.rs +15 -78
  64. package/crates/team-agent/src/lifecycle/tests/main_preserved.rs +7 -7
  65. package/crates/team-agent/src/lifecycle/tests/phase_b_contracts.rs +75 -69
  66. package/crates/team-agent/src/lifecycle/tests/phase_golden.rs +2 -10
  67. package/crates/team-agent/src/lifecycle/tests/pi_catalog_red.rs +6 -18
  68. package/crates/team-agent/src/lifecycle/tests/pi_command_red.rs +52 -70
  69. package/crates/team-agent/src/lifecycle/tests/pi_dual_entry_red.rs +4 -157
  70. package/crates/team-agent/src/lifecycle/tests/pi_executable_mcp_red.rs +10 -302
  71. package/crates/team-agent/src/lifecycle/tests/pi_lifecycle_doctor_red.rs +1 -68
  72. package/crates/team-agent/src/lifecycle/tests/pi_native_mcp_capability_red.rs +1 -19
  73. package/crates/team-agent/src/lifecycle/tests/pi_session_delivery_red.rs +2 -100
  74. package/crates/team-agent/src/lifecycle/tests/quick_start_worker_readiness_red.rs +15 -14
  75. package/crates/team-agent/src/lifecycle/tests/restart.rs +12 -153
  76. package/crates/team-agent/src/lifecycle/tests/restart_build_before_destroy_0540_contract.rs +27 -5
  77. package/crates/team-agent/src/lifecycle/tests/restart_liveness_red.rs +59 -10
  78. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +47 -6
  79. package/crates/team-agent/src/lifecycle/tests/restart_session_capture_red.rs +3 -1478
  80. package/crates/team-agent/src/lifecycle/tests/resume_recover_red.rs +27 -10
  81. package/crates/team-agent/src/lifecycle/tests/status_credential_redaction_contract.rs +7 -7
  82. package/crates/team-agent/src/lifecycle/tests/subprep_codex_trust_roundtrip_red.rs +67 -313
  83. package/crates/team-agent/src/lifecycle/tests/swallow_batch4_semantics_red.rs +2 -254
  84. package/crates/team-agent/src/lifecycle/tests/team_in_team_identity_scope_red.rs +2 -2
  85. package/crates/team-agent/src/lifecycle/tests/team_in_team_sibling_quick_start_red.rs +1 -1
  86. package/crates/team-agent/src/lifecycle/tests/team_in_team_state_scope_red.rs +2 -2
  87. package/crates/team-agent/src/lifecycle/tests/team_key_retirement_txn_red.rs +4 -4
  88. package/crates/team-agent/src/lifecycle/tests/upgrade_compat_0211_red.rs +74 -19
  89. package/crates/team-agent/src/lifecycle/tests/verify_rs031_window_consistency_red.rs +39 -38
  90. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +42 -97
  91. package/crates/team-agent/src/lifecycle/tests.rs +0 -7
  92. package/crates/team-agent/src/lifecycle/types.rs +2 -21
  93. package/crates/team-agent/src/mcp_server/readiness_tests.rs +15 -17
  94. package/crates/team-agent/src/messaging/delivery.rs +14 -195
  95. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +5 -5
  96. package/crates/team-agent/src/messaging/tests/dup_inject.rs +68 -69
  97. package/crates/team-agent/src/messaging/tests/main_preserved.rs +2 -2
  98. package/crates/team-agent/src/messaging/tests/runtime.rs +5 -5
  99. package/crates/team-agent/src/messaging/tests/spine.rs +30 -32
  100. package/crates/team-agent/src/messaging/tests/wave2.rs +13 -20
  101. package/crates/team-agent/src/provider/adapter.rs +71 -572
  102. package/crates/team-agent/src/provider/adapters/mod.rs +6 -8
  103. package/crates/team-agent/src/provider/model_catalog.rs +13 -201
  104. package/crates/team-agent/src/provider/session/capture.rs +11 -211
  105. package/crates/team-agent/src/provider/session/context_fork/outcome.rs +8 -24
  106. package/crates/team-agent/src/provider/session/context_fork.rs +29 -240
  107. package/crates/team-agent/src/provider/session/mod.rs +2 -3
  108. package/crates/team-agent/src/provider/session_scan/common.rs +27 -87
  109. package/crates/team-agent/src/provider/session_scan/pi.rs +1 -34
  110. package/crates/team-agent/src/provider/session_scan.rs +7 -23
  111. package/crates/team-agent/src/provider/tests/adapter.rs +66 -204
  112. package/crates/team-agent/src/provider/tests/command_helpers.rs +3 -29
  113. package/crates/team-agent/src/provider/tests/idle.rs +0 -68
  114. package/crates/team-agent/src/provider/types.rs +0 -4
  115. package/crates/team-agent/src/provider/wire.rs +77 -23
  116. package/crates/team-agent/src/state/abnormal_watch/tests/mod.rs +1 -1
  117. package/crates/team-agent/src/state/persist.rs +6 -6
  118. package/crates/team-agent/src/state/repository/tests.rs +2 -2
  119. package/crates/team-agent/src/tmux_backend.rs +4 -3
  120. package/package.json +4 -4
  121. package/skills/team-agent/SKILL.md +8 -5
  122. package/skills/team-agent/command-coverage.json +29 -1
  123. package/skills/team-agent/docs/reference/team-agent-operator.md +7 -3
  124. package/skills/team-agent/references/team-agent-operator.md +7 -3
  125. package/crates/team-agent/src/lifecycle/launch/grok_per_seat.rs +0 -260
  126. package/crates/team-agent/src/lifecycle/restart/avatar.rs +0 -1805
  127. package/crates/team-agent/src/lifecycle/tests/claude_compatible_config_red.rs +0 -325
  128. package/crates/team-agent/src/lifecycle/tests/codex_weak_window_attribution_red.rs +0 -683
  129. package/crates/team-agent/src/lifecycle/tests/grok_effort_argv_red.rs +0 -247
  130. package/crates/team-agent/src/lifecycle/tests/grok_mcp_overlay_red.rs +0 -507
  131. package/crates/team-agent/src/lifecycle/tests/grok_restart_resume_red.rs +0 -300
  132. package/crates/team-agent/src/lifecycle/tests/pi_compiler_red.rs +0 -210
  133. package/crates/team-agent/src/lifecycle/tests/pi_fork_session_inheritance_red.rs +0 -1409
  134. package/crates/team-agent/src/provider/adapters/claude.rs +0 -78
  135. package/crates/team-agent/src/provider/adapters/claude_fork.rs +0 -131
  136. package/crates/team-agent/src/provider/adapters/codex.rs +0 -101
  137. package/crates/team-agent/src/provider/adapters/grok.rs +0 -67
  138. package/crates/team-agent/src/provider/adapters/pi.rs +0 -100
  139. package/crates/team-agent/src/provider/session/context_fork/claude.rs +0 -123
  140. package/crates/team-agent/src/provider/session/context_fork/codex.rs +0 -514
  141. package/crates/team-agent/src/provider/session_scan/claude.rs +0 -523
  142. package/crates/team-agent/src/provider/session_scan/codex.rs +0 -326
  143. package/crates/team-agent/src/provider/session_scan/grok.rs +0 -288
  144. package/crates/team-agent/src/test_support/models_timeout_fixture.rs +0 -144
@@ -225,7 +225,7 @@ fn workspace_socket(path: &Path) -> Result<Option<(u64, u64)>, BackendError> {
225
225
 
226
226
  /// The selected root transport is authority; ambient TMUX is never a selector.
227
227
  /// This runs only in the owning lifecycle action, after native F0 admission.
228
- fn workspace_tmux(
228
+ pub(super) fn workspace_tmux(
229
229
  binding: &Binding,
230
230
  seat: &SeatId,
231
231
  claim: Option<&team_agent_contract::host::transport::TargetReceipt>,
@@ -396,7 +396,7 @@ pub(super) fn adapter(
396
396
  BTreeMap::new(),
397
397
  )?.with_launch_context(binding.workspace.path.clone(), None)?)
398
398
  }
399
- fn launch_adapter(
399
+ pub(super) fn launch_adapter(
400
400
  binding: &Binding,
401
401
  identity: &InstanceIdentity,
402
402
  provider: &ProviderId,
@@ -406,7 +406,7 @@ fn launch_adapter(
406
406
  binding.workspace.path.clone(), discovered.runtime.clone(),
407
407
  )?)
408
408
  }
409
- fn request(
409
+ pub(super) fn request(
410
410
  binding: &Binding,
411
411
  role: &RoleConfig,
412
412
  identity: InstanceIdentity,
@@ -482,7 +482,7 @@ fn preflight_request(
482
482
 
483
483
  /// Providers whose native config search would otherwise inherit a Git or
484
484
  /// project configuration ancestor. Metadata only; no body is read.
485
- fn require_private_primary(
485
+ pub(super) fn require_private_primary(
486
486
  selected: registry::NativeProvider,
487
487
  cwd: &team_agent_contract::contract::session::CwdIdentity,
488
488
  ) -> Result<(), BackendError> {
@@ -577,6 +577,8 @@ fn existing_start(backend: &Backend, seat: &SeatId) -> Result<Option<ExistingSta
577
577
  return match backend.store.creation_receipt(seat, None)? {
578
578
  None => Ok(None),
579
579
  Some(record) if record.outcome == Outcome::Compensated => Ok(None),
580
+ // remove/reset ended this identity explicitly; the next start is fresh.
581
+ Some(record) if backend.store.retired(&record.target.identity)? => Ok(None),
580
582
  Some(_) => Err(Error::Fence.into()),
581
583
  };
582
584
  };
@@ -589,7 +591,7 @@ fn existing_start(backend: &Backend, seat: &SeatId) -> Result<Option<ExistingSta
589
591
  else { ExistingStart::Committed(record) }))
590
592
  }
591
593
 
592
- fn require_candidate(binding: &Binding) -> Result<(), BackendError> {
594
+ pub(super) fn require_candidate(binding: &Binding) -> Result<(), BackendError> {
593
595
  let candidate = std::env::current_exe()?.canonicalize()?;
594
596
  if candidate != binding.candidate || fingerprint_file(&candidate, 1024 * 1024 * 1024,
595
597
  Duration::from_secs(10))? != binding.candidate_sha256 { return Err(Error::Fence.into()); }
@@ -694,6 +696,59 @@ fn finish_receipt(backend: &mut Backend, record: OperationRecord) -> Result<Oper
694
696
  Ok(Lifecycle { store: &mut backend.store, host: &mut host, io: &mut NoNewIo }.recover(&record.id)?)
695
697
  }
696
698
 
699
+ /// No creation receipt, unfinished lease or seat exists for this ID.
700
+ pub(super) fn seat_unclaimed(backend: &Backend, seat: &SeatId) -> Result<bool, BackendError> {
701
+ Ok(existing_start(backend, seat)?.is_none())
702
+ }
703
+
704
+ /// Team-level forwarding peers (legacy members and the leader) that every new
705
+ /// native seat's framework route depends on. Shared by fresh start and fork.
706
+ pub(super) fn publish_framework_routes(backend: &mut Backend, members: &[MemberRoute]) -> Result<(), BackendError> {
707
+ let route = backend.binding.framework().route()?;
708
+ let mut peers: Vec<_> = members
709
+ .iter()
710
+ .filter(|member| member.runtime == RuntimeFamily::Legacy)
711
+ .map(
712
+ |member| team_agent_contract::orchestration::forward::FrameworkPeer {
713
+ recipient: member.id.clone(),
714
+ route: route.clone(),
715
+ provider: member.provider.clone(),
716
+ },
717
+ )
718
+ .collect();
719
+ peers.push(team_agent_contract::orchestration::forward::FrameworkPeer {
720
+ recipient: "leader".into(),
721
+ route: route.clone(),
722
+ provider: "framework".into(),
723
+ });
724
+ backend.store.set_framework_routes(&peers, Some(&route))?;
725
+ Ok(())
726
+ }
727
+
728
+ /// The native session ID a launch names before spawn, for the leaves whose
729
+ /// fresh session is `Preassigned`. Shared by fresh start and a native fork's child.
730
+ pub(super) fn preassign_session(
731
+ selected: registry::NativeProvider,
732
+ request: &mut LaunchRequest,
733
+ discovered: &Discovery,
734
+ ) -> Result<(), BackendError> {
735
+ if selected == registry::NativeProvider::Claude {
736
+ // `--session-id` names the new session; derived from this proposed instance.
737
+ request.preassigned_session = Some(team_agent_contract::providers::claude::session_id(&request.identity));
738
+ }
739
+ if let Some(registry::NativeRuntime::Cursor(runtime)) = &discovered.runtime {
740
+ request.preassigned_session = Some(
741
+ team_agent_contract::providers::cursor::native::allocate_chat(
742
+ runtime, &request.paths.cwd, &mut RealCommandRunner::default(),
743
+ team_agent_contract::contract::hooks::ReadBounds {
744
+ deadline: Duration::from_secs(90), max_output_bytes: 1024 * 1024,
745
+ },
746
+ ).map_err(|error| BackendError::Discovery(DiscoveryError::Catalog(error)))?,
747
+ );
748
+ }
749
+ Ok(())
750
+ }
751
+
697
752
  /// Fresh startup is distinct from resume. An existing generation is never
698
753
  /// silently replaced with a new native session.
699
754
  pub fn start(
@@ -782,24 +837,7 @@ pub fn start(
782
837
  if existing_start(&backend, &role.id)?.is_some() {
783
838
  return Err(Error::Conflict.into());
784
839
  }
785
- let route = backend.binding.framework().route()?;
786
- let mut peers: Vec<_> = members
787
- .iter()
788
- .filter(|member| member.runtime == RuntimeFamily::Legacy)
789
- .map(
790
- |member| team_agent_contract::orchestration::forward::FrameworkPeer {
791
- recipient: member.id.clone(),
792
- route: route.clone(),
793
- provider: member.provider.clone(),
794
- },
795
- )
796
- .collect();
797
- peers.push(team_agent_contract::orchestration::forward::FrameworkPeer {
798
- recipient: "leader".into(),
799
- route: route.clone(),
800
- provider: "framework".into(),
801
- });
802
- backend.store.set_framework_routes(&peers, Some(&route))?;
840
+ publish_framework_routes(&mut backend, members)?;
803
841
  let identity = backend.store.propose_identity(&role.id)?;
804
842
  let server_key = selected.server_key_for(&identity)?;
805
843
  write_role(&backend.binding, &identity, role)?;
@@ -810,20 +848,7 @@ pub fn start(
810
848
  request.paths.cwd = super::workspace::prepare(&backend.binding, &role.id)?;
811
849
  }
812
850
  require_private_primary(selected, &request.paths.cwd)?;
813
- if selected == registry::NativeProvider::Claude {
814
- // `--session-id` names the fresh session; derived from this proposed instance.
815
- request.preassigned_session = Some(team_agent_contract::providers::claude::session_id(&request.identity));
816
- }
817
- if let Some(registry::NativeRuntime::Cursor(runtime)) = &discovered.runtime {
818
- request.preassigned_session = Some(
819
- team_agent_contract::providers::cursor::native::allocate_chat(
820
- runtime, &request.paths.cwd, &mut RealCommandRunner::default(),
821
- team_agent_contract::contract::hooks::ReadBounds {
822
- deadline: Duration::from_secs(90), max_output_bytes: 1024 * 1024,
823
- },
824
- ).map_err(|error| BackendError::Discovery(DiscoveryError::Catalog(error)))?,
825
- );
826
- }
851
+ preassign_session(selected, &mut request, &discovered)?;
827
852
  let resolved = resolve_launch(
828
853
  descriptor,
829
854
  &hooks,
@@ -1035,7 +1060,7 @@ fn role_path(binding: &Binding, identity: &InstanceIdentity) -> PathBuf {
1035
1060
  "role-{}-{}.json", identity.seat.as_str(), identity.instance.as_str(),
1036
1061
  ))
1037
1062
  }
1038
- fn write_role(binding: &Binding, identity: &InstanceIdentity, role: &RoleConfig) -> Result<(), BackendError> {
1063
+ pub(super) fn write_role(binding: &Binding, identity: &InstanceIdentity, role: &RoleConfig) -> Result<(), BackendError> {
1039
1064
  use std::os::unix::fs::OpenOptionsExt;
1040
1065
  if identity.scope != binding.scope || identity.seat != role.id {
1041
1066
  return Err(BackendError::Metadata);
@@ -1155,6 +1180,16 @@ impl OwnedIo for NoNewIo {
1155
1180
  }
1156
1181
  }
1157
1182
 
1183
+ /// Retire a stopped seat's current identity. None: the store holds no seat
1184
+ /// for this ID (never started, or already retired).
1185
+ pub(crate) fn retire(workspace: &Path, team: &str, seat: &SeatId) -> Result<Option<SeatRecord>, BackendError> {
1186
+ let mut backend = Backend::open(workspace, team)?;
1187
+ let Some(current) = backend.store.seat(seat)? else {
1188
+ return Ok(None);
1189
+ };
1190
+ Ok(Some(backend.store.retire(&current.identity)?))
1191
+ }
1192
+
1158
1193
  pub fn stop(workspace: &Path, team: &str, seat: &SeatId) -> Result<OperationRecord, BackendError> {
1159
1194
  let mut backend = Backend::open(workspace, team)?;
1160
1195
  let target = backend
@@ -1354,6 +1389,30 @@ mod tests {
1354
1389
  }
1355
1390
  }
1356
1391
 
1392
+ #[test]
1393
+ fn retired_identity_lets_its_seat_id_start_fresh_and_a_live_seat_never_retires() {
1394
+ {
1395
+ let mut fixture = RoleFixture::new();
1396
+ let backend = fixture.canonical(SeatStatus::Ready, Phase::F5Receipt, Outcome::Committed, None);
1397
+ let mut writer = ContractStore::open(&fixture.binding.transport_root,
1398
+ fixture.binding.scope.clone(), &fixture.binding.endpoint).unwrap();
1399
+ assert!(writer.retire(&fixture.identity).is_err());
1400
+ assert!(matches!(existing_start(&backend, &fixture.identity.seat).unwrap(),
1401
+ Some(ExistingStart::Committed(_))));
1402
+ }
1403
+ let mut fixture = RoleFixture::new();
1404
+ let backend = fixture.canonical(SeatStatus::Stopped, Phase::F5Receipt, Outcome::Committed, None);
1405
+ assert!(matches!(existing_start(&backend, &fixture.identity.seat).unwrap(),
1406
+ Some(ExistingStart::Resume(_))));
1407
+ let mut writer = ContractStore::open(&fixture.binding.transport_root,
1408
+ fixture.binding.scope.clone(), &fixture.binding.endpoint).unwrap();
1409
+ assert_eq!(writer.retire(&fixture.identity).unwrap().identity, fixture.identity);
1410
+ // Never a resume of the retired session, and never the missing-seat fence.
1411
+ assert!(existing_start(&backend, &fixture.identity.seat).unwrap().is_none());
1412
+ assert!(seat_unclaimed(&backend, &fixture.identity.seat).unwrap());
1413
+ assert_eq!(backend.store.propose_identity(&fixture.identity.seat).unwrap().generation, Generation(2));
1414
+ }
1415
+
1357
1416
  #[test]
1358
1417
  fn startup_receipt_lookup_refuses_cross_scope_and_generation_fallback() {
1359
1418
  let mut fixture = RoleFixture::new();
@@ -1,9 +1,14 @@
1
1
  //! Public lifecycle dispatch for contract seats. A private native pane is never
2
2
  //! operated through the legacy workspace socket or provider-enum fallback.
3
3
  use std::path::Path;
4
+ use std::time::Duration;
4
5
 
5
6
  use serde_json::{json, Value};
6
- use team_agent_contract::contract::types::SeatId;
7
+ use team_agent_contract::contract::delivery::InputSurface;
8
+ use team_agent_contract::contract::probe::{PaneReadyEvidence, Probe, ProbeOutcome};
9
+ use team_agent_contract::contract::types::{Digest, OperationId, SeatId};
10
+ use team_agent_contract::host::{clock::RealClock, process::{sample_process, ProcessState}};
11
+ use team_agent_contract::orchestration::physical::{PhysicalRuntime, Registration};
7
12
  use team_agent_contract::orchestration::store::{Outcome, SeatStatus};
8
13
 
9
14
  use crate::cli::CliError;
@@ -12,7 +17,7 @@ use crate::model::ids::AgentId;
12
17
  use crate::state::repository::{StateRepository, StateWriteIntent};
13
18
  use crate::state::selector::{resolve_active_team_readonly, SelectedTeam, SelectorMode};
14
19
 
15
- use super::{backend::{self, Backend, BackendError}, config, framework};
20
+ use super::{backend::{self, Backend, BackendError}, config, framework, registry};
16
21
 
17
22
  fn error(error: impl std::fmt::Display) -> CliError {
18
23
  CliError::Runtime(error.to_string())
@@ -127,8 +132,12 @@ pub fn start_agent(
127
132
  backend::preflight(&config).map_err(error)?;
128
133
  }
129
134
  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)?
135
+ let backend = Backend::open_readonly(&selected.run_workspace, &selected.team_key).map_err(error)?;
136
+ // A retired generation is history, not a session this start resumes.
137
+ match backend.store.creation_receipt(id, None).map_err(error)? {
138
+ Some(record) if backend.store.retired(&record.target.identity).map_err(error)? => None,
139
+ other => other,
140
+ }
132
141
  };
133
142
  crate::lifecycle::role_config::commit_contract_role(&source, &previous, &next).map_err(error)?;
134
143
  let receipt = backend::start(&selected.run_workspace, &selected.team_key, role, &config.members).map_err(error)?.1;
@@ -254,6 +263,267 @@ pub fn stop_agent(
254
263
  })
255
264
  }
256
265
 
266
+ /// What remove/reset may rely on. Idle needs positive evidence; anything the
267
+ /// framework cannot prove idle is never treated as idle.
268
+ #[derive(Debug, PartialEq, Eq)]
269
+ enum Activity {
270
+ Stopped,
271
+ Exited,
272
+ Idle,
273
+ Working(String),
274
+ Unverified(String),
275
+ }
276
+
277
+ // Two captures this far apart straddle a one-second elapsed counter, and a
278
+ // streamed reply that hides a provider's busy marker still changes the frame.
279
+ const SETTLE: Duration = Duration::from_millis(1500);
280
+ const REMOVE_WORKING: &str = "agent is currently working; stop the agent before removing it";
281
+ const RESET_WORKING: &str =
282
+ "agent is currently working; wait for completion or stop the agent before resetting session";
283
+
284
+ /// Read-only: a held seat lease, then the seat's own pane read twice, then
285
+ /// the lease and queue again so a delivery between the captures still counts.
286
+ fn activity(workspace: &Path, team: &str, id: &SeatId) -> Result<Activity, CliError> {
287
+ let backend = Backend::open_readonly(workspace, team).map_err(error)?;
288
+ let busy = || Activity::Working("a lifecycle operation or message delivery holds the seat".into());
289
+ // An interrupted startup holds the lease before its seat row is published.
290
+ if backend.store.leased(id).map_err(error)? {
291
+ return Ok(busy());
292
+ }
293
+ let Some(seat) = backend.store.seat(id).map_err(error)? else {
294
+ return Ok(Activity::Stopped);
295
+ };
296
+ if seat.status == SeatStatus::Stopped {
297
+ return Ok(Activity::Stopped);
298
+ }
299
+ let Some(target) = seat.physical.as_ref() else {
300
+ return Ok(Activity::Unverified("no native target is recorded".into()));
301
+ };
302
+ match sample_process(&target.process) {
303
+ ProcessState::Alive => {}
304
+ ProcessState::Exited | ProcessState::Replaced => return Ok(Activity::Exited),
305
+ ProcessState::Unknown(failure) => {
306
+ return Ok(Activity::Unverified(format!("native process state is unknown: {failure}")))
307
+ }
308
+ }
309
+ // Starting stays until the first delivery; only the surface decides then.
310
+ if seat.status == SeatStatus::Unknown {
311
+ return Ok(Activity::Unverified("native seat is quarantined after an uncertain native effect".into()));
312
+ }
313
+ let selected = registry::provider(seat.provider.as_str()).map_err(error)?;
314
+ let adapter = backend::adapter(&backend.binding, &seat.identity, &seat.provider).map_err(error)?;
315
+ let hooks = adapter.hooks();
316
+ let clock = RealClock::new();
317
+ let nonce = backend.store.propose_identity(id).map_err(error)?.instance;
318
+ let physical = PhysicalRuntime::new(
319
+ Registration {
320
+ descriptor: selected.descriptor(),
321
+ hooks: &hooks,
322
+ controls: selected.controls(),
323
+ startup: selected.startup(),
324
+ session_panel: selected.session_panel(),
325
+ },
326
+ backend::settings(&backend.binding, selected),
327
+ OperationId::new(format!("observe-{}", nonce.as_str())).map_err(error)?,
328
+ &clock,
329
+ ).map_err(error)?;
330
+ let capture = || physical.surface(&seat)
331
+ .map_err(|failure| Activity::Unverified(format!("native surface capture failed: {failure}")));
332
+ let first = match capture() {
333
+ Ok(sample) => sample,
334
+ Err(unverified) => return Ok(unverified),
335
+ };
336
+ std::thread::sleep(SETTLE);
337
+ let observed = match capture() {
338
+ Ok(second) => classify(&first, &second),
339
+ Err(unverified) => unverified,
340
+ };
341
+ if observed == Activity::Idle {
342
+ if backend.store.leased(id).map_err(error)? {
343
+ return Ok(busy());
344
+ }
345
+ if backend.store.has_queued_for(&seat.identity).map_err(error)? {
346
+ return Ok(Activity::Working("a queued message is about to be delivered".into()));
347
+ }
348
+ }
349
+ Ok(observed)
350
+ }
351
+
352
+ fn classify(
353
+ first: &(Probe<PaneReadyEvidence>, Digest),
354
+ second: &(Probe<PaneReadyEvidence>, Digest),
355
+ ) -> Activity {
356
+ let read = |sample: &(Probe<PaneReadyEvidence>, Digest)| match &sample.0.outcome {
357
+ ProbeOutcome::Observed(pane) => Some(pane.surface),
358
+ _ => None,
359
+ };
360
+ let (before, after) = (read(first), read(second));
361
+ if let Some(busy) = [before, after].into_iter().flatten().find(|surface| matches!(surface,
362
+ InputSurface::Busy | InputSurface::Queued | InputSurface::ComposerContainsPaste | InputSurface::NativeAccepted))
363
+ {
364
+ return Activity::Working(format!("native surface reads {busy:?}"));
365
+ }
366
+ match (before, after) {
367
+ (Some(InputSurface::ComposerReady), Some(InputSurface::ComposerReady)) if first.1 == second.1 => Activity::Idle,
368
+ (Some(InputSurface::ComposerReady), Some(InputSurface::ComposerReady)) => {
369
+ Activity::Working("native output changed between two captures".into())
370
+ }
371
+ _ => Activity::Unverified(format!("native surface reads {before:?} then {after:?}")),
372
+ }
373
+ }
374
+
375
+ fn refused(agent: &str, reason: &str, error: &str, evidence: Option<String>, action: &str) -> Value {
376
+ json!({"ok":false,"agent_id":agent,"status":"refused","runtime":"contract","reason":reason,
377
+ "error":error,"evidence":evidence,"action":action})
378
+ }
379
+
380
+ fn stop_seat(selected: &SelectedTeam, id: &SeatId) -> Result<OperationId, CliError> {
381
+ let receipt = backend::stop(&selected.run_workspace, &selected.team_key, id).map_err(error)?;
382
+ check_record(&receipt)?;
383
+ Ok(receipt.id)
384
+ }
385
+
386
+ /// A working seat is never removed, even with --force. A stopped seat needs
387
+ /// only --confirm; an idle live seat also needs --force and is stopped first.
388
+ pub fn remove_agent(
389
+ workspace: &Path,
390
+ team: Option<&str>,
391
+ agent: &str,
392
+ from_spec: bool,
393
+ confirm: bool,
394
+ force: bool,
395
+ ) -> Result<Option<Value>, CliError> {
396
+ with_agent(workspace, team, agent, "remove-agent", |selected, id| {
397
+ if !confirm {
398
+ return Ok(refused(agent, "confirm_required", "remove-agent requires --confirm", None, "rerun with --confirm"));
399
+ }
400
+ let row = selected.state.get("agents").and_then(|agents| agents.get(agent))
401
+ .ok_or(BackendError::Metadata).map_err(error)?;
402
+ let agent_id = AgentId::new(agent);
403
+ // Every shared-record input resolves before the native seat is touched.
404
+ crate::lifecycle::restart::remove::preflight_contract_removal(
405
+ &selected.run_workspace, &agent_id, Some(&selected.team_key),
406
+ ).map_err(error)?;
407
+ let mut stopped = None;
408
+ if !framework::is_paused_unstarted(row) {
409
+ match activity(&selected.run_workspace, &selected.team_key, id)? {
410
+ Activity::Stopped => {}
411
+ Activity::Working(evidence) => return Ok(refused(agent, "agent_working", REMOVE_WORKING,
412
+ Some(evidence), "wait for the agent to finish, or stop it, then rerun remove-agent")),
413
+ Activity::Unverified(evidence) => return Ok(refused(agent, "agent_activity_unverified",
414
+ "agent activity could not be verified idle; stop the agent before removing it",
415
+ Some(evidence), "stop the agent, then rerun remove-agent")),
416
+ Activity::Idle if !force => return Ok(refused(agent, "force_required",
417
+ "agent is running; remove-agent requires --force", None,
418
+ "rerun with --force to stop and remove the running agent")),
419
+ Activity::Idle | Activity::Exited => stopped = Some(stop_seat(selected, id)?),
420
+ }
421
+ // The native identity ends before the shared records: a failure
422
+ // below leaves a row a rerun removes, never a resumable old seat.
423
+ backend::retire(&selected.run_workspace, &selected.team_key, id).map_err(error)?;
424
+ }
425
+ let report = crate::lifecycle::restart::remove::remove_contract_records_locked(
426
+ &selected.run_workspace, &agent_id, from_spec, force, stopped.is_some(),
427
+ Some(&selected.team_key),
428
+ ).map_err(error)?;
429
+ Ok(json!({"ok":true,"agent_id":agent,"status":"removed","runtime":"contract",
430
+ "stopped":stopped.is_some(),"operation":stopped,"report":format!("{report:?}")}))
431
+ })
432
+ }
433
+
434
+ /// Ok: the seat is stopped, exited or idle; Err: the reset refusal receipt.
435
+ fn reset_guard(observed: Activity, agent: &str) -> Result<Activity, Value> {
436
+ match observed {
437
+ Activity::Working(evidence) => Err(refused(agent, "agent_working", RESET_WORKING,
438
+ Some(evidence), "wait for the agent to finish, or stop it, then rerun reset-agent")),
439
+ Activity::Unverified(evidence) => Err(refused(agent, "agent_activity_unverified",
440
+ "agent activity could not be verified idle; wait for completion or stop the agent before resetting session",
441
+ Some(evidence), "stop the agent, then rerun reset-agent")),
442
+ clear => Ok(clear),
443
+ }
444
+ }
445
+
446
+ /// Discards the native session only when the seat is provably not working,
447
+ /// then starts the same seat ID on a fresh generation and session.
448
+ pub fn reset_agent(
449
+ workspace: &Path,
450
+ team: Option<&str>,
451
+ agent: &str,
452
+ discard_session: bool,
453
+ ) -> Result<Option<Value>, CliError> {
454
+ with_agent(workspace, team, agent, "reset-agent", |selected, id| {
455
+ if !discard_session {
456
+ return Ok(json!({"ok":false,"agent_id":agent,"status":"refused","runtime":"contract",
457
+ "reason":"discard_session_required"}));
458
+ }
459
+ let row = selected.state.get("agents").and_then(|agents| agents.get(agent))
460
+ .ok_or(BackendError::Metadata).map_err(error)?;
461
+ let config = framework::team_config(&selected.run_workspace, &selected.team_dir, &selected.team_key)
462
+ .map_err(error)?.ok_or_else(|| error("contract role no longer configured"))?;
463
+ let role = config.roles.iter().find(|role| &role.id == id)
464
+ .ok_or_else(|| error("contract role no longer configured"))?;
465
+ if row.get("provider").and_then(Value::as_str) != Some(role.provider.as_str()) {
466
+ return Err(error("provider change requires a new seat identity"));
467
+ }
468
+ if role.paused {
469
+ return Ok(json!({"ok":false,"agent_id":agent,"status":"paused","reason":"agent_paused","runtime":"contract"}));
470
+ }
471
+ let live = !framework::is_paused_unstarted(row);
472
+ // The guard runs when the command is invoked, before the slow native
473
+ // admission below: a message sent just before reset is still queued or
474
+ // in flight then. It runs again right before the stop, so work that
475
+ // began during admission is refused too.
476
+ if live {
477
+ if let Err(refusal) = reset_guard(activity(&selected.run_workspace, &selected.team_key, id)?, agent) {
478
+ return Ok(refusal);
479
+ }
480
+ }
481
+ // Pure admission of the replacement precedes any stop or retirement.
482
+ let mut admission = config.clone();
483
+ admission.roles.retain(|candidate| &candidate.id == id);
484
+ backend::preflight(&admission).map_err(error)?;
485
+ let mut stopped = None;
486
+ let mut discarded = None;
487
+ if live {
488
+ // The fresh start below must not fail its candidate fence after the
489
+ // old seat is already gone.
490
+ backend::require_candidate(&Backend::open_readonly(&selected.run_workspace, &selected.team_key)
491
+ .map_err(error)?.binding).map_err(error)?;
492
+ match reset_guard(activity(&selected.run_workspace, &selected.team_key, id)?, agent) {
493
+ Err(refusal) => return Ok(refusal),
494
+ Ok(Activity::Stopped) => {}
495
+ Ok(_) => stopped = Some(stop_seat(selected, id)?),
496
+ }
497
+ discarded = backend::retire(&selected.run_workspace, &selected.team_key, id).map_err(error)?
498
+ .and_then(|seat| seat.session).map(|session| session.native_session);
499
+ }
500
+ // The row stops naming the retired incarnation. If the fresh start
501
+ // below fails, this unbound stopped seed is skipped by team restart
502
+ // and admitted fresh by a later start.
503
+ StateRepository::new(&selected.run_workspace).commit(
504
+ StateWriteIntent::StartAgent { team_key: &selected.team_key, agent_id: agent },
505
+ |state| {
506
+ if let Some(row) = state.get_mut("agents").and_then(|agents| agents.get_mut(agent)).and_then(Value::as_object_mut) {
507
+ for key in ["contract_scope", "contract_instance", "generation", "session_id"] {
508
+ row.insert(key.into(), Value::Null);
509
+ }
510
+ row.insert("status".into(), json!("stopped"));
511
+ }
512
+ },
513
+ ).map_err(error)?;
514
+ let projection = framework::start_configured(&selected.run_workspace, &selected.team_dir, &selected.team_key, id)?;
515
+ let coordinator = crate::coordinator::start_coordinator_with_team(
516
+ &crate::coordinator::WorkspacePath::new(selected.run_workspace.clone()), Some(&selected.team_key),
517
+ ).map_err(error)?;
518
+ Ok(json!({"ok":coordinator.ok,"agent_id":agent,"status":"reset","runtime":"contract",
519
+ "start_mode":"fresh","stopped":stopped.is_some(),"operation":stopped,
520
+ "discarded_session_id":discarded,"session_id":projection.get("session_id"),
521
+ "new_session_id":projection.get("session_id"),"generation":projection.get("generation"),
522
+ "coordinator":crate::lifecycle::coordinator_start_summary_value(
523
+ &crate::lifecycle::CoordinatorStartSummary::from_start_report(&coordinator))}))
524
+ })
525
+ }
526
+
257
527
  #[cfg(test)]
258
528
  mod tests {
259
529
  // Assembly guard, not a substitute for the real shared-session restart/
@@ -337,4 +607,65 @@ mod tests {
337
607
  .unwrap_err().to_string();
338
608
  assert!(error.contains("metadata is invalid"));
339
609
  }
610
+
611
+ fn surface(surface: Option<InputSurface>, text: &[u8]) -> (Probe<PaneReadyEvidence>, Digest) {
612
+ let scope = team_agent_contract::contract::probe::EvidenceScope {
613
+ identity: receipt(Outcome::Committed).target.identity, endpoint: "fixture".into(),
614
+ pane: "%0".into(), binding: "fixture".into(), session: None, sequence: 1,
615
+ observed_at: Duration::ZERO, valid_for: Duration::from_secs(2), source: "fixture".into(),
616
+ };
617
+ let outcome = match surface {
618
+ Some(surface) => ProbeOutcome::Observed(PaneReadyEvidence { profile_id: "fixture".into(), surface }),
619
+ None => ProbeOutcome::Pending { deadline: Duration::ZERO },
620
+ };
621
+ (Probe { scope, outcome }, team_agent_contract::host::digest(text))
622
+ }
623
+
624
+ #[test]
625
+ fn working_guard_calls_a_seat_idle_only_on_two_still_composer_ready_captures() {
626
+ let ready = surface(Some(InputSurface::ComposerReady), b"idle");
627
+ assert_eq!(classify(&ready, &ready.clone()), Activity::Idle);
628
+ // A streamed reply can hide the busy marker, but it still moves the frame.
629
+ assert!(matches!(classify(&ready, &surface(Some(InputSurface::ComposerReady), b"idle, then more")),
630
+ Activity::Working(_)));
631
+ for busy in [InputSurface::Busy, InputSurface::Queued, InputSurface::ComposerContainsPaste,
632
+ InputSurface::NativeAccepted]
633
+ {
634
+ assert!(matches!(classify(&ready, &surface(Some(busy), b"idle")), Activity::Working(_)), "{busy:?}");
635
+ assert!(matches!(classify(&surface(Some(busy), b"x"), &surface(None, b"x")), Activity::Working(_)),
636
+ "{busy:?}");
637
+ }
638
+ for other in [None, Some(InputSurface::Starting), Some(InputSurface::ShellOrUnknown),
639
+ Some(InputSurface::StartupRiskWarning), Some(InputSurface::Fault)]
640
+ {
641
+ assert!(matches!(classify(&ready, &surface(other, b"idle")), Activity::Unverified(_)), "{other:?}");
642
+ assert!(matches!(classify(&surface(other, b"idle"), &ready), Activity::Unverified(_)), "{other:?}");
643
+ }
644
+ }
645
+
646
+ // 2.8a: a reset issued right after a send must observe the queued or
647
+ // in-flight message, not a turn that the slow admission let finish.
648
+ #[test]
649
+ fn reset_guards_the_seat_before_its_slow_admission_and_again_before_the_stop() {
650
+ let source = include_str!("commands.rs");
651
+ let body = source.split_once("pub fn reset_agent(").unwrap().1
652
+ .split_once("#[cfg(test)]").unwrap().0;
653
+ let first = body.find("reset_guard(activity(").unwrap();
654
+ let admission = body.find("backend::preflight(&admission)").unwrap();
655
+ let second = body.rfind("reset_guard(activity(").unwrap();
656
+ let stop = body.find("stop_seat(selected, id)").unwrap();
657
+ assert!(first < admission && admission < second && second < stop);
658
+ }
659
+
660
+ #[test]
661
+ fn remove_and_reset_route_contract_seats_before_the_legacy_refusal() {
662
+ let cli = include_str!("../cli/mod.rs");
663
+ for (entry, native, gate) in [
664
+ ("pub fn remove_agent(", "contract_runtime::commands::remove_agent(", "\"remove-agent\","),
665
+ ("pub fn reset_agent(", "contract_runtime::commands::reset_agent(", "\"reset-agent\","),
666
+ ] {
667
+ let body = cli.split_once(entry).unwrap().1;
668
+ assert!(body.find(native).unwrap() < body.find(gate).unwrap(), "{entry}");
669
+ }
670
+ }
340
671
  }
@@ -99,7 +99,8 @@ fn mode(meta: &Value, path: &Path) -> Result<Option<CommunicationMode>, ConfigEr
99
99
  .transpose()
100
100
  }
101
101
 
102
- /// `contract_runtime` is an exact boolean; a bare shared key stays legacy.
102
+ /// `contract_runtime` is an exact boolean. Every contract name selects its leaf
103
+ /// without it; `true` only insists that the provider be a contract leaf.
103
104
  fn opted_in(meta: &Value, path: &Path) -> Result<bool, ConfigError> {
104
105
  match meta.get("contract_runtime") {
105
106
  None => Ok(false),
@@ -118,7 +119,7 @@ fn malformed_contract_header(body: &str) -> bool {
118
119
  .map(|(key, value)| (key.trim(), value.split('#').next().unwrap_or("").trim().trim_matches(['\'', '"'])))
119
120
  .collect();
120
121
  let opted_in = fields.iter().any(|(key, value)| *key == "contract_runtime" && *value == "true");
121
- opted_in || fields.iter().any(|(key, value)| *key == "provider" && super::registry::recognizes(value, false))
122
+ opted_in || fields.iter().any(|(key, value)| *key == "provider" && super::registry::recognizes(value))
122
123
  })
123
124
  }
124
125
 
@@ -186,11 +187,14 @@ fn read_team_inner(
186
187
  return Err(invalid(&path, "front matter"));
187
188
  }
188
189
  let opted = opted_in(&meta, &path)?;
190
+ // An omitted provider is the default `pi`, which declares the Pi leaf.
189
191
  if opted
190
- || meta
191
- .get("provider")
192
- .and_then(Value::as_str)
193
- .is_some_and(|provider| super::registry::recognizes(provider, false))
192
+ || match meta.get("provider") {
193
+ None | Some(Value::Null) => true,
194
+ Some(provider) => provider
195
+ .as_str()
196
+ .is_some_and(super::registry::recognizes),
197
+ }
194
198
  {
195
199
  selected = true;
196
200
  }
@@ -261,8 +265,8 @@ fn read_team_inner(
261
265
  }
262
266
  let provider = text(&meta, "provider", &source)?.unwrap_or_else(|| "pi".into());
263
267
  let opted = opted_in(&meta, &source)?;
264
- let registration = super::registry::declared(&provider, opted);
265
- if registration.is_none() && (opted || super::registry::recognizes(&provider, false)) {
268
+ let registration = super::registry::declared(&provider);
269
+ if registration.is_none() && (opted || super::registry::recognizes(&provider)) {
266
270
  return Err(invalid(&source, "provider"));
267
271
  }
268
272
  let runtime = if registration.is_some() {