merry-core 0.1.3

Core IDs, schemas, artifacts, events, and error contracts for the Merry agent runtime.
Documentation
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! Cross-platform host path, directory, and executable-lookup helpers.
//!
//! Centralizes operating-system path conventions so lower and higher layers
//! agree on home/config/state/data/cache directories, Windows verbatim
//! (`\\?\`) path simplification, clean absolute path checks, and `PATH`
//! resolution with `PATHEXT`.

use std::{
    env,
    ffi::OsStr,
    fs, io,
    path::{Component, Path, PathBuf},
};

/// Single-source-of-truth host path policy shared by OS process sandboxes
/// (`merry-process`) and in-process workspace file tools (`merry-tools`).
///
/// Centralizing all product path categories in one immutable value object
/// eliminates drift between sandbox rules and in-process tool checks:
/// - `denied`: invisible to both reads and writes (managed provider
///   credentials and external API key files).
/// - `product_readonly`: Merry-owned read-only subtrees (such as the platform
///   state directory `$XDG_STATE_HOME/merry` and config directory
///   `$XDG_CONFIG_HOME/merry`) that stay readable for history and config
///   inspection while remaining strictly non-writable.
/// - `product_writable_config`: non-secret Merry-owned writable directories
///   (configured skill roots, defaulting to `<config_dir>/skills`).
/// - `durable_memory_root`: optional durable memory root that stays writable
///   even when the workspace itself is read-only.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HostPathPolicy {
    denied: Vec<PathBuf>,
    product_readonly: Vec<PathBuf>,
    product_writable_config: Vec<PathBuf>,
    durable_memory_root: Option<PathBuf>,
}

impl HostPathPolicy {
    /// Creates an empty host path policy.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Builds Merry's standard host path policy covering read-only runtime
    /// state (`<state_dir>`, including session journals, archives, input
    /// history, and logs) and denied managed provider credentials
    /// (`<providers_dir>`).
    ///
    /// On platforms where `providers_dir` or `durable_memory_root` lives inside
    /// `state_dir` (such as Windows `%LOCALAPPDATA%\merry`), most-specific-prefix
    /// precedence keeps `providers_dir` denied while keeping `durable_memory_root`
    /// writable.
    #[must_use]
    pub fn from_merry_dirs(state_dir: PathBuf, providers_dir: PathBuf) -> Self {
        Self::new()
            .with_denied([providers_dir])
            .with_product_readonly([state_dir])
    }

    /// Replaces the denied absolute paths (invisible to both reads and writes).
    ///
    /// Non-absolute paths or paths containing `.` / `..` segments are ignored.
    #[must_use]
    pub fn with_denied(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        self.denied = clean_unique_absolute_paths(paths);
        self
    }

    /// Appends additional denied absolute paths without duplicates.
    #[must_use]
    pub fn extend_denied(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        for path in paths {
            if is_clean_absolute_path(&path) && !self.denied.contains(&path) {
                self.denied.push(path);
            }
        }
        self
    }

    /// Replaces Merry-owned read-only paths (readable even under a denied
    /// parent directory, never writable unless overridden by a strictly deeper
    /// writable product root such as configured skill roots or durable memory).
    #[must_use]
    pub fn with_product_readonly(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        self.product_readonly = clean_unique_absolute_paths(paths);
        self
    }

    /// Appends additional Merry-owned read-only paths without duplicates.
    #[must_use]
    pub fn extend_product_readonly(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        for path in paths {
            if is_clean_absolute_path(&path) && !self.product_readonly.contains(&path) {
                self.product_readonly.push(path);
            }
        }
        self
    }

    /// Replaces Merry-owned non-secret writable config and skill roots.
    #[must_use]
    pub fn with_product_writable_config(
        mut self,
        paths: impl IntoIterator<Item = PathBuf>,
    ) -> Self {
        self.product_writable_config = clean_unique_absolute_paths(paths);
        self
    }

    /// Sets the optional durable memory root directory.
    #[must_use]
    pub fn with_durable_memory_root(mut self, root: Option<PathBuf>) -> Self {
        self.durable_memory_root = root.filter(|path| is_clean_absolute_path(path));
        self
    }

    /// Returns denied paths in deterministic order.
    #[must_use]
    pub fn denied(&self) -> &[PathBuf] {
        &self.denied
    }

