openlatch-client 0.6.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Which Cline hosts are on this machine, the JS runtime each ships, and the @cline/core version each embeds.
//! Reads executables/bundles only (never Cline's store or data dir — C-6).
//!
//! - `Hub`: Cline.app's `code-sidecar`, which becomes Bun under `BUN_BE_BUN=1` (serves Desktop and
//!   hub-mode CLI sessions). Detected by [`crate::hooks::cline_app::detect`].
//! - `VsCode`: the VS Code Cline extension, whose runtime is VS Code's own Electron binary under
//!   `ELECTRON_RUN_AS_NODE=1`. Only `~/.vscode` / `~/.vscode-insiders` extensions are paired with it —
//!   a Cursor or Windsurf Cline extension is never paired with the VS Code binary.
//! - `Cli`: never detected here — the CLI ships its own bootstrap and runtime.

use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};

use crate::core::fs_secure;
use crate::hooks::cline::operator_supplied;

/// Serialized as exactly `"hub"`, `"vscode"`, `"cli"` — the keys plan 02's cline-plugin-delivery.json and plan 03's
/// cline-plugin-seen.json / doctor JSON use. A default derive would give "Hub"/"VsCode"; do not rely on it.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum HostClass {
    /// Cline.app's code-sidecar hub (serves Desktop and hub-mode CLI).
    Hub,
    VsCode,
    Cli,
}

impl HostClass {
    /// Every class, in `hub`, `vscode`, `cli` order.
    pub const ALL: [HostClass; 3] = [HostClass::Hub, HostClass::VsCode, HostClass::Cli];

    /// The serialized spelling, also used in file names (`cline-js-runtime-<class>`).
    pub fn as_str(self) -> &'static str {
        match self {
            HostClass::Hub => "hub",
            HostClass::VsCode => "vscode",
            HostClass::Cli => "cli",
        }
    }
}

/// One detected Cline host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Host {
    pub class: HostClass,
    /// Hub: `ClineApp.sidecar`; VsCode: the Electron binary; Cli: the CLI binary (info only).
    pub runtime: PathBuf,
    /// `"BUN_BE_BUN"` | `"ELECTRON_RUN_AS_NODE"`.
    pub runtime_var: &'static str,
    pub core_version: Option<semver::Version>,
    /// Where the version literal was read.
    pub source: PathBuf,
}

/// INDEX D-04: the first `@cline/core` whose resolver honours `CLINE_WRAPPER_PATH`.
pub const HOST_FLOOR: &str = "0.0.42";

/// The runtime variable Cline.app's sidecar honours.
pub const BUN_VAR: &str = "BUN_BE_BUN";
/// The runtime variable VS Code's Electron binary honours.
pub const ELECTRON_VAR: &str = "ELECTRON_RUN_AS_NODE";

/// Operator and test seam for the VS Code binary, mirroring `cline_app::APP_DIR_ENV`: UNSET (or
/// empty) → the default path list; set and absolute → ONLY that path (missing file → not detected);
/// set and relative → not detected.
pub const VSCODE_APP_ENV: &str = "OPENLATCH_VSCODE_APP";

/// True when `version` is at or above [`HOST_FLOOR`]. A prerelease compares as its release
/// (`0.0.86-nightly.x` is 0.0.86): a nightly of a floor-or-newer core carries the resolver.
pub fn meets_floor(version: &semver::Version) -> bool {
    let floor = semver::Version::parse(HOST_FLOOR).unwrap_or(semver::Version::new(0, 0, 42));
    semver::Version::new(version.major, version.minor, version.patch) >= floor
}

/// Every Cline host this machine carries that OpenLatch can give a runtime wrapper. `ol_dir` is
/// where the core-version cache lives.
pub fn detect(ol_dir: &Path) -> Vec<Host> {
    detect_with(ol_dir, crate::hooks::cline_app::detect())
}

