fresh-editor 0.3.9

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
//! Workspace Trust — gate process execution by a per-project trust level.
//!
//! A freshly opened project may contain attacker-controlled content that
//! only becomes dangerous when *executed*: a repo-placed `./.venv/bin/python`,
//! a `.envrc`, a project's analyzers/build commands. Workspace Trust is the
//! single gate that decides, per workspace, whether such content may run.
//!
//! There are three levels (see `docs/internal/remote-env-manager-design.md`):
//!
//! - [`TrustLevel::Restricted`] (the eventual default): no repo-controlled
//!   code runs. A spawn whose **explicit executable path** resolves inside the
//!   workspace is refused; ordinary spawns of system/user tools (a bare command
//!   name resolved via `$PATH`) proceed. Env managers do not activate, so no
//!   repo `bin/` is ever prepended to `PATH` — which is why a bare name is
//!   safe to allow.
//! - [`TrustLevel::Trusted`]: every spawn is allowed.
//! - [`TrustLevel::Blocked`]: every spawn fails.
//!
//! ## Enforcement point
//!
//! Every editor primitive that runs a child — the integrated terminal, LSP
//! server spawn, plugin `spawnProcess`, formatters, find-in-files — routes
//! through the active [`Authority`](crate::services::authority::Authority)'s
//! [`ProcessSpawner`] / [`LongRunningSpawner`]. Wrapping those two spawners is
//! therefore the one place that covers all of them with no per-caller
//! cooperation. [`Authority::with_trust`](crate::services::authority::Authority::with_trust)
//! installs the wrappers; the server calls it once per editor build.
//!
//! `editor.spawnHostProcess` (plugin internals that must run on the host,
//! e.g. `devcontainer up`) bypasses the authority spawner, so it can't be
//! caught at this choke-point; it consults [`WorkspaceTrust::decide`]
//! directly at its call site instead, so the level still applies there.
//!
//! ## What this does *not* yet cover
//!
//! The interactive "prompt each time" sub-mode of Blocked (ask before each
//! spawn rather than failing outright) is not implemented; Blocked currently
//! always fails. That sub-mode needs an async UI round-trip from the spawn
//! site and lands later; this module is the enforcement core it builds on.

use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::RwLock;

use crate::services::remote::SpawnError;

/// Per-workspace trust level.
///
/// `Default` is [`TrustLevel::Restricted`] — the safe choice for any
/// never-decided project, and the value persisted state should fall back to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TrustLevel {
    /// No repo-controlled execution; system/user tools still run.
    #[default]
    Restricted,
    /// Full execution.
    Trusted,
    /// No execution at all.
    Blocked,
}

impl TrustLevel {
    fn from_u8(v: u8) -> Self {
        match v {
            1 => TrustLevel::Trusted,
            2 => TrustLevel::Blocked,
            // 0 and any unexpected value fall back to the safe default.
            _ => TrustLevel::Restricted,
        }
    }

    fn as_u8(self) -> u8 {
        match self {
            TrustLevel::Restricted => 0,
            TrustLevel::Trusted => 1,
            TrustLevel::Blocked => 2,
        }
    }

    /// Stable lowercase name, matching the serde representation. Used to
    /// surface the level to plugins via the state snapshot.
    pub fn as_str(self) -> &'static str {
        match self {
            TrustLevel::Restricted => "restricted",
            TrustLevel::Trusted => "trusted",
            TrustLevel::Blocked => "blocked",
        }
    }
}

/// Outcome of consulting [`WorkspaceTrust::decide`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpawnDecision {
    /// The spawn may proceed.
    Allow,
    /// The spawn is refused; the string is a user-facing reason.
    Deny(String),
}

