car-external-agents 0.36.0

Detection of installed agentic CLIs (Claude Code, Codex, Gemini) for the Common Agent Runtime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Detection — locate installed adapter binaries on `$PATH`, probe
//! version and auth state, build [`ExternalAgentSpec`] entries.
//!
//! Detection is best-effort and idempotent. Failure of any sub-probe
//! (version timeout, missing cred file, malformed JSON) degrades the
//! affected field rather than dropping the entry — knowing "claude
//! is on disk but I can't tell you the version" is more useful than
//! a silent omission.

use crate::adapters::{self, Adapter};
use crate::types::ExternalAgentSpec;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const VERSION_PROBE_TIMEOUT: Duration = Duration::from_secs(2);

/// Exclude world-writable scratch directories so a binary staged
/// under `/tmp` (Unix) or `%TEMP%` (Windows) is never the one
/// detection picks up. Matches `car_registry::supervisor`'s denylist
/// for the same reason — the 2026-05 audit walked an exploit chain
/// that staged under a world-writable dir before lifecycle-spawning,
/// and detection should not be a backdoor around that.
///
/// The prefixes are lower-cased with a trailing separator so the
/// match in [`resolve_in_path`] is case-insensitive on Windows (NTFS)
/// and separator-agnostic. Returned as owned `String`s because the
/// Windows temp dir is resolved dynamically, not a fixed literal.
fn production_scratch_prefixes() -> Vec<String> {
    #[cfg(not(windows))]
    {
        ["/tmp/", "/private/tmp/", "/var/tmp/", "/dev/shm/"]
            .iter()
            .map(|s| s.to_string())
            .collect()
    }
    #[cfg(windows)]
    {
        fn norm(s: &str) -> String {
            format!("{}\\", s.replace('/', "\\").trim_end_matches('\\')).to_ascii_lowercase()
        }
        let mut v = vec![norm(&std::env::temp_dir().to_string_lossy())];
        for var in ["TEMP", "TMP"] {
            if let Some(t) = std::env::var_os(var) {
                v.push(norm(&Path::new(&t).to_string_lossy()));
            }
        }
        let sysroot = std::env::var_os("SystemRoot")
            .map(|s| Path::new(&s).to_string_lossy().into_owned())
            .unwrap_or_else(|| r"C:\Windows".to_string());
        v.push(norm(&format!("{}\\Temp", sysroot.trim_end_matches('\\'))));
        let drive = std::env::var_os("SystemDrive")
            .map(|s| Path::new(&s).to_string_lossy().into_owned())
            .unwrap_or_else(|| "C:".to_string());
        v.push(norm(&format!(
            "{}\\Users\\Public",
            drive.trim_end_matches('\\')
        )));
        v
    }
}