    /// Returns Merry-owned read-only paths in deterministic order.
    #[must_use]
    pub fn product_readonly(&self) -> &[PathBuf] {
        &self.product_readonly
    }

    /// Returns Merry-owned non-secret writable config and skill paths in
    /// deterministic order.
    #[must_use]
    pub fn product_writable_config(&self) -> &[PathBuf] {
        &self.product_writable_config
    }

    /// Returns the optional durable memory root.
    #[must_use]
    pub fn durable_memory_root(&self) -> Option<&Path> {
        self.durable_memory_root.as_deref()
    }

    /// Returns whether `path` is denied for reads by this policy.
    ///
    /// Precedence follows the most specific matching prefix (component depth):
    /// a `product_readonly` subtree overrides a broader denied parent, while an
    /// equally specific or deeper denied path (such as `<state_dir>/providers`
    /// on Windows or an external `api_key_file` inside `<state_dir>`) wins over
    /// `product_readonly`.
    #[must_use]
    pub fn is_denied_for_read(&self, path: &Path) -> bool {
        let Some(denied_depth) = deepest_matching_prefix_depth(&self.denied, path) else {
            return false;
        };
        let readonly_depth = deepest_matching_prefix_depth(&self.product_readonly, path);
        !matches!(readonly_depth, Some(depth) if depth > denied_depth)
    }

    /// Returns whether `path` falls inside an effective `product_readonly`
    /// subtree (not overridden by an equally specific or deeper `denied` path,
    /// nor by a strictly deeper writable product root such as durable memory).
    #[must_use]
    pub fn is_product_readonly(&self, path: &Path) -> bool {
        let Some(readonly_depth) = deepest_matching_prefix_depth(&self.product_readonly, path)
        else {
            return false;
        };
        let denied_depth = deepest_matching_prefix_depth(&self.denied, path);
        if matches!(denied_depth, Some(depth) if depth >= readonly_depth) {
            return false;
        }
        let writable_depth = self.deepest_writable_prefix_depth(path);
        !matches!(writable_depth, Some(depth) if depth > readonly_depth)
    }

    /// Returns whether `path` is denied for writes by this policy.
    ///
    /// `denied` paths are always non-writable. `product_readonly` paths are
    /// non-writable unless overridden by a strictly deeper writable product
    /// root (such as `durable_memory_root` under `%LOCALAPPDATA%\merry` on
    /// Windows).
    #[must_use]
    pub fn is_denied_for_write(&self, path: &Path) -> bool {
        if self.denied.iter().any(|denied| path.starts_with(denied)) {
            return true;
        }
        let Some(readonly_depth) = deepest_matching_prefix_depth(&self.product_readonly, path)
        else {
            return false;
        };
        let writable_depth = self.deepest_writable_prefix_depth(path);
        !matches!(writable_depth, Some(depth) if depth > readonly_depth)
    }

    fn deepest_writable_prefix_depth(&self, path: &Path) -> Option<usize> {
        self.product_writable_config
            .iter()
            .chain(self.durable_memory_root.iter())
            .filter(|prefix| path.starts_with(prefix))
            .map(|prefix| prefix.components().count())
            .max()
    }
}

fn deepest_matching_prefix_depth(prefixes: &[PathBuf], path: &Path) -> Option<usize> {
    prefixes
        .iter()
        .filter(|prefix| path.starts_with(prefix))
        .map(|prefix| prefix.components().count())
        .max()
}

fn clean_unique_absolute_paths(paths: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
    let mut unique = Vec::new();
    for path in paths {
        if is_clean_absolute_path(&path) && !unique.contains(&path) {
            unique.push(path);
        }
    }
    unique
}

/// Default Windows executable extensions tried when `PATHEXT` is unset.
const DEFAULT_WINDOWS_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";

/// Windows `MAX_PATH` limit where verbatim `\\?\` paths must be preserved.
const WINDOWS_MAX_PATH: usize = 260;

/// Resolves the current user's home directory from process environment.
///
/// On Unix, returns `HOME` when it is absolute. On Windows, prefers
/// `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH`, then `HOME` (for MSYS2 /
/// Git Bash and test overrides). Any Windows verbatim prefix is simplified
/// when safe.
#[must_use]
pub fn user_home_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        user_home_dir_for_windows(
            env::var_os("USERPROFILE").as_deref(),
            env::var_os("HOMEDRIVE").as_deref(),
            env::var_os("HOMEPATH").as_deref(),
            env::var_os("HOME").as_deref(),
        )
    }
    #[cfg(not(windows))]
    {
        user_home_dir_for_unix(env::var_os("HOME").as_deref())
    }
}