/// [`detect`] with Cline.app already detected (`cline_app::detect()`).
pub(crate) fn detect_with(
    ol_dir: &Path,
    app: Option<crate::hooks::cline_app::ClineApp>,
) -> Vec<Host> {
    let mut hosts = Vec::new();
    if let Some(app) = app {
        hosts.push(Host {
            class: HostClass::Hub,
            core_version: core_version_of(ol_dir, &app.sidecar),
            runtime: app.sidecar.clone(),
            runtime_var: BUN_VAR,
            source: app.sidecar,
        });
    }
    if let Some((extension, runtime)) = detect_vscode(dirs::home_dir().as_deref()) {
        let source = extension.join("dist").join("extension.js");
        hosts.push(Host {
            class: HostClass::VsCode,
            core_version: core_version_of(ol_dir, &source),
            runtime,
            runtime_var: ELECTRON_VAR,
            source,
        });
    }
    hosts
}

/// The VS Code editor roots whose extensions may be paired with the VS Code binary.
const VSCODE_ROOTS: [&str; 2] = [".vscode", ".vscode-insiders"];

/// `(extension dir, VS Code binary)`: the first of `~/.vscode`, `~/.vscode-insiders` holding a Cline
/// extension (the highest version dir) for which a VS Code binary is found.
fn detect_vscode(home: Option<&Path>) -> Option<(PathBuf, PathBuf)> {
    let home = home?;
    let seam = std::env::var_os(VSCODE_APP_ENV);
    let reports = crate::hooks::cline::extension_roots(Some(home));
    VSCODE_ROOTS.iter().find_map(|root_name| {
        let root = home.join(root_name);
        let report = reports.iter().find(|r| r.path == root)?;
        let ext = highest_cline_extension(&report.matched)?;
        let insiders = *root_name == ".vscode-insiders";
        let binary = vscode_binary_candidates(
            seam.as_deref(),
            Some(home),
            insiders,
            operator_supplied("LOCALAPPDATA").as_deref(),
            operator_supplied("ProgramFiles").as_deref(),
        )
        .into_iter()
        .find(|p| p.is_file())?;
        Some((root.join("extensions").join(ext), binary))
    })
}

/// The Cline extension directory name with the highest version among `matched` (names already
/// found Cline-lineage by `extension_roots`): `saoudrizwan.claude-dev-*` or anything with `cline`.
fn highest_cline_extension(matched: &[String]) -> Option<&str> {
    matched
        .iter()
        .filter(|name| {
            name.starts_with("saoudrizwan.claude-dev-")
                || name.to_ascii_lowercase().contains("cline")
        })
        .max_by(|a, b| {
            let va = trailing_version(a);
            let vb = trailing_version(b);
            va.cmp(&vb).then_with(|| a.cmp(b))
        })
        .map(String::as_str)
}

/// `publisher.name-1.2.3` → Some(1.2.3); unparseable → None (orders below every version).
fn trailing_version(name: &str) -> Option<semver::Version> {
    let (_, tail) = name.rsplit_once('-')?;
    semver::Version::parse(tail).ok().or_else(|| {
        // `publisher.name-1.2.3-darwin-arm64` style: try the first dotted triple after a '-'.
        name.split('-')
            .find_map(|part| semver::Version::parse(part).ok())
    })
}