/// True when `candidate` (a resolved absolute path) sits under one of
/// `scratch_prefixes`. Case-insensitive + separator-agnostic on Windows;
/// exact byte-prefix on Unix.
fn under_scratch(candidate: &str, scratch_prefixes: &[String]) -> bool {
    #[cfg(windows)]
    let candidate = candidate.replace('/', "\\").to_ascii_lowercase();
    #[cfg(windows)]
    let candidate = candidate.as_str();
    scratch_prefixes
        .iter()
        .any(|p| candidate.starts_with(p.as_str()))
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Candidate file names to try for a bare `bin_name` in each PATH dir.
///
/// On Unix this is just `[bin_name]`. On Windows an adapter's bare name
/// (`"claude"`) is installed by npm as several shims — `claude.exe`/`.cmd`/
/// `.ps1` plus an extensionless bash shim — and Windows resolves a bare command
/// against `%PATHEXT%`. So unless `bin_name` already carries an extension, try
/// `bin_name` + each `PATHEXT` entry (executable extensions first) and the bare
/// name last. Without this, an agent installed only as `claude.cmd` is missed
/// entirely (car#511). Mirrors the host's PATHEXT-aware lookup in
/// `apps/host-windows/src/paths.rs`.
fn candidate_names(bin_name: &str) -> Vec<String> {
    #[cfg(not(windows))]
    {
        vec![bin_name.to_string()]
    }
    #[cfg(windows)]
    {
        // Already has an extension → use it verbatim.
        if Path::new(bin_name).extension().is_some() {
            return vec![bin_name.to_string()];
        }
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
        let mut names: Vec<String> = pathext
            .split(';')
            .filter(|e| !e.is_empty())
            .map(|ext| format!("{bin_name}{}", ext.to_ascii_lowercase()))
            .collect();
        // The extensionless npm shim (a bash script) last: a real .exe/.cmd is
        // preferred because it can actually be spawned/probed on Windows.
        names.push(bin_name.to_string());
        names
    }
}

/// Resolve `bin_name` against the supplied `$PATH`-style search list
/// (`:`-separated on POSIX, `;` on Windows). Returns the first
/// executable match outside scratch directories. `None` when the
/// binary isn't found or every match is in a denied prefix.
///
/// `scratch_prefixes` is the list of path prefixes to refuse; in
/// production this is [`SCRATCH_PREFIXES`]. Tests pass `&[]` so
/// `tempfile`-created scratch dirs (which land under `/tmp/` on
/// Linux CI) work as PATH entries — the production denylist still
/// has unit coverage via [`tests::detect_rejects_scratch_dir_binaries`].
fn resolve_in_path(bin_name: &str, path_var: &str, scratch_prefixes: &[String]) -> Option<PathBuf> {
    let separator = if cfg!(windows) { ';' } else { ':' };
    let names = candidate_names(bin_name);
    for dir in path_var.split(separator) {
        if dir.is_empty() {
            continue;
        }
        for name in &names {
            let candidate = Path::new(dir).join(name);
            // Reject scratch dirs before any FS work — the lossy
            // string conversion is fine for prefix matching.
            let candidate_str = candidate.to_string_lossy();
            if under_scratch(&candidate_str, scratch_prefixes) {
                continue;
            }
            if !candidate.exists() {
                continue;
            }
            let Ok(meta) = std::fs::metadata(&candidate) else {
                continue;
            };
            if !meta.is_file() {
                continue;
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if meta.permissions().mode() & 0o111 == 0 {
                    continue;
                }
            }
            return Some(candidate);
        }
    }
    None
}

/// Run `<bin> --version` with a 2s timeout, return the trimmed stdout
/// if the probe succeeded with a zero exit code. Stderr is dropped —
/// some tools emit deprecation warnings there that pollute the parse
/// shape.
/// True when `bin` is a Windows `.cmd`/`.bat` batch shim (how npm installs
/// these CLIs). `CreateProcess` can't execute a batch file directly (os error
/// 193), so such a binary must be invoked through `cmd /C`. Always false off
/// Windows.
pub(crate) fn is_batch_shim(bin: &Path) -> bool {
    cfg!(windows)
        && bin
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| {
                let e = e.to_ascii_lowercase();
                e == "cmd" || e == "bat"
            })
            .unwrap_or(false)
}

/// Build a `tokio::process::Command` that invokes `bin`, routing a Windows
/// `.cmd`/`.bat` npm shim through `cmd /C` (see [`is_batch_shim`]). A `.exe` (or
/// any Unix binary) is invoked directly. The caller appends the tool's own
/// arguments via `.arg`/`.args`; for the batch path they land after
/// `cmd /C <bin>`, which is the correct batch invocation. This is the one place
/// that decides how an external-agent binary is spawned — detection's version
/// probe and every runner invoker share it, so a shim can never be spawned
/// directly (which fails on Windows).
pub(crate) fn base_command(bin: &Path) -> tokio::process::Command {
    if is_batch_shim(bin) {
        let mut c = tokio::process::Command::new("cmd");
        c.arg("/C").arg(bin);
        // The shim resolves `node` (etc.) through PATH, and cmd.exe drops a PATH
        // over ~8191 chars — see car_engine::win_env. None = inherit unchanged.
        if let Some(path) = car_engine::win_env::cmd_path_override() {
            c.env("PATH", path);
        }
        c
    } else {
        tokio::process::Command::new(bin)
    }
}

