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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//! Per-host JS runtime wrappers (INDEX D-05/D-06) and the headless probe that proves a host can
//! load the OpenLatch plugin through one (INDEX D-11, plan 01 §5).
//!
//! Each Cline host gets ITS OWN runtime: `<ol_dir>/bin/cline-js-runtime-hub` execs Cline.app's
//! `code-sidecar` with `BUN_BE_BUN=1`, `<ol_dir>/bin/cline-js-runtime-vscode` execs VS Code's binary
//! with `ELECTRON_RUN_AS_NODE=1`. The variable lives ONLY inside the wrapper (trap 1): set in an
//! app's own environment it turns the app itself into a runtime. On Windows the wrapper is a copy of
//! the `openlatch-cline-runtime` launcher beside a `.target` file, because Cline spawns the runtime
//! with no shell and Node refuses `.cmd`/`.bat` that way.
//!
//! Nothing here runs on the hook path, from `status`, or from `install_hooks` (the reconciler
//! reaches that): the probe is `init`'s, the delivery tick's and `doctor --fix`'s.

use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use sha2::{Digest, Sha256};

use crate::core::fs_secure;
use crate::hooks::cline_bootstrap;
use crate::hooks::cline_hosts::{Host, HostClass};
use crate::hooks::hook_files::sha256_bytes;

/// The launcher binary's name beside `openlatch` (plan 01 §6). The one spelling of it: every other
/// name (the `.exe`, the updater's staged and allow-listed names) derives from it.
pub const LAUNCHER_BIN: &str = "openlatch-cline-runtime";
/// [`LAUNCHER_BIN`] with `.exe`, spelled out only because a `&'static str` const cannot be
/// concatenated from another; pinned to [`LAUNCHER_BIN`] by a test.
const LAUNCHER_BIN_EXE: &str = "openlatch-cline-runtime.exe";

/// The launcher's file name on the given platform: `openlatch-cline-runtime(.exe)`.
pub fn launcher_file_name(windows: bool) -> &'static str {
    if windows {
        LAUNCHER_BIN_EXE
    } else {
        LAUNCHER_BIN
    }
}
/// Line 2 of every POSIX wrapper: `# openlatch-cline-runtime <sha256 of the lines below>`.
const MARKER: &str = "# openlatch-cline-runtime";
/// The probe's wall clock (the probe host's own is 6 s).
const PROBE_TIMEOUT: Duration = Duration::from_secs(8);
/// How much of the probe's stderr is kept for the error text.
const STDERR_TAIL: usize = 2048;
const PROBE_CACHE_FILE: &str = "cline-plugin-probe.json";
const PROBE_HOME_DIR: &str = "cline-probe-home";

/// Whether the Windows launcher relays Node's IPC channel, as proven by
/// `.github/workflows/cline-runtime-launcher.yml` (plan 01 §6). Flipped to `false` only if that
/// proof cannot be made green; then nothing is staged on Windows and doctor reports OL-1412
/// `windows-launcher-unproven`.
const WINDOWS_ARM_PROVEN: bool = true;

/// See [`WINDOWS_ARM_PROVEN`].
pub fn windows_arm_proven() -> bool {
    WINDOWS_ARM_PROVEN
}

/// Why a wrapper could not be written. Typed so the delivery tick maps reasons without parsing
/// strings (`OlError` carries only code/message/suggestion/docs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WrapperError {
    /// Windows: no `openlatch-cline-runtime.exe` beside `openlatch` (OL-1412 `windows-launcher-missing`).
    LauncherMissing,
    /// The host's runtime binary is gone (OL-1412 `runtime-missing`).
    RuntimeMissing,
    /// Windows: the launcher's IPC relay is unproven (OL-1412 `windows-launcher-unproven`).
    WindowsUnproven,
    /// Anything else, with the I/O error's text.
    Io(String),
}

impl std::fmt::Display for WrapperError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WrapperError::LauncherMissing => {
                write!(f, "{LAUNCHER_BIN} is missing beside openlatch")
            }
            WrapperError::RuntimeMissing => write!(f, "the host's runtime binary is missing"),
            WrapperError::WindowsUnproven => write!(f, "the Windows runtime launcher is unproven"),
            WrapperError::Io(e) => write!(f, "{e}"),
        }
    }
}