/// Pure: the VS Code binaries to try, in order.
///
/// Seam (`OPENLATCH_VSCODE_APP`) set and non-empty: absolute → ONLY that path; relative → none.
/// Unset: macOS `/Applications/Visual Studio Code.app/Contents/MacOS/Code`, then `~/Applications/…`,
/// then the `Visual Studio Code - Insiders.app` pair only for the `~/.vscode-insiders` root; Linux
/// `/usr/share/code/code`, `/snap/code/current/usr/share/code/code`, `/opt/visual-studio-code/code`
/// (never `/usr/bin/code`, a shell launcher); Windows `%LOCALAPPDATA%\Programs\Microsoft VS
/// Code\Code.exe`, `%ProgramFiles%\Microsoft VS Code\Code.exe`.
pub(crate) fn vscode_binary_candidates(
    seam: Option<&OsStr>,
    home: Option<&Path>,
    insiders: bool,
    local_appdata: Option<&Path>,
    program_files: Option<&Path>,
) -> Vec<PathBuf> {
    if let Some(seam) = seam.filter(|v| !v.is_empty()) {
        let path = PathBuf::from(seam);
        return if path.is_absolute() {
            vec![path]
        } else {
            Vec::new()
        };
    }
    let mut out = Vec::new();
    if cfg!(target_os = "macos") {
        let mut apps = vec!["Visual Studio Code.app"];
        if insiders {
            apps.push("Visual Studio Code - Insiders.app");
        }
        for app in apps {
            let tail = Path::new(app).join("Contents").join("MacOS").join("Code");
            out.push(Path::new("/Applications").join(&tail)); // portability-ok: macOS app root, reached only when cfg!(target_os = "macos")
            if let Some(h) = home {
                out.push(h.join("Applications").join(&tail));
            }
        }
    } else if cfg!(windows) {
        if let Some(d) = local_appdata {
            out.push(
                d.join("Programs")
                    .join("Microsoft VS Code")
                    .join("Code.exe"),
            );
        }
        if let Some(d) = program_files {
            out.push(d.join("Microsoft VS Code").join("Code.exe"));
        }
    } else {
        // Linux install paths, reached only off macOS and Windows.
        for p in [
            "/usr/share/code/code", // portability-ok: Linux-only VS Code install path
            "/snap/code/current/usr/share/code/code", // portability-ok: Linux-only VS Code install path
            "/opt/visual-studio-code/code", // portability-ok: Linux-only VS Code install path
        ] {
            out.push(PathBuf::from(p));
        }
    }
    out
}

// --- core version --------------------------------------------------------------------------------

const CHUNK: usize = 1024 * 1024;
const OVERLAP: usize = 4 * 1024;
const WINDOW: usize = 512;
const NEEDLE: &[u8] = b"\"@cline/core\"";
const CACHE_FILE: &str = "cline-hosts.json";
/// The scanner's version, stored in every cache entry. Bump it whenever `scan_core_version` can
/// answer differently for the same bytes: an entry from another scanner is rescanned, so a result
/// from an older one (version 1 took the FIRST match and cached the `0.0.0` placeholder) never sticks.
const SCAN_VERSION: u32 = 2;

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct CacheEntry {
    /// Missing in entries written before the field existed: 0, never a current version.
    #[serde(default)]
    scan: u32,
    len: u64,
    mtime_ns: u128,
    version: Option<String>,
}

fn cache_path(ol_dir: &Path) -> PathBuf {
    ol_dir.join("state").join(CACHE_FILE)
}

/// Scan for the embedded @cline/core manifest literal. Streaming, bounded memory: 1 MiB chunks
/// with a 4 KiB overlap; find `name: "@cline/core"` or `"name":"@cline/core"`; from there, within
/// the next 512 bytes, `version: "<x.y.z…>"` or `"version":"…"`; the HIGHEST match wins, because a
/// bundle also carries `{ name: "@cline/core", version: "0.0.0" }` placeholders (Cline.app 0.0.39's
/// `code-sidecar` has two before its real manifest, core 0.0.88). The CLI layout
/// (`…/@cline/core/package.json`) is parsed as JSON. Cached in `<ol_dir>/state/cline-hosts.json`
/// by (canonical path, len, mtime) and [`SCAN_VERSION`]: a hit skips the scan. Never on the hook path.
pub fn core_version_of(ol_dir: &Path, path: &Path) -> Option<semver::Version> {
    let meta = std::fs::metadata(path).ok()?;
    let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let key = canonical.to_string_lossy().into_owned();
    let len = meta.len();
    let mtime_ns = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_nanos())
        .unwrap_or(0);

    let mut cache: BTreeMap<String, CacheEntry> = std::fs::read(cache_path(ol_dir))
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    if let Some(hit) = cache.get(&key) {
        if hit.scan == SCAN_VERSION && hit.len == len && hit.mtime_ns == mtime_ns {
            return hit
                .version
                .as_deref()
                .and_then(|v| semver::Version::parse(v).ok());
        }
    }

    let version = if path.file_name() == Some(OsStr::new("package.json")) {
        package_json_version(path)
    } else {
        std::fs::File::open(path).ok().and_then(scan_core_version)
    };
    cache.insert(
        key,
        CacheEntry {
            scan: SCAN_VERSION,
            len,
            mtime_ns,
            version: version.as_ref().map(|v| v.to_string()),
        },
    );
    if let Err(e) = fs_secure::write_json_state(&cache_path(ol_dir), &cache) {
        tracing::debug!(error = %e, "could not cache the Cline host core version");
    }
    version
}