async fn probe_version(bin: &Path) -> Option<String> {
    let mut cmd = base_command(bin);
    cmd.arg("--version");
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::null());
    cmd.kill_on_drop(true);
    let child = cmd.spawn().ok()?;
    let output = match tokio::time::timeout(VERSION_PROBE_TIMEOUT, child.wait_with_output()).await {
        Ok(Ok(out)) => out,
        _ => return None,
    };
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8(output.stdout).ok()?;
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

/// Build a spec for one adapter, or `None` when the binary isn't
/// installed.
async fn detect_one(
    adapter: &Adapter,
    path_var: &str,
    home: &Path,
    scratch_prefixes: &[String],
) -> Option<ExternalAgentSpec> {
    let binary_path = resolve_in_path(adapter.bin_name, path_var, scratch_prefixes)?;
    let version_raw = probe_version(&binary_path).await;
    let version = version_raw.and_then(|raw| (adapter.parse_version)(&raw));
    let auth_kind = (adapter.probe_auth)(home);
    Some(ExternalAgentSpec {
        id: adapter.id.as_str().to_string(),
        display_name: adapter.id.display_name().to_string(),
        binary_path,
        version,
        auth_kind,
        capabilities: adapter.capabilities.clone(),
        detected_at: now_secs(),
        health: None,
    })
}

/// Run detection for every known adapter against the current process
/// environment. Returns specs for installed adapters only — uninstalled
/// adapters are simply omitted from the list. Sorted by `id` for
/// deterministic UI ordering.
///
/// Best-effort: a failed sub-probe degrades the affected field rather
/// than dropping the entry. Only a missing binary causes omission.
pub async fn detect() -> Vec<ExternalAgentSpec> {
    let path_var = std::env::var("PATH").unwrap_or_default();
    let Some(home) = home_dir() else {
        // No HOME → can't probe auth state. Still detect binaries on
        // PATH; auth_kind defaults to Unknown.
        return detect_with_paths(&path_var, Path::new("/")).await;
    };
    detect_with_paths(&path_var, &home).await
}

/// Same as [`detect`] but with explicit `$PATH` and `$HOME` overrides.
/// Production scratch denylist applies. Used by tests; not part of the
/// public API.
pub(crate) async fn detect_with_paths(path_var: &str, home: &Path) -> Vec<ExternalAgentSpec> {
    detect_with_paths_filtered(path_var, home, &production_scratch_prefixes()).await
}

/// Underlying implementation of [`detect_with_paths`] with an
/// overridable scratch-prefix list. Tests pass `&[]` so binaries
/// staged in `tempfile`-created dirs (which land under `/tmp/` on
/// Linux CI) survive the resolver. The production scratch denylist
/// keeps full unit coverage via [`tests::detect_rejects_scratch_dir_binaries`].
pub(crate) async fn detect_with_paths_filtered(
    path_var: &str,
    home: &Path,
    scratch_prefixes: &[String],
) -> Vec<ExternalAgentSpec> {
    // Probe adapters concurrently — each is an independent binary lookup +
    // `--version` subprocess (bounded by VERSION_PROBE_TIMEOUT). Sequential, the
    // worst case is N × that timeout, which on a slow machine overshoots
    // callers' own deadlines (e.g. discovery's per-provider bound) and starves
    // detection entirely. Concurrent, the worst case is ~one probe timeout.
    let probes = adapters::all()
        .iter()
        .map(|adapter| detect_one(adapter, path_var, home, scratch_prefixes));
    let mut specs: Vec<ExternalAgentSpec> = futures::future::join_all(probes)
        .await
        .into_iter()
        .flatten()
        .collect();
    // Deterministic order regardless of which probe finished first.
    specs.sort_by(|a, b| a.id.cmp(&b.id));
    specs
}