/// Pure Unix home-directory resolution from an explicit `HOME` value.
#[cfg(not(windows))]
fn user_home_dir_for_unix(home: Option<&OsStr>) -> Option<PathBuf> {
    non_empty_absolute_path(home)
}

/// Pure Windows home-directory resolution from explicit environment values.
///
/// Prefers `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH`, then `HOME`.
#[cfg(any(windows, test))]
fn user_home_dir_for_windows(
    userprofile: Option<&OsStr>,
    homedrive: Option<&OsStr>,
    homepath: Option<&OsStr>,
    home: Option<&OsStr>,
) -> Option<PathBuf> {
    if let Some(path) = non_empty_windows_absolute_path(userprofile) {
        return Some(path);
    }
    if let (Some(drive), Some(path)) = (non_empty_str(homedrive), non_empty_str(homepath)) {
        let combined = format!("{drive}{path}");
        if is_windows_or_native_absolute(&combined) {
            return Some(PathBuf::from(simplify_windows_verbatim_owned(combined)));
        }
    }
    non_empty_windows_absolute_path(home)
}

/// Resolves the platform base directory for configuration files (`merry` is
/// appended by callers).
///
/// An explicit absolute `XDG_CONFIG_HOME` always wins. On Windows, falls back
/// to `%APPDATA%` when absolute, then `<home>/AppData/Roaming`. On Unix, falls
/// back to `<home>/.config`.
#[must_use]
pub fn platform_config_base(
    home: &Path,
    xdg_config_home: Option<&Path>,
    appdata: Option<&Path>,
) -> PathBuf {
    resolve_platform_base(
        cfg!(windows),
        home,
        xdg_config_home,
        appdata,
        &["AppData", "Roaming"],
        ".config",
    )
}

/// Resolves the platform base directory for runtime state and logs (`merry` is
/// appended by callers).
///
/// An explicit absolute `XDG_STATE_HOME` always wins. On Windows, falls back
/// to `%LOCALAPPDATA%` when absolute, then `<home>/AppData/Local`. On Unix,
/// falls back to `<home>/.local/state`.
#[must_use]
pub fn platform_state_base(
    home: &Path,
    xdg_state_home: Option<&Path>,
    local_appdata: Option<&Path>,
) -> PathBuf {
    resolve_platform_base(
        cfg!(windows),
        home,
        xdg_state_home,
        local_appdata,
        &["AppData", "Local"],
        ".local/state",
    )
}

/// Resolves the platform base directory for durable data (`merry` is appended
/// by callers).
///
/// An explicit absolute `XDG_DATA_HOME` always wins. On Windows, falls back to
/// `%LOCALAPPDATA%` when absolute, then `<home>/AppData/Local`. On Unix, falls
/// back to `<home>/.local/share`.
#[must_use]
pub fn platform_data_base(
    home: &Path,
    xdg_data_home: Option<&Path>,
    local_appdata: Option<&Path>,
) -> PathBuf {
    resolve_platform_base(
        cfg!(windows),
        home,
        xdg_data_home,
        local_appdata,
        &["AppData", "Local"],
        ".local/share",
    )
}

/// Resolves the platform base directory for caches and ephemeral worktrees
/// (`merry` is appended by callers).
///
/// An explicit absolute `XDG_CACHE_HOME` always wins. On Windows, falls back
/// to `%LOCALAPPDATA%` when absolute, then `<home>/AppData/Local`. On Unix,
/// falls back to `<home>/.cache`.
#[must_use]
pub fn platform_cache_base(
    home: &Path,
    xdg_cache_home: Option<&Path>,
    local_appdata: Option<&Path>,
) -> PathBuf {
    resolve_platform_base(
        cfg!(windows),
        home,
        xdg_cache_home,
        local_appdata,
        &["AppData", "Local"],
        ".cache",
    )
}

fn resolve_platform_base(
    windows: bool,
    home: &Path,
    xdg_override: Option<&Path>,
    windows_override: Option<&Path>,
    windows_fallback: &[&str],
    unix_fallback: &str,
) -> PathBuf {
    if let Some(path) = usable_base_path(windows, xdg_override) {
        return path;
    }
    if windows {
        if let Some(path) = usable_base_path(true, windows_override) {
            return path;
        }
        return windows_fallback
            .iter()
            .fold(home.to_path_buf(), |acc, segment| acc.join(segment));
    }
    home.join(unix_fallback)
}