/// `<ol_dir>/bin/cline-js-runtime-<class>` (Windows: `.exe`, beside a `.target`).
pub fn wrapper_for(ol_dir: &Path, class: HostClass) -> PathBuf {
    ol_dir
        .join("bin")
        .join(wrapper_file_name(class, cfg!(windows)))
}

/// A wrapper's file name on the given platform: `cline-js-runtime-<class>(.exe)`. On Windows it is
/// a copy of the [`LAUNCHER_BIN`] launcher.
pub fn wrapper_file_name(class: HostClass, windows: bool) -> String {
    let name = format!("cline-js-runtime-{}", class.as_str());
    if windows {
        format!("{name}.exe")
    } else {
        name
    }
}

/// The Windows launcher's config file beside its `.exe`: `<exe stem>.target`.
fn target_file_for(wrapper: &Path) -> PathBuf {
    wrapper.with_extension("target")
}

/// The POSIX wrapper body — exactly the shape the live gate proved (plan 01 §0):
///
/// ```text
/// #!/bin/sh
/// # openlatch-cline-runtime <sha256 of the lines below>
/// <VAR>=1 exec '<runtime>' "$@"
/// ```
///
/// NEVER exports the variable: a prefix assignment applies to the exec'd process only.
pub(crate) fn wrapper_body(runtime: &Path, var: &str) -> String {
    let exec = format!(
        "{var}=1 exec {} \"$@\"\n",
        crate::hooks::hook_files::quote_posix(&runtime.to_string_lossy())
    );
    format!(
        "#!/bin/sh\n{MARKER} {}\n{exec}",
        sha256_bytes(exec.as_bytes())
    )
}

/// The Windows launcher's `.target` body: `runtime=<absolute path>\nenv=<NAME>=1\n`.
pub(crate) fn target_body(runtime: &Path, var: &str) -> String {
    format!("runtime={}\nenv={var}=1\n", runtime.to_string_lossy())
}

/// Write (only when the content differs) the host's wrapper and return its path.
///
/// Unix: [`wrapper_body`] via `fs_secure::write_executable` (0755, atomic). Windows: a copy of the
/// launcher beside `openlatch` plus the `.target` file, placed by [`stage_launcher`].
pub fn write_wrapper(ol_dir: &Path, host: &Host) -> Result<PathBuf, WrapperError> {
    if host.class == HostClass::Cli {
        return Err(WrapperError::Io(
            "the Cline CLI ships its own runtime; it gets no wrapper".to_string(),
        ));
    }
    if !host.runtime.is_file() {
        return Err(WrapperError::RuntimeMissing);
    }
    let wrapper = wrapper_for(ol_dir, host.class);
    let bin = wrapper
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| ol_dir.join("bin"));
    std::fs::create_dir_all(&bin).map_err(|e| WrapperError::Io(e.to_string()))?;

    if cfg!(windows) {
        if !windows_arm_proven() {
            return Err(WrapperError::WindowsUnproven);
        }
        let source = std::env::current_exe()
            .map(|exe| crate::core::update::launcher_beside(&exe))
            .map_err(|_| WrapperError::LauncherMissing)?;
        stage_launcher(&source, &wrapper)?;
        write_if_differs(
            &target_file_for(&wrapper),
            target_body(&host.runtime, host.runtime_var).as_bytes(),
            false,
        )?;
        return Ok(wrapper);
    }

    write_if_differs(
        &wrapper,
        wrapper_body(&host.runtime, host.runtime_var).as_bytes(),
        true,
    )?;
    Ok(wrapper)
}

fn write_if_differs(path: &Path, body: &[u8], executable: bool) -> Result<(), WrapperError> {
    if std::fs::read(path).is_ok_and(|current| current == body) {
        return Ok(());
    }
    let written = if executable {
        fs_secure::write_executable_bytes(path, body)
    } else {
        fs_secure::write_readable_bytes(path, body)
    };
    written.map_err(|e| WrapperError::Io(format!("{}: {e}", path.display())))
}