/// Shared, interior-mutable trust state for one workspace.
///
/// Held behind an `Arc` by the server (so the level survives editor rebuilds)
/// and by the guarding spawners (so they read the current level on every
/// spawn). The workspace root is mutable because a session can change its
/// working directory in place.
pub struct WorkspaceTrust {
    /// Normalized workspace roots a spawn is checked against: the working
    /// directory as given, plus its canonical form (they differ when the
    /// path traverses a symlink, e.g. `/tmp` → `/private/tmp` on macOS).
    /// A spawn inside *either* counts as inside the workspace.
    roots: RwLock<Vec<PathBuf>>,
    /// The workspace root as given. `None` when no working directory is known.
    root: RwLock<Option<PathBuf>>,
    level: AtomicU8,
    /// On-disk persistence for *this* project (a per-project file). `None`
    /// for in-memory instances (e.g. tests); when present, [`Self::set_level`]
    /// writes the decision through. Swapped via [`Self::set_store`] when the
    /// working directory changes.
    store: RwLock<Option<TrustStore>>,
}

impl WorkspaceTrust {
    /// Build in-memory trust state (no persistence) for `root` at `level`.
    pub fn new(root: Option<PathBuf>, level: TrustLevel) -> Self {
        Self::build(root, level, None)
    }

    /// Build trust state backed by `store` (a per-project trust file), so
    /// [`Self::set_level`] persists the decision for this workspace.
    pub fn new_persistent(root: Option<PathBuf>, level: TrustLevel, store: TrustStore) -> Self {
        Self::build(root, level, Some(store))
    }

    /// A permissive, in-memory trust with no workspace root — every spawn is
    /// allowed. Used as the placeholder authority before the real trust is
    /// installed at boot, and by tests/fixtures that don't exercise gating.
    pub fn permissive() -> Self {
        Self::new(None, TrustLevel::Trusted)
    }

    fn build(root: Option<PathBuf>, level: TrustLevel, store: Option<TrustStore>) -> Self {
        Self {
            roots: RwLock::new(compute_roots(root.clone())),
            root: RwLock::new(root),
            level: AtomicU8::new(level.as_u8()),
            store: RwLock::new(store),
        }
    }

    /// Current trust level.
    pub fn level(&self) -> TrustLevel {
        TrustLevel::from_u8(self.level.load(Ordering::Relaxed))
    }

    /// Set the trust level. Takes effect on the next spawn — no rebuild
    /// required (the guarding spawners read this live). When the instance is
    /// persistent, the decision is written through to disk for this workspace.
    pub fn set_level(&self, level: TrustLevel) {
        self.level.store(level.as_u8(), Ordering::Relaxed);
        if let Ok(store) = self.store.read() {
            if let Some(store) = store.as_ref() {
                if let Err(e) = store.record(level) {
                    tracing::warn!("workspace trust: failed to persist level: {e}");
                }
            }
        }
    }

    /// Update the workspace root after a working-directory change. Only the
    /// containment roots move here; the per-project store is swapped
    /// separately via [`Self::set_store`] (the caller knows the new project's
    /// state directory).
    pub fn set_root(&self, root: Option<PathBuf>) {
        if let Ok(mut guard) = self.roots.write() {
            *guard = compute_roots(root.clone());
        }
        if let Ok(mut guard) = self.root.write() {
            *guard = root;
        }
    }

    /// Point persistence at a new project's trust store and adopt that
    /// project's stored level (if any). Called on a working-directory change,
    /// since trust is per-project. Passing `None` detaches persistence.
    pub fn set_store(&self, store: Option<TrustStore>) {
        if let Some(store) = &store {
            // Adopt the new project's level (the safe default when it has no
            // recorded decision) — never inherit the previous project's level.
            self.level.store(store.level().as_u8(), Ordering::Relaxed);
        }
        if let Ok(mut guard) = self.store.write() {
            *guard = store;
        }
    }

    /// Decide whether spawning `command` (with the child's `cwd`) may proceed.
    pub fn decide(&self, command: &str, cwd: Option<&str>) -> SpawnDecision {
        match self.level() {
            TrustLevel::Trusted => SpawnDecision::Allow,
            TrustLevel::Blocked => SpawnDecision::Deny(
                "workspace trust is set to Blocked — no processes may run".to_string(),
            ),
            TrustLevel::Restricted => self.decide_restricted(command, cwd),
        }
    }