fn package_json_version(path: &Path) -> Option<semver::Version> {
    let meta = std::fs::metadata(path).ok()?;
    if meta.len() > 1024 * 1024 {
        return None;
    }
    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
    if value.get("name")?.as_str()? != "@cline/core" {
        return None;
    }
    semver::Version::parse(value.get("version")?.as_str()?).ok()
}

/// The streaming scan over any reader (pure over bytes, so the chunk boundary is testable).
fn scan_core_version<R: Read>(mut reader: R) -> Option<semver::Version> {
    let mut data: Vec<u8> = Vec::with_capacity(CHUNK + OVERLAP);
    let mut chunk = vec![0u8; CHUNK];
    let mut best: Option<semver::Version> = None;
    loop {
        let n = read_full(&mut reader, &mut chunk);
        let eof = n < CHUNK;
        data.extend_from_slice(&chunk[..n]);

        let mut from = 0;
        let mut deferred: Option<usize> = None;
        while let Some(pos) = find(&data[from..], NEEDLE).map(|p| p + from) {
            let window_end = pos + NEEDLE.len() + WINDOW;
            if window_end > data.len() && !eof {
                // The version window straddles the chunk boundary: keep it for the next round.
                deferred = Some(pos);
                break;
            }
            if name_precedes(&data[..pos]) {
                let window = &data[pos + NEEDLE.len()..window_end.min(data.len())];
                if let Some(v) = version_in(window) {
                    best = best.max(Some(v));
                }
            }
            from = pos + 1;
        }
        if eof {
            return best;
        }
        // Keep what the next chunk may still need: a deferred match with its lead-in, else the
        // overlap (so a needle split across the boundary is found whole).
        let keep_from = match deferred {
            Some(pos) => pos.saturating_sub(OVERLAP),
            None => data.len().saturating_sub(OVERLAP),
        };
        data.drain(..keep_from);
    }
}