/// Strips a leading `~/` or `~\` prefix from a user-configured path.
#[must_use]
pub fn strip_home_tilde_prefix(value: &str) -> Option<&str> {
    value
        .strip_prefix("~/")
        .or_else(|| value.strip_prefix("~\\"))
}

/// Returns whether `path` is an absolute path without `.` or `..` components.
///
/// Accepts Windows drive/UNC prefixes (`Component::Prefix`) alongside
/// `Component::RootDir` and `Component::Normal`.
#[must_use]
pub fn is_clean_absolute_path(path: &Path) -> bool {
    path.is_absolute()
        && path.components().all(|component| {
            matches!(
                component,
                Component::Prefix(_) | Component::RootDir | Component::Normal(_)
            )
        })
}

/// Canonicalizes `path` and simplifies a Windows verbatim (`\\?\`) prefix when
/// safe so paths remain comparable with user/model inputs and external tools
/// such as `git`.
pub fn canonicalize_clean(path: &Path) -> io::Result<PathBuf> {
    let canonical = fs::canonicalize(path)?;
    Ok(simplify_verbatim_path(&canonical))
}

/// Simplifies a Windows verbatim (`\\?\`) path prefix when safe.
///
/// Leaves paths untouched on non-Windows targets or when the simplified form
/// would violate Windows `MAX_PATH`, reserved DOS device name, or trailing
/// dot/space rules.
#[must_use]
pub fn simplify_verbatim_path(path: &Path) -> PathBuf {
    #[cfg(windows)]
    {
        match path.to_str().and_then(simplify_windows_verbatim_str) {
            Some(simplified) => PathBuf::from(simplified),
            None => path.to_path_buf(),
        }
    }
    #[cfg(not(windows))]
    {
        path.to_path_buf()
    }
}