    fn decide_restricted(&self, command: &str, cwd: Option<&str>) -> SpawnDecision {
        // A bare command name (no path separator) is resolved by the OS via
        // `$PATH`. Under Restricted no env is activated, so the repo's `bin/`
        // is never on `$PATH` and a bare name resolves to a system/user tool.
        // Allow it; only explicit paths can be judged for containment.
        if !looks_like_path(command) {
            return SpawnDecision::Allow;
        }

        let roots = match self.roots.read() {
            Ok(g) => g,
            // A poisoned lock should never gate the editor open/shut; fail
            // open here (Restricted's job is to stop *repo* execution, and a
            // poisoned lock is an internal bug, not a hostile project).
            Err(_) => return SpawnDecision::Allow,
        };
        if roots.is_empty() {
            // No known workspace root → can't judge containment. Allow.
            return SpawnDecision::Allow;
        }

        let base = roots[0].as_path();
        let candidate = resolve_against(command, cwd, base);
        if roots.iter().any(|r| path_is_within(&candidate, r)) {
            SpawnDecision::Deny(format!(
                "workspace trust is Restricted — refusing to run '{command}' \
                 from inside the project; trust this folder to allow it"
            ))
        } else {
            SpawnDecision::Allow
        }
    }
}

/// Build the list of normalized roots (given + canonical) to check against.
fn compute_roots(root: Option<PathBuf>) -> Vec<PathBuf> {
    let Some(root) = root else {
        return Vec::new();
    };
    let mut roots = vec![lexical_normalize(&root)];
    if let Ok(canonical) = std::fs::canonicalize(&root) {
        let canonical = lexical_normalize(&canonical);
        if !roots.contains(&canonical) {
            roots.push(canonical);
        }
    }
    roots
}

/// Whether `command` names a path (vs. a bare name resolved via `$PATH`).
fn looks_like_path(command: &str) -> bool {
    command.contains('/') || command.contains('\\')
}

/// Resolve `command` to an absolute, lexically-normalized path. Relative
/// commands resolve against the child's `cwd` when given (else `base`).
fn resolve_against(command: &str, cwd: Option<&str>, base: &Path) -> PathBuf {
    let p = Path::new(command);
    if p.is_absolute() {
        return lexical_normalize(p);
    }
    let cwd_base = match cwd {
        Some(c) if Path::new(c).is_absolute() => PathBuf::from(c),
        Some(c) => base.join(c),
        None => base.to_path_buf(),
    };
    lexical_normalize(&cwd_base.join(p))
}