fn read_full<R: Read>(reader: &mut R, buf: &mut [u8]) -> usize {
    let mut filled = 0;
    while filled < buf.len() {
        match reader.read(&mut buf[filled..]) {
            Ok(0) => break,
            Ok(n) => filled += n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(_) => break,
        }
    }
    filled
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// The bytes before `"@cline/core"` end in `name:` or `"name":` (whitespace allowed around `:`).
fn name_precedes(before: &[u8]) -> bool {
    let mut end = before.len();
    while end > 0 && before[end - 1].is_ascii_whitespace() {
        end -= 1;
    }
    if end == 0 || before[end - 1] != b':' {
        return false;
    }
    end -= 1;
    while end > 0 && before[end - 1].is_ascii_whitespace() {
        end -= 1;
    }
    let head = &before[..end];
    head.ends_with(b"\"name\"") || (head.ends_with(b"name") && !head.ends_with(b"\"name"))
}

/// The first `version: "x.y.z…"` / `"version":"x.y.z…"` in `window`.
fn version_in(window: &[u8]) -> Option<semver::Version> {
    let mut from = 0;
    while let Some(pos) = find(&window[from..], b"version").map(|p| p + from) {
        let mut i = pos + b"version".len();
        if window.get(i) == Some(&b'"') {
            i += 1;
        }
        while window.get(i).is_some_and(u8::is_ascii_whitespace) {
            i += 1;
        }
        if window.get(i) == Some(&b':') {
            i += 1;
            while window.get(i).is_some_and(u8::is_ascii_whitespace) {
                i += 1;
            }
            if window.get(i) == Some(&b'"') {
                let start = i + 1;
                if let Some(len) = window[start..].iter().position(|b| *b == b'"') {
                    if let Ok(text) = std::str::from_utf8(&window[start..start + len]) {
                        if let Ok(v) = semver::Version::parse(text) {
                            return Some(v);
                        }
                    }
                }
            }
        }
        from = pos + 1;
    }
    None
}

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

    #[test]
    fn host_class_serializes_as_the_file_keys() {
        assert_eq!(serde_json::to_string(&HostClass::Hub).unwrap(), "\"hub\"");
        assert_eq!(
            serde_json::to_string(&HostClass::VsCode).unwrap(),
            "\"vscode\""
        );
        assert_eq!(serde_json::to_string(&HostClass::Cli).unwrap(), "\"cli\"");
        for class in [HostClass::Hub, HostClass::VsCode, HostClass::Cli] {
            assert_eq!(
                serde_json::to_string(&class).unwrap(),
                format!("\"{}\"", class.as_str())
            );
        }
    }

    #[test]
    fn core_version_scan_finds_literal_across_chunk_boundary() {
        // The JS-object spelling, split exactly across the 1 MiB boundary.
        let literal =
            br#"name: "@cline/core", description: "x", version: "0.0.86", type: "module""#;
        for split in [3usize, 12, 20, 40, literal.len() - 5] {
            let mut bytes = vec![b'a'; CHUNK - split];
            bytes.extend_from_slice(literal);
            bytes.extend(std::iter::repeat_n(b'z', 5000));
            assert_eq!(
                scan_core_version(&bytes[..]),
                Some(semver::Version::new(0, 0, 86)),
                "split {split}"
            );
        }

        // The JSON spelling, with a prerelease.
        let json = br#"{"name":"@cline/core","version":"0.0.88-nightly.3","main":"dist/index.js"}"#;
        let mut bytes = vec![b' '; 2 * CHUNK - 10];
        bytes.extend_from_slice(json);
        assert_eq!(
            scan_core_version(&bytes[..]).map(|v| v.to_string()),
            Some("0.0.88-nightly.3".to_string())
        );

        // A `0.0.0` placeholder before the real manifest (Cline.app 0.0.39's code-sidecar): the
        // highest literal wins, whichever comes first.
        let placeholders = br#"x={name: "@cline/core", version: "0.0.0" };y={name: "@cline/core", description: "Cline Core SDK", version: _r4 };z={name: "@cline/core", description: "Cline Core SDK", version: "0.0.88" };w={name: "@cline/core", version: "0.0.0" }"#;
        assert_eq!(
            scan_core_version(&placeholders[..]),
            Some(semver::Version::new(0, 0, 88))
        );

        // A mention of the package that is not its manifest is not a version.
        let prose = br#"import x from "@cline/core"; const version = "9.9.9";"#;
        assert_eq!(scan_core_version(&prose[..]), None);
        // The version must be within 512 bytes of the name.
        let mut far = br#"name:"@cline/core","#.to_vec();
        far.extend(std::iter::repeat_n(b' ', 600));
        far.extend_from_slice(br#"version:"0.0.50""#);
        assert_eq!(scan_core_version(&far[..]), None);
    }

    #[test]
    fn core_version_of_reads_and_caches() {
        let ol = tempfile::tempdir().expect("tempdir");
        let bin = ol.path().join("fake-sidecar");
        std::fs::write(&bin, br#"xx name:"@cline/core",version:"0.0.61" yy"#).expect("write");
        assert_eq!(
            core_version_of(ol.path(), &bin),
            Some(semver::Version::new(0, 0, 61))
        );
        assert!(cache_path(ol.path()).is_file(), "the scan is cached");

        let pkg_dir = ol.path().join("node_modules").join("@cline").join("core");
        std::fs::create_dir_all(&pkg_dir).expect("mkdir");
        let pkg = pkg_dir.join("package.json");
        std::fs::write(&pkg, r#"{"name":"@cline/core","version":"0.0.70"}"#).expect("write");
        assert_eq!(
            core_version_of(ol.path(), &pkg),
            Some(semver::Version::new(0, 0, 70))
        );
        assert_eq!(core_version_of(ol.path(), &ol.path().join("absent")), None);
    }

    #[test]
    fn a_cache_entry_from_an_older_scanner_is_rescanned() {
        let ol = tempfile::tempdir().expect("tempdir");
        let bin = ol.path().join("fake-sidecar");
        std::fs::write(
            &bin,
            br#"x={name: "@cline/core", version: "0.0.0" };z={name: "@cline/core", version: "0.0.88" }"#,
        )
        .expect("write");
        let meta = std::fs::metadata(&bin).expect("meta");
        let mtime_ns = meta
            .modified()
            .expect("mtime")
            .duration_since(std::time::UNIX_EPOCH)
            .expect("epoch")
            .as_nanos();
        let key = std::fs::canonicalize(&bin)
            .expect("canonical")
            .to_string_lossy()
            .into_owned();
        // The pre-fix format: no `scan` field, the first-match placeholder, for the unchanged file.
        let old = serde_json::json!({ key.clone(): {"len": meta.len(), "mtime_ns": mtime_ns, "version": "0.0.0"} });
        std::fs::create_dir_all(ol.path().join("state")).expect("mkdir");
        std::fs::write(cache_path(ol.path()), old.to_string()).expect("write cache");

        assert_eq!(
            core_version_of(ol.path(), &bin),
            Some(semver::Version::new(0, 0, 88))
        );
        let cache: BTreeMap<String, CacheEntry> =
            serde_json::from_slice(&std::fs::read(cache_path(ol.path())).expect("read"))
                .expect("parse");
        assert_eq!(cache[&key].scan, SCAN_VERSION);
        assert_eq!(cache[&key].version.as_deref(), Some("0.0.88"));
    }

    #[test]
    fn host_floor_is_0_0_42() {
        let v = |s: &str| semver::Version::parse(s).expect("semver");
        assert!(!meets_floor(&v("0.0.41")));
        assert!(meets_floor(&v("0.0.42")));
        assert!(meets_floor(&v("0.0.87")));
        assert!(meets_floor(&v("0.1.0")));
        assert!(
            meets_floor(&v("0.0.86-nightly.1")),
            "a prerelease compares as its release"
        );
        assert!(
            !meets_floor(&v("0.0.41-nightly.9")),
            "and below the floor stays below it"
        );
        assert!(
            meets_floor(&v("0.0.42-rc.1")),
            "0.0.42-rc.1 compares as 0.0.42, not below it"
        );
    }

    #[test]
    fn vscode_seam_relative_is_not_detected() {
        let home = Path::new("/home-for-test");
        assert!(
            vscode_binary_candidates(Some(OsStr::new("Code")), Some(home), false, None, None)
                .is_empty()
        );
        assert!(vscode_binary_candidates(
            Some(OsStr::new("apps/Code")),
            Some(home),
            true,
            None,
            None
        )
        .is_empty());
        let abs = std::env::temp_dir().join("no-such-vscode-binary");
        assert_eq!(
            vscode_binary_candidates(Some(abs.as_os_str()), Some(home), false, None, None),
            vec![abs.clone()],
            "an absolute seam is the only candidate"
        );
        assert!(
            !vscode_binary_candidates(Some(OsStr::new("")), Some(home), false, None, None)
                .is_empty()
                || !cfg!(any(target_os = "macos", target_os = "linux")),
            "an empty seam is unset: the default list"
        );
    }

    #[test]
    fn the_highest_cline_extension_wins() {
        let names = vec![
            "saoudrizwan.claude-dev-4.1.9".to_string(),
            "saoudrizwan.claude-dev-4.1.22".to_string(),
            "saoudrizwan.claude-dev-4.1.21".to_string(),
        ];
        assert_eq!(
            highest_cline_extension(&names),
            Some("saoudrizwan.claude-dev-4.1.22")
        );
        assert_eq!(highest_cline_extension(&[]), None);
    }
}