/// Place a copy of the launcher at `target` when it is missing or its bytes differ from `source`.
///
/// Not `staging::stage_hook_binary`: that returns `AlreadyStaged` whenever the target exists (so an
/// upgraded launcher would never be refreshed), is hardcoded to the hook's name, and honours
/// `OPENLATCH_HOOK_BIN`. A running plugin sandbox holds the target open, and a rename ONTO a running
/// image fails on Windows while a rename OF it succeeds — so a differing target is first renamed
/// aside to `<target>.old-<n>`; every call sweeps stale `.old-*` files, ignoring in-use errors.
/// Pure over its two paths, so it runs (and is tested) on every OS.
pub(crate) fn stage_launcher(source: &Path, target: &Path) -> Result<(), WrapperError> {
    sweep_old(target);
    let wanted = match std::fs::read(source) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(WrapperError::LauncherMissing)
        }
        Err(e) => return Err(WrapperError::Io(format!("{}: {e}", source.display()))),
    };
    let aside = match std::fs::read(target) {
        Ok(current) if current == wanted => return Ok(()),
        Ok(_) => {
            let aside = (0u32..1000)
                .map(|n| old_name(target, n))
                .find(|p| std::fs::symlink_metadata(p).is_err())
                .ok_or_else(|| WrapperError::Io("too many stale launcher copies".to_string()))?;
            std::fs::rename(target, &aside)
                .map_err(|e| WrapperError::Io(format!("{}: {e}", target.display())))?;
            Some(aside)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(WrapperError::Io(format!("{}: {e}", target.display()))),
    };
    // Atomic temp + rename (fs_secure's exclusive, symlink-safe temp); the launcher stays executable.
    if let Err(e) = fs_secure::write_executable_bytes(target, &wanted) {
        // Never leave the target missing: the working copy moved aside goes back.
        if let Some(aside) = aside {
            let _ = std::fs::rename(&aside, target);
        }
        return Err(WrapperError::Io(format!("{}: {e}", target.display())));
    }
    Ok(())
}

fn old_name(target: &Path, n: u32) -> PathBuf {
    let mut name = target
        .file_name()
        .map(|n| n.to_os_string())
        .unwrap_or_default();
    name.push(format!(".old-{n}"));
    target.with_file_name(name)
}

/// Remove every `<target>.old-*` beside `target`; an in-use copy is left for the next call.
fn sweep_old(target: &Path) {
    let (Some(dir), Some(name)) = (target.parent(), target.file_name()) else {
        return;
    };
    let prefix = format!("{}.old-", name.to_string_lossy());
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        if entry.file_name().to_string_lossy().starts_with(&prefix) {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Remove the wrappers for classes not in `keep` (all of them on uninstall), with their `.target`
/// and stale `.old-*` copies. Absent files are not an error.
pub fn remove_wrappers(ol_dir: &Path, keep: &[HostClass]) -> std::io::Result<()> {
    for class in [HostClass::Hub, HostClass::VsCode] {
        if keep.contains(&class) {
            continue;
        }
        let wrapper = wrapper_for(ol_dir, class);
        sweep_old(&wrapper);
        for path in [target_file_for(&wrapper), wrapper] {
            match std::fs::remove_file(&path) {
                Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
                _ => {}
            }
        }
    }
    Ok(())
}

// --- §5 · the headless probe ---------------------------------------------------------------------

/// One probe's answer. `stage` is `spawn` | `initialize` | `invoke` | `timeout` when `ok` is false.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProbeResult {
    pub ok: bool,
    pub stage: Option<String>,
    pub error: Option<String>,
}

impl ProbeResult {
    fn failed(stage: &str, error: impl Into<String>) -> ProbeResult {
        ProbeResult {
            ok: false,
            stage: Some(stage.to_string()),
            error: Some(error.into()),
        }
    }
}

/// `<ol_dir>/state/cline-plugin-probe.json`: `{ "<class>": { key, ok, stage, error, at_ms } }`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct ProbeRecord {
    key: String,
    #[serde(flatten)]
    result: ProbeResult,
    at_ms: i64,
}

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