/// Lexically resolve `.`/`..` without touching the filesystem (so it never
/// fails or blocks, and works on paths that don't exist yet).
fn lexical_normalize(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for comp in p.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => {
                // Pop a real directory component; otherwise keep the `..`
                // (e.g. a leading `..` with nothing above it to cancel).
                if out.file_name().is_some() {
                    out.pop();
                } else {
                    out.push("..");
                }
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Whether `candidate` is at or under `root` (both already normalized).
fn path_is_within(candidate: &Path, root: &Path) -> bool {
    candidate == root || candidate.starts_with(root)
}

/// Serialized form of one project's trust decision. A struct (rather than a
/// bare enum) leaves room to record more per-decision metadata later without
/// breaking the file format.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct StoredTrust {
    level: TrustLevel,
}

/// On-disk persistence of *one* project's trust decision: a small JSON file
/// (`trust.json`) inside that project's state directory
/// (`<data_dir>/workspaces/<encoded-path>/`).
///
/// One file per project — not a shared map — so concurrent `fresh` processes
/// on different projects never contend over the same file. Trust is a
/// per-user security decision and lives in the user's data dir, never inside
/// the repository (a repo must not be able to vouch for itself).
#[derive(Debug, Clone)]
pub struct TrustStore {
    path: PathBuf,
}

impl TrustStore {
    /// Trust file for the project whose state lives in `project_state_dir`
    /// (see `DirectoryContext::project_state_dir`).
    pub fn for_project_dir(project_state_dir: &Path) -> Self {
        Self {
            path: project_state_dir.join("trust.json"),
        }
    }

    /// This project's trust level. Always concrete: a project that has never
    /// been decided reads as the safe default (`Restricted`) — there is no
    /// "undecided" trust *value*. Whether a decision has actually been recorded
    /// (and thus whether to prompt) is a separate question, see [`Self::is_decided`].
    pub fn level(&self) -> TrustLevel {
        self.recorded_level().unwrap_or_default()
    }

    /// Whether this project has a recorded trust decision on disk. Drives the
    /// open-time prompt: undecided projects are prompted, decided ones are not.
    pub fn is_decided(&self) -> bool {
        self.recorded_level().is_some()
    }

    /// The raw recorded level, or `None` if no valid decision is on disk. A
    /// corrupt file reads as `None` (treated as undecided; the next write
    /// rewrites it cleanly) rather than crashing. Private: callers want either
    /// a concrete [`Self::level`] or the [`Self::is_decided`] predicate.
    fn recorded_level(&self) -> Option<TrustLevel> {
        let text = std::fs::read_to_string(&self.path).ok()?;
        serde_json::from_str::<StoredTrust>(&text)
            .ok()
            .map(|s| s.level)
    }

    /// Record `level` for this project, written atomically (a pid-tagged temp
    /// file, then rename, so a half-written file is never observed and two
    /// processes don't clobber each other's temp).
    pub fn record(&self, level: TrustLevel) -> io::Result<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let json =
            serde_json::to_string_pretty(&StoredTrust { level }).map_err(io::Error::other)?;
        let tmp = self
            .path
            .with_extension(format!("json.{}.tmp", std::process::id()));
        std::fs::write(&tmp, json.as_bytes())?;
        std::fs::rename(&tmp, &self.path)?;
        Ok(())
    }
}

/// Whether a workspace contains content whose execution trust matters — i.e.
/// whether opening it should prompt for a trust decision. Detection is
/// **passive** (a shallow scan of the root for marker files/dirs); it never
/// runs anything.
///
/// This covers both env-manager files *and* project manifests, because a
/// recognized project is one whose language server will auto-start — and that
/// load runs project-controlled code (analyzers, build scripts, proc-macros),
/// which is gated on trust (see `LspManager`). So prompting for a recognized
/// project is what lets the user enable its tooling. A folder with none of
/// these is plain text/docs — nothing to gate, no prompt.
pub fn workspace_has_executable_content(root: &Path) -> bool {
    !executable_content_markers(root).is_empty()
}

/// The specific marker files/dirs in `root` that make it "executable content"
/// (see [`workspace_has_executable_content`]). Returned so the trust prompt can
/// tell the user *why* it appeared (e.g. ".envrc, .venv, App.sln"). Shallow,
/// passive scan — never runs anything. Order is roughly env-managers, then
/// repo-local toolchains, then devcontainer, then .NET project files.
pub fn executable_content_markers(root: &Path) -> Vec<String> {
    // Files that drive env activation or whose project loader runs code.
    const FILE_MARKERS: &[&str] = &[
        // env managers
        ".envrc",         // direnv
        "mise.toml",      // mise
        ".mise.toml",     // mise
        ".tool-versions", // mise / asdf
        "Pipfile",        // pipenv
        "poetry.lock",    // poetry
        // project manifests (their language servers run project code at load)
        "Cargo.toml",            // rust-analyzer: build scripts, proc-macros
        "go.mod",                // gopls
        "package.json",          // ts/eslint, npm scripts
        "pyproject.toml",        // python tooling
        "pom.xml",               // jdtls / maven
        "build.gradle",          // jdtls / gradle
        "build.gradle.kts",      // gradle (kotlin dsl)
        "CMakeLists.txt",        // clangd (compile_commands generation)
        "compile_commands.json", // clangd
        "Gemfile",               // ruby
        "composer.json",         // php
    ];
    // Directories that hold a repo-local interpreter/toolchain.
    const DIR_MARKERS: &[&str] = &[".venv", "venv"];

    let mut found = Vec::new();

    for m in FILE_MARKERS {
        if root.join(m).is_file() {
            found.push((*m).to_string());
        }
    }
    for m in DIR_MARKERS {
        if root.join(m).is_dir() {
            found.push((*m).to_string());
        }
    }
    // Dev container: reopening / building it runs code.
    if root
        .join(".devcontainer")
        .join("devcontainer.json")
        .is_file()
        || root.join(".devcontainer.json").is_file()
    {
        found.push("devcontainer.json".to_string());
    }
    // C# / .NET: loading a project runs restore/build and design-time
    // analyzers/source-generators, so a solution or project file at the root
    // is executable content. Report the actual file name(s).
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
                if matches!(ext, "sln" | "csproj" | "fsproj") {
                    if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
                        found.push(name.to_string());
                    }
                }
            }
        }
    }
    found
}

