@team-agent/installer 0.5.123 → 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.
@@ -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,
@@ -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");
@@ -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")
@@ -20,9 +20,7 @@ fn request(session: PiSessionSelector<'static>) -> PiCommandRequest<'static> {
20
20
 
21
21
  #[test]
22
22
  fn pi_command_omits_unset_model_and_thinking_flags() {
23
- let mut request = request(PiSessionSelector::Fresh {
24
- session_id: "a2320d4e-7b3a-44ae-b3b8-d5de57033b01",
25
- });
23
+ let mut request = request(PiSessionSelector::Fresh);
26
24
  request.model = None;
27
25
  request.effort = None;
28
26
  let argv = build_pi_command_argv(request).expect("Pi provider defaults");
@@ -38,9 +36,7 @@ fn leader_request() -> PiCommandRequest<'static> {
38
36
  effort: None,
39
37
  system_prompt: "frozen leader prompt",
40
38
  session_dir: None,
41
- session: PiSessionSelector::Fresh {
42
- session_id: "da8c3622-2378-4d05-a26c-e826a6ef6d63",
43
- },
39
+ session: PiSessionSelector::Fresh,
44
40
  agent_id: "leader",
45
41
  }
46
42
  }
@@ -57,8 +53,6 @@ fn pi_interactive_leader_argv_preserves_native_session_discovery() {
57
53
  "/workspace/.team/runtime/pi/current/leader/team-mcp.ts",
58
54
  "--append-system-prompt",
59
55
  "frozen leader prompt",
60
- "--session-id",
61
- "da8c3622-2378-4d05-a26c-e826a6ef6d63",
62
56
  "--name",
63
57
  "leader",
64
58
  ]
@@ -98,9 +92,7 @@ fn pi_leader_session_scope_keeps_explicit_and_external_routes_isolated() {
98
92
 
99
93
  #[test]
100
94
  fn pi_command_preserves_direct_pi_defaults_with_only_team_runtime_additions() {
101
- let fresh = build_pi_command_argv(request(PiSessionSelector::Fresh {
102
- session_id: "da8c3622-2378-4d05-a26c-e826a6ef6d63",
103
- }))
95
+ let fresh = build_pi_command_argv(request(PiSessionSelector::Fresh))
104
96
  .expect("fresh Pi command");
105
97
  assert_eq!(
106
98
  fresh,
@@ -116,8 +108,6 @@ fn pi_command_preserves_direct_pi_defaults_with_only_team_runtime_additions() {
116
108
  "frozen worker prompt",
117
109
  "--session-dir",
118
110
  "/workspace/.team/runtime/pi/team-a/worker-a/sessions",
119
- "--session-id",
120
- "da8c3622-2378-4d05-a26c-e826a6ef6d63",
121
111
  "--name",
122
112
  "worker-a",
123
113
  ]
@@ -178,9 +168,7 @@ fn pi_command_preserves_direct_pi_defaults_with_only_team_runtime_additions() {
178
168
 
179
169
  #[test]
180
170
  fn pi_command_keeps_direct_plugins_skills_context_auth_and_tools() {
181
- let argv = build_pi_command_argv(request(PiSessionSelector::Fresh {
182
- session_id: "76f682b1-ecc3-4586-850f-ab2e2bb04cb3",
183
- }))
171
+ let argv = build_pi_command_argv(request(PiSessionSelector::Fresh))
184
172
  .expect("fresh Pi command");
185
173
 
186
174
  for forbidden in [
@@ -58,9 +58,7 @@ fn command(_tools: &[&str], effort: ProviderEffort, model: &str) -> Result<Vec<S
58
58
  session_dir: Some(Path::new(
59
59
  "/workspace/.team/runtime/pi/t1/pi-worker/sessions",
60
60
  )),
61
- session: PiSessionSelector::Fresh {
62
- session_id: "c5ddf218-24a5-4e74-960c-ab6606ea7e8c",
63
- },
61
+ session: PiSessionSelector::Fresh,
64
62
  agent_id: "pi-worker",
65
63
  })
66
64
  .map_err(|error| error.to_string())
@@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicU32, Ordering};
4
4
 
5
5
  use crate::lifecycle::launch::launch_with_transport_in_workspace;
6
6
  use crate::lifecycle::launch::pi_mcp::{
7
- PiExecutableChain, PiExecutableFileType, PiMaterializeRequest, PiSessionScope,
7
+ PiExecutableChain, PiMaterializeRequest, PiSessionScope,
8
8
  PiWrapperRequest, materialize_pi_plan, materialize_pi_resume_plan,
9
9
  parse_pi_list_models_table, pi_seat_paths, resolve_pi_executable_chain,
10
10
  validate_pi_executable_chain, validate_pi_wrapper_source, write_pi_wrapper,
@@ -105,47 +105,35 @@ fn mcp_config(candidate: &Path, workspace: &Path, agent_id: &str) -> McpConfig {
105
105
  }
106
106
 
107
107
  #[test]
108
- fn pi_executable_chain_freezes_wrapper_real_binary_and_catalog() {
108
+ fn pi_executable_chain_accepts_any_first_path_entry_and_freezes_catalog() {
109
109
  let chain = PiExecutableChain {
110
110
  path_entry: PathBuf::from("/Users/fixture/.local/bin/pi"),
111
- path_entry_type: PiExecutableFileType::Wrapper,
112
- launch_executable: PathBuf::from("/Users/fixture/.local/bin/pi"),
113
- real_binary: PathBuf::from(
114
- "/opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js",
115
- ),
116
111
  pi_version: "0.84.3".to_string(),
117
112
  catalog_sha256: CATALOG_DIGEST.to_string(),
118
113
  };
119
- validate_pi_executable_chain(&chain).expect("the protocol-capable wrapper chain is valid");
114
+ validate_pi_executable_chain(&chain).expect("the PATH wrapper entry is valid");
120
115
 
121
- let mut homebrew_symlink_entry = chain.clone();
122
- homebrew_symlink_entry.real_binary = PathBuf::from("/opt/homebrew/bin/pi");
123
- validate_pi_executable_chain(&homebrew_symlink_entry)
124
- .expect("the distinct Homebrew symlink entry may resolve to the shebang cli.js target");
116
+ // A plain binary or compiled wrapper first on PATH is what bare `pi` runs.
117
+ let mut direct_binary = chain.clone();
118
+ direct_binary.path_entry = PathBuf::from("/opt/homebrew/bin/pi");
119
+ validate_pi_executable_chain(&direct_binary)
120
+ .expect("a direct binary first on PATH is the native launch entry");
125
121
 
126
- let mut wrong_version = chain.clone();
127
- wrong_version.pi_version = "0.84.4".to_string();
128
- validate_pi_executable_chain(&wrong_version)
122
+ let mut newer = chain.clone();
123
+ newer.pi_version = "0.84.4".to_string();
124
+ validate_pi_executable_chain(&newer)
129
125
  .expect("an arbitrary newer Pi version with the same public protocol is valid");
130
126
 
131
- let mut missing_real = chain.clone();
132
- missing_real.real_binary = PathBuf::new();
133
- assert!(validate_pi_executable_chain(&missing_real).is_err());
127
+ for bad in ["", "pi", "/opt/homebrew/bin/pi-native"] {
128
+ let mut wrong = chain.clone();
129
+ wrong.path_entry = PathBuf::from(bad);
130
+ assert!(validate_pi_executable_chain(&wrong).is_err(), "{bad:?}");
131
+ }
134
132
 
135
133
  let mut wrong_catalog = chain.clone();
136
134
  wrong_catalog.catalog_sha256 = "00".repeat(32);
137
135
  assert!(validate_pi_executable_chain(&wrong_catalog).is_err());
138
136
 
139
- let mut direct_binary = chain.clone();
140
- direct_binary.path_entry = PathBuf::from("/opt/homebrew/bin/pi");
141
- direct_binary.path_entry_type = PiExecutableFileType::Binary;
142
- direct_binary.launch_executable = direct_binary.path_entry.clone();
143
- direct_binary.real_binary = direct_binary.path_entry.clone();
144
- assert!(
145
- validate_pi_executable_chain(&direct_binary).is_err(),
146
- "a direct Homebrew binary must not replace the verified PATH wrapper launch entry"
147
- );
148
-
149
137
  assert!(parse_pi_list_models_table(b"provider model\nopenai-codex gpt-5.6-luna\n").is_ok());
150
138
  assert!(parse_pi_list_models_table(b"provider model\n").is_err());
151
139
  assert!(parse_pi_list_models_table(b"provider model\nmalformed\n").is_err());
@@ -178,14 +166,38 @@ fn pi_standard_npm_symlink_is_a_verified_launch_entry() {
178
166
 
179
167
  let (chain, models) = resolve_pi_executable_chain()
180
168
  .expect("the first PATH Pi entry must define direct Pi behavior");
181
- assert_eq!(chain.path_entry, bin.join("pi"));
182
- assert_eq!(chain.path_entry_type, PiExecutableFileType::Symlink);
183
- assert_eq!(chain.launch_executable, bin.join("pi"));
169
+ assert_eq!(chain.path_entry, bin.join("pi"), "the npm symlink is kept as found");
170
+ assert_eq!(models, ["team-agent/qwen3.8-27b"]);
171
+
172
+ // A user wrapper prepended to PATH is the entry, and every probe runs it.
173
+ let wrappers = root.join("wrappers");
174
+ std::fs::create_dir_all(&wrappers).expect("create wrapper dir");
175
+ let marker = root.join("wrapper-invocations");
176
+ std::fs::write(
177
+ wrappers.join("pi"),
178
+ format!(
179
+ "#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{}'\nexec '{}' \"$@\"\n",
180
+ marker.display(),
181
+ bin.join("pi").display()
182
+ ),
183
+ )
184
+ .expect("write user Pi wrapper");
185
+ std::fs::set_permissions(wrappers.join("pi"), std::fs::Permissions::from_mode(0o755))
186
+ .expect("make user Pi wrapper executable");
187
+ unsafe {
188
+ std::env::set_var(
189
+ "PATH",
190
+ std::env::join_paths([&wrappers, &bin, &later_bin]).expect("join wrapper PATH"),
191
+ );
192
+ }
193
+ let (chain, models) =
194
+ resolve_pi_executable_chain().expect("a user wrapper first on PATH is accepted");
195
+ assert_eq!(chain.path_entry, wrappers.join("pi"));
196
+ assert_eq!(models, ["team-agent/qwen3.8-27b"]);
184
197
  assert_eq!(
185
- chain.real_binary,
186
- std::fs::canonicalize(&real).expect("canonical real Pi entry")
198
+ std::fs::read_to_string(&marker).expect("the wrapper genuinely ran"),
199
+ "--version\n--list-models\n"
187
200
  );
188
- assert_eq!(models, ["team-agent/qwen3.8-27b"]);
189
201
  std::fs::remove_dir_all(root).expect("remove symlink fixture");
190
202
  });
191
203
  }
@@ -678,13 +690,14 @@ fn pi_materializer_and_worker_routes_body(hermetic: &HermeticTestEnv) {
678
690
  .any(|arg| arg.as_str() == other_candidate.to_string_lossy().as_ref())
679
691
  );
680
692
 
681
- let pending_session_id = started_agent
682
- .pending_session_id
683
- .clone()
684
- .expect("fresh worker carries a pending Pi session id");
693
+ assert!(
694
+ started_agent.pending_session_id.is_none(),
695
+ "fresh Pi assigns its own session id"
696
+ );
697
+ let foreign_session_id = format!("{worker}-foreign");
685
698
  write_pi_session_header(
686
699
  &home_candidate,
687
- pending_session_id.as_str(),
700
+ &foreign_session_id,
688
701
  &worker_workspace,
689
702
  "2099-01-01T00:00:00Z",
690
703
  );
@@ -698,27 +711,45 @@ fn pi_materializer_and_worker_routes_body(hermetic: &HermeticTestEnv) {
698
711
  .join("foreign.jsonl");
699
712
  write_pi_session_header(
700
713
  &cross_seat,
701
- pending_session_id.as_str(),
714
+ &foreign_session_id,
702
715
  &worker_workspace,
703
716
  "2099-01-01T00:00:00Z",
704
717
  );
705
- let candidates = scan_session_candidates_once(
706
- Provider::Pi,
707
- &CaptureSessionContext {
708
- agent_id: worker.to_string(),
709
- spawn_cwd: worker_workspace.clone(),
710
- pane_id: None,
711
- pane_pid: None,
712
- spawned_at: Some(started_agent.spawned_at.clone()),
713
- expected_session_id: Some(pending_session_id),
714
- provider_projects_root: Some(paths.sessions.clone()),
715
- },
716
- )
717
- .expect("scan the recorded worker seat only");
718
+ let context = CaptureSessionContext {
719
+ agent_id: worker.to_string(),
720
+ spawn_cwd: worker_workspace.clone(),
721
+ pane_id: None,
722
+ pane_pid: None,
723
+ spawned_at: Some(started_agent.spawned_at.clone()),
724
+ expected_session_id: None,
725
+ provider_projects_root: Some(paths.sessions.clone()),
726
+ };
727
+ let candidates = scan_session_candidates_once(Provider::Pi, &context)
728
+ .expect("scan the recorded worker seat only");
718
729
  assert!(
719
730
  candidates.is_empty(),
720
731
  "HOME and another worker seat must not become capture candidates: {candidates:?}"
721
732
  );
733
+ // Positive control: Pi's own header inside the recorded seat is captured.
734
+ let own = paths.sessions.join("own.jsonl");
735
+ write_pi_session_header(
736
+ &own,
737
+ &format!("{worker}-own"),
738
+ &worker_workspace,
739
+ "2099-01-01T00:00:00Z",
740
+ );
741
+ let candidates = scan_session_candidates_once(Provider::Pi, &context)
742
+ .expect("scan the recorded worker seat only");
743
+ assert_eq!(candidates.len(), 1, "{candidates:?}");
744
+ assert_eq!(
745
+ candidates[0]
746
+ .captured
747
+ .session_id
748
+ .as_ref()
749
+ .map(SessionId::as_str),
750
+ Some(format!("{worker}-own").as_str())
751
+ );
752
+ std::fs::remove_file(&cross_seat).expect("clear foreign header from the other seat");
722
753
  }
723
754
 
724
755
  let restart_workspace = hermetic.workspace("worker-restart");
@@ -812,7 +812,25 @@ fn r05_bad_source_tuples_and_jsonl_fail_closed_without_a_fresh_target() {
812
812
  }
813
813
  _ => unreachable!(),
814
814
  }
815
- fixture.save_state(&state);
815
+ if case == "missing-tuple" {
816
+ // An ordinary save backfills the latest complete tuple (stale-writer
817
+ // protection), so only a capture-backfill-skipping writer can drop it.
818
+ team_agent::state::projection::save_team_scoped_state_with_lifecycle_topology_authority_and_capture_backfill_skip(
819
+ &fixture.run_workspace,
820
+ &state,
821
+ &fixture.team_key,
822
+ &[SOURCE],
823
+ &[],
824
+ )
825
+ .expect("persist the incomplete source tuple");
826
+ } else {
827
+ fixture.save_state(&state);
828
+ }
829
+ assert_eq!(
830
+ fixture.state()["agents"][SOURCE]["rollout_path"],
831
+ state["agents"][SOURCE]["rollout_path"],
832
+ "R05 ({case}): the adversarial source row must be what fork reads"
833
+ );
816
834
  let transport = fixture.transport();
817
835
  let result = fixture.fork(TARGET, None, &transport);
818
836
  assert!(
@@ -133,6 +133,27 @@ fn pi_session_capture_requires_header_id_cwd_generation_and_unique_claim() {
133
133
  std::fs::remove_dir_all(root).expect("remove session fixture");
134
134
  }
135
135
 
136
+ #[test]
137
+ fn pi_fresh_capture_reads_the_header_id_pi_wrote() {
138
+ let root = temp_root("native-header");
139
+ let cwd = root.join("workspace");
140
+ let sessions = root.join("seat/sessions");
141
+ std::fs::create_dir_all(&cwd).expect("create cwd");
142
+ let native_id = "410271aa-2a95-46fe-a92e-41927688fb0c";
143
+ let path = sessions.join("pi-created.jsonl");
144
+ write_header(&path, native_id, &cwd, "2026-08-29T10:00:01Z");
145
+ let mut context = scan_context(&cwd, &sessions, "unused", "2026-08-29T10:00:00Z");
146
+ context.expected_session_id = None;
147
+
148
+ let candidates = scan_session_candidates_once(Provider::Pi, &context).expect("native header scan");
149
+ assert_eq!(candidates.len(), 1);
150
+ assert_eq!(
151
+ candidates[0].captured.session_id.as_ref().map(SessionId::as_str),
152
+ Some(native_id)
153
+ );
154
+ std::fs::remove_dir_all(root).expect("remove native header fixture");
155
+ }
156
+
136
157
  #[test]
137
158
  fn pi_restart_uses_exact_path_and_refuses_missing_backing() {
138
159
  let root = temp_root("resume");
@@ -2587,9 +2587,11 @@ fn leader_rollout_path(state: &serde_json::Value) -> Option<std::path::PathBuf>
2587
2587
  pane_id: None,
2588
2588
  pane_pid: None,
2589
2589
  spawned_at: Some(native.get("spawned_at")?.as_str()?.into()),
2590
- expected_session_id: Some(crate::provider::SessionId::new(
2591
- native.get("expected_session_id")?.as_str()?,
2592
- )),
2590
+ expected_session_id: native
2591
+ .get("expected_session_id")
2592
+ .and_then(|value| value.as_str())
2593
+ .filter(|value| !value.is_empty())
2594
+ .map(crate::provider::SessionId::new),
2593
2595
  provider_projects_root: Some(native.get("provider_projects_root")?.as_str()?.into()),
2594
2596
  };
2595
2597
  if !context.spawn_cwd.is_absolute()
@@ -18,7 +18,9 @@ use crate::provider::command_helpers::{append_opt_pair, append_pair};
18
18
 
19
19
  #[derive(Debug, Clone, Copy)]
20
20
  pub(crate) enum PiSessionSelector<'a> {
21
- Fresh { session_id: &'a str },
21
+ /// Pi assigns the session id. Passing `--session-id` makes Pi warn and
22
+ /// then create, because the id is not a project session yet.
23
+ Fresh,
22
24
  Resume { path: &'a Path },
23
25
  }
24
26
 
@@ -74,9 +76,7 @@ pub(crate) fn build_pi_command_argv(
74
76
  // Keep the pure argv builder usable before a fixture root is materialized, while
75
77
  // refusing a missing exact file once the recorded path's parent exists.
76
78
  match request.session {
77
- PiSessionSelector::Fresh { session_id } if !session_id.trim().is_empty() => {
78
- append_pair(&mut argv, "--session-id", session_id);
79
- }
79
+ PiSessionSelector::Fresh => {}
80
80
  PiSessionSelector::Resume { path }
81
81
  if !path.as_os_str().is_empty()
82
82
  && (!path.parent().is_some_and(Path::is_dir) || path.is_file()) =>