/// Probe `host` through its wrapper, reusing the cached answer when the cache key — (class,
/// wrapper sha, runtime path+len+mtime, tree signature) — is unchanged.
pub fn probe(ol_dir: &Path, host: &Host) -> ProbeResult {
    probe_with(ol_dir, host, true)
}

/// `probe` with the cache bypassed: always runs, then overwrites that class's entry. For
/// `doctor --fix` (plan 03 §3.4).
pub fn probe_fresh(ol_dir: &Path, host: &Host) -> ProbeResult {
    probe_with(ol_dir, host, false)
}

fn probe_with(ol_dir: &Path, host: &Host, use_cache: bool) -> ProbeResult {
    let wrapper = wrapper_for(ol_dir, host.class);
    // The key takes the EMBEDDED tree's signature, so a cache hit costs no re-read of the tree; the
    // on-disk tree is verified only when the probe is about to run.
    let Some(signature) = cline_bootstrap::expected_signature() else {
        return ProbeResult::failed(
            "spawn",
            cline_bootstrap::TreeProblem::UnsupportedPlatform.to_string(),
        );
    };
    let key = cache_key(host, &wrapper, &signature);
    let mut cache = read_probe_cache(ol_dir);
    if use_cache {
        if let Some(hit) = cache.get(host.class.as_str()).filter(|r| r.key == key) {
            return hit.result.clone();
        }
    }
    let tree = match cline_bootstrap::verify(ol_dir) {
        Ok(tree) => tree,
        Err(problem) => return ProbeResult::failed("spawn", problem.to_string()),
    };
    let Some(bootstrap) = cline_bootstrap::bootstrap_path(ol_dir) else {
        return ProbeResult::failed("spawn", "this platform has no Cline plugin-sandbox package");
    };

    let result = run_probe(ol_dir, &wrapper, &tree.root, &bootstrap);
    cache.insert(
        host.class.as_str().to_string(),
        ProbeRecord {
            key,
            result: result.clone(),
            at_ms: chrono::Utc::now().timestamp_millis(),
        },
    );
    if let Err(e) = fs_secure::write_json_state(&probe_cache_path(ol_dir), &cache) {
        tracing::warn!(error = %e, "could not record the Cline plugin probe result");
    }
    result
}

fn read_probe_cache(ol_dir: &Path) -> BTreeMap<String, ProbeRecord> {
    std::fs::read(probe_cache_path(ol_dir))
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default()
}

fn cache_key(host: &Host, wrapper: &Path, tree_signature: &str) -> String {
    let wrapper_sha = std::fs::read(wrapper)
        .map(|b| sha256_bytes(&b))
        .unwrap_or_default();
    let (len, mtime) = std::fs::metadata(&host.runtime)
        .map(|m| {
            let mtime = m
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_nanos())
                .unwrap_or(0);
            (m.len(), mtime)
        })
        .unwrap_or((0, 0));
    let mut hasher = Sha256::new();
    for part in [
        host.class.as_str().to_string(),
        wrapper_sha,
        host.runtime.to_string_lossy().into_owned(),
        len.to_string(),
        mtime.to_string(),
        tree_signature.to_string(),
    ] {
        hasher.update(part.as_bytes());
        hasher.update([0u8]);
    }
    hex::encode(hasher.finalize())
}