/// Pure Windows verbatim-prefix simplifier (`\\?\C:\...` -> `C:\...`,
/// `\\?\UNC\server\share\...` -> `\\server\share\...`).
///
/// Returns `None` if `raw` does not carry a simplifiable verbatim prefix or
/// must retain verbatim syntax for Windows filesystem safety.
fn simplify_windows_verbatim_str(raw: &str) -> Option<String> {
    let stripped = if let Some(unc_rest) = raw
        .strip_prefix(r"\\?\UNC\")
        .or_else(|| raw.strip_prefix(r"\\?\unc\"))
    {
        format!(r"\\{unc_rest}")
    } else {
        let rest = raw.strip_prefix(r"\\?\")?;
        let bytes = rest.as_bytes();
        if bytes.len() < 3
            || !bytes[0].is_ascii_alphabetic()
            || bytes[1] != b':'
            || bytes[2] != b'\\'
        {
            return None;
        }
        rest.to_owned()
    };

    if stripped.len() >= WINDOWS_MAX_PATH {
        return None;
    }
    if stripped.contains('/') {
        return None;
    }
    for segment in stripped.split('\\').skip(1) {
        if segment.is_empty() {
            continue;
        }
        if segment == "." || segment == ".." {
            return None;
        }
        if segment.ends_with('.') || segment.ends_with(' ') {
            return None;
        }
        if is_windows_reserved_device_name(segment) {
            return None;
        }
    }
    Some(stripped)
}

/// Searches `path_env` for the first runnable executable matching any entry in
/// `names`, expanding `PATHEXT` extensions on Windows.
pub fn find_executable_in_path(
    path_env: &OsStr,
    names: &[&str],
    mut is_executable: impl FnMut(&Path) -> bool,
) -> Option<PathBuf> {
    let pathext = env::var_os("PATHEXT");
    find_executable_in_path_for(
        path_env,
        names,
        pathext.as_deref(),
        cfg!(windows),
        &mut is_executable,
    )
}

/// Pure testable variant of [`find_executable_in_path`].
pub fn find_executable_in_path_for(
    path_env: &OsStr,
    names: &[&str],
    pathext: Option<&OsStr>,
    use_pathext: bool,
    mut is_executable: impl FnMut(&Path) -> bool,
) -> Option<PathBuf> {
    let extensions = if use_pathext {
        parse_pathext(pathext)
    } else {
        Vec::new()
    };

    for directory in env::split_paths(path_env) {
        if directory.as_os_str().is_empty() {
            continue;
        }
        for name in names {
            let direct = directory.join(name);
            if is_executable(&direct) {
                return Some(direct);
            }
            if use_pathext && !has_windows_executable_extension(name, &extensions) {
                for ext in &extensions {
                    let candidate = directory.join(format!("{name}{ext}"));
                    if is_executable(&candidate) {
                        return Some(candidate);
                    }
                }
            }
        }
    }
    None
}

fn parse_pathext(pathext: Option<&OsStr>) -> Vec<String> {
    let raw = pathext
        .and_then(OsStr::to_str)
        .filter(|value| !value.trim().is_empty())
        .unwrap_or(DEFAULT_WINDOWS_PATHEXT);
    let mut extensions = Vec::new();
    for entry in raw.split(';') {
        let trimmed = entry.trim();
        if trimmed.is_empty() {
            continue;
        }
        let normalized = if trimmed.starts_with('.') {
            trimmed.to_ascii_lowercase()
        } else {
            format!(".{}", trimmed.to_ascii_lowercase())
        };
        if !extensions.contains(&normalized) {
            extensions.push(normalized);
        }
    }
    if extensions.is_empty() {
        extensions.push(".exe".to_owned());
    }
    extensions
}

fn has_windows_executable_extension(name: &str, extensions: &[String]) -> bool {
    let lower = name.to_ascii_lowercase();
    extensions.iter().any(|ext| lower.ends_with(ext))
}

fn is_windows_reserved_device_name(segment: &str) -> bool {
    let stem = segment.split('.').next().unwrap_or(segment);
    let upper = stem.to_ascii_uppercase();
    matches!(
        upper.as_str(),
        "CON"
            | "PRN"
            | "AUX"
            | "NUL"
            | "COM1"
            | "COM2"
            | "COM3"
            | "COM4"
            | "COM5"
            | "COM6"
            | "COM7"
            | "COM8"
            | "COM9"
            | "LPT1"
            | "LPT2"
            | "LPT3"
            | "LPT4"
            | "LPT5"
            | "LPT6"
            | "LPT7"
            | "LPT8"
            | "LPT9"
    )
}

#[cfg(any(windows, test))]
fn non_empty_str(value: Option<&OsStr>) -> Option<&str> {
    value.and_then(OsStr::to_str).filter(|s| !s.is_empty())
}

#[cfg(not(windows))]
fn non_empty_absolute_path(value: Option<&OsStr>) -> Option<PathBuf> {
    value
        .filter(|raw| !raw.is_empty())
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}

#[cfg(any(windows, test))]
fn non_empty_windows_absolute_path(value: Option<&OsStr>) -> Option<PathBuf> {
    let raw = value.filter(|raw| !raw.is_empty())?;
    let as_str = raw.to_str();
    if let Some(text) = as_str {
        if is_windows_or_native_absolute(text) {
            return Some(PathBuf::from(simplify_windows_verbatim_owned(
                text.to_owned(),
            )));
        }
        return None;
    }
    let path = PathBuf::from(raw);
    path.is_absolute().then_some(path)
}

fn is_windows_or_native_absolute(value: &str) -> bool {
    if Path::new(value).is_absolute() {
        return true;
    }
    let bytes = value.as_bytes();
    (bytes.len() >= 3
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && matches!(bytes[2], b'\\' | b'/'))
        || value.starts_with(r"\\")
}

fn usable_base_path(windows: bool, candidate: Option<&Path>) -> Option<PathBuf> {
    let path = candidate?;
    if path.as_os_str().is_empty() {
        return None;
    }
    let is_abs = if windows {
        path.to_str().is_some_and(is_windows_or_native_absolute) || path.is_absolute()
    } else {
        path.is_absolute()
    };
    if !is_abs {
        return None;
    }
    Some(if windows {
        match path.to_str().and_then(simplify_windows_verbatim_str) {
            Some(simplified) => PathBuf::from(simplified),
            None => path.to_path_buf(),
        }
    } else {
        path.to_path_buf()
    })
}

#[cfg(any(windows, test))]
fn simplify_windows_verbatim_owned(raw: String) -> String {
    simplify_windows_verbatim_str(&raw).unwrap_or(raw)
}

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

    #[test]
    fn windows_home_prefers_userprofile_then_homedrive_homepath_then_home() {
        assert_eq!(
            user_home_dir_for_windows(
                Some(OsStr::new(r"C:\Users\Alice")),
                Some(OsStr::new("D:")),
                Some(OsStr::new(r"\Users\Bob")),
                Some(OsStr::new(r"E:\Home")),
            ),
            Some(PathBuf::from(r"C:\Users\Alice"))
        );
        assert_eq!(
            user_home_dir_for_windows(
                None,
                Some(OsStr::new("C:")),
                Some(OsStr::new(r"\Users\Bob")),
                Some(OsStr::new(r"E:\Home")),
            ),
            Some(PathBuf::from(r"C:\Users\Bob"))
        );
        assert_eq!(
            user_home_dir_for_windows(None, None, None, Some(OsStr::new(r"C:\Users\Fallback"))),
            Some(PathBuf::from(r"C:\Users\Fallback"))
        );
        assert_eq!(
            user_home_dir_for_windows(Some(OsStr::new("relative")), None, None, None),
            None
        );
    }

    #[test]
    fn windows_platform_bases_respect_xdg_overrides_and_fall_back_to_appdata() {
        let home = Path::new(r"C:\Users\Alice");
        assert_eq!(
            resolve_platform_base(
                true,
                home,
                None,
                Some(Path::new(r"C:\Users\Alice\AppData\Roaming")),
                &["AppData", "Roaming"],
                ".config",
            ),
            PathBuf::from(r"C:\Users\Alice\AppData\Roaming")
        );
        assert_eq!(
            resolve_platform_base(
                true,
                home,
                Some(Path::new(r"D:\CustomConfig")),
                Some(Path::new(r"C:\Users\Alice\AppData\Roaming")),
                &["AppData", "Roaming"],
                ".config",
            ),
            PathBuf::from(r"D:\CustomConfig")
        );
        assert_eq!(
            resolve_platform_base(
                true,
                home,
                None,
                Some(Path::new(r"C:\Users\Alice\AppData\Local")),
                &["AppData", "Local"],
                ".local/state",
            ),
            PathBuf::from(r"C:\Users\Alice\AppData\Local")
        );
        assert_eq!(
            resolve_platform_base(
                true,
                home,
                None,
                None,
                &["AppData", "Local"],
                ".local/share"
            ),
            home.join("AppData").join("Local")
        );
    }

    #[test]
    fn simplifies_safe_windows_verbatim_paths_and_preserves_unsafe_ones() {
        assert_eq!(
            simplify_windows_verbatim_str(r"\\?\C:\Users\Alice\repo"),
            Some(r"C:\Users\Alice\repo".to_owned())
        );
        assert_eq!(
            simplify_windows_verbatim_str(r"\\?\UNC\server\share\repo"),
            Some(r"\\server\share\repo".to_owned())
        );
        assert_eq!(simplify_windows_verbatim_str(r"C:\Users\Alice"), None);
        assert_eq!(
            simplify_windows_verbatim_str(r"\\?\C:\Users\Alice\NUL\file.txt"),
            None
        );
        assert_eq!(
            simplify_windows_verbatim_str(r"\\?\C:\Users\Alice\trailing."),
            None
        );
        let long = format!(r"\\?\C:\{}", "a".repeat(260));
        assert_eq!(simplify_windows_verbatim_str(&long), None);
    }

    #[test]
    fn strip_home_tilde_prefix_accepts_forward_and_backslash() {
        assert_eq!(
            strip_home_tilde_prefix("~/.config/merry"),
            Some(".config/merry")
        );
        assert_eq!(
            strip_home_tilde_prefix(r"~\AppData\Roaming"),
            Some(r"AppData\Roaming")
        );
        assert_eq!(strip_home_tilde_prefix("~alice/foo"), None);
    }

    #[test]
    fn find_executable_in_path_for_expands_pathext_when_enabled() {
        let bin_dir = Path::new("/tools/bin");
        let expected = bin_dir.join("rg.exe");
        let path_env = env::join_paths([bin_dir]).expect("join paths");
        let found = find_executable_in_path_for(
            &path_env,
            &["rg"],
            Some(&OsString::from(".COM;.EXE;.CMD")),
            true,
            |candidate| candidate == expected,
        );
        assert_eq!(found, Some(expected.clone()));

        let not_found_unix = find_executable_in_path_for(
            &path_env,
            &["rg"],
            Some(&OsString::from(".EXE")),
            false,
            |candidate| candidate == expected,
        );
        assert_eq!(not_found_unix, None);
    }

    #[test]
    fn host_path_policy_deduplicates_rejects_unclean_paths_and_exposes_readonly_state_dir() {
        let home = if cfg!(windows) {
            PathBuf::from(r"C:\Users\alice")
        } else {
            PathBuf::from("/home/alice")
        };
        let state_dir = home.join(".local").join("state").join("merry");
        let sessions_dir = state_dir.join("sessions");
        let providers_dir = home
            .join(".local")
            .join("share")
            .join("merry")
            .join("providers");
        let policy = HostPathPolicy::new()
            .with_denied([
                providers_dir.clone(),
                PathBuf::from("relative/secret"),
                home.join("..").join("etc"),
                providers_dir.clone(),
            ])
            .with_product_readonly([state_dir.clone(), PathBuf::from("relative/state")]);

        assert_eq!(policy.denied(), std::slice::from_ref(&providers_dir));
        assert_eq!(policy.product_readonly(), std::slice::from_ref(&state_dir));
        assert_eq!(
            HostPathPolicy::from_merry_dirs(state_dir.clone(), providers_dir.clone()),
            policy
        );

        let nested_secret = state_dir.join("external.key");
        let policy_with_nested_secret = policy.extend_denied([nested_secret.clone()]);
        let journal_file = sessions_dir.join("sess-1").join("journal.jsonl");
        let input_history = state_dir.join("input-history").join("workspace.jsonl");
        let log_file = state_dir.join("logs").join("merry.jsonl");
        let trust_file = state_dir.join("workspace-trust.json");
        let providers_file = providers_dir.join("providers.toml");

        for readonly_target in [
            state_dir.as_path(),
            journal_file.as_path(),
            input_history.as_path(),
            log_file.as_path(),
            trust_file.as_path(),
        ] {
            assert!(!policy_with_nested_secret.is_denied_for_read(readonly_target));
            assert!(policy_with_nested_secret.is_product_readonly(readonly_target));
            assert!(policy_with_nested_secret.is_denied_for_write(readonly_target));
        }

        assert!(policy_with_nested_secret.is_denied_for_read(&nested_secret));
        assert!(!policy_with_nested_secret.is_product_readonly(&nested_secret));
        assert!(policy_with_nested_secret.is_denied_for_write(&nested_secret));
        assert!(policy_with_nested_secret.is_denied_for_read(&providers_file));
        assert!(policy_with_nested_secret.is_denied_for_write(&providers_file));
    }

    #[test]
    fn host_path_policy_handles_shared_state_and_data_parent_cross_platform() {
        // Mirrors Windows (`%LOCALAPPDATA%\merry`) and Unix when
        // `XDG_STATE_HOME == XDG_DATA_HOME`, where `providers/` and `memory/`
        // both live inside `state_dir`.
        let root = if cfg!(windows) {
            PathBuf::from(r"C:\Users\alice\AppData\Local\merry")
        } else {
            PathBuf::from("/home/alice/.local/share/merry")
        };
        let providers_dir = root.join("providers");
        let memory_dir = root.join("memory");
        let secret_in_memory = memory_dir.join("leaked.key");

        let policy = HostPathPolicy::from_merry_dirs(root.clone(), providers_dir.clone())
            .with_durable_memory_root(Some(memory_dir.clone()))
            .extend_denied([secret_in_memory.clone()]);

        let history = root.join("sessions").join("s1").join("journal.jsonl");
        let provider_secret = providers_dir.join("secrets").join("openai.key");
        let memory_note = memory_dir.join("topics").join("sandbox.md");

        assert!(!policy.is_denied_for_read(&history));
        assert!(policy.is_product_readonly(&history));
        assert!(policy.is_denied_for_write(&history));

        assert!(policy.is_denied_for_read(&provider_secret));
        assert!(!policy.is_product_readonly(&provider_secret));
        assert!(policy.is_denied_for_write(&provider_secret));

        assert!(!policy.is_denied_for_read(&memory_note));
        assert!(!policy.is_product_readonly(&memory_note));
        assert!(!policy.is_denied_for_write(&memory_note));

        assert!(policy.is_denied_for_read(&secret_in_memory));
        assert!(policy.is_denied_for_write(&secret_in_memory));
    }
}