返回 CodeWhale
lib.rs
根目录 / crates / dependencies / src / lib.rs
1 //! External-binary dependency resolution for tools that shell out to
2 //! locally-installed programs (Python for `code_execution` / RLM REPL,
3 //! `pdftotext` for PDF reading in `read_file`, future tools as added).
4 //!
5 //! Before v0.8.31, tools that called external binaries hardcoded the
6 //! command name and failed at execution time when the binary wasn't on
7 //! `PATH`. The most-cited example was `code_execution`, which spawned
8 //! `python3` directly — Windows users (where the launcher is `py` or
9 //! `python`, not `python3`) saw `Failed to execute tool: program not
10 //! found` with no upstream hint of what was wrong.
11 //!
12 //! This module centralises the probe-then-decide pattern. The supported
13 //! callers today are:
14 //!
15 //! - Tool catalog construction (`core::engine::tool_catalog`): for
16 //! tools that should be advertised to the model only when the
17 //! required runtime is present.
18 //! - Doctor command (`run_doctor` in `main.rs`): for surfacing the
19 //! resolved state to the user so missing dependencies aren't an
20 //! invisible failure.
21 //! - Long-lived REPL runtime (`repl::runtime`): for RLM and inline `repl`
22 //! blocks that need to spawn Python on every supported platform.
23 //!
24 //! Results are cached for the process lifetime via [`std::sync::OnceLock`]
25 //! — probing a binary involves a `Command::output` per candidate and
26 //! we'd rather not pay that on every model turn.
27
28 use std::io;
29 use std::path::{Path, PathBuf};
30 use std::process::{Command, Output};
31 use std::sync::OnceLock;
32 use std::time::Duration;
33 use wait_timeout::ChildExt;
34
35 /// Candidate executable names for the Python interpreter, in the
36 /// order we try them. On Windows the launcher convention is `py -3`,
37 /// so we add it as a third option; the resolver splits on whitespace
38 /// at execution time so `py -3 /tmp/code.py` runs correctly.
39 ///
40 /// Order matters: `python3` first because it's the unambiguous v3
41 /// binary on Unix and rules out Python 2 leftovers. `python` second
42 /// covers Windows installations that drop the version suffix and
43 /// modern macOS where Homebrew installs both. `py -3` last as a
44 /// Windows-launcher fallback.
45 pub const PYTHON_CANDIDATES: &[&str] = &["python3", "python", "py -3"];
46
47 /// Probe a single executable. Returns `true` when the candidate
48 /// responds to `--version` with a successful exit. Splits on
49 /// whitespace so `"py -3"` works as a candidate.
50 ///
51 /// We deliberately use `--version` rather than `which` so the probe
52 /// is portable across Unix, Windows (no `which` by default), and
53 /// containers. The downside is that we spawn a subprocess per
54 /// candidate; the resolver caches the result so this only fires
55 /// once per process.
56 #[must_use]
57 pub fn probe_executable(spec: &str) -> bool {
58 probe_executable_with_flag(spec, "--version")
59 }
60
61 /// Probe a single executable using an explicit version/help flag.
62 ///
63 /// Most tools report their presence via `--version`, but some do not:
64 /// Poppler's `pdftotext` treats `--version` as an input *filename* and
65 /// exits non-zero ("I/O Error: Couldn't open file '--version'"), so the
66 /// default probe reports it missing even when it is installed (#1667).
67 /// Such tools pass their own flag (e.g. `-v`) here.
68 #[must_use]
69 pub fn probe_executable_with_flag(spec: &str, version_flag: &str) -> bool {
70 let mut parts = spec.split_whitespace();
71 let Some(program) = parts.next() else {
72 return false;
73 };
74 let mut cmd = version_probe_command(program);
75 cmd.args(parts).arg(version_flag);
76 probe_found(&mut cmd)
77 }
78
79 /// A probe that launched and was still running at its deadline found an
80 /// installed tool that is slow under load; only a failed launch or a failing
81 /// exit means the tool is absent.
82 fn probe_found(command: &mut Command) -> bool {
83 match probe_output(command, false, VERSION_PROBE_TIMEOUT) {
84 Ok(output) => output.status.success(),
85 Err(error) => error.kind() == std::io::ErrorKind::TimedOut,
86 }
87 }
88
89 /// Probe a single executable and capture its version banner in one spawn.
90 ///
91 /// Same contract as [`probe_executable`] (success = exit 0), but returns the
92 /// trimmed stdout so callers that want the banner don't need a second process
93 /// launch. Returns `None` when the probe fails or stdout is not valid UTF-8.
94 pub fn probe_executable_capturing(spec: &str, version_flag: &str) -> Option<String> {
95 let mut parts = spec.split_whitespace();
96 let program = parts.next()?;
97 let mut cmd = version_probe_command(program);
98 cmd.args(parts).arg(version_flag);
99 let output = probe_output(&mut cmd, true, VERSION_PROBE_TIMEOUT).ok()?;
100 if !output.status.success() {
101 return None;
102 }
103 String::from_utf8(output.stdout)
104 .ok()
105 .map(|s| s.trim().to_string())
106 .filter(|s| !s.is_empty())
107 }
108
109 const VERSION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
110 const VERSION_PROBE_MAX_OUTPUT: u64 = 16 * 1024;
111
112 fn version_probe_command(program: impl AsRef<std::ffi::OsStr>) -> Command {
113 let mut cmd = Command::new(program);
114 codewhale_util::utils::suppress_console_window(&mut cmd);
115 codewhale_runtime::child_env::apply_to_command(&mut cmd, std::iter::empty::<(&str, &str)>());
116 // A presence probe needs no bootstrap code or import paths from the
117 // parent. The general child allowlist retains these for normal SDK tools.
118 for key in ["NODE_OPTIONS", "NODE_PATH", "PYTHONPATH", "RUSTC_WRAPPER"] {
119 cmd.env_remove(key);
120 }
121 cmd
122 }
123
124 const TOOLCHAIN_PIN_MAX_BYTES: u64 = 4096;
125 const TOOLCHAIN_PIN_MAX_NAME: usize = 64;
126
127 fn rustup_probe_dir() -> Option<PathBuf> {
128 let codewhale_home = codewhale_runtime::config::home_config_path()
129 .and_then(|path| path.parent().map(Path::to_path_buf));
130 codewhale_home
131 .into_iter()
132 .chain(codewhale_paths::user_home())
133 .filter_map(|directory| std::fs::canonicalize(directory).ok())
134 .find(|directory| directory.is_dir())
135 }
136
137 fn is_plain_toolchain_name(name: &str) -> bool {
138 let mut characters = name.chars();
139 name.len() <= TOOLCHAIN_PIN_MAX_NAME
140 && characters
141 .next()
142 .is_some_and(|first| first.is_ascii_alphanumeric())
143 && characters.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
144 }
145
146 fn toolchain_pin_channel(text: &str, legacy: bool) -> Option<String> {
147 let channel = if legacy && text.lines().count() == 1 {
148 text.trim().to_string()
149 } else {
150 let table: toml::Table = toml::from_str(text).ok()?;
151 let toolchain = table.get("toolchain")?.as_table()?;
152 if toolchain.contains_key("path") {
153 return None;
154 }
155 toolchain.get("channel")?.as_str()?.to_string()
156 };
157 is_plain_toolchain_name(&channel).then_some(channel)
158 }
159
160 fn workspace_toolchain_channel(workspace: &Path) -> Option<String> {
161 use std::io::Read as _;
162 for directory in workspace.ancestors() {
163 for (name, legacy) in [("rust-toolchain", true), ("rust-toolchain.toml", false)] {
164 let path = directory.join(name);
165 match std::fs::symlink_metadata(&path) {
166 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
167 Err(_) => return None,
168 Ok(_) => {}
169 }
170 let file = codewhale_util::bundle_file::open_bundle_file(&path).ok()?;
171 let mut text = String::new();
172 file.take(TOOLCHAIN_PIN_MAX_BYTES + 1)
173 .read_to_string(&mut text)
174 .ok()?;
175 if text.len() as u64 > TOOLCHAIN_PIN_MAX_BYTES {
176 return None;
177 }
178 return toolchain_pin_channel(&text, legacy);
179 }
180 }
181 None
182 }
183
184 fn toolchain_file_in_ancestors(start: &Path) -> bool {
185 start.ancestors().any(|directory| {
186 ["rust-toolchain", "rust-toolchain.toml"]
187 .iter()
188 .any(|name| {
189 !matches!(
190 std::fs::symlink_metadata(directory.join(name)),
191 Err(error) if error.kind() == std::io::ErrorKind::NotFound
192 )
193 })
194 })
195 }
196
197 fn rustup_toolchain_installed(channel: &str) -> bool {
198 let home = match std::env::var_os("RUSTUP_HOME").filter(|value| !value.is_empty()) {
199 Some(home) => PathBuf::from(home),
200 None => match codewhale_paths::user_home() {
201 Some(home) => home.join(".rustup"),
202 None => return false,
203 },
204 };
205 let Ok(entries) = std::fs::read_dir(home.join("toolchains")) else {
206 return false;
207 };
208 let prefix = format!("{channel}-");
209 entries.flatten().any(|entry| {
210 entry
211 .file_name()
212 .to_str()
213 .is_some_and(|name| name == channel || name.starts_with(&prefix))
214 })
215 }
216
217 pub fn rustup_command(
218 program: impl AsRef<std::ffi::OsStr>,
219 workspace: Option<&Path>,
220 ) -> Option<Command> {
221 let probe_dir = rustup_probe_dir()?;
222 let program = program.as_ref();
223 if Path::new(program).components().count() > 1 && !Path::new(program).is_absolute() {
224 return None;
225 }
226 for variable in ["RUSTUP_HOME", "CARGO_HOME", "HOME", "USERPROFILE"] {
227 if std::env::var_os(variable)
228 .filter(|value| !value.is_empty())
229 .is_some_and(|value| !Path::new(&value).is_absolute())
230 {
231 return None;
232 }
233 }
234 let search_path = std::env::join_paths(
235 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
236 .filter(|entry| entry.is_absolute()),
237 )
238 .ok()
239 .filter(|joined| !joined.is_empty())?;
240 let mut command = version_probe_command(program);
241 command
242 .current_dir(&probe_dir)
243 .env("PATH", search_path)
244 .env("RUSTUP_AUTO_INSTALL", "0");
245 let user_toolchain = std::env::var_os("RUSTUP_TOOLCHAIN").filter(|value| !value.is_empty());
246 if user_toolchain.is_none() {
247 command.env_remove("RUSTUP_TOOLCHAIN");
248 if let Some(channel) = workspace
249 .and_then(workspace_toolchain_channel)
250 .filter(|channel| rustup_toolchain_installed(channel))
251 {
252 command.env("RUSTUP_TOOLCHAIN", channel);
253 } else if toolchain_file_in_ancestors(&probe_dir) {
254 return None;
255 }
256 }
257 Some(command)
258 }
259
260 pub fn rustup_version(program: &str, workspace: Option<&Path>) -> Option<String> {
261 let mut command = rustup_command(program, workspace)?;
262 command.arg("--version");
263 let output = probe_output(&mut command, true, VERSION_PROBE_TIMEOUT).ok()?;
264 if !output.status.success() {
265 return None;
266 }
267 Some(String::from_utf8_lossy(&output.stdout).trim().to_string()).filter(|s| !s.is_empty())
268 }
269
270 /// Version/help probes never inherit stdin, retain unbounded banners, or leave
271 /// a normal descendant alive after their deadline. No runtime is constructed.
272 fn probe_output(
273 command: &mut Command,
274 capture: bool,
275 timeout: std::time::Duration,
276 ) -> std::io::Result<std::process::Output> {
277 probe_output_bounded(command, capture, timeout, VERSION_PROBE_MAX_OUTPUT)
278 }
279
280 pub fn probe_output_bounded(
281 command: &mut Command,
282 capture: bool,
283 timeout: std::time::Duration,
284 max_output: u64,
285 ) -> std::io::Result<std::process::Output> {
286 use std::io::Read;
287 use std::process::Stdio;
288 command
289 .stdin(Stdio::null())
290 .stderr(Stdio::null())
291 .stdout(if capture {
292 Stdio::piped()
293 } else {
294 Stdio::null()
295 });
296 let (mut child, tree) = codewhale_runtime::process_tree::spawn_contained_std(command)?;
297 let mut tree = Some(tree);
298 let result = (|| {
299 let reader = if capture {
300 let pipe = child
301 .stdout
302 .take()
303 .ok_or_else(|| std::io::Error::other("version probe stdout missing"))?;
304 let (tx, rx) = std::sync::mpsc::sync_channel(1);
305 std::thread::Builder::new()
306 .name("version-probe-output".into())
307 .spawn(move || {
308 let mut bytes = Vec::new();
309 let result = pipe
310 .take(max_output.saturating_add(1))
311 .read_to_end(&mut bytes)
312 .and_then(|_| {
313 if bytes.len() as u64 > max_output {
314 Err(std::io::Error::new(
315 std::io::ErrorKind::InvalidData,
316 "version probe output exceeded limit",
317 ))
318 } else {
319 Ok(bytes)
320 }
321 });
322 let _ = tx.send(result);
323 })?;
324 Some(rx)
325 } else {
326 None
327 };
328 let status = child.wait_timeout(timeout)?.ok_or_else(|| {
329 std::io::Error::new(
330 std::io::ErrorKind::TimedOut,
331 "version probe did not finish before its deadline",
332 )
333 })?;
334 // A successful parent may leave an inherited pipe open in a child.
335 drop(tree.take());
336 let stdout = match reader {
337 Some(reader) => reader
338 .recv_timeout(std::time::Duration::from_millis(250))
339 .map_err(|_| {
340 std::io::Error::new(
341 std::io::ErrorKind::TimedOut,
342 "version probe pipe did not close",
343 )
344 })??,
345 None => Vec::new(),
346 };
347 Ok(std::process::Output {
348 status,
349 stdout,
350 stderr: Vec::new(),
351 })
352 })();
353 if result.is_err() {
354 drop(tree.take());
355 let _ = child.kill();
356 let _ = child.wait_timeout(std::time::Duration::from_millis(250));
357 }
358 result
359 }
360
361 fn executable_path_candidates(program: &str) -> Vec<PathBuf> {
362 let program_path = Path::new(program);
363 if program_path.components().count() > 1 {
364 return vec![program_path.to_path_buf()];
365 }
366
367 let Some(path) = std::env::var_os("PATH") else {
368 return vec![PathBuf::from(program)];
369 };
370
371 let mut candidates = Vec::new();
372 for dir in std::env::split_paths(&path) {
373 let bare = dir.join(program);
374 candidates.push(bare.clone());
375
376 #[cfg(windows)]
377 if Path::new(program).extension().is_none() {
378 let pathext =
379 std::env::var_os("PATHEXT").unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
380 for ext in pathext.to_string_lossy().split(';') {
381 if ext.is_empty() {
382 continue;
383 }
384 candidates.push(bare.with_extension(ext.trim_start_matches('.')));
385 }
386 }
387 }
388
389 candidates
390 }
391
392 fn resolve_executable_path(spec: &str, version_flag: &str) -> Option<String> {
393 let mut parts = spec.split_whitespace();
394 let program = parts.next()?;
395 let args: Vec<&str> = parts.collect();
396
397 for candidate in executable_path_candidates(program) {
398 if !candidate.is_file() {
399 continue;
400 }
401
402 let mut cmd = version_probe_command(&candidate);
403 cmd.args(&args).arg(version_flag);
404
405 if probe_found(&mut cmd) {
406 return Some(candidate.to_string_lossy().into_owned());
407 }
408 }
409
410 None
411 }
412
413 /// Resolve the Python interpreter once per process. Returns the
414 /// candidate spec (e.g. `"python3"` or `"py -3"`) that succeeded,
415 /// or `None` when every candidate failed.
416 ///
417 /// Callers that need to spawn the interpreter should split this
418 /// string on whitespace — see [`split_interpreter_spec`].
419 pub fn resolve_python_interpreter() -> Option<String> {
420 static CACHE: OnceLock<Option<String>> = OnceLock::new();
421 CACHE
422 .get_or_init(|| {
423 for candidate in PYTHON_CANDIDATES {
424 if probe_executable(candidate) {
425 tracing::info!(
426 target: "tool_dependencies",
427 candidate = candidate,
428 "Resolved Python interpreter",
429 );
430 return Some((*candidate).to_string());
431 }
432 }
433 tracing::warn!(
434 target: "tool_dependencies",
435 tried = ?PYTHON_CANDIDATES,
436 "No Python interpreter found",
437 );
438 None
439 })
440 .clone()
441 }
442
443 /// Resolve `pdftotext` (from Poppler) once per process. Used by
444 /// file and web PDF paths for truthful availability diagnostics. Unlike
445 /// the Python case, `read_file` itself still works for text files
446 /// when `pdftotext` is missing — this resolver exists so the doctor
447 /// command can surface the miss before a PDF read returns its typed
448 /// `binary_unavailable` result.
449 pub fn resolve_pdftotext() -> Option<String> {
450 static CACHE: OnceLock<Option<String>> = OnceLock::new();
451 CACHE
452 .get_or_init(|| {
453 // Poppler's `pdftotext` rejects `--version` (it is parsed as an
454 // input filename and exits non-zero), so probe with `-v`, which
455 // prints the version banner and exits 0 (#1667).
456 if probe_executable_with_flag("pdftotext", "-v") {
457 Some("pdftotext".to_string())
458 } else {
459 None
460 }
461 })
462 .clone()
463 }
464
465 /// Resolve `tesseract` (OCR engine) once per process. Used by the
466 /// `image_ocr` tool on platforms that do not have a native OCR backend.
467 /// Tesseract is the de-facto open-source OCR engine and ships as a single
468 /// binary on every platform we support, so the candidate list is just
469 /// `tesseract`.
470 pub fn resolve_tesseract() -> Option<String> {
471 static CACHE: OnceLock<Option<String>> = OnceLock::new();
472 CACHE
473 .get_or_init(|| {
474 if probe_executable("tesseract") {
475 tracing::info!(
476 target: "tool_dependencies",
477 "Resolved tesseract binary for image_ocr",
478 );
479 Some("tesseract".to_string())
480 } else {
481 tracing::warn!(
482 target: "tool_dependencies",
483 "tesseract binary not found; image_ocr will rely on native OCR if available",
484 );
485 None
486 }
487 })
488 .clone()
489 }
490
491 /// Resolve `pandoc` (universal document converter) once per
492 /// process. Used by the `pandoc_convert` tool to decide whether
493 /// to register itself with the model. Pandoc is a single-binary
494 /// install, so the candidate list is just `pandoc` — no platform
495 /// fallback path.
496 pub fn resolve_pandoc() -> Option<String> {
497 static CACHE: OnceLock<Option<String>> = OnceLock::new();
498 CACHE
499 .get_or_init(|| {
500 if let Some(path) = resolve_executable_path("pandoc", "--version") {
501 tracing::info!(
502 target: "tool_dependencies",
503 "Resolved pandoc binary for pandoc_convert",
504 );
505 Some(path)
506 } else {
507 tracing::warn!(
508 target: "tool_dependencies",
509 "pandoc binary not found; pandoc_convert tool will not be registered",
510 );
511 None
512 }
513 })
514 .clone()
515 }
516
517 /// Whether an optional tool whose backend lives on this host (an interpreter,
518 /// a converter, an OCR engine) is available: `probe` decides, except that a
519 /// test fixture answers with the recorded host's set so results do not
520 /// depend on what the machine running them has installed (test builds only).
521 pub fn host_tool_available(tool: &str, probe: impl FnOnce() -> bool) -> bool {
522 #[cfg(any(test, feature = "test-support"))]
523 if let Some(available) = RECORDED_HOST_TOOLS.with(|cell| {
524 cell.borrow()
525 .as_ref()
526 .map(|tools| tools.iter().any(|name| name == tool))
527 }) {
528 return available;
529 }
530 // Only test fixtures read the name.
531 #[cfg(not(any(test, feature = "test-support")))]
532 let _ = tool;
533 probe()
534 }
535
536 #[cfg(any(test, feature = "test-support"))]
537 thread_local! {
538 static RECORDED_HOST_TOOLS: std::cell::RefCell<Option<Vec<String>>> =
539 const { std::cell::RefCell::new(None) };
540 }
541
542 /// Pin [`host_tool_available`] on this thread to a recorded host's tools until
543 /// the guard drops.
544 #[cfg(any(test, feature = "test-support"))]
545 pub fn pin_recorded_host_tools(tools: Vec<String>) -> RecordedHostToolsGuard {
546 RECORDED_HOST_TOOLS.with(|cell| *cell.borrow_mut() = Some(tools));
547 RecordedHostToolsGuard
548 }
549
550 #[cfg(any(test, feature = "test-support"))]
551 pub struct RecordedHostToolsGuard;
552
553 #[cfg(any(test, feature = "test-support"))]
554 impl Drop for RecordedHostToolsGuard {
555 fn drop(&mut self) {
556 RECORDED_HOST_TOOLS.with(|cell| *cell.borrow_mut() = None);
557 }
558 }
559
560 /// A Node.js runtime chosen by *running* each candidate, plus every candidate
561 /// rejected on the way and why (for `/plugin` and doctor diagnostics).
562 #[derive(Debug, Clone, PartialEq, Eq, Default)]
563 pub struct NodeResolution {
564 pub selected: Option<(PathBuf, (u32, u32, u32))>,
565 pub rejected: Vec<(PathBuf, String)>,
566 }
567
568 impl NodeResolution {
569 /// One-line human summary of why no `kind` candidate was selected.
570 #[must_use]
571 pub fn describe_rejections(&self, kind: HostRuntimeKind) -> String {
572 if self.rejected.is_empty() {
573 return format!("no `{}` found {}", kind.name(), kind.search_scope());
574 }
575 self.rejected
576 .iter()
577 .map(|(path, reason)| format!("{}: {reason}", path.display()))
578 .collect::<Vec<_>>()
579 .join("; ")
580 }
581 }
582
583 /// `major.minor.patch` at the start of `text`, ignoring any pre-release or
584 /// build suffix (`1.4.2-canary.3+abc`).
585 fn parse_version_triple(text: &str) -> Option<(u32, u32, u32)> {
586 let mut parts = text.split(['.', '-', '+']);
587 let major = parts.next()?.parse().ok()?;
588 let minor = parts.next()?.parse().ok()?;
589 let patch = parts.next()?.parse().ok()?;
590 Some((major, minor, patch))
591 }
592
593 /// Parse `node --version` output (`v22.20.0`).
594 #[must_use]
595 pub fn parse_node_version(banner: &str) -> Option<(u32, u32, u32)> {
596 parse_version_triple(banner.trim().strip_prefix('v')?)
597 }
598
599 /// Whether `version` satisfies the extension host floor `^22.19 || >=24`
600 /// (the DSH `engines` range: odd-numbered 23 is not an LTS line).
601 #[must_use]
602 pub fn node_version_supported_for_extension_host(version: (u32, u32, u32)) -> bool {
603 let (major, minor, _) = version;
604 (major == 22 && minor >= 19) || major >= 24
605 }
606
607 /// Parse `bun --version` output (`1.4.0`, or `1.4.0-canary.1+abc`).
608 #[must_use]
609 pub fn parse_bun_version(banner: &str) -> Option<(u32, u32, u32)> {
610 parse_version_triple(banner.trim())
611 }
612
613 /// The oldest Bun the extension host accepts. The `Bun.plugin` module shim,
614 /// `--no-install`, `--no-env-file`, the macOS jetsam memory limit and the
615 /// native-code lockdown were measured against Bun 1.4.0 on macOS 26.1 arm64
616 /// only. CI's JS host-suite leg installs Bun 1.4.0 on `ubuntu-latest`; the
617 /// Rust host integration tests do not run on Bun in CI, and no Windows Bun
618 /// run is recorded. A newer Bun on which a lock no longer holds fails the
619 /// host's start (`extension-host/src/runtime.ts`).
620 pub const BUN_MIN_VERSION_FOR_EXTENSION_HOST: (u32, u32, u32) = (1, 4, 0);
621
622 /// Node flags that switch off builtins able to load native code in-process:
623 /// `node:sqlite` (SQLite extensions are `dlopen`ed even under `--no-addons`)
624 /// and `node:ffi` (on by default where it exists: Node 26.10 has it, 22.20 and
625 /// 24.19 reject the flag). Each is passed only when the chosen Node accepts
626 /// it; the host refuses to start if either builtin is still available.
627 pub const NODE_NATIVE_CODE_FLAGS: &[&str] = &["--no-experimental-sqlite", "--no-experimental-ffi"];
628
629 /// A JavaScript runtime that can run the extension host.
630 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
631 pub enum HostRuntimeKind {
632 Bun,
633 Node,
634 }
635
636 impl HostRuntimeKind {
637 /// The name the host reports in `host/hello` (`bun` / `node`).
638 #[must_use]
639 pub fn name(self) -> &'static str {
640 match self {
641 Self::Bun => "bun",
642 Self::Node => "node",
643 }
644 }
645
646 fn program(self) -> &'static str {
647 match (self, cfg!(windows)) {
648 (Self::Bun, false) => "bun",
649 (Self::Bun, true) => "bun.exe",
650 (Self::Node, false) => "node",
651 (Self::Node, true) => "node.exe",
652 }
653 }
654
655 fn floor(self) -> String {
656 match self {
657 Self::Bun => {
658 let (major, minor, patch) = BUN_MIN_VERSION_FOR_EXTENSION_HOST;
659 format!(">={major}.{minor}.{patch}")
660 }
661 // `node_version_supported_for_extension_host`.
662 Self::Node => "^22.19 || >=24".to_string(),
663 }
664 }
665
666 /// Where a search for this runtime looks ([`runtime_candidates`]).
667 fn search_scope(self) -> &'static str {
668 match self {
669 Self::Bun => "on PATH or in $BUN_INSTALL/bin (default ~/.bun/bin)",
670 Self::Node => "on PATH",
671 }
672 }
673
674 fn parse(self, banner: &str) -> Option<(u32, u32, u32)> {
675 match self {
676 Self::Bun => parse_bun_version(banner),
677 Self::Node => parse_node_version(banner),
678 }
679 }
680
681 fn supported(self, version: (u32, u32, u32)) -> bool {
682 match self {
683 Self::Bun => version >= BUN_MIN_VERSION_FOR_EXTENSION_HOST,
684 Self::Node => node_version_supported_for_extension_host(version),
685 }
686 }
687 }
688
689 /// The runtime chosen for the extension host.
690 #[derive(Debug, Clone, PartialEq, Eq)]
691 pub struct HostRuntime {
692 pub kind: HostRuntimeKind,
693 pub path: PathBuf,
694 pub version: (u32, u32, u32),
695 /// Node: the [`NODE_NATIVE_CODE_FLAGS`] this Node accepts. Empty for Bun.
696 pub native_code_flags: Vec<&'static str>,
697 /// The canonical host entry is embedded in this Bun executable.
698 pub compiled: bool,
699 }
700
701 impl HostRuntime {
702 #[must_use]
703 pub fn version_string(&self) -> String {
704 let (major, minor, patch) = self.version;
705 format!("{major}.{minor}.{patch}")
706 }
707
708 /// Whether a version the running host reported (`process.versions.bun`
709 /// or `process.versions.node`: no `v`, maybe a pre-release suffix) is the
710 /// version this runtime's probe saw.
711 #[must_use]
712 pub fn reports_version(&self, reported: &str) -> bool {
713 parse_version_triple(reported.trim().trim_start_matches('v')) == Some(self.version)
714 }
715 }
716
717 /// The outcome of `[extension_host] runtime` selection, with every rejected
718 /// candidate (for `/plugin` and doctor). `bun` / `node` are `None` when that
719 /// runtime was not probed.
720 #[derive(Debug, Clone, PartialEq, Eq)]
721 pub struct HostRuntimeResolution {
722 pub choice: codewhale_config::extension_host::ExtensionHostRuntime,
723 pub selected: Option<HostRuntime>,
724 pub bun: Option<NodeResolution>,
725 pub node: Option<NodeResolution>,
726 }
727
728 impl HostRuntimeResolution {
729 /// One line: what runs the host and why, including why Bun was passed
730 /// over when `auto` fell back to Node, and every candidate of the chosen
731 /// runtime that was skipped or rejected on the way.
732 #[must_use]
733 pub fn summary(&self) -> String {
734 let choice = self.choice.as_str();
735 let Some(runtime) = &self.selected else {
736 return self.failure();
737 };
738 let mut line = format!(
739 "{} {} at {} (runtime = \"{choice}\")",
740 runtime.kind.name(),
741 runtime.version_string(),
742 runtime.path.display()
743 );
744 if runtime.compiled {
745 line.push_str("; compiled canonical host (runtime embedded)");
746 }
747 if runtime.kind == HostRuntimeKind::Node
748 && let Some(bun) = &self.bun
749 {
750 line.push_str(&format!(
751 "; Bun {} not used: {}",
752 HostRuntimeKind::Bun.floor(),
753 bun.describe_rejections(HostRuntimeKind::Bun)
754 ));
755 }
756 let probed = match runtime.kind {
757 HostRuntimeKind::Bun => self.bun.as_ref(),
758 HostRuntimeKind::Node => self.node.as_ref(),
759 };
760 if let Some(probed) = probed
761 && !probed.rejected.is_empty()
762 {
763 line.push_str(&format!(
764 "; passed over: {}",
765 probed.describe_rejections(runtime.kind)
766 ));
767 }
768 line
769 }
770
771 /// Why no runtime was selected.
772 #[must_use]
773 pub fn failure(&self) -> String {
774 let mut reasons = Vec::new();
775 if let Some(bun) = &self.bun {
776 reasons.push(format!(
777 "bun: {}",
778 bun.describe_rejections(HostRuntimeKind::Bun)
779 ));
780 }
781 if let Some(node) = &self.node {
782 reasons.push(format!(
783 "node: {}",
784 node.describe_rejections(HostRuntimeKind::Node)
785 ));
786 }
787 let (bun, node) = (HostRuntimeKind::Bun.floor(), HostRuntimeKind::Node.floor());
788 let wanted = match self.choice {
789 codewhale_config::extension_host::ExtensionHostRuntime::Auto => {
790 format!("Bun {bun} or Node.js {node} (set `[extension_host] bun` or `node`)")
791 }
792 codewhale_config::extension_host::ExtensionHostRuntime::Bun => {
793 format!("Bun {bun} (`runtime = \"bun\"`; set `[extension_host] bun`)")
794 }
795 codewhale_config::extension_host::ExtensionHostRuntime::Node => {
796 format!("Node.js {node} (set `[extension_host] node`)")
797 }
798 };
799 format!("the plugin host needs {wanted}; {}", reasons.join("; "))
800 }
801 }
802
803 /// A probe of a runtime binary: no inherited environment (no credentials, no
804 /// `NODE_OPTIONS` preloads), since it runs unsandboxed; Windows needs
805 /// `SystemRoot` to load system DLLs.
806 fn probe_command(path: &Path) -> Command {
807 let mut cmd = Command::new(path);
808 codewhale_util::utils::suppress_console_window(&mut cmd);
809 cmd.env_clear();
810 #[cfg(windows)]
811 if let Some(root) = std::env::var_os("SystemRoot") {
812 cmd.env("SystemRoot", root);
813 }
814 cmd.stdin(std::process::Stdio::null())
815 .stderr(std::process::Stdio::null());
816 cmd
817 }
818
819 fn probe_runtime_version(
820 kind: HostRuntimeKind,
821 path: &Path,
822 bundle_sha256: &str,
823 ) -> Result<(u32, u32, u32), String> {
824 // Only absolute candidates are run: a relative `PATH` entry resolves
825 // against the current (workspace) directory, where a repository could
826 // plant a `node`.
827 if !path.is_absolute() {
828 return Err("not an absolute path; skipped".to_string());
829 }
830 let mut cmd = probe_command(path);
831 let compiled = kind == HostRuntimeKind::Bun && is_compiled_host_path(path);
832 cmd.arg(if compiled {
833 "--codewhale-host-info"
834 } else {
835 "--version"
836 });
837 let output = probe_output(&mut cmd, true, VERSION_PROBE_TIMEOUT)
838 .map_err(|error| format!("does not start ({error})"))?;
839 if !output.status.success() {
840 return Err(format!("does not run (exit {})", output.status));
841 }
842 if compiled {
843 return parse_compiled_host_info(&output.stdout, bundle_sha256);
844 }
845 let banner = String::from_utf8_lossy(&output.stdout);
846 kind.parse(&banner)
847 .ok_or_else(|| format!("unrecognized version banner `{}`", banner.trim()))
848 }
849
850 /// A packaged host is adjacent to the running Engine, not searched in a
851 /// repository or downloaded at launch. Explicit runtime overrides remain sole
852 /// candidates; `runtime = "node"` never probes this optional Bun image.
853 fn compiled_host_candidate() -> Option<PathBuf> {
854 let executable = std::env::current_exe().ok()?;
855 let candidate = executable.parent()?.join(if cfg!(windows) {
856 "codewhale-extension-host.exe"
857 } else {
858 "codewhale-extension-host"
859 });
860 candidate.is_file().then_some(candidate)
861 }
862
863 fn is_compiled_host_path(path: &Path) -> bool {
864 path.file_name().is_some_and(|name| {
865 name == "codewhale-extension-host" || name == "codewhale-extension-host.exe"
866 })
867 }
868
869 fn parse_compiled_host_info(
870 bytes: &[u8],
871 expected_source: &str,
872 ) -> Result<(u32, u32, u32), String> {
873 #[derive(serde::Deserialize)]
874 #[serde(deny_unknown_fields)]
875 struct Info {
876 kind: String,
877 runtime: String,
878 platform: String,
879 arch: String,
880 version: String,
881 bundle_sha256: String,
882 }
883 if bytes.len() > 4096 {
884 return Err("compiled host identity exceeds 4096 bytes".to_string());
885 }
886 let info: Info = serde_json::from_slice(bytes)
887 .map_err(|error| format!("invalid compiled host identity ({error})"))?;
888 if info.kind != "codewhale-extension-host" || info.runtime != "bun" {
889 return Err("executable is not a compiled Bun plugin host".to_string());
890 }
891 let expected_platform = match std::env::consts::OS {
892 "macos" => "darwin",
893 "windows" => "win32",
894 os => os,
895 };
896 let expected_arch = match std::env::consts::ARCH {
897 "aarch64" => "arm64",
898 "x86_64" => "x64",
899 arch => arch,
900 };
901 if info.platform != expected_platform || info.arch != expected_arch {
902 return Err("compiled host executed target differs from this Engine".to_string());
903 }
904 if info.bundle_sha256 != expected_source {
905 return Err("compiled host source digest differs from this Engine; reinstall matching release assets or choose a system runtime".to_string());
906 }
907 parse_bun_version(&info.version).ok_or_else(|| "invalid compiled Bun version".to_string())
908 }
909
910 /// Every `program` on `PATH`; for Bun also its default install location
911 /// (`$BUN_INSTALL/bin`, else `~/.bun/bin`), which the Bun installer adds to
912 /// shell profiles but a GUI-launched process may not see.
913 fn runtime_candidates(kind: HostRuntimeKind) -> Vec<PathBuf> {
914 let mut candidates: Vec<PathBuf> = executable_path_candidates(kind.program())
915 .into_iter()
916 .filter(|candidate| candidate.is_file())
917 .collect();
918 if kind == HostRuntimeKind::Bun {
919 let install = std::env::var_os("BUN_INSTALL")
920 .map(PathBuf::from)
921 .or_else(|| codewhale_paths::user_home().map(|home| home.join(".bun")));
922 if let Some(bin) = install.map(|root| root.join("bin").join(kind.program()))
923 && bin.is_file()
924 {
925 candidates.push(bin);
926 }
927 }
928 candidates
929 }
930
931 /// Why a runtime found by *searching* must not be run: it sits in a
932 /// `node_modules` tree (a package's bin shim, such as
933 /// `node_modules/.bin/bun`), or inside the current working directory (usually
934 /// the workspace), where a repository could plant it. Either would run
935 /// unsandboxed as a version probe and then host plugin code. A configured
936 /// override is never checked: naming a path is the opt-in.
937 ///
938 /// Known limits: a working directory that contains the user's home (a
939 /// launch from `~`, or from `/` as GUI apps are) is not treated as a
940 /// workspace, because every user-level install lives under it, so a runtime
941 /// planted directly there is not caught. The `node_modules` test reads the
942 /// `PATH` spelling, not the resolved target, so a global npm install reached
943 /// through a symlink outside `node_modules` still counts as trusted.
944 fn untrusted_location(
945 kind: HostRuntimeKind,
946 candidate: &Path,
947 cwd: Option<&Path>,
948 home: Option<&Path>,
949 ) -> Option<String> {
950 let opt_in = format!("set `[extension_host] {}` to use it anyway", kind.name());
951 if candidate
952 .components()
953 .any(|part| part.as_os_str().eq_ignore_ascii_case("node_modules"))
954 {
955 return Some(format!(
956 "inside a `node_modules` directory; skipped ({opt_in})"
957 ));
958 }
959 let cwd = cwd?;
960 let contains_home = |home: &Path| {
961 home.starts_with(cwd) || std::fs::canonicalize(home).is_ok_and(|home| home.starts_with(cwd))
962 };
963 if cwd.parent().is_none() || home.is_some_and(contains_home) {
964 return None;
965 }
966 // `current_dir` is the resolved path; a `PATH` entry may be spelled
967 // through a symlink (`/tmp` on macOS), so compare its resolved directory.
968 let inside = candidate.starts_with(cwd)
969 || candidate
970 .parent()
971 .and_then(|dir| std::fs::canonicalize(dir).ok())
972 .is_some_and(|dir| dir.starts_with(cwd));
973 inside.then(|| {
974 format!(
975 "inside the working directory {}; skipped ({opt_in})",
976 cwd.display()
977 )
978 })
979 }
980
981 /// Resolve one runtime. A configured override is the only candidate: one
982 /// that does not run or is below the floor fails resolution for this
983 /// runtime with its reason, rather than falling through to a search.
984 /// Otherwise the search candidates, minus those in an [`untrusted_location`],
985 /// which are recorded as rejected without being run. Blocking.
986 fn resolve_runtime(
987 kind: HostRuntimeKind,
988 override_path: Option<&Path>,
989 bundle_sha256: &str,
990 ) -> NodeResolution {
991 if let Some(path) = override_path {
992 return select_runtime(kind, vec![path.to_path_buf()], bundle_sha256);
993 }
994 let cwd = std::env::current_dir().ok();
995 let home = codewhale_paths::user_home();
996 let mut skipped = Vec::new();
997 let compiled = (kind == HostRuntimeKind::Bun)
998 .then(compiled_host_candidate)
999 .flatten();
1000 let candidates = compiled
1001 .iter()
1002 .cloned()
1003 .chain(runtime_candidates(kind))
1004 .filter(|candidate| {
1005 // An image shipped beside the Engine has its install authority.
1006 // It is still probed for the exact embedded source identity.
1007 if compiled.as_ref() == Some(candidate) {
1008 return true;
1009 }
1010 match untrusted_location(kind, candidate, cwd.as_deref(), home.as_deref()) {
1011 Some(reason) => {
1012 skipped.push((candidate.clone(), reason));
1013 false
1014 }
1015 None => true,
1016 }
1017 })
1018 .collect();
1019 let mut resolution = select_runtime(kind, candidates, bundle_sha256);
1020 skipped.append(&mut resolution.rejected);
1021 resolution.rejected = skipped;
1022 resolution
1023 }
1024
1025 /// Choose the extension host's runtime for `[extension_host] runtime`:
1026 /// `bun` and `node` try only that runtime (an explicit choice never falls
1027 /// back); `auto` prefers a supported Bun and otherwise uses Node, recording
1028 /// why Bun was passed over. Blocking: call from `spawn_blocking`.
1029 #[must_use]
1030 pub fn resolve_extension_host_runtime(
1031 choice: codewhale_config::extension_host::ExtensionHostRuntime,
1032 node_override: Option<&Path>,
1033 bun_override: Option<&Path>,
1034 bundle_sha256: &str,
1035 ) -> HostRuntimeResolution {
1036 select_host_runtime(
1037 choice,
1038 || resolve_runtime(HostRuntimeKind::Bun, bun_override, bundle_sha256),
1039 || resolve_runtime(HostRuntimeKind::Node, node_override, bundle_sha256),
1040 )
1041 }
1042
1043 fn select_host_runtime(
1044 choice: codewhale_config::extension_host::ExtensionHostRuntime,
1045 probe_bun: impl FnOnce() -> NodeResolution,
1046 probe_node: impl FnOnce() -> NodeResolution,
1047 ) -> HostRuntimeResolution {
1048 use codewhale_config::extension_host::ExtensionHostRuntime as Choice;
1049 let mut resolution = HostRuntimeResolution {
1050 choice,
1051 selected: None,
1052 bun: None,
1053 node: None,
1054 };
1055 let pick = |kind: HostRuntimeKind, probe: &NodeResolution| {
1056 probe.selected.clone().map(|(path, version)| HostRuntime {
1057 native_code_flags: match kind {
1058 HostRuntimeKind::Bun => Vec::new(),
1059 HostRuntimeKind::Node => accepted_flags(&path, NODE_NATIVE_CODE_FLAGS),
1060 },
1061 compiled: kind == HostRuntimeKind::Bun && is_compiled_host_path(&path),
1062 kind,
1063 path,
1064 version,
1065 })
1066 };
1067 if matches!(choice, Choice::Auto | Choice::Bun) {
1068 let bun = probe_bun();
1069 resolution.selected = pick(HostRuntimeKind::Bun, &bun);
1070 resolution.bun = Some(bun);
1071 }
1072 if resolution.selected.is_none() && matches!(choice, Choice::Auto | Choice::Node) {
1073 let node = probe_node();
1074 resolution.selected = pick(HostRuntimeKind::Node, &node);
1075 resolution.node = Some(node);
1076 }
1077 resolution
1078 }
1079
1080 /// The `flags` a runtime starts with (`<runtime> <flag> --version` exits 0).
1081 /// Blocking: one short probe per flag.
1082 fn accepted_flags(path: &Path, flags: &[&'static str]) -> Vec<&'static str> {
1083 flags
1084 .iter()
1085 .copied()
1086 .filter(|flag| {
1087 let mut cmd = probe_command(path);
1088 cmd.args([*flag, "--version"])
1089 .stdout(std::process::Stdio::null());
1090 cmd.status().is_ok_and(|status| status.success())
1091 })
1092 .collect()
1093 }
1094
1095 fn select_runtime(
1096 kind: HostRuntimeKind,
1097 candidates: Vec<PathBuf>,
1098 bundle_sha256: &str,
1099 ) -> NodeResolution {
1100 let mut seen = std::collections::HashSet::new();
1101 let mut resolution = NodeResolution::default();
1102 for candidate in candidates {
1103 // Deduplicate by spelling only: resolving symlinks here would be a
1104 // blocking call per candidate for a cosmetic gain.
1105 if !seen.insert(candidate.clone()) {
1106 continue;
1107 }
1108 match probe_runtime_version(kind, &candidate, bundle_sha256) {
1109 Ok(version) if kind.supported(version) => {
1110 resolution.selected = Some((candidate, version));
1111 break;
1112 }
1113 Ok((major, minor, patch)) => resolution.rejected.push((
1114 candidate,
1115 format!(
1116 "{major}.{minor}.{patch} is below the {} floor",
1117 kind.floor()
1118 ),
1119 )),
1120 Err(reason) => resolution.rejected.push((candidate, reason)),
1121 }
1122 }
1123 resolution
1124 }
1125
1126 // ---------------------------------------------------------------------------
1127 // ExternalTool trait — unified subprocess interface
1128 // ---------------------------------------------------------------------------
1129
1130 /// A tool that DeepSeek-TUI shells out to. Instead of scattering
1131 /// `Command::new("git")` / `Command::new("gh")` across the codebase,
1132 /// each external dependency implements this trait once in this module.
1133 /// Callers ask the tool for a pre-populated [`Command`] and chain their
1134 /// own args, working directory, and spawn method.
1135 ///
1136 /// # Example
1137 ///
1138 /// ```ignore
1139 /// let output = Git::command()
1140 /// .expect("git not found")
1141 /// .args(["diff", "--stat"])
1142 /// .current_dir(&workspace)
1143 /// .output()?;
1144 /// ```
1145 pub trait ExternalTool {
1146 /// Candidate binary names, tried in order until one responds to
1147 /// `--version`. For single-binary tools (git, gh, node) this is a
1148 /// one-element slice.
1149 fn candidates() -> &'static [&'static str];
1150
1151 /// Resolve the best candidate once per process (cached). Returns
1152 /// the spec string (e.g. `"python3"` or `"py -3"`).
1153 fn resolve() -> Option<String>;
1154
1155 /// Quick availability check — true when the tool was found on PATH.
1156 fn available() -> bool {
1157 Self::resolve().is_some()
1158 }
1159
1160 /// Build a `std::process::Command` pre-populated with the resolved
1161 /// binary (and any fixed arguments from a multi-word candidate like
1162 /// `"py -3"`). Returns `None` when the tool isn't installed.
1163 ///
1164 /// Callers should chain `.args(...)`, `.current_dir(...)`, and then
1165 /// call `.output()`, `.status()`, or `.spawn()`.
1166 fn command() -> Option<Command> {
1167 Some(command_for_spec(&Self::resolve()?))
1168 }
1169
1170 /// The error a caller sees when the tool is not installed. It names the
1171 /// binary the user would install (`git`, `python3`), never the Rust type
1172 /// path (`codewhale_tui::dependencies::Git`).
1173 fn not_found_error() -> std::io::Error {
1174 let name = Self::candidates().first().copied().unwrap_or("tool");
1175 std::io::Error::new(
1176 std::io::ErrorKind::NotFound,
1177 format!("{name} not found on PATH"),
1178 )
1179 }
1180
1181 /// Convenience: run the tool with arguments in a working directory
1182 /// and return the captured output.
1183 fn output(args: &[&str], cwd: &std::path::Path) -> std::io::Result<std::process::Output> {
1184 let mut cmd = Self::command().ok_or_else(Self::not_found_error)?;
1185 cmd.args(args).current_dir(cwd).output()
1186 }
1187
1188 /// Convenience: run the tool with arguments and return only the
1189 /// exit status (discards stdout/stderr).
1190 fn status(args: &[&str], cwd: &std::path::Path) -> std::io::Result<std::process::ExitStatus> {
1191 let mut cmd = Self::command().ok_or_else(Self::not_found_error)?;
1192 cmd.args(args).current_dir(cwd).status()
1193 }
1194
1195 /// Build a `tokio::process::Command` pre-populated with the resolved
1196 /// binary (and any fixed arguments from a multi-word candidate like
1197 /// `"py -3"`). Returns `None` when the tool isn't installed.
1198 ///
1199 /// Async callers (`code_execution`) use this instead
1200 /// of [`ExternalTool::command`] so they can `.await` the child.
1201 fn tokio_command() -> Option<tokio::process::Command> {
1202 let spec = Self::resolve()?;
1203 let (program, fixed_args) = split_interpreter_spec(&spec);
1204 let mut cmd = tokio::process::Command::new(&program);
1205 codewhale_util::utils::suppress_tokio_console_window(&mut cmd);
1206 for arg in &fixed_args {
1207 cmd.arg(arg);
1208 }
1209 Some(cmd)
1210 }
1211 }
1212
1213 /// Build a `std::process::Command` for an interpreter spec such as `"py -3"`.
1214 fn command_for_spec(spec: &str) -> Command {
1215 let (program, fixed_args) = split_interpreter_spec(spec);
1216 let mut cmd = Command::new(&program);
1217 codewhale_util::utils::suppress_console_window(&mut cmd);
1218 for arg in &fixed_args {
1219 cmd.arg(arg);
1220 }
1221 cmd
1222 }
1223
1224 /// [`command_for_spec`] started from the sanitized child environment. Used by
1225 /// the runtime whose every caller runs model-authored code (Python),
1226 /// so no constructor for them hands out the parent's credentials.
1227 fn scrubbed_command_for_spec(spec: &str) -> Command {
1228 let mut cmd = command_for_spec(spec);
1229 codewhale_runtime::child_env::apply_to_command(&mut cmd, std::iter::empty::<(&str, &str)>());
1230 cmd
1231 }
1232
1233 // ---------------------------------------------------------------------------
1234 // Concrete tool implementations
1235 // ---------------------------------------------------------------------------
1236
1237 /// Git version control.
1238 pub struct Git;
1239
1240 /// Keep a git child from ever waiting on a human.
1241 ///
1242 /// Git and ssh read credentials, passphrases and host-key confirmations from
1243 /// `/dev/tty` directly — `stdin(null)` does not stop them — so inside the
1244 /// raw-mode TUI or an HTTP request a prompt is an invisible, indefinite hang.
1245 /// `GIT_TERMINAL_PROMPT=0` makes git fail instead of asking for a username or
1246 /// password; BatchMode ssh fails instead of asking for a passphrase or an
1247 /// unknown host key; an empty `GIT_PAGER` keeps output from ever being paged.
1248 /// A user who pinned their own ssh transport (`GIT_SSH_COMMAND` or `GIT_SSH`)
1249 /// keeps it untouched.
1250 ///
1251 /// This is the single definition site; [`Git::command`] and
1252 /// [`Git::tokio_command`] apply it to every product git spawn. Call it
1253 /// directly only for a non-git program that may shell out to git (`gh`).
1254 pub fn apply_git_noninteractive_env(cmd: &mut Command) {
1255 cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_PAGER", "");
1256 if std::env::var_os("GIT_SSH_COMMAND").is_none() && std::env::var_os("GIT_SSH").is_none() {
1257 cmd.env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes");
1258 }
1259 }
1260
1261 impl Git {
1262 /// Flags every `diff`, `show` or patch `log` that collects repository
1263 /// content passes. `--no-ext-diff`/`--no-textconv` skip diff drivers; a
1264 /// dirty check or `diff.submodule=diff` spawns a child git inside each
1265 /// submodule that inherits neither flag, so submodules compare by commit
1266 /// only. A read that touches the working tree also runs the superproject's
1267 /// clean filters, which no flag disables: build it from
1268 /// [`Self::review_command`] too.
1269 pub const REVIEW_DIFF_ARGS: [&'static str; 4] = [
1270 "--no-ext-diff",
1271 "--no-textconv",
1272 "--submodule=short",
1273 "--ignore-submodules=dirty",
1274 ];
1275
1276 #[cfg(windows)]
1277 pub const INERT_HELPER: &'static str = "cmd.exe /d /c exit 1";
1278 #[cfg(not(windows))]
1279 pub const INERT_HELPER: &'static str = "/usr/bin/false";
1280
1281 const REVIEW_CONFIG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1282
1283 const REVIEW_BASE_CONFIG: [(&'static str, &'static str); 9] = [
1284 ("core.fsmonitor", "false"),
1285 (
1286 "core.hooksPath",
1287 if cfg!(windows) { "NUL" } else { "/dev/null" },
1288 ),
1289 ("core.quotePath", "false"),
1290 ("diff.ignoreSubmodules", "dirty"),
1291 ("log.showSignature", "false"),
1292 ("gpg.program", Self::INERT_HELPER),
1293 ("gpg.openpgp.program", Self::INERT_HELPER),
1294 ("gpg.x509.program", Self::INERT_HELPER),
1295 ("gpg.ssh.program", Self::INERT_HELPER),
1296 ];
1297
1298 /// Construct a read-only review command with content conversion disabled.
1299 /// Review callers also pass [`Self::REVIEW_DIFF_ARGS`] for diffs.
1300 /// Configured filters otherwise execute even when those flags are present.
1301 pub fn review_command(workspace: &Path) -> anyhow::Result<Command> {
1302 let overrides = Self::review_filter_overrides(workspace)?;
1303 Self::with_filter_overrides(workspace, overrides)
1304 }
1305
1306 /// Returns `git status --ignore-submodules=dirty`; callers append output
1307 /// options and pathspecs. Like [`Self::review_command`] it keeps the
1308 /// user's own global or system filters (such as Git LFS) working and
1309 /// neutralizes only repository-controlled filter drivers, falling back to
1310 /// neutralizing every driver if the scoped probe fails.
1311 pub fn status_command(workspace: &Path) -> anyhow::Result<Command> {
1312 let mut command = Self::workspace_command(workspace)?;
1313 command.args(["status", "--ignore-submodules=dirty"]);
1314 Ok(command)
1315 }
1316
1317 pub fn workspace_command(workspace: &Path) -> anyhow::Result<Command> {
1318 let overrides = match Self::filter_overrides(workspace, true) {
1319 Ok(overrides) => overrides,
1320 Err(_) => Self::review_filter_overrides(workspace)?,
1321 };
1322 Self::with_filter_overrides(workspace, overrides)
1323 }
1324
1325 fn with_filter_overrides(
1326 workspace: &Path,
1327 overrides: Vec<(String, &'static str)>,
1328 ) -> anyhow::Result<Command> {
1329 let mut command = Self::review_base(workspace)?;
1330 let mut count = Self::REVIEW_BASE_CONFIG.len();
1331 for (key, value) in overrides {
1332 // A subsection may contain '='; `-c key=value` would then
1333 // override a different key. Separate env fields preserve it.
1334 command.env(format!("GIT_CONFIG_KEY_{count}"), key);
1335 command.env(format!("GIT_CONFIG_VALUE_{count}"), value);
1336 count += 1;
1337 }
1338 command.env("GIT_CONFIG_COUNT", count.to_string());
1339 Ok(command)
1340 }
1341
1342 /// Git with fsmonitor, hooks, lazy fetch, replace objects, path quoting
1343 /// and signature verification (including every signature program)
1344 /// disabled, running in `workspace`, and submodule dirty checks off by
1345 /// default. That default is only a config value: a tracked `.gitmodules`
1346 /// `ignore` entry takes precedence over it, so every `status` or `diff`
1347 /// also passes `--ignore-submodules=dirty` on its own command line
1348 /// ([`Self::REVIEW_DIFF_ARGS`] carries it for diffs). Filter and merge
1349 /// drivers defined in repository config are neutralized only by
1350 /// [`Self::review_command`],
1351 /// [`Self::status_command`] and [`Self::workspace_command`]; filters from
1352 /// the user's global or system config are left alone by the last two.
1353 pub fn review_base(workspace: &Path) -> anyhow::Result<Command> {
1354 use anyhow::Context;
1355
1356 let mut command = Self::command().context("git not found on PATH")?;
1357
1358 // Runtime config pairs are required to disable filter names containing
1359 // '=' without changing which key Git sees. Older Git ignores them.
1360 // Probe once for this process's cached executable, before any read.
1361 // A random value prevents repository config from spoofing support.
1362 static REVIEW_CONFIG_SUPPORTED: OnceLock<bool> = OnceLock::new();
1363 let supported = match REVIEW_CONFIG_SUPPORTED.get() {
1364 Some(supported) => *supported,
1365 None => {
1366 let supported = match Self::command() {
1367 None => false,
1368 Some(mut probe) => {
1369 let value = uuid::Uuid::new_v4().to_string();
1370 probe
1371 .current_dir(workspace)
1372 .env_remove("GIT_CONFIG")
1373 .env_remove("GIT_CONFIG_PARAMETERS")
1374 .env("GIT_CONFIG_COUNT", "1")
1375 .env("GIT_CONFIG_KEY_0", "codewhale.reviewConfigCapability")
1376 .env("GIT_CONFIG_VALUE_0", &value)
1377 .args(["config", "--get", "codewhale.reviewConfigCapability"]);
1378 match run_bounded_git_with_timeout(
1379 &mut probe,
1380 "config",
1381 Self::REVIEW_CONFIG_TIMEOUT,
1382 ) {
1383 Ok(output) => {
1384 output.status.success()
1385 && output.stdout == format!("{value}\n").as_bytes()
1386 }
1387 Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {
1388 let context = format!(
1389 "Cannot safely inspect Git review configuration: {error}"
1390 );
1391 return Err(anyhow::Error::new(error).context(context));
1392 }
1393 Err(_) => false,
1394 }
1395 }
1396 };
1397 *REVIEW_CONFIG_SUPPORTED.get_or_init(|| supported)
1398 }
1399 };
1400 if !supported {
1401 anyhow::bail!(
1402 "Cannot safely inspect Git review configuration: Git runtime configuration overrides are unavailable; upgrade Git (2.31 or newer)"
1403 );
1404 }
1405
1406 command
1407 .current_dir(workspace)
1408 .stdin(std::process::Stdio::null())
1409 // GIT_CONFIG redirects only `git config`, not `git diff`.
1410 // Both phases must observe the same effective repository config.
1411 .env_remove("GIT_CONFIG")
1412 .env_remove("GIT_CONFIG_PARAMETERS")
1413 .env(
1414 "GIT_CONFIG_COUNT",
1415 Self::REVIEW_BASE_CONFIG.len().to_string(),
1416 );
1417 for (index, (key, value)) in Self::REVIEW_BASE_CONFIG.iter().enumerate() {
1418 command.env(format!("GIT_CONFIG_KEY_{index}"), key);
1419 command.env(format!("GIT_CONFIG_VALUE_{index}"), value);
1420 }
1421 command
1422 .env("GIT_NO_LAZY_FETCH", "1")
1423 .env("GIT_NO_REPLACE_OBJECTS", "1");
1424 Ok(command)
1425 }
1426
1427 /// Config overrides (`key`, `value`) that neutralize every clean, smudge and
1428 /// process filter driver and every merge driver configured for the repository at `workspace`. Callers
1429 /// apply them through `GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n`.
1430 pub fn review_filter_overrides(
1431 workspace: &Path,
1432 ) -> anyhow::Result<Vec<(String, &'static str)>> {
1433 Self::filter_overrides(workspace, false)
1434 }
1435
1436 pub fn review_shell_config_overrides(
1437 workspace: &Path,
1438 ) -> anyhow::Result<Vec<(String, &'static str)>> {
1439 use anyhow::{Context, bail};
1440
1441 let mut command = Self::review_base(workspace)?;
1442 command.args([
1443 "config",
1444 "--null",
1445 "--name-only",
1446 "--get-regexp",
1447 r"^(filter\..*\.(clean|smudge|process|required)|diff\..*\.(command|textconv)|gpg\..*\.program|credential\..*\.helper)$",
1448 ]);
1449 let output =
1450 run_bounded_git_with_timeout(&mut command, "config", Self::REVIEW_CONFIG_TIMEOUT)
1451 .context("Failed to inspect Git review configuration")?;
1452 let no_matches =
1453 output.status.code() == Some(1) && output.stdout.is_empty() && output.stderr.is_empty();
1454 if (!output.status.success() && !no_matches)
1455 || (!output.stdout.is_empty() && !output.stdout.ends_with(&[0]))
1456 {
1457 bail!("Cannot safely inspect Git review configuration");
1458 }
1459 let mut overrides = std::collections::BTreeMap::<String, &'static str>::new();
1460 for field in output
1461 .stdout
1462 .split(|byte| *byte == 0)
1463 .filter(|field| !field.is_empty())
1464 {
1465 let key =
1466 std::str::from_utf8(field).context("Git review config key is not valid UTF-8")?;
1467 let lower = key.to_ascii_lowercase();
1468 if lower.starts_with("filter.") {
1469 let (driver, _) = key
1470 .rsplit_once('.')
1471 .context("Invalid Git review filter key")?;
1472 overrides.insert(format!("{driver}.clean"), "");
1473 overrides.insert(format!("{driver}.smudge"), "");
1474 overrides.insert(format!("{driver}.process"), "");
1475 overrides.insert(format!("{driver}.required"), "false");
1476 } else if lower.starts_with("diff.") || lower.starts_with("credential.") {
1477 overrides.insert(key.to_string(), "");
1478 } else if lower.starts_with("gpg.") {
1479 overrides.insert(key.to_string(), Self::INERT_HELPER);
1480 }
1481 }
1482 Ok(overrides.into_iter().collect())
1483 }
1484
1485 pub fn defines_repository_filters(workspace: &Path) -> anyhow::Result<bool> {
1486 Ok(!Self::repository_driver_keys(workspace, true, false)?
1487 .0
1488 .is_empty())
1489 }
1490
1491 fn filter_overrides(
1492 workspace: &Path,
1493 repository_only: bool,
1494 ) -> anyhow::Result<Vec<(String, &'static str)>> {
1495 let (filters, merge_drivers) =
1496 Self::repository_driver_keys(workspace, repository_only, true)?;
1497 Ok(filters
1498 .into_iter()
1499 .flat_map(|driver| {
1500 [
1501 ("clean", ""),
1502 ("smudge", ""),
1503 ("process", ""),
1504 ("required", "false"),
1505 ]
1506 .map(|(suffix, value)| (format!("{driver}.{suffix}"), value))
1507 })
1508 .chain(
1509 merge_drivers
1510 .into_iter()
1511 .map(|key| (key, Self::INERT_HELPER)),
1512 )
1513 .collect())
1514 }
1515
1516 fn repository_driver_keys(
1517 workspace: &Path,
1518 repository_only: bool,
1519 include_merge_drivers: bool,
1520 ) -> anyhow::Result<(
1521 std::collections::BTreeSet<String>,
1522 std::collections::BTreeSet<String>,
1523 )> {
1524 use anyhow::{Context, bail};
1525
1526 let mut command = Self::review_base(workspace)?;
1527 command.arg("config");
1528 if repository_only {
1529 command.arg("--show-scope");
1530 }
1531 command.args([
1532 "--null",
1533 "--name-only",
1534 "--get-regexp",
1535 if include_merge_drivers {
1536 r"^(filter\..*\.(clean|smudge|process|required)|merge\..*\.driver)$"
1537 } else {
1538 r"^filter\..*\.(clean|smudge|process|required)$"
1539 },
1540 ]);
1541 let output =
1542 run_bounded_git_with_timeout(&mut command, "config", Self::REVIEW_CONFIG_TIMEOUT)
1543 .context("Failed to inspect Git review filters")?;
1544 let no_filters =
1545 output.status.code() == Some(1) && output.stdout.is_empty() && output.stderr.is_empty();
1546 if (!output.status.success() && !no_filters)
1547 || (!output.stdout.is_empty() && !output.stdout.ends_with(&[0]))
1548 {
1549 bail!("Cannot safely inspect Git review configuration");
1550 }
1551 let mut filters = std::collections::BTreeSet::new();
1552 let mut merge_drivers = std::collections::BTreeSet::new();
1553 let mut fields = output
1554 .stdout
1555 .split(|byte| *byte == 0)
1556 .filter(|field| !field.is_empty());
1557 while let Some(field) = fields.next() {
1558 let key = if repository_only {
1559 let key = fields
1560 .next()
1561 .context("Git review filter scope has no key")?;
1562 if matches!(field, b"global" | b"system") {
1563 continue;
1564 }
1565 key
1566 } else {
1567 field
1568 };
1569 let key =
1570 std::str::from_utf8(key).context("Git review filter name is not valid UTF-8")?;
1571 if key.to_ascii_lowercase().starts_with("merge.") {
1572 merge_drivers.insert(key.to_string());
1573 continue;
1574 }
1575 let (driver, _) = key
1576 .rsplit_once('.')
1577 .context("Invalid Git review filter key")?;
1578 filters.insert(driver.to_string());
1579 }
1580 Ok((filters, merge_drivers))
1581 }
1582 }
1583
1584 impl ExternalTool for Git {
1585 fn candidates() -> &'static [&'static str] {
1586 &["git"]
1587 }
1588
1589 /// Every `Git` invocation in the product is issued against a repository
1590 /// the user also works in by hand. `git status` and `git diff`
1591 /// opportunistically refresh the index, and that refresh takes
1592 /// `.git/index.lock` — which is why a user's own `git commit` could fail
1593 /// with "Unable to create '.../.git/index.lock': File exists" while
1594 /// codewhale was merely idling in the same repo (#5617, reported by
1595 /// @LmeSzinc).
1596 ///
1597 /// `GIT_OPTIONAL_LOCKS=0` suppresses only *optional* lock-taking, so
1598 /// reads stop touching the index while genuine writes (`add`, `commit`,
1599 /// `stash`, `update-ref`) are unaffected — including the snapshot
1600 /// side-repo runner, which writes to its own git dir. `git diff --quiet`
1601 /// exit-code semantics are preserved, which `snapshot::repo` relies on
1602 /// for `/undo` cursoring.
1603 ///
1604 /// Set here rather than on the `ExternalTool::command` default so it does
1605 /// not leak onto `Gh`, `Cargo`, `Python`, or `RustC`. Prefer the
1606 /// environment variable over the `--no-optional-locks` flag: the flag is
1607 /// top-level (it must precede the subcommand, awkward for the several
1608 /// call sites that build argument vectors), it would change the
1609 /// agent-visible command string rendered by `tools::git::format_command`,
1610 /// and an unknown flag hard-fails on old git while an unknown environment
1611 /// variable is silently ignored.
1612 ///
1613 /// The child also starts from the sanitized environment (see
1614 /// [`codewhale_runtime::child_env::apply_to_git_command`]): workspace config such as
1615 /// `core.fsmonitor` or a clean filter makes even a read like `git status`
1616 /// run a program the workspace chose, so no git child gets the parent's
1617 /// credentials. The guards below are applied after the scrub.
1618 fn command() -> Option<Command> {
1619 let mut cmd = Command::new(Self::resolve()?);
1620 codewhale_util::utils::suppress_console_window(&mut cmd);
1621 codewhale_runtime::child_env::apply_to_git_command(&mut cmd);
1622 cmd.env("GIT_OPTIONAL_LOCKS", "0");
1623 apply_git_noninteractive_env(&mut cmd);
1624 Some(cmd)
1625 }
1626
1627 /// Same environment as [`Git::command`]: the trait default would build a
1628 /// bare command and silently drop the lock and prompt guards.
1629 fn tokio_command() -> Option<tokio::process::Command> {
1630 Self::command().map(tokio::process::Command::from)
1631 }
1632
1633 fn resolve() -> Option<String> {
1634 static CACHE: OnceLock<Option<String>> = OnceLock::new();
1635 CACHE
1636 .get_or_init(|| {
1637 // The review capability cache must follow the executable
1638 // checked here even if a later child changes PATH or cwd.
1639 let path = resolve_executable_path(Self::candidates().first()?, "--version")?;
1640 let path = std::path::absolute(path).ok()?;
1641 tracing::info!(target: "tool_dependencies", "Resolved git binary");
1642 Some(path.to_string_lossy().into_owned())
1643 })
1644 .clone()
1645 }
1646 }
1647
1648 /// GitHub CLI.
1649 pub struct Gh;
1650
1651 impl ExternalTool for Gh {
1652 fn candidates() -> &'static [&'static str] {
1653 &["gh"]
1654 }
1655
1656 fn resolve() -> Option<String> {
1657 static CACHE: OnceLock<Option<String>> = OnceLock::new();
1658 CACHE
1659 .get_or_init(|| {
1660 for candidate in Self::candidates() {
1661 if probe_executable(candidate) {
1662 tracing::info!(target: "tool_dependencies", "Resolved gh binary");
1663 return Some((*candidate).to_string());
1664 }
1665 }
1666 None
1667 })
1668 .clone()
1669 }
1670 }
1671
1672 /// Rust compiler — used for version reporting in diagnostics.
1673 pub struct RustC;
1674
1675 impl ExternalTool for RustC {
1676 fn candidates() -> &'static [&'static str] {
1677 &["rustc"]
1678 }
1679
1680 fn resolve() -> Option<String> {
1681 static CACHE: OnceLock<Option<String>> = OnceLock::new();
1682 CACHE
1683 .get_or_init(|| {
1684 // Probe with capture so the `--version` banner observed during
1685 // resolution is reused by [`rustc_version_banner`] instead of
1686 // paying a second rustc process launch (each launch loads
1687 // libLLVM, which dominated diagnostic-command init profiles).
1688 for candidate in Self::candidates() {
1689 if let Some(banner) = rustup_version(candidate, None) {
1690 tracing::info!(target: "tool_dependencies", "Resolved rustc binary");
1691 let _ = RUSTC_VERSION_BANNER.set(Some(banner));
1692 return Some((*candidate).to_string());
1693 }
1694 }
1695 None
1696 })
1697 .clone()
1698 }
1699 }
1700
1701 /// Captured `--version` banner from the [`RustC`] resolution probe.
1702 ///
1703 /// `None` until `RustC::resolve()`/`available()`/`command()` first runs, or
1704 /// when rustc is absent/failing. Reading this after an `available()` check
1705 /// yields the same string the tool would print, without a second process.
1706 static RUSTC_VERSION_BANNER: OnceLock<Option<String>> = OnceLock::new();
1707
1708 /// The rustc `--version` banner, if rustc resolved successfully.
1709 ///
1710 /// Populated as a side effect of resolving [`RustC`]; this reads no fresh
1711 /// process state. Callers wanting the value should touch `RustC::available()`
1712 /// first (as the diagnostics path does).
1713 #[must_use]
1714 pub fn rustc_version_banner() -> Option<String> {
1715 RUSTC_VERSION_BANNER.get().cloned().flatten()
1716 }
1717
1718 /// Rust build tool — used by the `run_tests` tool.
1719 pub struct Cargo;
1720
1721 impl ExternalTool for Cargo {
1722 fn candidates() -> &'static [&'static str] {
1723 &["cargo"]
1724 }
1725
1726 fn resolve() -> Option<String> {
1727 static CACHE: OnceLock<Option<String>> = OnceLock::new();
1728 CACHE
1729 .get_or_init(|| {
1730 for candidate in Self::candidates() {
1731 if rustup_version(candidate, None).is_some()
1732 || executable_path_candidates(candidate)
1733 .iter()
1734 .any(|path| path.is_file())
1735 {
1736 tracing::info!(target: "tool_dependencies", "Resolved cargo binary");
1737 return Some((*candidate).to_string());
1738 }
1739 }
1740 None
1741 })
1742 .clone()
1743 }
1744 }
1745
1746 /// Python interpreter — used by `code_execution` tool and RLM REPL.
1747 /// Delegates to the existing [`resolve_python_interpreter`] so the
1748 /// multi-candidate ladder (`python3` → `python` → `py -3`) is
1749 /// shared with legacy callers until they migrate to the trait.
1750 pub struct Python;
1751
1752 impl ExternalTool for Python {
1753 fn candidates() -> &'static [&'static str] {
1754 PYTHON_CANDIDATES
1755 }
1756
1757 /// Every Python caller runs model-authored code (`code_execution`, the
1758 /// RLM REPL), so both constructors (and the `output`/`status` helpers
1759 /// built on them) start the child from the sanitized environment instead
1760 /// of inheriting provider credentials and other parent secrets. Callers
1761 /// that need extra variables re-apply them through
1762 /// [`codewhale_runtime::child_env::apply_to_tokio_command`] with explicit overrides.
1763 fn command() -> Option<Command> {
1764 Some(scrubbed_command_for_spec(&Self::resolve()?))
1765 }
1766
1767 fn tokio_command() -> Option<tokio::process::Command> {
1768 Self::command().map(tokio::process::Command::from)
1769 }
1770
1771 fn resolve() -> Option<String> {
1772 resolve_python_interpreter()
1773 }
1774 }
1775
1776 // ---------------------------------------------------------------------------
1777 // Legacy interpreter helpers (kept for existing callers until migrated)
1778 // ---------------------------------------------------------------------------
1779
1780 /// Split an interpreter spec like `"py -3"` into the program name
1781 /// and any initial arguments. Returns `("py", vec!["-3"])` for the
1782 /// example; returns `("python3", vec![])` for a bare name.
1783 ///
1784 /// Callers spawn `Command::new(program).args(args).arg(script_path)`.
1785 #[must_use]
1786 pub fn split_interpreter_spec(spec: &str) -> (String, Vec<String>) {
1787 let mut parts = spec.split_whitespace();
1788 let program = parts.next().unwrap_or("").to_string();
1789 let args = parts.map(str::to_string).collect();
1790 (program, args)
1791 }
1792
1793 /// Grace granted to the pipe readers after git has exited. A clean git
1794 /// closes its own write ends, so EOF is already waiting; only a grandchild
1795 /// that inherited the pipes (a post-checkout hook, a `git gc` pack worker)
1796 /// can hold them past exit, and it must not hold the turn pipeline either.
1797 const GIT_PIPE_DRAIN_GRACE: Duration = Duration::from_secs(2);
1798
1799 /// Run a pre-configured git command under `timeout` with both pipes drained
1800 /// while the child runs (the same concurrent drain `Command::output`
1801 /// performs). A wedged git degrades to an error instead of hanging the caller.
1802 ///
1803 /// The timeout path kills the child and reaps it on a detached thread: on a
1804 /// hard-wedged mount git can sit in uninterruptible kernel I/O where even
1805 /// SIGKILL is deferred.
1806 pub fn run_bounded_git_with_timeout(
1807 cmd: &mut std::process::Command,
1808 subcommand: &str,
1809 timeout: Duration,
1810 ) -> io::Result<Output> {
1811 cmd.stdin(std::process::Stdio::null())
1812 .stdout(std::process::Stdio::piped())
1813 .stderr(std::process::Stdio::piped());
1814 let (mut child, tree) = codewhale_runtime::process_tree::spawn_contained_std(cmd)?;
1815 // Drain both pipes while waiting: the restore path's `ls-tree -r` and
1816 // the diff commands emit output that grows with workspace size, and a
1817 // child blocked on a full pipe buffer never exits — it would turn every
1818 // such call into a guaranteed timeout. Readers stream into shared
1819 // buffers, and the completion channel lets the collect below bound how
1820 // long a grandchild-held pipe may hold the call after git has exited.
1821 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1822 let stdout_pipe = child.stdout.take();
1823 let stderr_pipe = child.stderr.take();
1824 let stdout_buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1825 let stderr_buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1826 {
1827 let buf = std::sync::Arc::clone(&stdout_buf);
1828 let done_tx = done_tx.clone();
1829 std::thread::spawn(move || {
1830 if let Some(mut reader) = stdout_pipe {
1831 read_pipe_to_buffer(&mut reader, &buf);
1832 }
1833 let _ = done_tx.send(());
1834 });
1835 }
1836 {
1837 let buf = std::sync::Arc::clone(&stderr_buf);
1838 let done_tx = done_tx.clone();
1839 std::thread::spawn(move || {
1840 if let Some(mut reader) = stderr_pipe {
1841 read_pipe_to_buffer(&mut reader, &buf);
1842 }
1843 let _ = done_tx.send(());
1844 });
1845 }
1846 drop(done_tx);
1847
1848 let Some(status) = child.wait_timeout(timeout)? else {
1849 let _ = tree.kill();
1850 let _ = child.kill();
1851 // Reap off the pipeline thread (see the doc comment): the kernel may
1852 // not deliver the kill until an uninterruptible syscall returns.
1853 std::thread::spawn(move || {
1854 let _ = child.wait();
1855 tree.disarm();
1856 });
1857 return Err(io::Error::new(
1858 io::ErrorKind::TimedOut,
1859 format!("git {subcommand} timed out after {}s", timeout.as_secs()),
1860 ));
1861 };
1862 tree.release();
1863 // Wait for the readers up to the grace, then return what was captured. A
1864 // clean git already closed its write ends, so both readers deliver
1865 // immediately; the grace only covers a pipe still held open by an
1866 // inherited copy (a daemonizing hook). On expiry the captured output is
1867 // returned with a note on stderr instead of silently truncating; the
1868 // reader itself ends whenever whatever holds the pipe exits, holding
1869 // only a pipe read — never the turn pipeline.
1870 let mut partial = false;
1871 let mut drained = 0;
1872 while drained < 2 {
1873 match done_rx.recv_timeout(GIT_PIPE_DRAIN_GRACE) {
1874 Ok(()) => drained += 1,
1875 Err(_) => {
1876 partial = true;
1877 break;
1878 }
1879 }
1880 }
1881 let stdout = stdout_buf.lock().map(|buf| buf.clone()).unwrap_or_default();
1882 let mut stderr = stderr_buf.lock().map(|buf| buf.clone()).unwrap_or_default();
1883 if partial {
1884 if !stderr.is_empty() && stderr.last() != Some(&b'\n') {
1885 stderr.push(b'\n');
1886 }
1887 stderr.extend_from_slice(
1888 b"[codewhale] git output pipes did not close after git exited \
1889 (kept open by a hook or subprocess?); captured output may be partial\n",
1890 );
1891 }
1892 Ok(Output {
1893 status,
1894 stdout,
1895 stderr,
1896 })
1897 }
1898
1899 /// Read a child's pipe to end into a shared buffer, tolerating interruption.
1900 fn read_pipe_to_buffer(reader: &mut impl io::Read, buf: &std::sync::Mutex<Vec<u8>>) {
1901 let mut chunk = [0_u8; 8192];
1902 loop {
1903 match reader.read(&mut chunk) {
1904 Ok(0) => return,
1905 Ok(read) => {
1906 if let Ok(mut buf) = buf.lock() {
1907 buf.extend_from_slice(&chunk[..read]);
1908 }
1909 }
1910 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
1911 Err(_) => return,
1912 }
1913 }
1914 }
1915
1916 #[cfg(test)]
1917 mod tests {
1918 use super::*;
1919
1920 #[test]
1921 fn compiled_host_identity_requires_exact_engine_source_and_real_bun_version() {
1922 let digest = "a".repeat(64);
1923 let info = serde_json::json!({
1924 "kind": "codewhale-extension-host", "runtime": "bun", "version": "1.4.0", "bundle_sha256": digest,
1925 "platform": match std::env::consts::OS { "macos" => "darwin", "windows" => "win32", os => os },
1926 "arch": match std::env::consts::ARCH { "aarch64" => "arm64", "x86_64" => "x64", arch => arch },
1927 });
1928 assert_eq!(
1929 parse_compiled_host_info(&serde_json::to_vec(&info).unwrap(), &digest),
1930 Ok((1, 4, 0))
1931 );
1932 let mut changed = info.clone();
1933 changed["bundle_sha256"] = "b".repeat(64).into();
1934 assert!(
1935 parse_compiled_host_info(&serde_json::to_vec(&changed).unwrap(), &digest)
1936 .unwrap_err()
1937 .contains("differs from this Engine")
1938 );
1939 for (key, value) in [
1940 ("runtime", "node"),
1941 ("kind", "bun"),
1942 ("version", "not-a-version"),
1943 ("platform", "incorrect-platform"),
1944 ("arch", "incorrect-arch"),
1945 ] {
1946 let mut invalid = info.clone();
1947 invalid[key] = value.into();
1948 assert!(
1949 parse_compiled_host_info(&serde_json::to_vec(&invalid).unwrap(), &digest).is_err()
1950 );
1951 }
1952 assert!(
1953 parse_compiled_host_info(&vec![b' '; 4097], &digest)
1954 .unwrap_err()
1955 .contains("4096")
1956 );
1957 assert!(parse_compiled_host_info(b"{}", &digest).is_err());
1958 }
1959
1960 #[cfg(unix)]
1961 #[test]
1962 fn version_probes_scrub_credentials_preloads_and_close_stdin() {
1963 let _home = codewhale_runtime::test_support::SealedHome::new();
1964 let _secret = codewhale_runtime::test_support::EnvVarGuard::set(
1965 "DEEPSEEK_API_KEY",
1966 "synthetic-probe-secret",
1967 );
1968 let _preload =
1969 codewhale_runtime::test_support::EnvVarGuard::set("NODE_OPTIONS", "synthetic-preload");
1970 let mut command = version_probe_command("/bin/sh");
1971 command.args(["-c", "[ -z \"${DEEPSEEK_API_KEY+x}\" ] && [ -z \"${NODE_OPTIONS+x}\" ] && ! read ignored && printf clean"]);
1972 let output = probe_output(&mut command, true, VERSION_PROBE_TIMEOUT).unwrap();
1973 assert!(output.status.success());
1974 assert_eq!(output.stdout, b"clean");
1975 }
1976
1977 #[test]
1978 fn toolchain_pin_honours_only_a_plain_channel_name() {
1979 let toml_pin = |body: &str| toolchain_pin_channel(body, false);
1980 assert_eq!(
1981 toml_pin("[toolchain]\nchannel = \"1.100.0\"\ncomponents = [\"rustfmt\"]\n").as_deref(),
1982 Some("1.100.0")
1983 );
1984 assert_eq!(
1985 toml_pin("[toolchain]\nchannel = \"nightly-2026-01-01-aarch64-apple-darwin\"\n")
1986 .as_deref(),
1987 Some("nightly-2026-01-01-aarch64-apple-darwin")
1988 );
1989 let long = format!("[toolchain]\nchannel = \"{}\"\n", "a".repeat(65));
1990 for refused in [
1991 "[toolchain]\npath = \"/opt/elsewhere\"\n",
1992 "[toolchain]\nchannel = \"stable\"\npath = \"/opt/elsewhere\"\n",
1993 "toolchain = { path = \"/opt/elsewhere\" }\n",
1994 "[toolchain]\nchannel = \"/opt/elsewhere\"\n",
1995 "[toolchain]\nchannel = \"../elsewhere\"\n",
1996 "[toolchain]\nchannel = \"a/b\"\n",
1997 "[toolchain]\nchannel = \"a\\\\b\"\n",
1998 "[toolchain]\nchannel = \"C:elsewhere\"\n",
1999 "[toolchain]\nchannel = \"-flag\"\n",
2000 "[toolchain]\nchannel = \".hidden\"\n",
2001 "[toolchain]\nchannel = \"\"\n",
2002 "[toolchain]\nchannel = \"a\\nb\"\n",
2003 "[toolchain]\nchannel = 1\n",
2004 "[toolchain]\ncomponents = []\n",
2005 "[other]\nchannel = \"stable\"\n",
2006 "not toml at all\n",
2007 long.as_str(),
2008 ] {
2009 assert_eq!(toml_pin(refused), None, "{refused:?}");
2010 }
2011 assert_eq!(
2012 toolchain_pin_channel("stable\n", true).as_deref(),
2013 Some("stable")
2014 );
2015 assert_eq!(toolchain_pin_channel("/opt/elsewhere\n", true), None);
2016 assert_eq!(toolchain_pin_channel("stable\n", false), None);
2017 assert_eq!(
2018 toolchain_pin_channel("[toolchain]\npath = \"/opt/elsewhere\"\n", true),
2019 None
2020 );
2021 }
2022
2023 #[test]
2024 fn workspace_toolchain_pin_is_read_as_bounded_data_from_the_nearest_file() {
2025 let root = tempfile::tempdir().unwrap();
2026 let nested = root.path().join("a/b");
2027 std::fs::create_dir_all(&nested).unwrap();
2028 let pin = |dir: &Path, name: &str, body: &str| {
2029 std::fs::write(dir.join(name), body).unwrap();
2030 };
2031 pin(
2032 root.path(),
2033 "rust-toolchain.toml",
2034 "[toolchain]\nchannel = \"outer\"\n",
2035 );
2036 assert_eq!(
2037 workspace_toolchain_channel(&nested).as_deref(),
2038 Some("outer")
2039 );
2040 pin(
2041 &root.path().join("a"),
2042 "rust-toolchain.toml",
2043 "[toolchain]\npath = \"/opt/elsewhere\"\n",
2044 );
2045 assert_eq!(workspace_toolchain_channel(&nested), None);
2046 pin(
2047 &nested,
2048 "rust-toolchain.toml",
2049 "[toolchain]\nchannel = \"inner\"\n",
2050 );
2051 pin(&nested, "rust-toolchain", "legacy\n");
2052 assert_eq!(
2053 workspace_toolchain_channel(&nested).as_deref(),
2054 Some("legacy")
2055 );
2056 pin(&nested, "rust-toolchain", &"x".repeat(5000));
2057 assert_eq!(workspace_toolchain_channel(&nested), None);
2058 }
2059
2060 #[cfg(unix)]
2061 #[test]
2062 fn workspace_toolchain_pin_refuses_links_and_special_files() {
2063 let root = tempfile::tempdir().unwrap();
2064 let linked = root.path().join("linked");
2065 let fifo = root.path().join("fifo");
2066 std::fs::create_dir_all(&linked).unwrap();
2067 std::fs::create_dir_all(&fifo).unwrap();
2068 std::fs::write(
2069 root.path().join("real.toml"),
2070 "[toolchain]\nchannel = \"stable\"\n",
2071 )
2072 .unwrap();
2073 std::os::unix::fs::symlink(
2074 root.path().join("real.toml"),
2075 linked.join("rust-toolchain.toml"),
2076 )
2077 .unwrap();
2078 assert_eq!(workspace_toolchain_channel(&linked), None);
2079 let made = std::process::Command::new("mkfifo")
2080 .arg(fifo.join("rust-toolchain"))
2081 .status()
2082 .is_ok_and(|status| status.success());
2083 assert!(made, "mkfifo is required for this test");
2084 assert_eq!(workspace_toolchain_channel(&fifo), None);
2085 }
2086
2087 #[cfg(unix)]
2088 #[test]
2089 fn rustup_commands_ignore_repository_toolchain_files() {
2090 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2091 use std::os::unix::fs::PermissionsExt;
2092 let home = SealedHome::new();
2093 let shims = tempfile::tempdir().unwrap();
2094 let shim = shims.path().join("rustc");
2095 std::fs::write(
2096 &shim,
2097 "#!/bin/sh\nprintf 'cwd=%s toolchain=%s auto=%s' \"$(pwd -P)\" \"${RUSTUP_TOOLCHAIN-unset}\" \"${RUSTUP_AUTO_INSTALL-unset}\"\n",
2098 )
2099 .unwrap();
2100 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2101 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
2102 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2103 let rustup_home = tempfile::tempdir().unwrap();
2104 let _rustup_home = EnvVarGuard::set("RUSTUP_HOME", rustup_home.path());
2105 let workspace = tempfile::tempdir().unwrap();
2106 let run = |workspace: Option<&Path>| {
2107 let banner = rustup_version("rustc", workspace).expect("shim answers");
2108 let probe_dir =
2109 std::fs::canonicalize(home.codewhale_home()).expect("the Codewhale home exists");
2110 let workspace_dir = workspace.and_then(|path| std::fs::canonicalize(path).ok());
2111 if let Some(workspace_dir) = workspace_dir {
2112 assert!(
2113 !banner.contains(workspace_dir.to_str().unwrap()),
2114 "{banner}"
2115 );
2116 }
2117 assert!(
2118 banner.starts_with(&format!("cwd={} ", probe_dir.display())),
2119 "{banner}"
2120 );
2121 banner
2122 };
2123
2124 assert!(run(None).ends_with("toolchain=unset auto=0"));
2125
2126 std::fs::write(
2127 workspace.path().join("rust-toolchain.toml"),
2128 "[toolchain]\npath = \"/opt/elsewhere\"\n",
2129 )
2130 .unwrap();
2131 assert!(run(Some(workspace.path())).ends_with("toolchain=unset auto=0"));
2132
2133 std::fs::write(
2134 workspace.path().join("rust-toolchain.toml"),
2135 "[toolchain]\nchannel = \"nightly-2026-01-01\"\n",
2136 )
2137 .unwrap();
2138 assert!(run(Some(workspace.path())).ends_with("toolchain=unset auto=0"));
2139
2140 std::fs::create_dir_all(
2141 rustup_home
2142 .path()
2143 .join("toolchains/nightly-2026-01-01-aarch64-apple-darwin"),
2144 )
2145 .unwrap();
2146 assert!(run(Some(workspace.path())).ends_with("toolchain=nightly-2026-01-01 auto=0"));
2147
2148 std::fs::write(
2149 workspace.path().join("rust-toolchain.toml"),
2150 "[toolchain]\nchannel = \"/tmp/x\"\n",
2151 )
2152 .unwrap();
2153 assert!(run(Some(workspace.path())).ends_with("toolchain=unset auto=0"));
2154
2155 std::fs::write(
2156 workspace.path().join("rust-toolchain.toml"),
2157 "[toolchain]\nchannel = \"nightly-2026-01-01\"\n",
2158 )
2159 .unwrap();
2160 let _user_pin = EnvVarGuard::set("RUSTUP_TOOLCHAIN", "user-choice");
2161 assert!(run(Some(workspace.path())).ends_with("toolchain=user-choice auto=0"));
2162 }
2163
2164 #[cfg(unix)]
2165 #[test]
2166 fn rustup_probe_treats_an_empty_toolchain_variable_as_unset() {
2167 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2168 use std::os::unix::fs::PermissionsExt;
2169 let workspace = tempfile::tempdir().unwrap();
2170 let _home = SealedHome::at(workspace.path());
2171 let shims = tempfile::tempdir().unwrap();
2172 let shim = shims.path().join("rustc");
2173 std::fs::write(
2174 &shim,
2175 "#!/bin/sh\nprintf 'toolchain=%s' \"${RUSTUP_TOOLCHAIN-unset}\"",
2176 )
2177 .unwrap();
2178 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2179 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
2180 let _empty = EnvVarGuard::set("RUSTUP_TOOLCHAIN", "");
2181 std::fs::write(
2182 workspace.path().join("rust-toolchain.toml"),
2183 "[toolchain]\npath = \"/opt/elsewhere\"\n",
2184 )
2185 .unwrap();
2186 assert_eq!(rustup_version("rustc", Some(workspace.path())), None);
2187 std::fs::remove_file(workspace.path().join("rust-toolchain.toml")).unwrap();
2188 assert_eq!(
2189 rustup_version("rustc", Some(workspace.path())).as_deref(),
2190 Some("toolchain=unset")
2191 );
2192 }
2193
2194 #[cfg(unix)]
2195 #[test]
2196 fn rustup_commands_refuse_toolchain_files_above_the_probe_directory() {
2197 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2198 use std::os::unix::fs::PermissionsExt;
2199 let workspace = tempfile::tempdir().unwrap();
2200 let _home = SealedHome::at(workspace.path());
2201 std::fs::create_dir_all(workspace.path().join(".codewhale")).unwrap();
2202 let shims = tempfile::tempdir().unwrap();
2203 let shim = shims.path().join("rustc");
2204 std::fs::write(&shim, "#!/bin/sh\nprintf answered").unwrap();
2205 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2206 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
2207 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2208
2209 assert_eq!(
2210 rustup_version("rustc", Some(workspace.path())).as_deref(),
2211 Some("answered")
2212 );
2213
2214 std::fs::write(
2215 workspace.path().join("rust-toolchain.toml"),
2216 "[toolchain]\npath = \"/opt/elsewhere\"\n",
2217 )
2218 .unwrap();
2219 assert_eq!(rustup_version("rustc", Some(workspace.path())), None);
2220 assert_eq!(rustup_version("rustc", None), None);
2221
2222 let _user_pin = EnvVarGuard::set("RUSTUP_TOOLCHAIN", "user-choice");
2223 assert_eq!(
2224 rustup_version("rustc", Some(workspace.path())).as_deref(),
2225 Some("answered")
2226 );
2227 }
2228
2229 #[cfg(unix)]
2230 #[test]
2231 fn rustup_commands_refuse_a_toolchain_file_in_the_probe_directory_itself() {
2232 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2233 use std::os::unix::fs::PermissionsExt;
2234 let home = SealedHome::new();
2235 let shims = tempfile::tempdir().unwrap();
2236 let shim = shims.path().join("rustc");
2237 std::fs::write(&shim, "#!/bin/sh\nprintf answered").unwrap();
2238 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2239 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
2240 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2241 assert_eq!(rustup_version("rustc", None).as_deref(), Some("answered"));
2242 std::fs::write(home.codewhale_home().join("rust-toolchain"), "stable\n").unwrap();
2243 assert_eq!(rustup_version("rustc", None), None);
2244 }
2245
2246 #[cfg(unix)]
2247 #[test]
2248 fn rustup_probe_ignores_relative_path_entries() {
2249 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2250 use std::os::unix::fs::PermissionsExt;
2251 let home = SealedHome::new();
2252 let planted = home.codewhale_home().join("rustc");
2253 std::fs::write(&planted, "#!/bin/sh\nprintf planted").unwrap();
2254 std::fs::set_permissions(&planted, std::fs::Permissions::from_mode(0o755)).unwrap();
2255 let shims = tempfile::tempdir().unwrap();
2256 let shim = shims.path().join("rustc");
2257 std::fs::write(&shim, "#!/bin/sh\nprintf answered").unwrap();
2258 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2259 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2260 for prefix in [".:", ":", ""] {
2261 let _path = EnvVarGuard::set(
2262 "PATH",
2263 format!("{prefix}{}:/usr/bin:/bin:", shims.path().display()),
2264 );
2265 assert_eq!(
2266 rustup_version("rustc", None).as_deref(),
2267 Some("answered"),
2268 "{prefix:?}"
2269 );
2270 }
2271 let _only_relative = EnvVarGuard::set("PATH", ".:");
2272 assert_eq!(rustup_version("rustc", None), None);
2273 }
2274
2275 #[cfg(unix)]
2276 #[test]
2277 fn rustup_probe_refuses_relative_toolchain_homes() {
2278 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2279 let _home = SealedHome::new();
2280 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2281 for variable in ["RUSTUP_HOME", "CARGO_HOME"] {
2282 let _relative = EnvVarGuard::set(variable, ".rustup");
2283 assert!(rustup_command("rustc", None).is_none(), "{variable}");
2284 }
2285 let absolute = std::env::var("HOME").unwrap();
2286 for value in [".".to_string(), "build".to_string(), format!(" {absolute}")] {
2287 let _relative = EnvVarGuard::set("HOME", &value);
2288 assert!(rustup_command("rustc", None).is_none(), "{value:?}");
2289 }
2290 }
2291
2292 #[cfg(unix)]
2293 #[test]
2294 fn rustup_probe_creates_nothing_on_disk() {
2295 use codewhale_runtime::test_support::{EnvVarGuard, SealedHome};
2296 use std::os::unix::fs::PermissionsExt;
2297 let home = SealedHome::new();
2298 let shims = tempfile::tempdir().unwrap();
2299 let shim = shims.path().join("rustc");
2300 std::fs::write(&shim, "#!/bin/sh\nprintf answered").unwrap();
2301 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
2302 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
2303 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
2304 let listing = |dir: &Path| {
2305 let mut names = std::fs::read_dir(dir)
2306 .unwrap()
2307 .map(|entry| entry.unwrap().file_name())
2308 .collect::<Vec<_>>();
2309 names.sort();
2310 names
2311 };
2312
2313 let before = listing(home.codewhale_home());
2314 let before_home = listing(home.home());
2315 assert!(rustup_version("rustc", None).is_some());
2316 assert_eq!(listing(home.codewhale_home()), before);
2317 assert_eq!(listing(home.home()), before_home);
2318
2319 std::fs::remove_dir(home.codewhale_home()).unwrap();
2320 assert!(rustup_version("rustc", None).is_some());
2321 assert!(!home.codewhale_home().exists());
2322 assert_eq!(listing(home.home()), before_home);
2323 }
2324
2325 #[cfg(unix)]
2326 #[test]
2327 fn version_probe_timeout_kills_ordinary_descendants() {
2328 let root = tempfile::tempdir().unwrap();
2329 let pid_file = root.path().join("descendant.pid");
2330 let mut command = version_probe_command("/bin/sh");
2331 command
2332 .args(["-c", "sleep 30 & echo $! > \"$1\"; wait", "probe"])
2333 .arg(&pid_file);
2334 let started = std::time::Instant::now();
2335 let error =
2336 probe_output(&mut command, false, std::time::Duration::from_millis(150)).unwrap_err();
2337 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2338 assert!(started.elapsed() < std::time::Duration::from_secs(2));
2339 let pid = codewhale_runtime::process_tree::read_pid_file(
2340 &pid_file,
2341 std::time::Duration::from_secs(1),
2342 );
2343 assert!(codewhale_runtime::process_tree::wait_for_pid_exit(
2344 pid,
2345 std::time::Duration::from_secs(2)
2346 ));
2347 }
2348
2349 #[cfg(unix)]
2350 #[test]
2351 fn version_probe_reaps_successful_parents_inherited_pipe_child() {
2352 let root = tempfile::tempdir().unwrap();
2353 let pid_file = root.path().join("pipe-child.pid");
2354 let mut command = version_probe_command("/bin/sh");
2355 command
2356 .args(["-c", "sleep 30 & echo $! > \"$1\"; printf version", "probe"])
2357 .arg(&pid_file);
2358 let output = probe_output(&mut command, true, VERSION_PROBE_TIMEOUT).unwrap();
2359 assert!(output.status.success());
2360 assert_eq!(output.stdout, b"version");
2361 let pid = codewhale_runtime::process_tree::read_pid_file(
2362 &pid_file,
2363 std::time::Duration::from_secs(1),
2364 );
2365 assert!(codewhale_runtime::process_tree::wait_for_pid_exit(
2366 pid,
2367 std::time::Duration::from_secs(2)
2368 ));
2369 }
2370
2371 #[cfg(unix)]
2372 #[test]
2373 fn bounded_git_timeout_kills_descendants_holding_pipes() {
2374 let root = tempfile::tempdir().unwrap();
2375 let pid_file = root.path().join("git-descendant.pid");
2376 let mut command = std::process::Command::new("/bin/sh");
2377 command
2378 .args([
2379 "-c",
2380 "sleep 30 & echo $! > \"$1\"; wait",
2381 "git-timeout-test",
2382 ])
2383 .arg(&pid_file);
2384 let started = std::time::Instant::now();
2385 let error = run_bounded_git_with_timeout(
2386 &mut command,
2387 "sleep",
2388 std::time::Duration::from_millis(250),
2389 )
2390 .unwrap_err();
2391 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2392 assert!(started.elapsed() < std::time::Duration::from_secs(2));
2393 let pid = codewhale_runtime::process_tree::read_pid_file(
2394 &pid_file,
2395 std::time::Duration::from_secs(1),
2396 );
2397 assert!(codewhale_runtime::process_tree::wait_for_pid_exit(
2398 pid,
2399 std::time::Duration::from_secs(2)
2400 ));
2401 }
2402
2403 #[cfg(unix)]
2404 #[test]
2405 fn version_probe_refuses_oversized_banner() {
2406 let mut command = version_probe_command("/bin/sh");
2407 command.args(["-c", "head -c 20000 /dev/zero"]);
2408 assert_eq!(
2409 probe_output(&mut command, true, VERSION_PROBE_TIMEOUT)
2410 .unwrap_err()
2411 .kind(),
2412 std::io::ErrorKind::InvalidData
2413 );
2414 }
2415
2416 #[test]
2417 fn node_version_banner_parses_and_floor_matches_dsh_engines() {
2418 assert_eq!(parse_node_version("v22.20.0\n"), Some((22, 20, 0)));
2419 assert_eq!(parse_node_version("v24.1.0-nightly"), Some((24, 1, 0)));
2420 assert_eq!(parse_node_version("22.20.0"), None);
2421 assert!(node_version_supported_for_extension_host((22, 19, 0)));
2422 assert!(!node_version_supported_for_extension_host((22, 18, 9)));
2423 assert!(!node_version_supported_for_extension_host((23, 11, 0)));
2424 assert!(!node_version_supported_for_extension_host((20, 19, 0)));
2425 assert!(node_version_supported_for_extension_host((24, 0, 0)));
2426 }
2427
2428 #[cfg(unix)]
2429 #[test]
2430 fn node_ladder_skips_broken_and_old_candidates() {
2431 use std::os::unix::fs::PermissionsExt;
2432 let dir = tempfile::tempdir().unwrap();
2433 let script = |name: &str, body: &str| {
2434 let path = dir.path().join(name);
2435 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
2436 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
2437 path
2438 };
2439 let broken = script(
2440 "broken-node",
2441 "echo 'dyld: Library not loaded' >&2; exit 134",
2442 );
2443 let old = script("old-node", "echo v20.11.1");
2444 let good = script("good-node", "echo v22.20.0");
2445 let later = script("later-node", "echo v24.0.0");
2446 let relative = PathBuf::from("node_modules/.bin/node");
2447 let resolution = select_runtime(
2448 HostRuntimeKind::Node,
2449 vec![
2450 relative.clone(),
2451 broken.clone(),
2452 old.clone(),
2453 good.clone(),
2454 later,
2455 ],
2456 "",
2457 );
2458 assert_eq!(resolution.selected, Some((good, (22, 20, 0))));
2459 assert_eq!(resolution.rejected.len(), 3);
2460 assert_eq!(resolution.rejected[0].0, relative);
2461 assert!(resolution.rejected[0].1.contains("not an absolute path"));
2462 assert_eq!(resolution.rejected[1].0, broken);
2463 assert!(resolution.rejected[1].1.contains("does not run"));
2464 assert_eq!(resolution.rejected[2].0, old);
2465 assert!(resolution.rejected[2].1.contains("below"));
2466 }
2467
2468 #[test]
2469 fn bun_version_banner_parses_and_floor_is_the_validated_release() {
2470 assert_eq!(parse_bun_version("1.4.0\n"), Some((1, 4, 0)));
2471 assert_eq!(parse_bun_version("1.4.2-canary.3+abc"), Some((1, 4, 2)));
2472 assert_eq!(parse_bun_version("v1.4.0"), None);
2473 assert!(HostRuntimeKind::Bun.supported((1, 4, 0)));
2474 assert!(HostRuntimeKind::Bun.supported((2, 0, 0)));
2475 assert!(!HostRuntimeKind::Bun.supported((1, 3, 14)));
2476 }
2477
2478 #[cfg(unix)]
2479 #[test]
2480 fn host_runtime_auto_prefers_bun_and_explicit_choices_never_fall_back() {
2481 use codewhale_config::extension_host::ExtensionHostRuntime as Choice;
2482 use std::os::unix::fs::PermissionsExt;
2483 let dir = tempfile::tempdir().unwrap();
2484 let script = |name: &str, body: &str| {
2485 let path = dir.path().join(name);
2486 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
2487 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
2488 path
2489 };
2490 let bun = script("bun", "echo 1.4.0");
2491 let old_bun = script("old-bun", "echo 1.3.14");
2492 // A Node without `node:ffi`: it rejects `--no-experimental-ffi` the
2493 // way Node 22 and 24 do.
2494 let node = script(
2495 "node",
2496 "case \"$1\" in --no-experimental-ffi) echo 'bad option' >&2; exit 9;; esac\necho v24.1.0",
2497 );
2498
2499 let probe = |kind, candidates: &[&PathBuf]| {
2500 select_runtime(
2501 kind,
2502 candidates.iter().map(|path| (*path).clone()).collect(),
2503 "",
2504 )
2505 };
2506
2507 // auto: a supported Bun wins, and Node is never probed. The Bun
2508 // passed over on the way is in the summary.
2509 let auto = select_host_runtime(
2510 Choice::Auto,
2511 || probe(HostRuntimeKind::Bun, &[&old_bun, &bun]),
2512 || panic!("node must not be probed when Bun is usable"),
2513 );
2514 let selected = auto.selected.clone().unwrap();
2515 assert_eq!(selected.kind, HostRuntimeKind::Bun);
2516 assert_eq!(selected.path, bun);
2517 assert_eq!(selected.version_string(), "1.4.0");
2518 assert!(selected.native_code_flags.is_empty());
2519 let summary = auto.summary();
2520 assert!(summary.starts_with("bun 1.4.0 at "), "{summary}");
2521 assert!(summary.contains("(runtime = \"auto\")"), "{summary}");
2522 assert!(
2523 summary.contains("passed over: ") && summary.contains("1.3.14 is below"),
2524 "{summary}"
2525 );
2526
2527 // auto without a supported Bun: Node, and the summary says why.
2528 let fallback = select_host_runtime(
2529 Choice::Auto,
2530 || probe(HostRuntimeKind::Bun, &[&old_bun]),
2531 || probe(HostRuntimeKind::Node, &[&node]),
2532 );
2533 assert_eq!(
2534 fallback.selected.as_ref().unwrap().kind,
2535 HostRuntimeKind::Node
2536 );
2537 let summary = fallback.summary();
2538 assert!(summary.starts_with("node 24.1.0 at "), "{summary}");
2539 assert!(summary.contains("Bun >=1.4.0 not used"), "{summary}");
2540 assert!(
2541 summary.contains("1.3.14 is below the >=1.4.0 floor"),
2542 "{summary}"
2543 );
2544 // Nothing found: the message names every place that was searched.
2545 let none_found = select_host_runtime(Choice::Auto, NodeResolution::default, || {
2546 probe(HostRuntimeKind::Node, &[&node])
2547 });
2548 assert!(
2549 none_found
2550 .summary()
2551 .contains("no `bun` found on PATH or in $BUN_INSTALL/bin (default ~/.bun/bin)"),
2552 "{}",
2553 none_found.summary()
2554 );
2555
2556 // runtime = "bun": no Node fallback, even when Node works.
2557 let bun_only = select_host_runtime(
2558 Choice::Bun,
2559 || probe(HostRuntimeKind::Bun, &[&old_bun]),
2560 || panic!("runtime = \"bun\" must not probe node"),
2561 );
2562 assert!(bun_only.selected.is_none());
2563 assert!(
2564 bun_only.failure().contains("needs Bun >=1.4.0"),
2565 "{}",
2566 bun_only.failure()
2567 );
2568
2569 // runtime = "node": Bun is never probed.
2570 let node_only = select_host_runtime(
2571 Choice::Node,
2572 || panic!("runtime = \"node\" must not probe bun"),
2573 || probe(HostRuntimeKind::Node, &[&node]),
2574 );
2575 let node_runtime = node_only.selected.unwrap();
2576 assert_eq!(node_runtime.kind, HostRuntimeKind::Node);
2577 // Only the flags this Node starts with are passed.
2578 assert_eq!(
2579 node_runtime.native_code_flags,
2580 vec!["--no-experimental-sqlite"]
2581 );
2582 assert!(node_only.bun.is_none());
2583 }
2584
2585 /// A runtime found by searching that a repository could have planted is
2586 /// never run; a configured override is exempt from that check but is
2587 /// final: when it fails, resolution fails with its reason.
2588 #[cfg(unix)]
2589 #[test]
2590 fn untrusted_search_candidates_are_skipped_and_a_failing_override_is_final() {
2591 use codewhale_config::extension_host::ExtensionHostRuntime as Choice;
2592 use std::os::unix::fs::PermissionsExt;
2593 let dir = tempfile::tempdir().unwrap();
2594 let script = |name: &str, body: &str| {
2595 let path = dir.path().join(name);
2596 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
2597 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
2598 path
2599 };
2600 let kind = HostRuntimeKind::Bun;
2601 let home = dir.path().join("home");
2602 let workspace = dir.path().join("workspace");
2603 std::fs::create_dir_all(workspace.join("bin")).unwrap();
2604 // `current_dir` is resolved; the temp dir may be spelled through a
2605 // symlink (`/var` → `/private/var` on macOS).
2606 let cwd = std::fs::canonicalize(&workspace).unwrap();
2607
2608 let shim = Path::new("/opt/tools/node_modules/.bin/bun");
2609 let reason = untrusted_location(kind, shim, None, None).unwrap();
2610 assert!(reason.contains("`node_modules`"), "{reason}");
2611 let reason = untrusted_location(
2612 kind,
2613 &workspace.join("bin/bun"),
2614 Some(cwd.as_path()),
2615 Some(home.as_path()),
2616 )
2617 .unwrap();
2618 assert!(reason.contains("inside the working directory"), "{reason}");
2619 assert!(reason.contains("`[extension_host] bun`"), "{reason}");
2620 let link = dir.path().join("link");
2621 std::os::unix::fs::symlink(workspace.join("bin"), &link).unwrap();
2622 assert!(
2623 untrusted_location(
2624 kind,
2625 &link.join("bun"),
2626 Some(cwd.as_path()),
2627 Some(home.as_path())
2628 )
2629 .is_some()
2630 );
2631 assert_eq!(
2632 untrusted_location(
2633 kind,
2634 &dir.path().join("elsewhere/bun"),
2635 Some(cwd.as_path()),
2636 Some(home.as_path())
2637 ),
2638 None
2639 );
2640 // A working directory that contains the home is not a workspace.
2641 let user_bun = home.join(".bun/bin/bun");
2642 assert_eq!(
2643 untrusted_location(kind, &user_bun, Some(home.as_path()), Some(home.as_path())),
2644 None
2645 );
2646 assert_eq!(
2647 untrusted_location(kind, &user_bun, Some(Path::new("/")), Some(home.as_path())),
2648 None
2649 );
2650
2651 // A failing override never falls through to a search.
2652 let broken = script("broken-bun", "exit 3");
2653 let bun_only =
2654 resolve_extension_host_runtime(Choice::Bun, None, Some(broken.as_path()), "");
2655 assert!(bun_only.selected.is_none());
2656 let failure = bun_only.failure();
2657 assert!(
2658 failure.contains(&format!("{}: does not run", broken.display())),
2659 "{failure}"
2660 );
2661 assert_eq!(bun_only.bun.as_ref().unwrap().rejected.len(), 1);
2662 // Under `auto` the Node that runs instead says why the Bun did not.
2663 let node = script("node", "echo v24.1.0");
2664 let auto = resolve_extension_host_runtime(
2665 Choice::Auto,
2666 Some(node.as_path()),
2667 Some(broken.as_path()),
2668 "",
2669 );
2670 let summary = auto.summary();
2671 assert!(summary.starts_with("node 24.1.0 at "), "{summary}");
2672 assert!(
2673 summary.contains(&format!(
2674 "Bun >=1.4.0 not used: {}: does not run",
2675 broken.display()
2676 )),
2677 "{summary}"
2678 );
2679 }
2680
2681 #[test]
2682 fn probe_executable_returns_false_for_unknown_binary() {
2683 // Pick a name we're confident isn't on any developer's PATH.
2684 // If this ever starts failing locally, rename it.
2685 assert!(!probe_executable("codewhale-tui-imaginary-binary-xyz123"));
2686 }
2687
2688 #[test]
2689 fn probe_executable_handles_multi_word_specs() {
2690 // `py -3` should split correctly. The probe will fail on
2691 // most non-Windows machines (no `py` launcher), which is
2692 // fine — we're checking that the *split* doesn't crash.
2693 let _ = probe_executable("py -3");
2694 }
2695
2696 #[test]
2697 fn probe_executable_with_flag_returns_false_for_unknown_binary() {
2698 assert!(!probe_executable_with_flag(
2699 "codewhale-tui-imaginary-binary-xyz123",
2700 "-v"
2701 ));
2702 }
2703
2704 #[test]
2705 fn probe_executable_delegates_to_double_dash_version() {
2706 // `probe_executable` must remain exactly
2707 // `probe_executable_with_flag(.., "--version")`.
2708 let spec = "codewhale-tui-imaginary-binary-xyz123";
2709 assert_eq!(
2710 probe_executable(spec),
2711 probe_executable_with_flag(spec, "--version")
2712 );
2713 }
2714
2715 #[test]
2716 fn pdftotext_resolver_detects_installed_poppler_via_dash_v() {
2717 // Regression for #1667: Poppler's `pdftotext` rejects `--version`
2718 // (it is parsed as an input filename and exits non-zero), so the
2719 // generic `--version` probe reports it missing even when installed.
2720 // The resolver must probe with `-v`. Gated on pdftotext actually
2721 // being installed so CI without Poppler stays green.
2722 let mut probe = version_probe_command("pdftotext");
2723 probe.arg("-v");
2724 let answers_dash_v = probe_output(&mut probe, false, std::time::Duration::from_secs(60))
2725 .is_ok_and(|output| output.status.success());
2726 if answers_dash_v {
2727 assert!(
2728 resolve_pdftotext().is_some(),
2729 "an installed pdftotext must be detected via -v (#1667)"
2730 );
2731 }
2732 }
2733
2734 #[test]
2735 fn split_interpreter_spec_strips_args() {
2736 assert_eq!(
2737 split_interpreter_spec("python3"),
2738 ("python3".to_string(), Vec::<String>::new())
2739 );
2740 assert_eq!(
2741 split_interpreter_spec("py -3"),
2742 ("py".to_string(), vec!["-3".to_string()])
2743 );
2744 assert_eq!(
2745 split_interpreter_spec(" python3 "),
2746 ("python3".to_string(), Vec::<String>::new()),
2747 "leading/trailing whitespace must be tolerated"
2748 );
2749 }
2750
2751 #[test]
2752 fn split_interpreter_spec_handles_empty_string() {
2753 assert_eq!(
2754 split_interpreter_spec(""),
2755 (String::new(), Vec::<String>::new())
2756 );
2757 }
2758
2759 #[test]
2760 fn python_resolver_is_cached_across_calls() {
2761 // Whatever the first call returns, subsequent calls return
2762 // the same value (cached). If this test ever flakes, the
2763 // OnceLock semantics changed and we need to rethink the
2764 // resolver.
2765 let first = resolve_python_interpreter();
2766 let second = resolve_python_interpreter();
2767 assert_eq!(first, second);
2768 }
2769
2770 #[test]
2771 fn python_resolver_returns_some_on_developer_machines() {
2772 // CI hosts have Python; developer machines have Python.
2773 // The one environment where this returns None is bare-bones
2774 // Windows / minimal CI containers — fine, those just don't
2775 // get code_execution registered, which is the whole point.
2776 // We don't assert Some() because we don't want this test
2777 // to fail in those environments. Instead we just confirm
2778 // the resolver doesn't panic and returns a stable value.
2779 let resolved = resolve_python_interpreter();
2780 if let Some(name) = resolved {
2781 assert!(
2782 !name.is_empty(),
2783 "resolved interpreter name must be non-empty"
2784 );
2785 // The resolved name must be one of our candidates.
2786 assert!(
2787 PYTHON_CANDIDATES.contains(&name.as_str()),
2788 "resolved {name:?} is not in PYTHON_CANDIDATES {PYTHON_CANDIDATES:?}"
2789 );
2790 }
2791 }
2792
2793 // ===================================================================
2794 // ExternalTool trait tests
2795 // ===================================================================
2796
2797 #[test]
2798 fn python_candidates_matches_const() {
2799 assert_eq!(Python::candidates(), PYTHON_CANDIDATES);
2800 }
2801
2802 #[test]
2803 fn git_candidates_is_git_only() {
2804 assert_eq!(Git::candidates(), &["git"]);
2805 }
2806
2807 #[test]
2808 fn gh_candidates_is_gh_only() {
2809 assert_eq!(Gh::candidates(), &["gh"]);
2810 }
2811
2812 #[test]
2813 fn rustc_candidates_is_rustc_only() {
2814 assert_eq!(RustC::candidates(), &["rustc"]);
2815 }
2816
2817 #[test]
2818 fn missing_tool_error_names_the_binary_not_the_rust_type() {
2819 struct Missing;
2820 impl ExternalTool for Missing {
2821 fn candidates() -> &'static [&'static str] {
2822 &["codewhale-imaginary-tool", "fallback-name"]
2823 }
2824 fn resolve() -> Option<String> {
2825 None
2826 }
2827 }
2828
2829 let error = Missing::output(&["--version"], std::path::Path::new("."))
2830 .expect_err("an unresolvable tool must not spawn");
2831 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
2832 assert_eq!(
2833 error.to_string(),
2834 "codewhale-imaginary-tool not found on PATH"
2835 );
2836 assert!(!error.to_string().contains("::"), "{error}");
2837 assert_eq!(Git::not_found_error().to_string(), "git not found on PATH");
2838 }
2839
2840 #[test]
2841 fn cargo_candidates_is_cargo_only() {
2842 assert_eq!(Cargo::candidates(), &["cargo"]);
2843 }
2844
2845 #[test]
2846 fn concrete_resolvers_do_not_cross_contaminate_when_available() {
2847 let values = [
2848 Git::resolve().map(|v| ("git", v)),
2849 Gh::resolve().map(|v| ("gh", v)),
2850 RustC::resolve().map(|v| ("rustc", v)),
2851 Cargo::resolve().map(|v| ("cargo", v)),
2852 ];
2853 let resolved: Vec<(&str, String)> = values.into_iter().flatten().collect();
2854
2855 for i in 0..resolved.len() {
2856 for j in (i + 1)..resolved.len() {
2857 assert_ne!(
2858 resolved[i].1, resolved[j].1,
2859 "{} and {} unexpectedly resolved to the same binary",
2860 resolved[i].0, resolved[j].0
2861 );
2862 }
2863 }
2864 }
2865
2866 #[test]
2867 fn git_resolve_is_cached() {
2868 let first = Git::resolve();
2869 let second = Git::resolve();
2870 assert_eq!(first, second);
2871 }
2872
2873 #[test]
2874 fn gh_resolve_is_cached() {
2875 let first = Gh::resolve();
2876 let second = Gh::resolve();
2877 assert_eq!(first, second);
2878 }
2879
2880 #[test]
2881 fn python_trait_resolve_is_cached() {
2882 let first = Python::resolve();
2883 let second = Python::resolve();
2884 assert_eq!(first, second);
2885 }
2886
2887 #[test]
2888 fn rustc_resolve_is_cached() {
2889 let first = RustC::resolve();
2890 let second = RustC::resolve();
2891 assert_eq!(first, second);
2892 }
2893
2894 #[test]
2895 fn cargo_resolve_is_cached() {
2896 let first = Cargo::resolve();
2897 let second = Cargo::resolve();
2898 assert_eq!(first, second);
2899 }
2900
2901 #[test]
2902 fn git_available_matches_resolve() {
2903 assert_eq!(Git::available(), Git::resolve().is_some());
2904 }
2905
2906 #[test]
2907 fn python_available_matches_resolve() {
2908 assert_eq!(Python::available(), Python::resolve().is_some());
2909 }
2910
2911 #[test]
2912 fn rustc_available_matches_resolve() {
2913 assert_eq!(RustC::available(), RustC::resolve().is_some());
2914 }
2915
2916 #[test]
2917 fn cargo_available_matches_resolve() {
2918 assert_eq!(Cargo::available(), Cargo::resolve().is_some());
2919 }
2920
2921 #[test]
2922 fn git_command_returns_some_when_available() {
2923 if Git::available() {
2924 assert!(Git::command().is_some());
2925 }
2926 }
2927
2928 /// Every git command we build must be lock-free (#5617). Without this,
2929 /// a read-only probe can take `.git/index.lock` in the user's own
2930 /// repository and break a `git commit` they run by hand.
2931 #[test]
2932 fn git_command_never_takes_optional_locks() {
2933 if !Git::available() {
2934 return;
2935 }
2936 let cmd = Git::command().expect("git resolves when available");
2937 let value = cmd
2938 .get_envs()
2939 .find(|(key, _)| *key == std::ffi::OsStr::new("GIT_OPTIONAL_LOCKS"))
2940 .and_then(|(_, value)| value)
2941 .expect("GIT_OPTIONAL_LOCKS must be set on every git command");
2942 assert_eq!(value, std::ffi::OsStr::new("0"));
2943 }
2944
2945 /// No git spawn may prompt on `/dev/tty` (0.10.1 item 3): a credential,
2946 /// passphrase or host-key prompt inside the raw-mode TUI is a silent hang.
2947 #[test]
2948 fn git_commands_are_non_interactive() {
2949 if !Git::available() {
2950 return;
2951 }
2952 let std_cmd = Git::command().expect("git resolves when available");
2953 let tokio_cmd = Git::tokio_command().expect("git resolves when available");
2954 for envs in [
2955 std_cmd.get_envs().collect::<Vec<_>>(),
2956 tokio_cmd.as_std().get_envs().collect::<Vec<_>>(),
2957 ] {
2958 let get = |name: &str| {
2959 envs.iter()
2960 .find(|(key, _)| *key == std::ffi::OsStr::new(name))
2961 .and_then(|(_, value)| *value)
2962 };
2963 assert_eq!(get("GIT_TERMINAL_PROMPT"), Some(std::ffi::OsStr::new("0")));
2964 assert_eq!(get("GIT_PAGER"), Some(std::ffi::OsStr::new("")));
2965 assert_eq!(get("GIT_OPTIONAL_LOCKS"), Some(std::ffi::OsStr::new("0")));
2966 if std::env::var_os("GIT_SSH_COMMAND").is_none()
2967 && std::env::var_os("GIT_SSH").is_none()
2968 {
2969 assert_eq!(
2970 get("GIT_SSH_COMMAND"),
2971 Some(std::ffi::OsStr::new("ssh -o BatchMode=yes"))
2972 );
2973 }
2974 }
2975 }
2976
2977 /// The suppression is deliberately scoped to git. Other external tools
2978 /// have no index to protect and must not inherit a git-specific variable.
2979 #[test]
2980 fn optional_lock_suppression_does_not_leak_to_other_tools() {
2981 for cmd in [Gh::command(), Cargo::command()].into_iter().flatten() {
2982 assert!(
2983 !cmd.get_envs()
2984 .any(|(key, _)| key == std::ffi::OsStr::new("GIT_OPTIONAL_LOCKS")),
2985 "only Git may set GIT_OPTIONAL_LOCKS"
2986 );
2987 }
2988 }
2989
2990 /// The Python constructor runs model-authored code, so the
2991 /// command it builds must not carry the parent's environment. This
2992 /// runs on every unix runner, with or without Python installed.
2993 #[cfg(unix)]
2994 #[test]
2995 fn runtime_commands_do_not_inherit_parent_secret_env() {
2996 let _env_lock = codewhale_runtime::test_support::lock_test_env();
2997 let _secret = codewhale_runtime::test_support::EnvVarGuard::set(
2998 "CODEWHALE_TEST_RUNTIME_SECRET",
2999 "runtime-secret-value",
3000 );
3001 let output = scrubbed_command_for_spec("env").output().expect("env runs");
3002 let stdout = String::from_utf8_lossy(&output.stdout);
3003 assert!(output.status.success(), "{stdout}");
3004 assert!(!stdout.contains("runtime-secret-value"), "{stdout}");
3005 assert!(stdout.contains("PATH="), "{stdout}");
3006
3007 // Both constructors of the runtime are built on the scrubbed spec,
3008 // which sets the sanitized environment explicitly.
3009 let has_explicit_path = |cmd: &Command| {
3010 cmd.get_envs()
3011 .any(|(key, value)| key == std::ffi::OsStr::new("PATH") && value.is_some())
3012 };
3013 for cmd in [Python::command()].into_iter().flatten() {
3014 assert!(has_explicit_path(&cmd), "{cmd:?}");
3015 }
3016 for cmd in [Python::tokio_command()].into_iter().flatten() {
3017 assert!(has_explicit_path(cmd.as_std()), "{cmd:?}");
3018 }
3019 }
3020
3021 /// Workspace git config can make even `git status` run a program
3022 /// (`core.fsmonitor`); that program must not see the parent's secrets.
3023 #[cfg(unix)]
3024 #[test]
3025 fn git_command_does_not_inherit_parent_secret_env() {
3026 use std::os::unix::fs::PermissionsExt;
3027 if !Git::available() {
3028 return;
3029 }
3030 let _env_lock = codewhale_runtime::test_support::lock_test_env();
3031 let _secret = codewhale_runtime::test_support::EnvVarGuard::set(
3032 "CODEWHALE_TEST_GIT_SECRET",
3033 "git-secret-value",
3034 );
3035 let repo = tempfile::tempdir().expect("repo");
3036 let hooks = tempfile::tempdir().expect("hooks");
3037 let marker = hooks.path().join("seen");
3038 let hook = hooks.path().join("fsmonitor.sh");
3039 std::fs::write(
3040 &hook,
3041 format!(
3042 "#!/bin/sh\nprintf 'leak=%s\\n' \"${{CODEWHALE_TEST_GIT_SECRET-unset}}\" >> '{}'\nexit 1\n",
3043 marker.display()
3044 ),
3045 )
3046 .expect("write hook");
3047 std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).expect("chmod");
3048 let run = |args: &[&str]| {
3049 let status = Git::status(args, repo.path()).expect("git spawns");
3050 assert!(status.success(), "git {args:?}");
3051 };
3052 run(&["init", "-q"]);
3053 run(&["config", "user.email", "test@example.com"]);
3054 run(&["config", "user.name", "Test User"]);
3055 std::fs::write(repo.path().join("file.txt"), "hello\n").expect("write");
3056 run(&["add", "."]);
3057 run(&["commit", "-q", "-m", "init"]);
3058 run(&["config", "core.fsmonitor", &hook.to_string_lossy()]);
3059
3060 let output = Git::output(&["status", "--porcelain"], repo.path()).expect("status");
3061 assert!(output.status.success());
3062 let seen = std::fs::read_to_string(&marker).expect("fsmonitor hook ran");
3063 assert!(seen.contains("leak=unset"), "{seen}");
3064 assert!(!seen.contains("git-secret-value"), "{seen}");
3065 }
3066
3067 #[cfg(unix)]
3068 #[test]
3069 fn status_command_runs_no_repository_or_nested_filter() {
3070 use std::os::unix::fs::PermissionsExt;
3071 if !Git::available() {
3072 return;
3073 }
3074 let _env_lock = codewhale_runtime::test_support::lock_test_env();
3075 let work = tempfile::tempdir().expect("work");
3076 let outside = tempfile::tempdir().expect("outside");
3077 let helper = outside.path().join("filter.sh");
3078 std::fs::write(&helper, "#!/bin/sh\nprintf touched >> \"$1\"\ncat\n").expect("helper");
3079 std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).expect("chmod");
3080 let top_marker = outside.path().join("top-ran");
3081 let sub_marker = outside.path().join("sub-ran");
3082 let git = |dir: &Path, args: &[&str]| {
3083 let output = Git::output(args, dir).expect("git spawns");
3084 assert!(
3085 output.status.success(),
3086 "git {args:?}: {}",
3087 String::from_utf8_lossy(&output.stderr)
3088 );
3089 };
3090 let init = |dir: &Path| {
3091 std::fs::create_dir_all(dir).expect("mkdir");
3092 git(dir, &["init", "-q"]);
3093 git(dir, &["config", "user.email", "test@example.com"]);
3094 git(dir, &["config", "user.name", "Test User"]);
3095 git(dir, &["config", "commit.gpgsign", "false"]);
3096 };
3097 let age = |path: &Path| {
3098 std::fs::File::options()
3099 .write(true)
3100 .open(path)
3101 .and_then(|file| {
3102 file.set_modified(std::time::SystemTime::now() - Duration::from_secs(7200))
3103 })
3104 .expect("age file");
3105 };
3106 let top = work.path().join("top");
3107 let sub = top.join("sub");
3108 init(&top);
3109 init(&sub);
3110 std::fs::write(top.join(".gitattributes"), "a.md filter=custom\n").expect("attrs");
3111 std::fs::write(top.join("a.md"), "one\n").expect("a.md");
3112 std::fs::write(sub.join(".gitattributes"), "b.md filter=custom\n").expect("attrs");
3113 std::fs::write(sub.join("b.md"), "two\n").expect("b.md");
3114 git(&sub, &["add", "."]);
3115 git(&sub, &["commit", "-q", "-m", "sub"]);
3116 git(&top, &["add", "."]);
3117 git(&top, &["commit", "-q", "-m", "top"]);
3118 for (dir, marker) in [(&top, &top_marker), (&sub, &sub_marker)] {
3119 let clean = format!("{} {}", helper.display(), marker.display());
3120 git(dir, &["config", "filter.custom.clean", &clean]);
3121 }
3122 git(&top, &["config", "submodule.sub.ignore", "none"]);
3123 age(&top.join("a.md"));
3124 age(&sub.join("b.md"));
3125
3126 let control = Git::output(&["status", "--porcelain"], &top).expect("status");
3127 assert!(control.status.success());
3128 assert!(top_marker.exists(), "positive control: repository filter");
3129 assert!(sub_marker.exists(), "positive control: nested filter");
3130 std::fs::remove_file(&top_marker).expect("reset");
3131 std::fs::remove_file(&sub_marker).expect("reset");
3132
3133 let output = Git::status_command(&top)
3134 .expect("status command")
3135 .arg("--porcelain=v1")
3136 .output()
3137 .expect("status");
3138 assert!(output.status.success());
3139 assert!(output.stdout.is_empty(), "{:?}", output.stdout);
3140 assert!(!top_marker.exists(), "status ran the repository filter");
3141 assert!(!sub_marker.exists(), "status ran the nested filter");
3142 }
3143
3144 #[cfg(unix)]
3145 #[test]
3146 fn review_commands_start_no_program_named_by_repository_config() {
3147 use std::io::Write as _;
3148 use std::os::unix::fs::PermissionsExt;
3149 use std::process::Stdio;
3150 assert!(Git::available(), "git is required for this test");
3151 let _env_lock = codewhale_runtime::test_support::lock_test_env();
3152 let repo = tempfile::tempdir().expect("repo");
3153 let outside = tempfile::tempdir().expect("outside");
3154 let root = repo.path();
3155 let marker = outside.path().join("ran");
3156 let script = outside.path().join("helper.sh");
3157 std::fs::write(
3158 &script,
3159 format!(
3160 "#!/bin/sh\necho \"$0 $*\" >> '{}'\nexit 1\n",
3161 marker.display()
3162 ),
3163 )
3164 .expect("helper");
3165 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
3166 let helper = script.to_string_lossy().to_string();
3167 let git = |args: &[&str]| {
3168 let output = Git::output(args, root).expect("git spawns");
3169 assert!(
3170 output.status.success(),
3171 "git {args:?}: {}",
3172 String::from_utf8_lossy(&output.stderr)
3173 );
3174 String::from_utf8_lossy(&output.stdout).into_owned()
3175 };
3176 git(&["init", "-q", "--initial-branch=main"]);
3177 git(&["config", "user.email", "test@example.com"]);
3178 git(&["config", "user.name", "Test User"]);
3179 git(&["config", "commit.gpgsign", "false"]);
3180 std::fs::write(
3181 root.join(".gitattributes"),
3182 "a.txt merge=custom diff=custom filter=custom\nb.txt merge=we.ird\n",
3183 )
3184 .expect("attributes");
3185 std::fs::write(root.join("a.txt"), "base\n").expect("a.txt");
3186 std::fs::write(root.join("b.txt"), "base\n").expect("b.txt");
3187 git(&["add", "."]);
3188 git(&["commit", "-q", "-m", "base"]);
3189 git(&["checkout", "-q", "-b", "side"]);
3190 std::fs::write(root.join("a.txt"), "side\n").expect("a.txt");
3191 std::fs::write(root.join("b.txt"), "side\n").expect("b.txt");
3192 git(&["commit", "-q", "-am", "side"]);
3193 git(&["checkout", "-q", "main"]);
3194 std::fs::write(root.join("a.txt"), "main\n").expect("a.txt");
3195 std::fs::write(root.join("b.txt"), "main\n").expect("b.txt");
3196 git(&["commit", "-q", "-am", "main"]);
3197 let unsigned = git(&["cat-file", "commit", "HEAD"]);
3198 let (headers, message) = unsigned.split_once("\n\n").expect("commit layout");
3199 let signed = format!(
3200 "{headers}\ngpgsig -----BEGIN PGP SIGNATURE-----\n fixture\n -----END PGP SIGNATURE-----\n\n{message}"
3201 );
3202 let mut child = Git::command()
3203 .expect("git available")
3204 .args(["hash-object", "-t", "commit", "-w", "--stdin"])
3205 .current_dir(root)
3206 .stdin(Stdio::piped())
3207 .stdout(Stdio::piped())
3208 .spawn()
3209 .expect("hash-object");
3210 child
3211 .stdin
3212 .take()
3213 .expect("stdin")
3214 .write_all(signed.as_bytes())
3215 .expect("write commit");
3216 let object = child.wait_with_output().expect("hash-object output");
3217 assert!(object.status.success());
3218 let oid = String::from_utf8(object.stdout).expect("oid");
3219 git(&["update-ref", "refs/heads/main", oid.trim()]);
3220 git(&["reset", "-q", "--hard", "main"]);
3221
3222 let merge_driver = format!("{helper} %O %A %B");
3223 for (key, value) in [
3224 ("log.showSignature", "true"),
3225 ("gpg.program", helper.as_str()),
3226 ("gpg.openpgp.program", helper.as_str()),
3227 ("gpg.x509.program", helper.as_str()),
3228 ("gpg.ssh.program", helper.as_str()),
3229 ("merge.custom.driver", merge_driver.as_str()),
3230 ("merge.we.ird.driver", merge_driver.as_str()),
3231 ("diff.custom.textconv", helper.as_str()),
3232 ("diff.custom.command", helper.as_str()),
3233 ("diff.external", helper.as_str()),
3234 ("filter.custom.clean", helper.as_str()),
3235 ("filter.custom.smudge", helper.as_str()),
3236 ("core.pager", helper.as_str()),
3237 ("core.alternateRefsCommand", helper.as_str()),
3238 ("core.fsmonitor", helper.as_str()),
3239 ] {
3240 git(&["config", key, value]);
3241 }
3242
3243 let reads: &[&[&str]] = &[
3244 &["log", "-3"],
3245 &["log", "-1", "--format=%GS"],
3246 &["log", "-1", "--format=%G?"],
3247 &[
3248 "show",
3249 "--no-ext-diff",
3250 "--no-textconv",
3251 "--submodule=short",
3252 "--ignore-submodules=dirty",
3253 "HEAD",
3254 ],
3255 &["merge-tree", "--write-tree", "main", "side"],
3256 &[
3257 "diff",
3258 "--no-ext-diff",
3259 "--no-textconv",
3260 "--submodule=short",
3261 "--ignore-submodules=dirty",
3262 "HEAD~1",
3263 "HEAD",
3264 ],
3265 &["blame", "--no-textconv", "a.txt"],
3266 &["status", "--porcelain"],
3267 &["for-each-ref"],
3268 ];
3269 let seen = |control: &str| {
3270 std::fs::read_to_string(&marker).unwrap_or_else(|_| {
3271 panic!("positive control `{control}` did not start the repository program")
3272 })
3273 };
3274 git(&["log", "-1", "--format=%GS"]);
3275 seen("signature");
3276 std::fs::remove_file(&marker).expect("reset");
3277 Git::output(&["merge-tree", "--write-tree", "main", "side"], root).expect("git spawns");
3278 seen("merge driver");
3279 std::fs::remove_file(&marker).expect("reset");
3280
3281 for (name, build) in [
3282 (
3283 "review_command",
3284 Git::review_command as fn(&Path) -> anyhow::Result<Command>,
3285 ),
3286 ("workspace_command", Git::workspace_command),
3287 ("status_command", Git::status_command),
3288 ] {
3289 for args in reads {
3290 let mut command = build(root).expect(name);
3291 if name == "status_command" {
3292 if args[0] != "status" {
3293 continue;
3294 }
3295 command.args(&args[1..]);
3296 } else {
3297 command.args(*args);
3298 }
3299 command.output().expect("git spawns");
3300 assert!(
3301 !marker.exists(),
3302 "{name} {args:?} started a repository program: {}",
3303 std::fs::read_to_string(&marker).unwrap_or_default()
3304 );
3305 }
3306 }
3307 }
3308
3309 #[cfg(unix)]
3310 struct NestedFilterFixture {
3311 root: tempfile::TempDir,
3312 _helpers: tempfile::TempDir,
3313 marker: PathBuf,
3314 }
3315
3316 #[cfg(unix)]
3317 impl NestedFilterFixture {
3318 fn new(gitmodules_ignore_none: bool) -> Self {
3319 use std::os::unix::fs::PermissionsExt;
3320 let root = tempfile::tempdir().expect("root");
3321 let helpers = tempfile::tempdir().expect("helpers");
3322 let marker = helpers.path().join("seen");
3323 let script = helpers.path().join("clean.sh");
3324 std::fs::write(
3325 &script,
3326 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
3327 )
3328 .expect("write script");
3329 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
3330 .expect("chmod");
3331 let run = |dir: &Path, args: &[&str]| {
3332 let status = Git::status(args, dir).expect("git spawns");
3333 assert!(status.success(), "git {args:?}");
3334 };
3335 let init = |dir: &Path| {
3336 run(dir, &["init", "-q"]);
3337 run(dir, &["config", "user.email", "test@example.com"]);
3338 run(dir, &["config", "user.name", "Test User"]);
3339 };
3340 init(root.path());
3341 std::fs::write(root.path().join("file.txt"), "hello\n").expect("write");
3342 if gitmodules_ignore_none {
3343 std::fs::write(
3344 root.path().join(".gitmodules"),
3345 "[submodule \"nested\"]\n\tpath = nested\n\tignore = none\n",
3346 )
3347 .expect("gitmodules");
3348 }
3349 run(root.path(), &["add", "."]);
3350 run(root.path(), &["commit", "-q", "-m", "init"]);
3351
3352 let nested = root.path().join("nested");
3353 std::fs::create_dir(&nested).expect("nested");
3354 init(&nested);
3355 std::fs::write(nested.join(".gitattributes"), "*.txt filter=fixture\n").expect("attrs");
3356 std::fs::write(nested.join("tracked.txt"), "one\n").expect("write");
3357 run(&nested, &["add", "."]);
3358 run(&nested, &["commit", "-q", "-m", "nested"]);
3359 run(
3360 &nested,
3361 &["config", "filter.fixture.clean", &script.to_string_lossy()],
3362 );
3363 run(root.path(), &["add", "nested"]);
3364 std::fs::write(nested.join("tracked.txt"), "two\n").expect("modify");
3365 std::fs::File::options()
3366 .write(true)
3367 .open(nested.join("tracked.txt"))
3368 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
3369 .expect("age the file so git re-reads it");
3370 Self {
3371 root,
3372 _helpers: helpers,
3373 marker,
3374 }
3375 }
3376
3377 fn seen(&self) -> String {
3378 std::fs::read_to_string(&self.marker).unwrap_or_default()
3379 }
3380
3381 fn reset(&self) {
3382 let _ = std::fs::remove_file(&self.marker);
3383 }
3384 }
3385
3386 #[cfg(unix)]
3387 #[test]
3388 fn review_command_does_not_enter_nested_repositories() {
3389 if !Git::available() {
3390 return;
3391 }
3392 let fixture = NestedFilterFixture::new(false);
3393 let output = Git::review_command(fixture.root.path())
3394 .expect("review command")
3395 .args(["status", "--porcelain"])
3396 .output()
3397 .expect("status");
3398 assert!(output.status.success());
3399 let seen = fixture.seen();
3400 assert!(
3401 seen.is_empty(),
3402 "a nested repository's clean filter ran: {seen:?}"
3403 );
3404 }
3405
3406 #[cfg(unix)]
3407 #[test]
3408 fn explicit_ignore_flag_holds_against_a_gitmodules_ignore_entry() {
3409 if !Git::available() {
3410 return;
3411 }
3412 let fixture = NestedFilterFixture::new(true);
3413 let control =
3414 Git::output(&["status", "--porcelain"], fixture.root.path()).expect("control status");
3415 assert!(control.status.success());
3416 assert!(
3417 !fixture.seen().is_empty(),
3418 "positive control: .gitmodules ignore = none enters the nested repository"
3419 );
3420 fixture.reset();
3421
3422 for constructor in [
3423 Git::review_command,
3424 Git::status_command,
3425 Git::workspace_command,
3426 ] {
3427 let output = constructor(fixture.root.path())
3428 .expect("command")
3429 .args(["status", "--porcelain=v1", "--ignore-submodules=dirty"])
3430 .output()
3431 .expect("status");
3432 assert!(output.status.success());
3433 let seen = fixture.seen();
3434 assert!(
3435 seen.is_empty(),
3436 "a nested repository's clean filter ran: {seen:?}"
3437 );
3438 }
3439 let output = Git::review_command(fixture.root.path())
3440 .expect("review command")
3441 .arg("diff")
3442 .args(Git::REVIEW_DIFF_ARGS)
3443 .output()
3444 .expect("diff");
3445 assert!(output.status.success());
3446 let seen = fixture.seen();
3447 assert!(
3448 seen.is_empty(),
3449 "a nested repository's clean filter ran: {seen:?}"
3450 );
3451 }
3452
3453 #[cfg(unix)]
3454 #[test]
3455 fn repository_filters_are_reported_only_for_repository_scope() {
3456 if !Git::available() {
3457 return;
3458 }
3459 let dir = tempfile::tempdir().expect("dir");
3460 let run = |args: &[&str]| {
3461 let status = Git::status(args, dir.path()).expect("git spawns");
3462 assert!(status.success(), "git {args:?}");
3463 };
3464 run(&["init", "-q"]);
3465 assert!(!Git::defines_repository_filters(dir.path()).expect("inspect"));
3466 run(&["config", "merge.union.driver", "cat"]);
3467 assert!(!Git::defines_repository_filters(dir.path()).expect("inspect"));
3468 run(&["config", "filter.crypt.clean", "cat"]);
3469 assert!(Git::defines_repository_filters(dir.path()).expect("inspect"));
3470 }
3471
3472 #[test]
3473 fn python_command_returns_some_when_available() {
3474 if Python::available() {
3475 assert!(Python::command().is_some());
3476 }
3477 }
3478
3479 #[test]
3480 fn python_tokio_command_returns_some_when_available() {
3481 if Python::available() {
3482 assert!(Python::tokio_command().is_some());
3483 }
3484 }
3485
3486 #[test]
3487 fn git_review_accepts_supported_runtime_config() {
3488 let dir = tempfile::tempdir().unwrap();
3489 let output = Git::review_command(dir.path())
3490 .expect("native Git supports runtime overrides")
3491 .args(["config", "--get", "core.fsmonitor"])
3492 .output()
3493 .unwrap();
3494 assert!(output.status.success());
3495 assert_eq!(output.stdout, b"false\n");
3496 }
3497
3498 /// The child has a fresh executable/capability cache. Its wrapper ignores
3499 /// runtime config as older Git would; it is not an old-Git installation.
3500 #[cfg(unix)]
3501 #[test]
3502 fn git_review_refuses_unsupported_runtime_config() {
3503 use std::os::unix::fs::PermissionsExt;
3504 const CHILD: &str = "CODEWHALE_TEST_UNSUPPORTED_GIT_REVIEW";
3505 if let Some(repo) = std::env::var_os(CHILD) {
3506 let repo = PathBuf::from(repo);
3507 if std::env::var_os("CODEWHALE_TEST_MISSING_GIT_REVIEW").is_some() {
3508 let error = Git::review_command(&repo).expect_err("Git is absent");
3509 assert_eq!(error.to_string(), "git not found on PATH");
3510 return;
3511 }
3512 match Git::review_command(&repo) {
3513 Err(error) => assert!(
3514 error
3515 .to_string()
3516 .contains("runtime configuration overrides are unavailable"),
3517 "{error:#}"
3518 ),
3519 Ok(mut command) => {
3520 let output = command.args(["status", "--porcelain"]).output().unwrap();
3521 let witness = std::fs::read_to_string(repo.join("helper-seen"))
3522 .unwrap_or_else(|_| "no helper witness".into());
3523 panic!(
3524 "unsupported Git reached repository read: status={:?}; {witness}",
3525 output.status
3526 );
3527 }
3528 }
3529 assert!(!repo.join("helper-seen").exists());
3530 return;
3531 }
3532 let _lock = codewhale_runtime::test_support::lock_test_env();
3533 let real_git = resolve_executable_path("git", "--version").expect("absolute native Git");
3534 let repo = tempfile::tempdir().unwrap();
3535 let wrapper_dir = tempfile::tempdir().unwrap();
3536 let helper = repo.path().join("fsmonitor.sh");
3537 let marker = repo.path().join("helper-seen");
3538 std::fs::write(
3539 &helper,
3540 format!(
3541 "#!/bin/sh\nprintf 'unsupported-runtime-config-helper\\n' >> '{}'\nexit 1\n",
3542 marker.display()
3543 ),
3544 )
3545 .unwrap();
3546 std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).unwrap();
3547 for args in [
3548 vec!["init", "-q"],
3549 vec!["config", "core.fsmonitor", helper.to_str().unwrap()],
3550 // A static capability marker would falsely accept this repository.
3551 vec!["config", "codewhale.reviewConfigCapability", "supported"],
3552 ] {
3553 let output = Git::output(&args, repo.path()).unwrap();
3554 assert!(output.status.success(), "{output:?}");
3555 }
3556 let wrapper = wrapper_dir.path().join("git");
3557 let quoted_git = real_git.replace('\'', "'\\''");
3558 std::fs::write(
3559 &wrapper,
3560 format!("#!/bin/sh\nunset GIT_CONFIG_COUNT\nexec '{quoted_git}' \"$@\"\n"),
3561 )
3562 .unwrap();
3563 std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
3564 let output = Command::new(std::env::current_exe().unwrap())
3565 .args([
3566 "--exact",
3567 "dependencies::tests::git_review_refuses_unsupported_runtime_config",
3568 "--nocapture",
3569 ])
3570 .env(CHILD, repo.path())
3571 .env("PATH", wrapper_dir.path())
3572 .output()
3573 .unwrap();
3574 assert!(
3575 output.status.success(),
3576 "emulated unsupported Git refusal failed:\n{}\n{}",
3577 String::from_utf8_lossy(&output.stdout),
3578 String::from_utf8_lossy(&output.stderr)
3579 );
3580 assert!(!marker.exists());
3581 let missing_path = tempfile::tempdir().unwrap();
3582 let missing = Command::new(std::env::current_exe().unwrap())
3583 .args([
3584 "--exact",
3585 "dependencies::tests::git_review_refuses_unsupported_runtime_config",
3586 "--nocapture",
3587 ])
3588 .env(CHILD, repo.path())
3589 .env("CODEWHALE_TEST_MISSING_GIT_REVIEW", "1")
3590 .env("PATH", missing_path.path())
3591 .output()
3592 .unwrap();
3593 assert!(
3594 missing.status.success(),
3595 "missing Git diagnostic failed: {}\n{}",
3596 String::from_utf8_lossy(&missing.stdout),
3597 String::from_utf8_lossy(&missing.stderr)
3598 );
3599 }
3600
3601 #[cfg(unix)]
3602 #[test]
3603 fn git_review_keeps_checked_executable_after_path_changes() {
3604 use std::os::unix::fs::PermissionsExt;
3605 const CHILD: &str = "CODEWHALE_TEST_GIT_REVIEW_PATH_CHANGE";
3606 if let Some(repo) = std::env::var_os(CHILD) {
3607 let _lock = codewhale_runtime::test_support::lock_test_env();
3608 let repo = PathBuf::from(repo);
3609 let initial = Git::review_command(&repo)
3610 .unwrap()
3611 .args(["config", "--get", "core.fsmonitor"])
3612 .output()
3613 .unwrap();
3614 assert!(initial.status.success());
3615 assert_eq!(initial.stdout, b"false\n");
3616 let changed = std::env::var_os("CODEWHALE_TEST_CHANGED_GIT_PATH").unwrap();
3617 let _path = codewhale_runtime::test_support::EnvVarGuard::set("PATH", changed);
3618 let output = Git::review_command(&repo)
3619 .unwrap()
3620 .args(["status", "--porcelain"])
3621 .output()
3622 .unwrap();
3623 assert!(output.status.success(), "{output:?}");
3624 let marker = repo.join("path-change-helper-seen");
3625 assert!(
3626 !marker.exists(),
3627 "cached review switched to unchecked Git: {}",
3628 std::fs::read_to_string(marker).unwrap_or_default()
3629 );
3630 return;
3631 }
3632 let _lock = codewhale_runtime::test_support::lock_test_env();
3633 let real_git = resolve_executable_path("git", "--version").expect("absolute native Git");
3634 let quoted_git = real_git.replace('\'', "'\\''");
3635 let repo = tempfile::tempdir().unwrap();
3636 let original_path = tempfile::tempdir().unwrap();
3637 let supported_git_dir = original_path.path().join("Git path with spaces");
3638 std::fs::create_dir(&supported_git_dir).unwrap();
3639 let changed_path = tempfile::tempdir().unwrap();
3640 for (dir, prefix) in [
3641 (supported_git_dir.as_path(), ""),
3642 (changed_path.path(), "unset GIT_CONFIG_COUNT\n"),
3643 ] {
3644 let script = dir.join("git");
3645 std::fs::write(
3646 &script,
3647 format!("#!/bin/sh\n{prefix}exec '{quoted_git}' \"$@\"\n"),
3648 )
3649 .unwrap();
3650 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3651 }
3652 let helper = repo.path().join("fsmonitor.sh");
3653 std::fs::write(
3654 &helper,
3655 format!(
3656 "#!/bin/sh\nprintf 'path-change-fixture-helper\\n' >> '{}'\nexit 1\n",
3657 repo.path().join("path-change-helper-seen").display()
3658 ),
3659 )
3660 .unwrap();
3661 std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).unwrap();
3662 for args in [
3663 vec!["init", "-q"],
3664 vec!["config", "core.fsmonitor", helper.to_str().unwrap()],
3665 ] {
3666 assert!(Git::output(&args, repo.path()).unwrap().status.success());
3667 }
3668 let output = Command::new(std::env::current_exe().unwrap())
3669 .args([
3670 "--exact",
3671 "dependencies::tests::git_review_keeps_checked_executable_after_path_changes",
3672 "--nocapture",
3673 ])
3674 .env(CHILD, repo.path())
3675 .env("CODEWHALE_TEST_CHANGED_GIT_PATH", changed_path.path())
3676 .env("PATH", &supported_git_dir)
3677 .output()
3678 .unwrap();
3679 assert!(
3680 output.status.success(),
3681 "native PATH-switch review fixture failed:\n{}\n{}",
3682 String::from_utf8_lossy(&output.stdout),
3683 String::from_utf8_lossy(&output.stderr)
3684 );
3685 assert!(!repo.path().join("path-change-helper-seen").exists());
3686 }
3687
3688 #[test]
3689 fn git_output_version_succeeds() {
3690 // Only run when git is actually installed.
3691 if !Git::available() {
3692 return;
3693 }
3694 let tmp = std::env::temp_dir();
3695 let out = Git::output(&["--version"], &tmp);
3696 assert!(
3697 out.is_ok(),
3698 "git --version must succeed when git is available"
3699 );
3700 let out = out.unwrap();
3701 assert!(out.status.success(), "git --version must exit 0");
3702 let stdout = String::from_utf8_lossy(&out.stdout);
3703 assert!(
3704 stdout.contains("git version"),
3705 "git --version stdout must contain 'git version', got: {}",
3706 stdout.trim()
3707 );
3708 }
3709
3710 #[test]
3711 fn python_output_version_succeeds() {
3712 if !Python::available() {
3713 return;
3714 }
3715 let tmp = std::env::temp_dir();
3716 let out = Python::output(&["--version"], &tmp);
3717 assert!(out.is_ok(), "python --version must spawn");
3718 let out = out.unwrap();
3719 // Python --version writes to stdout on 3.x, so just check
3720 // that it succeeded (exit 0).
3721 assert!(out.status.success(), "python --version must exit 0");
3722 }
3723
3724 #[test]
3725 fn cargo_output_version_succeeds() {
3726 if !Cargo::available() {
3727 return;
3728 }
3729 let tmp = std::env::temp_dir();
3730 let out = Cargo::output(&["--version"], &tmp);
3731 assert!(out.is_ok(), "cargo --version must spawn");
3732 let out = out.unwrap();
3733 assert!(out.status.success(), "cargo --version must exit 0");
3734 }
3735
3736 #[test]
3737 fn external_tool_output_respects_cwd() {
3738 // Verify that `output()` runs in the requested directory.
3739 if !Git::available() {
3740 return;
3741 }
3742 let tmp = std::env::temp_dir();
3743 let out = Git::output(&["rev-parse", "--show-toplevel"], &tmp);
3744 assert!(out.is_ok(), "git rev-parse must spawn");
3745 let out = out.unwrap();
3746 // rev-parse --show-toplevel in a non-git dir should fail
3747 // because temp_dir is not a git repo. That's expected.
3748 // The key assertion: the command executed without IO errors.
3749 // We don't assert success because temp_dir might or might not
3750 // be inside a git worktree.
3751 let _ = out; // just checking it didn't panic/IO-error
3752 }
3753 }
3754
3754 lines RUST