/// Run `<wrapper> <tree>/openlatch-probe-host.mjs <bootstrap> <tree>/openlatch-probe-plugin` in a
/// throwaway HOME under `<ol_dir>/state/cline-probe-home`, with nothing able to start a hub, for at
/// most [`PROBE_TIMEOUT`]. Parses the last stdout line; no parseable line or a nonzero exit →
/// `spawn`; killed at the deadline → `timeout`; in both, `error` is the stderr tail.
fn run_probe(ol_dir: &Path, wrapper: &Path, tree: &Path, bootstrap: &Path) -> ProbeResult {
    let home = ol_dir.join("state").join(PROBE_HOME_DIR);
    let cline_dir = home.join(".cline");
    if let Err(e) = std::fs::create_dir_all(&cline_dir) {
        return ProbeResult::failed("spawn", format!("cannot create the probe home: {e}"));
    }
    let mut child = match Command::new(wrapper)
        .arg(tree.join(cline_bootstrap::PROBE_HOST))
        .arg(bootstrap)
        .arg(tree.join(cline_bootstrap::PROBE_PLUGIN_DIR))
        .env("OPENLATCH_PROBE_RUNTIME", wrapper)
        .env("HOME", &home)
        .env("USERPROFILE", &home)
        .env("CLINE_DIR", &cline_dir)
        .env("CLINE_DATA_DIR", &cline_dir)
        .env("CLINE_HUB_PORT", "0")
        .env("CLINE_HUB_DISCOVERY_PATH", home.join("hub-discovery.json"))
        .current_dir(&home)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(e) => return ProbeResult::failed("spawn", e.to_string()),
    };

    let stdout = child.stdout.take().map(drain);
    let stderr = child.stderr.take().map(drain);
    let deadline = Instant::now() + PROBE_TIMEOUT;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(50)),
            Err(_) => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
        }
    };
    let out = stdout.and_then(|h| h.join().ok()).unwrap_or_default();
    let err = stderr.and_then(|h| h.join().ok()).unwrap_or_default();
    let err_text = String::from_utf8_lossy(&err);
    let tail: String = {
        let chars: Vec<char> = err_text.chars().collect();
        chars[chars.len().saturating_sub(STDERR_TAIL)..]
            .iter()
            .collect()
    };

    let Some(status) = status else {
        return ProbeResult::failed("timeout", tail);
    };
    let parsed = String::from_utf8_lossy(&out)
        .lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .and_then(|l| serde_json::from_str::<ProbeResult>(l.trim()).ok());
    match parsed {
        Some(result) if status.success() => result,
        _ => ProbeResult::failed("spawn", tail),
    }
}

fn drain<R: Read + Send + 'static>(mut reader: R) -> std::thread::JoinHandle<Vec<u8>> {
    std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = reader.read_to_end(&mut buf);
        buf
    })
}

// --- plan 02 §3 step 4 · would this host be delivered to? -------------------------------------

/// The reason codes a host's delivery carries (INDEX D-20). A reason is `"<code>"` or `"<code>: <detail>"`;
/// readers match on the code before the first `:`.
pub mod reason {
    pub const DELIVERY_OFF: &str = "delivery-off";
    pub const HOST_TOO_OLD: &str = "host-too-old";
    pub const WINDOWS_LAUNCHER_UNPROVEN: &str = "windows-launcher-unproven";
    pub const WINDOWS_LAUNCHER_MISSING: &str = "windows-launcher-missing";
    pub const RUNTIME_MISSING: &str = "runtime-missing";
    pub const PROBE_FAILED: &str = "probe-failed";
    pub const NOT_MANAGED: &str = "not-managed";
    pub const CUSTOMER_OVERRIDE: &str = "customer-override";
    pub const NOT_DETECTED_ON_PLATFORM: &str = "not-detected-on-platform";
    pub const PENDING_RESTART: &str = "pending-restart";
}

/// One host's delivery verdict, before ownership: whether the plugin may be advertised to it at all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostAssessment {
    pub host: Host,
    /// The runtime wrapper, when it was written.
    pub wrapper: Option<PathBuf>,
    /// None = deliverable. Otherwise the FIRST failing of: delivery-off | host-too-old |
    /// windows-launcher-unproven | windows-launcher-missing | runtime-missing | probe-failed.
    pub reason: Option<String>,
}

impl HostAssessment {
    pub fn deliverable(&self) -> bool {
        self.reason.is_none()
    }
}