/// Run detection and immediately populate each spec's `health` field
/// with the ground-truth result from each tool's auth-status command.
/// Slower than plain [`detect`] (subprocess spawn per tool) but gives
/// host UIs a one-stop call for "what's installed AND ready to use."
///
/// Pass `force = true` to bypass the 30s per-tool health-check TTL
/// cache.
pub async fn detect_with_health(force: bool) -> Vec<ExternalAgentSpec> {
    let mut specs = detect().await;
    let healths = crate::health::check_all(&specs, force).await;
    let by_id: std::collections::HashMap<&str, &crate::health::ExternalAgentHealth> =
        healths.iter().map(|h| (h.id.as_str(), h)).collect();
    for spec in specs.iter_mut() {
        if let Some(h) = by_id.get(spec.id.as_str()) {
            spec.health = Some((*h).clone());
        }
    }
    specs
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a fake executable for `name` that prints `version_output`.
    /// On Unix this is an extensionless `#!/bin/sh` script; on Windows it's a
    /// `name.cmd` npm-style batch shim (the real-world install shape), so
    /// detection exercises the PATHEXT resolution + `cmd /C` probe path.
    /// Returns the created path.
    fn make_fake_bin(dir: &Path, name: &str, version_output: &str) -> PathBuf {
        #[cfg(windows)]
        {
            let path = dir.join(format!("{name}.cmd"));
            std::fs::write(&path, format!("@echo off\r\necho {version_output}\r\n")).unwrap();
            path
        }
        #[cfg(not(windows))]
        {
            let path = dir.join(name);
            let script = format!("#!/bin/sh\necho '{version_output}'\n");
            std::fs::write(&path, script).unwrap();
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        }
    }

    #[cfg(windows)]
    #[test]
    fn candidate_names_expands_pathext_on_windows() {
        std::env::set_var("PATHEXT", ".COM;.EXE;.BAT;.CMD");
        let names = candidate_names("claude");
        // Executable extensions are tried, plus the bare npm shim last.
        assert!(names.contains(&"claude.exe".to_string()), "{names:?}");
        assert!(names.contains(&"claude.cmd".to_string()), "{names:?}");
        assert_eq!(names.last().unwrap(), "claude", "bare shim tried last");
        // A name that already has an extension is used verbatim.
        assert_eq!(
            candidate_names("claude.cmd"),
            vec!["claude.cmd".to_string()]
        );
    }

    #[cfg(windows)]
    #[test]
    fn batch_shim_routed_through_cmd() {
        assert!(is_batch_shim(Path::new(r"C:\x\claude.cmd")));
        assert!(is_batch_shim(Path::new(r"C:\x\claude.bat")));
        assert!(is_batch_shim(Path::new(r"C:\x\CLAUDE.CMD"))); // case-insensitive
        assert!(!is_batch_shim(Path::new(r"C:\x\claude.exe")));
        // A `.cmd` shim spawns `cmd` (…/C <shim>); a `.exe` spawns directly.
        let c = base_command(Path::new(r"C:\x\claude.cmd"));
        assert_eq!(c.as_std().get_program(), "cmd");
        let c = base_command(Path::new(r"C:\x\claude.exe"));
        assert_eq!(c.as_std().get_program(), r"C:\x\claude.exe");
    }

    #[cfg(not(windows))]
    #[test]
    fn batch_shim_never_on_unix() {
        assert!(!is_batch_shim(Path::new("/x/claude.cmd")));
        let c = base_command(Path::new("/x/claude"));
        assert_eq!(c.as_std().get_program(), "/x/claude");
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn detect_finds_cmd_shim_on_path() {
        // The npm `.cmd` shim must be found via PATHEXT and version-probed
        // through `cmd /C` (car#511).
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51 (Claude Code)");
        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(
            claude.is_some(),
            "expected claude-code via .cmd shim in {specs:?}"
        );
        assert_eq!(claude.unwrap().version.as_deref(), Some("1.0.51"));
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn detect_rejects_windows_temp_dir_binaries() {
        // A shim staged under %TEMP% (a world-writable staging dir) must be
        // ignored by the *production* denylist — the Windows analogue of the
        // `/tmp` exploit block. `tempfile` lands under %TEMP%, and unlike the
        // `&[]` tests above this goes through `detect_with_paths`, which applies
        // `production_scratch_prefixes()`.
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51 (Claude Code)");
        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths(&path_var, home_dir.path()).await;
        assert!(
            specs.iter().all(|s| s.id != "claude-code"),
            "temp-dir binary must be rejected by the production denylist, got {specs:?}"
        );
    }

    #[tokio::test]
    async fn detect_finds_fake_binary_on_path() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51 (Claude Code)");

        let path_var = bin_dir.path().to_string_lossy().to_string();
        // Empty scratch denylist — `tempfile` lands under /tmp/ on
        // Linux CI, which the production list rejects. The
        // production-denylist behavior is covered by
        // `detect_rejects_scratch_dir_binaries` below.
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;

        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(claude.is_some(), "expected claude-code in {specs:?}");
        let claude = claude.unwrap();
        assert_eq!(claude.version.as_deref(), Some("1.0.51"));
        // No cred file → Unauthenticated, not Unknown.
        assert!(matches!(
            claude.auth_kind,
            crate::types::AuthKind::Unauthenticated
        ));
    }

    #[tokio::test]
    async fn detect_omits_uninstalled_binaries() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        // Empty PATH dir — no binaries installed.
        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths(&path_var, home_dir.path()).await;
        assert!(specs.is_empty(), "expected no detections, got {specs:?}");
    }

    #[tokio::test]
    async fn detect_picks_subscription_when_oauth_creds_present() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        // Write a fake credential file with an oauth-shaped key.
        let claude_dir = home_dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join(".credentials.json"),
            r#"{"oauthAccount": {"email": "[email protected]"}}"#,
        )
        .unwrap();

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code").unwrap();
        assert!(matches!(
            claude.auth_kind,
            crate::types::AuthKind::Subscription
        ));
    }

    #[tokio::test]
    async fn detect_picks_apikey_when_only_apikey_present() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        let claude_dir = home_dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join(".credentials.json"),
            r#"{"apiKey": "sk-ant-..."}"#,
        )
        .unwrap();

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code").unwrap();
        assert!(matches!(claude.auth_kind, crate::types::AuthKind::ApiKey));
    }

    #[tokio::test]
    async fn detect_rejects_scratch_dir_binaries() {
        // Skip on platforms where TMPDIR doesn't land under /tmp
        // (macOS resolves to /var/folders/... — outside the denylist
        // by design).
        let tmp = std::env::temp_dir();
        if !tmp.starts_with("/tmp") && !tmp.starts_with("/private/tmp") {
            return;
        }
        let bin_dir = tempfile::TempDir::new_in("/tmp").unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths(&path_var, home_dir.path()).await;
        assert!(
            specs.iter().all(|s| s.id != "claude-code"),
            "scratch-dir binary must be rejected, got {specs:?}"
        );
    }

    #[tokio::test]
    async fn detect_keeps_entry_when_version_probe_fails() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        // A binary that exits non-zero — version probe returns None.
        let path = bin_dir.path().join("claude");
        std::fs::write(&path, "#!/bin/sh\nexit 1\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(claude.is_some(), "entry must survive failed version probe");
        assert!(claude.unwrap().version.is_none());
    }
}