/// Map a trust decision for `command` (with the child's `cwd`) onto a spawn
/// result: `Ok(())` to proceed, or an `Err` carrying the deny reason. The
/// shared one-liner every spawner impl calls at the top of each spawn method,
/// so the Allow/Deny→error policy lives in exactly one place even though the
/// *check site* is per-backend.
pub fn gate(trust: &WorkspaceTrust, command: &str, cwd: Option<&str>) -> Result<(), SpawnError> {
    match trust.decide(command, cwd) {
        SpawnDecision::Allow => Ok(()),
        SpawnDecision::Deny(reason) => Err(SpawnError::Process(reason)),
    }
}

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

    fn trust(root: &str, level: TrustLevel) -> WorkspaceTrust {
        WorkspaceTrust::new(Some(PathBuf::from(root)), level)
    }

    #[test]
    fn trusted_allows_everything() {
        let t = trust("/home/u/proj", TrustLevel::Trusted);
        assert_eq!(
            t.decide("/home/u/proj/.venv/bin/python", None),
            SpawnDecision::Allow
        );
        assert_eq!(t.decide("rg", None), SpawnDecision::Allow);
    }

    #[test]
    fn blocked_denies_everything() {
        let t = trust("/home/u/proj", TrustLevel::Blocked);
        assert!(matches!(t.decide("rg", None), SpawnDecision::Deny(_)));
        assert!(matches!(
            t.decide("/usr/bin/git", None),
            SpawnDecision::Deny(_)
        ));
    }

    #[test]
    fn restricted_allows_bare_command_names() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        // System/user tools resolved via $PATH are fine.
        assert_eq!(t.decide("git", None), SpawnDecision::Allow);
        assert_eq!(t.decide("rg", Some("/home/u/proj")), SpawnDecision::Allow);
        assert_eq!(t.decide("python3", None), SpawnDecision::Allow);
    }

    #[test]
    fn restricted_blocks_absolute_path_inside_workspace() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        assert!(matches!(
            t.decide("/home/u/proj/.venv/bin/python", None),
            SpawnDecision::Deny(_)
        ));
    }

    #[test]
    fn restricted_allows_absolute_path_outside_workspace() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        assert_eq!(t.decide("/usr/bin/python3", None), SpawnDecision::Allow);
    }

    #[test]
    fn restricted_blocks_relative_path_resolving_into_workspace() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        // `./.venv/bin/python` from the project cwd.
        assert!(matches!(
            t.decide("./.venv/bin/python", Some("/home/u/proj")),
            SpawnDecision::Deny(_)
        ));
        // A nested cwd still resolves inside.
        assert!(matches!(
            t.decide("../.venv/bin/python", Some("/home/u/proj/src")),
            SpawnDecision::Deny(_)
        ));
    }

    #[test]
    fn restricted_allows_relative_path_escaping_workspace() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        // `../evil` from the project root lands outside the workspace.
        assert_eq!(
            t.decide("../evil", Some("/home/u/proj")),
            SpawnDecision::Allow
        );
    }

    #[test]
    fn restricted_does_not_confuse_sibling_prefix() {
        // `/home/u/proj-evil` must not count as inside `/home/u/proj`.
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        assert_eq!(
            t.decide("/home/u/proj-evil/bin/x", None),
            SpawnDecision::Allow
        );
    }

    #[test]
    fn restricted_without_root_allows() {
        let t = WorkspaceTrust::new(None, TrustLevel::Restricted);
        assert_eq!(t.decide("/anything/at/all", None), SpawnDecision::Allow);
    }

    #[test]
    fn set_level_takes_effect_immediately() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        let cmd = "/home/u/proj/.venv/bin/python";
        assert!(matches!(t.decide(cmd, None), SpawnDecision::Deny(_)));
        t.set_level(TrustLevel::Trusted);
        assert_eq!(t.decide(cmd, None), SpawnDecision::Allow);
        t.set_level(TrustLevel::Blocked);
        assert!(matches!(t.decide("rg", None), SpawnDecision::Deny(_)));
    }

    #[test]
    fn set_root_updates_containment() {
        let t = trust("/home/u/proj", TrustLevel::Restricted);
        let cmd = "/home/u/other/.venv/bin/python";
        assert_eq!(t.decide(cmd, None), SpawnDecision::Allow);
        t.set_root(Some(PathBuf::from("/home/u/other")));
        assert!(matches!(t.decide(cmd, None), SpawnDecision::Deny(_)));
    }

    #[test]
    fn level_round_trips_through_u8() {
        for lvl in [
            TrustLevel::Restricted,
            TrustLevel::Trusted,
            TrustLevel::Blocked,
        ] {
            assert_eq!(TrustLevel::from_u8(lvl.as_u8()), lvl);
        }
        // Unknown byte falls back to the safe default.
        assert_eq!(TrustLevel::from_u8(99), TrustLevel::Restricted);
    }

    #[test]
    fn lexical_normalize_resolves_dot_segments() {
        assert_eq!(
            lexical_normalize(Path::new("/a/b/../c/./d")),
            PathBuf::from("/a/c/d")
        );
    }

    #[test]
    fn store_round_trips_level_for_one_project() {
        let tmp = tempfile::tempdir().unwrap();
        let proj_dir = tmp.path().join("a/b/proj");
        let store = TrustStore::for_project_dir(&proj_dir);

        // Undecided reads as the safe default, not as a missing value.
        assert!(!store.is_decided());
        assert_eq!(store.level(), TrustLevel::default());
        store.record(TrustLevel::Trusted).unwrap();
        assert!(store.is_decided());
        assert_eq!(store.level(), TrustLevel::Trusted);
        // Overwrite wins.
        store.record(TrustLevel::Blocked).unwrap();
        assert_eq!(store.level(), TrustLevel::Blocked);
        // The file lives inside the project's own state directory.
        assert!(proj_dir.join("trust.json").exists());
    }

    #[test]
    fn separate_projects_use_separate_files() {
        let tmp = tempfile::tempdir().unwrap();
        let a = TrustStore::for_project_dir(&tmp.path().join("a"));
        let b = TrustStore::for_project_dir(&tmp.path().join("b"));
        a.record(TrustLevel::Trusted).unwrap();
        // b is untouched by a's write — no shared file.
        assert_eq!(a.level(), TrustLevel::Trusted);
        assert!(a.is_decided());
        assert!(!b.is_decided());
        assert_eq!(b.level(), TrustLevel::default());
    }

    #[test]
    fn set_level_persists_through_store() {
        let tmp = tempfile::tempdir().unwrap();
        let proj_dir = tmp.path().join("proj");
        let wt = WorkspaceTrust::new_persistent(
            Some(proj_dir.clone()),
            TrustLevel::Restricted,
            TrustStore::for_project_dir(&proj_dir),
        );
        wt.set_level(TrustLevel::Trusted);
        // A fresh store reading the project's file sees the decision.
        assert_eq!(
            TrustStore::for_project_dir(&proj_dir).level(),
            TrustLevel::Trusted
        );
    }

    #[test]
    fn set_store_adopts_new_projects_persisted_level() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a");
        let b = tmp.path().join("b");
        TrustStore::for_project_dir(&b)
            .record(TrustLevel::Blocked)
            .unwrap();

        let wt = WorkspaceTrust::new_persistent(
            Some(a.clone()),
            TrustLevel::Trusted,
            TrustStore::for_project_dir(&a),
        );
        assert_eq!(wt.level(), TrustLevel::Trusted);
        // Switching to project b adopts b's stored decision.
        wt.set_root(Some(b.clone()));
        wt.set_store(Some(TrustStore::for_project_dir(&b)));
        assert_eq!(wt.level(), TrustLevel::Blocked);
    }

    #[test]
    fn in_memory_set_level_does_not_require_store() {
        // The non-persistent constructor must never touch disk.
        let wt = WorkspaceTrust::new(Some(PathBuf::from("/home/u/proj")), TrustLevel::Restricted);
        wt.set_level(TrustLevel::Blocked);
        assert_eq!(wt.level(), TrustLevel::Blocked);
    }

    #[test]
    fn set_store_to_undecided_project_resets_to_default() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a");
        let b = tmp.path().join("b"); // never recorded
        TrustStore::for_project_dir(&a)
            .record(TrustLevel::Trusted)
            .unwrap();
        let wt = WorkspaceTrust::new_persistent(
            Some(a.clone()),
            TrustLevel::Trusted,
            TrustStore::for_project_dir(&a),
        );
        assert_eq!(wt.level(), TrustLevel::Trusted);
        // Switching to an undecided project must not inherit Trusted.
        wt.set_store(Some(TrustStore::for_project_dir(&b)));
        assert_eq!(wt.level(), TrustLevel::default());
        assert_eq!(TrustLevel::default(), TrustLevel::Restricted);
    }

    #[test]
    fn executable_content_detection() {
        let tmp = tempfile::tempdir().unwrap();
        let empty = tmp.path().join("empty");
        std::fs::create_dir_all(&empty).unwrap();
        assert!(!workspace_has_executable_content(&empty));

        let envrc = tmp.path().join("envrc");
        std::fs::create_dir_all(&envrc).unwrap();
        std::fs::write(envrc.join(".envrc"), "use flake\n").unwrap();
        assert!(workspace_has_executable_content(&envrc));

        let venv = tmp.path().join("venv");
        std::fs::create_dir_all(venv.join(".venv")).unwrap();
        assert!(workspace_has_executable_content(&venv));

        let dotnet = tmp.path().join("dotnet");
        std::fs::create_dir_all(&dotnet).unwrap();
        std::fs::write(dotnet.join("App.csproj"), "<Project/>\n").unwrap();
        assert!(workspace_has_executable_content(&dotnet));
    }

    #[test]
    fn executable_content_markers_lists_what_triggered() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join(".envrc"), "use flake\n").unwrap();
        std::fs::write(root.join("mise.toml"), "[tools]\n").unwrap();
        std::fs::create_dir_all(root.join(".venv")).unwrap();
        std::fs::create_dir_all(root.join(".devcontainer")).unwrap();
        std::fs::write(root.join(".devcontainer").join("devcontainer.json"), "{}\n").unwrap();
        std::fs::write(root.join("App.csproj"), "<Project/>\n").unwrap();

        let markers = executable_content_markers(root);
        for expected in [
            ".envrc",
            "mise.toml",
            ".venv",
            "devcontainer.json",
            "App.csproj",
        ] {
            assert!(
                markers.iter().any(|m| m == expected),
                "expected '{expected}' in {markers:?}"
            );
        }

        // A plain folder reports nothing.
        let empty = tmp.path().join("empty");
        std::fs::create_dir_all(&empty).unwrap();
        assert!(executable_content_markers(&empty).is_empty());
    }
}