/// The per-host part of plan 02 §3 step 4, with the probe injectable. `tree` is `materialise`'s answer (an `Err`
/// makes every host `probe-failed: tree`). The wrapper is written whatever the verdict (it is cheap and idempotent);
/// its error NEVER propagates — it becomes the reason, so a caller always gets to remove our values.
pub fn assess_with(
    ol_dir: &Path,
    host: &Host,
    enabled: bool,
    tree: &Result<(), String>,
    probe: &dyn Fn(&Path, &Host) -> ProbeResult,
) -> HostAssessment {
    let wrapper = write_wrapper(ol_dir, host);
    let floor = match &host.core_version {
        // Orchestrator ruling: an unreadable core version is not deliverable (fail toward not-loaded).
        None => Some(format!("{}: core version unreadable", reason::HOST_TOO_OLD)),
        Some(v) if !crate::hooks::cline_hosts::meets_floor(v) => Some(format!(
            "{}: core {v} is below {}",
            reason::HOST_TOO_OLD,
            crate::hooks::cline_hosts::HOST_FLOOR
        )),
        Some(_) => None,
    };
    let wrapper_reason = wrapper.as_ref().err().map(|e| match e {
        WrapperError::WindowsUnproven => reason::WINDOWS_LAUNCHER_UNPROVEN.to_string(),
        WrapperError::LauncherMissing => reason::WINDOWS_LAUNCHER_MISSING.to_string(),
        WrapperError::RuntimeMissing => reason::RUNTIME_MISSING.to_string(),
        WrapperError::Io(d) => format!("{}: wrapper: {d}", reason::PROBE_FAILED),
    });
    let reason = if !enabled {
        Some(reason::DELIVERY_OFF.to_string())
    } else if floor.is_some() {
        floor
    } else if wrapper_reason.is_some() {
        wrapper_reason
    } else if tree.is_err() {
        Some(format!("{}: tree", reason::PROBE_FAILED))
    } else if host.class == HostClass::VsCode && !login_env_can_carry(ol_dir, host) {
        Some(format!(
            "{}: unsupported path characters",
            reason::PROBE_FAILED
        ))
    } else {
        let result = probe(ol_dir, host);
        (!result.ok).then(|| {
            format!(
                "{}: {}{}",
                reason::PROBE_FAILED,
                result.stage.as_deref().unwrap_or("probe"),
                result
                    .error
                    .as_deref()
                    .map(|e| format!(": {e}"))
                    .unwrap_or_default()
            )
        })
    };
    HostAssessment {
        host: host.clone(),
        wrapper: wrapper.ok(),
        reason,
    }
}

/// Whether both values VS Code would receive through the login environment can be carried verbatim there.
fn login_env_can_carry(ol_dir: &Path, host: &Host) -> bool {
    [
        cline_bootstrap::wrapper_path(ol_dir),
        wrapper_for(ol_dir, host.class),
    ]
    .iter()
    .all(|p| {
        p.to_str()
            .is_some_and(crate::core::login_env::value_is_deliverable)
    })
}

/// Plan 02 §3 steps 3-4 against the real machine: materialise the tree, detect the hosts, and assess each with the
/// cached probe. The daemon's delivery tick and `init`'s notice (§6) both read it; neither delivers here.
pub fn assess_hosts(ol_dir: &Path, enabled: bool) -> Vec<HostAssessment> {
    assess_hosts_with(ol_dir, enabled, crate::hooks::cline_app::detect())
}

/// [`assess_hosts`] with Cline.app already detected (`cline_app::detect()`).
pub(crate) fn assess_hosts_with(
    ol_dir: &Path,
    enabled: bool,
    app: Option<crate::hooks::cline_app::ClineApp>,
) -> Vec<HostAssessment> {
    let tree = cline_bootstrap::materialise(ol_dir)
        .map(|_| ())
        .map_err(|e| e.message);
    crate::hooks::cline_hosts::detect_with(ol_dir, app)
        .iter()
        .map(|host| assess_with(ol_dir, host, enabled, &tree, &probe))
        .collect()
}

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

    #[test]
    fn wrapper_body_never_exports() {
        let runtime = Path::new("/Apps/Visual Studio Code.app/Contents/MacOS/O'Brien Code");
        let body = wrapper_body(runtime, "ELECTRON_RUN_AS_NODE");
        let lines: Vec<&str> = body.lines().collect();
        assert_eq!(lines.len(), 3, "{body}");
        assert_eq!(lines[0], "#!/bin/sh");
        assert!(lines[1].starts_with("# openlatch-cline-runtime "));
        assert_eq!(
            lines[2],
            r#"ELECTRON_RUN_AS_NODE=1 exec '/Apps/Visual Studio Code.app/Contents/MacOS/O'\''Brien Code' "$@""#
        );
        assert!(!body.contains("export"), "the variable is never exported");
        let sha = hex::encode(Sha256::digest(format!("{}\n", lines[2]).as_bytes()));
        assert_eq!(lines[1], format!("# openlatch-cline-runtime {sha}"));

        let hub = wrapper_body(Path::new("/A/code-sidecar"), "BUN_BE_BUN");
        assert!(hub.contains("\nBUN_BE_BUN=1 exec '/A/code-sidecar' \"$@\"\n"));
    }

    #[test]
    fn launcher_file_name_derives_from_launcher_bin() {
        assert_eq!(launcher_file_name(false), LAUNCHER_BIN);
        assert_eq!(launcher_file_name(true), format!("{LAUNCHER_BIN}.exe"));
    }

    #[test]
    fn probe_record_keeps_its_on_disk_shape() {
        let existing = r#"{"key":"k1","ok":false,"stage":"spawn","error":"boom","at_ms":42}"#;
        let record: ProbeRecord = serde_json::from_str(existing).expect("parse");
        assert_eq!(
            record,
            ProbeRecord {
                key: "k1".to_string(),
                result: ProbeResult::failed("spawn", "boom"),
                at_ms: 42,
            }
        );
        assert_eq!(
            serde_json::to_value(&record).expect("serialize"),
            serde_json::from_str::<serde_json::Value>(existing).expect("json")
        );
        let ok = r#"{"key":"k2","ok":true,"stage":null,"error":null,"at_ms":7}"#;
        let record: ProbeRecord = serde_json::from_str(ok).expect("parse ok");
        assert!(record.result.ok);
        assert_eq!(
            serde_json::to_value(&record).expect("serialize"),
            serde_json::from_str::<serde_json::Value>(ok).expect("json")
        );
    }

    #[test]
    fn target_body_names_one_runtime_and_one_variable() {
        assert_eq!(
            target_body(Path::new("C:/VS Code/Code.exe"), "ELECTRON_RUN_AS_NODE"),
            "runtime=C:/VS Code/Code.exe\nenv=ELECTRON_RUN_AS_NODE=1\n"
        );
    }

    #[test]
    fn stage_launcher_refreshes_and_renames_aside() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = dir.path().join("src-launcher");
        let target = dir.path().join("bin").join("cline-js-runtime-vscode.exe");
        std::fs::create_dir_all(target.parent().expect("parent")).expect("mkdir");
        assert_eq!(
            stage_launcher(&source, &target),
            Err(WrapperError::LauncherMissing)
        );
        std::fs::write(&source, b"v1").expect("write");
        stage_launcher(&source, &target).expect("place");
        assert_eq!(std::fs::read(&target).expect("read"), b"v1");
        stage_launcher(&source, &target).expect("already current");

        std::fs::write(&source, b"v2").expect("write");
        stage_launcher(&source, &target).expect("refresh");
        assert_eq!(std::fs::read(&target).expect("read"), b"v2");
        // The aside copy is swept on the next call.
        stage_launcher(&source, &target).expect("sweep");
        let leftovers: Vec<_> = std::fs::read_dir(target.parent().expect("parent"))
            .expect("read_dir")
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().contains(".old-"))
            .collect();
        assert!(leftovers.is_empty(), "stale copies are swept");
    }

    #[test]
    fn stage_launcher_restores_the_target_when_placement_fails() {
        let dir = tempfile::tempdir().expect("tempdir");
        let source = dir.path().join("src-launcher");
        let target = dir.path().join("cline-js-runtime-vscode.exe");
        std::fs::write(&source, b"v1").expect("write");
        stage_launcher(&source, &target).expect("place");
        // A directory squatting on the temp name makes the write fail after the rename aside.
        let tmp = old_name(&target, u32::MAX).with_extension("openlatch-tmp");
        std::fs::create_dir(&tmp).expect("squat");
        std::fs::write(&source, b"v2").expect("write");
        assert!(stage_launcher(&source, &target).is_err());
        assert_eq!(
            std::fs::read(&target).expect("target is still there"),
            b"v1"
        );
    }

    /// Owner of I-5 §5 "no byte into an app bundle or extension dir".
    #[cfg(unix)]
    #[test]
    fn cline_runtime_never_writes_outside_ol_dir() {
        use crate::hooks::cline::{cline_isolated, ASSETS_DIR_ENV, DATA_DIR_ENV, STORE_DIR_ENV};
        use crate::hooks::cline_app::{write_fake_bundle, APP_DIR_ENV, BUNDLE_ID};
        use crate::hooks::cline_hosts::VSCODE_APP_ENV;
        use std::os::unix::fs::PermissionsExt;

        let a = tempfile::tempdir().expect("tempdir A");
        let b = tempfile::tempdir().expect("tempdir B");
        let apps = a.path().join("apps");
        let bundle = write_fake_bundle(&apps, BUNDLE_ID, "0.0.39");
        let sidecar = bundle.join("Contents").join("MacOS").join("code-sidecar");
        std::fs::write(&sidecar, "#!/bin/sh\nexit 1\n").expect("sidecar");
        std::fs::set_permissions(&sidecar, std::fs::Permissions::from_mode(0o755)).expect("chmod");
        let code = a.path().join("vscode").join("Code");
        std::fs::create_dir_all(code.parent().expect("parent")).expect("mkdir");
        std::fs::write(&code, "#!/bin/sh\nexit 1\n").expect("code");
        std::fs::set_permissions(&code, std::fs::Permissions::from_mode(0o755)).expect("chmod");
        let home = a.path().join("home");
        let ext = home
            .join(".vscode")
            .join("extensions")
            .join("saoudrizwan.claude-dev-4.1.22");
        std::fs::create_dir_all(ext.join("dist")).expect("mkdir");
        std::fs::write(
            ext.join("dist").join("extension.js"),
            r#"var p={name:"@cline/core",version:"0.0.88"};"#,
        )
        .expect("extension.js");

        let _seam = cline_isolated([
            (STORE_DIR_ENV, Some(a.path().join("store").into_os_string())),
            (DATA_DIR_ENV, Some(a.path().join("data").into_os_string())),
            (
                ASSETS_DIR_ENV,
                Some(a.path().join("assets").into_os_string()),
            ),
            (APP_DIR_ENV, Some(apps.clone().into_os_string())),
            (VSCODE_APP_ENV, Some(code.clone().into_os_string())),
            ("HOME", Some(home.clone().into_os_string())),
        ]);

        let snapshot = |root: &Path| {
            let mut out = BTreeMap::new();
            let mut stack = vec![root.to_path_buf()];
            while let Some(dir) = stack.pop() {
                for entry in std::fs::read_dir(&dir).expect("read_dir").flatten() {
                    let meta = std::fs::symlink_metadata(entry.path()).expect("meta");
                    if meta.is_dir() {
                        stack.push(entry.path());
                    }
                    out.insert(entry.path(), (meta.len(), meta.modified().ok()));
                }
            }
            out
        };
        let before = snapshot(a.path());

        cline_bootstrap::materialise(b.path()).expect("materialise");
        let hosts = crate::hooks::cline_hosts::detect(b.path());
        assert_eq!(
            hosts.iter().map(|h| h.class).collect::<Vec<_>>(),
            vec![HostClass::Hub, HostClass::VsCode]
        );
        for host in &hosts {
            let wrapper = write_wrapper(b.path(), host).expect("wrapper");
            assert!(wrapper.starts_with(b.path()));
            let result = probe(b.path(), host);
            assert!(!result.ok, "a runtime that exits 1 cannot pass the probe");
        }

        assert_eq!(before, snapshot(a.path()), "nothing under A changed");
        for path in snapshot(b.path()).keys() {
            assert!(path.starts_with(b.path()));
        }
        let record: serde_json::Value = serde_json::from_slice(
            &std::fs::read(b.path().join("state").join(PROBE_CACHE_FILE)).expect("probe cache"),
        )
        .expect("json");
        assert_eq!(record["hub"]["ok"], false);
        assert_eq!(record["vscode"]["ok"], false);
    }
}