pi_agent_rust 0.5.1

Native AI coding agent CLI - Rust port of Pi Agent
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Workspace trust: a trust-on-first-use gate for project-local configuration
//! that can execute code (GitHub #151).
//!
//! A repository can select Git/npm packages via `.pi/settings.json` (whose npm
//! lifecycle scripts run as the local user during install) and can auto-load
//! JavaScript from `.pi/extensions/` (which may call `pi.exec` during session
//! startup). Neither is model-generated content — it is deterministic
//! configuration execution controlled by whoever authored the repository.
//!
//! This module decides, before any of that resolution runs, whether the
//! current workspace is trusted:
//!
//! - The decision is keyed to the canonical workspace path **and** a content
//!   digest over the project-controlled surfaces (`.pi/settings.json`, every
//!   file under `.pi/extensions/`, and project-local MCP configuration). Any
//!   content change re-prompts.
//! - Interactive launches prompt once and persist the answer (trusted or
//!   untrusted) in `<global_dir>/workspace-trust.json`.
//! - Non-interactive launches (RPC, `--print`, piped stdin) fail closed:
//!   project-local configuration is skipped for that run with a warning, and
//!   nothing is persisted, so a later interactive launch still prompts.
//! - `--trust` (or `trustAllWorkspaces` in the *global* settings, or the
//!   `PI_WORKSPACE_TRUST` env var) covers automation.
//!
//! Explicit CLI resource paths (`-e/--extension`, `--skill`, …) are user
//! consent and are deliberately not gated here.

use crate::config::Config;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Read as _;
use std::path::{Path, PathBuf};

/// File name of the trust store inside the global configuration directory.
pub const TRUST_STORE_FILE: &str = "workspace-trust.json";

/// Environment override for automation: `trusted` (or `1`) forces trust for
/// this run, `untrusted` (or `0`) forces the fail-closed path. Neither value
/// is persisted.
pub const TRUST_ENV_VAR: &str = "PI_WORKSPACE_TRUST";

const TRUST_STORE_VERSION: u32 = 1;
const TRUST_SURFACE_DIGEST_DOMAIN: &[u8] = b"pi_agent_rust:workspace-trust-surface:v2";
const MAX_TRUST_CONFIG_BYTES: usize = 1024 * 1024;
const MAX_TRUST_EXTENSION_BYTES: usize = 16 * 1024 * 1024;

/// A recorded (or requested) trust decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrustDecision {
    Trusted,
    Untrusted,
}

/// What the workspace declares that could execute local code.
#[derive(Debug, Clone)]
pub struct WorkspaceTrustSurface {
    /// Escaped canonical workspace path suitable for an untrusted terminal
    /// prompt. The trust-store key retains the underlying canonical path.
    pub workspace_display: String,
    /// True when `.pi/settings.json` exists.
    pub has_project_settings: bool,
    /// Number of `packages` entries declared in `.pi/settings.json`.
    pub package_count: usize,
    /// Files under `.pi/extensions/`, relative to the workspace root, sorted.
    pub extension_entries: Vec<String>,
    /// Project-local MCP configuration files, relative to the workspace root,
    /// sorted. Explicit CLI and global MCP files are deliberate operator
    /// inputs and are not workspace trust surfaces.
    pub mcp_config_entries: Vec<String>,
    /// Hex sha256 over the canonical surface manifest.
    pub digest: String,
}

impl WorkspaceTrustSurface {
    /// Scan `cwd` for project-controlled executable surfaces.
    ///
    /// Returns `Ok(None)` when the workspace declares nothing to trust
    /// (no `.pi/settings.json`, no `.pi/extensions/` entries, and no
    /// project-local MCP configuration).
    pub fn scan(cwd: &Path) -> Result<Option<Self>> {
        const PROJECT_MCP_CONFIGS: &[&str] = &[
            ".agents/mcp.json",
            ".claude/mcp.json",
            ".codex/config.toml",
            ".cursor/mcp.json",
            ".gemini/settings.json",
            ".pi/mcp.json",
            ".windsurf/mcp.json",
        ];

        let project_dir = cwd.join(Config::project_dir());
        let settings_path = project_dir.join("settings.json");
        let extensions_dir = project_dir.join("extensions");

        let settings_bytes = read_bounded_regular_file(&settings_path, MAX_TRUST_CONFIG_BYTES)?;

        let mut extension_files = Vec::new();
        collect_files_recursive(&extensions_dir, &extensions_dir, &mut extension_files)?;
        extension_files.sort_by(|a, b| a.relative.cmp(&b.relative));

        let mut mcp_config_files = Vec::new();
        for relative in PROJECT_MCP_CONFIGS {
            let absolute = cwd.join(relative);
            if let Some(bytes) = read_bounded_regular_file(&absolute, MAX_TRUST_CONFIG_BYTES)? {
                mcp_config_files.push((PathBuf::from(*relative), bytes));
            }
        }

        if settings_bytes.is_none() && extension_files.is_empty() && mcp_config_files.is_empty() {
            return Ok(None);
        }

        let package_count = settings_bytes
            .as_deref()
            .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(bytes).ok())
            .and_then(|value| {
                value
                    .get("packages")
                    .and_then(|packages| packages.as_array().map(Vec::len))
            })
            .unwrap_or(0);

        // Versioned, domain-separated records use raw path bytes and explicit
        // lengths, so control characters or non-UTF-8 names cannot make two
        // different surface sets hash to the same manifest.
        let mut surface_hasher = Sha256::new();
        surface_hasher.update(TRUST_SURFACE_DIGEST_DOMAIN);
        if let Some(bytes) = &settings_bytes {
            hash_surface_record(
                &mut surface_hasher,
                b"settings",
                Path::new(".pi/settings.json"),
                bytes,
            );
        }
        let mut extension_entries = Vec::with_capacity(extension_files.len());
        for found in &extension_files {
            let bytes = read_bounded_regular_file(&found.absolute, MAX_TRUST_EXTENSION_BYTES)?
                .ok_or_else(|| {
                    Error::config(format!(
                        "Trust surface disappeared while scanning {}",
                        escaped_path(&found.absolute)
                    ))
                })?;
            let relative = Path::new(".pi/extensions").join(&found.relative);
            hash_surface_record(&mut surface_hasher, b"extension", &relative, &bytes);
            extension_entries.push(escaped_path(&relative));
        }
        let mut mcp_config_entries = Vec::with_capacity(mcp_config_files.len());
        for (relative, bytes) in mcp_config_files {
            hash_surface_record(&mut surface_hasher, b"mcp", &relative, &bytes);
            mcp_config_entries.push(escaped_path(&relative));
        }

        Ok(Some(Self {
            workspace_display: escaped_path(
                &std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()),
            ),
            has_project_settings: settings_bytes.is_some(),
            package_count,
            extension_entries,
            mcp_config_entries,
            digest: crate::package_manager::hex_encode(&surface_hasher.finalize()),
        }))
    }
}

fn read_bounded_regular_file(path: &Path, max_bytes: usize) -> Result<Option<Vec<u8>>> {
    let metadata = match std::fs::metadata(path) {
        Ok(metadata) => metadata,
        // A missing path and a regular file where a directory was expected
        // (`.codex` as a file makes `.codex/config.toml` ENOTDIR) both mean
        // the surface does not exist; neither is a reason to refuse startup.
        Err(err)
            if matches!(
                err.kind(),
                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
            ) =>
        {
            return Ok(None);
        }
        Err(err) => {
            return Err(Error::config(format!(
                "Failed to inspect {}: {err}",
                escaped_path(path)
            )));
        }
    };
    if !metadata.is_file() {
        return Err(Error::config(format!(
            "Trust surface is not a regular file: {}",
            escaped_path(path)
        )));
    }
    if metadata.len() > max_bytes as u64 {
        return Err(Error::config(format!(
            "Trust surface exceeds {max_bytes} bytes: {}",
            escaped_path(path)
        )));
    }

    let file = File::open(path)
        .map_err(|err| Error::config(format!("Failed to read {}: {err}", escaped_path(path))))?;
    // Capacity hint only: the value is clamped to `max_bytes`, and a wrapped
    // cast on a 32-bit target could at worst under-reserve.
    #[allow(clippy::cast_possible_truncation)]
    let mut bytes = Vec::with_capacity((metadata.len() as usize).min(max_bytes));
    file.take(max_bytes as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|err| Error::config(format!("Failed to read {}: {err}", escaped_path(path))))?;
    if bytes.len() > max_bytes {
        return Err(Error::config(format!(
            "Trust surface exceeds {max_bytes} bytes: {}",
            escaped_path(path)
        )));
    }
    Ok(Some(bytes))
}

fn hash_surface_record(hasher: &mut Sha256, kind: &[u8], path: &Path, bytes: &[u8]) {
    hash_length_prefixed(hasher, kind);
    hash_length_prefixed(hasher, path.as_os_str().as_encoded_bytes());
    hash_length_prefixed(hasher, bytes);
}

fn hash_length_prefixed(hasher: &mut Sha256, bytes: &[u8]) {
    hasher.update((bytes.len() as u64).to_be_bytes());
    hasher.update(bytes);
}

fn escaped_path(path: &Path) -> String {
    path.as_os_str()
        .to_string_lossy()
        .chars()
        .flat_map(char::escape_default)
        .collect()
}

/// A surface file discovered under `.pi/extensions/`: the absolute path comes
/// straight from directory traversal (never re-derived by joining), and the
/// relative path is only used for display and manifest keys.
struct FoundSurfaceFile {
    relative: PathBuf,
    absolute: PathBuf,
}

fn collect_files_recursive(root: &Path, dir: &Path, out: &mut Vec<FoundSurfaceFile>) -> Result<()> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(err) => {
            return Err(Error::config(format!(
                "Failed to scan {}: {err}",
                dir.display()
            )));
        }
    };
    for entry in entries {
        let entry = entry
            .map_err(|err| Error::config(format!("Failed to scan {}: {err}", dir.display())))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|err| Error::config(format!("Failed to inspect {}: {err}", path.display())))?;
        if file_type.is_dir() {
            collect_files_recursive(root, &path, out)?;
        } else if file_type.is_file() || file_type.is_symlink() {
            // Symlinked entries hash their target content via fs::read later;
            // a broken symlink surfaces as a read error, which fails closed.
            if let Ok(relative) = path.strip_prefix(root) {
                let relative = relative.to_path_buf();
                out.push(FoundSurfaceFile {
                    relative,
                    absolute: path,
                });
            }
        }
    }
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TrustRecord {
    digest: String,
    decision: TrustDecision,
    #[serde(default)]
    updated_at: String,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct TrustStoreFile {
    #[serde(default)]
    version: u32,
    #[serde(default)]
    workspaces: BTreeMap<String, TrustRecord>,
}

/// Persistent map of workspace path -> (surface digest, decision).
#[derive(Debug)]
pub struct WorkspaceTrustStore {
    path: PathBuf,
    data: TrustStoreFile,
}

impl WorkspaceTrustStore {
    /// Default store location inside the global configuration directory.
    #[must_use]
    pub fn default_path() -> PathBuf {
        Config::global_dir().join(TRUST_STORE_FILE)
    }

    /// Load the store, tolerating a missing or corrupt file (corrupt files
    /// are treated as empty so a damaged store can never grant trust).
    #[must_use]
    pub fn load(path: &Path) -> Self {
        let data = std::fs::read(path)
            .ok()
            .and_then(|bytes| serde_json::from_slice::<TrustStoreFile>(&bytes).ok())
            .unwrap_or_default();
        Self {
            path: path.to_path_buf(),
            data,
        }
    }

    /// The stored decision for `workspace`, if its digest still matches.
    #[must_use]
    pub fn decision(&self, workspace: &str, digest: &str) -> Option<TrustDecision> {
        self.data
            .workspaces
            .get(workspace)
            .filter(|record| record.digest == digest)
            .map(|record| record.decision)
    }

    /// Record a decision for `workspace` at `digest` and save the store.
    pub fn record(&mut self, workspace: &str, digest: &str, decision: TrustDecision) -> Result<()> {
        self.data.version = TRUST_STORE_VERSION;
        self.data.workspaces.insert(
            workspace.to_string(),
            TrustRecord {
                digest: digest.to_string(),
                decision,
                updated_at: chrono::Utc::now().to_rfc3339(),
            },
        );
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(|err| {
                Error::config(format!("Failed to create {}: {err}", parent.display()))
            })?;
        }
        let json = serde_json::to_string_pretty(&self.data)
            .map_err(|err| Error::config(format!("Failed to encode trust store: {err}")))?;
        std::fs::write(&self.path, json).map_err(|err| {
            Error::config(format!("Failed to write {}: {err}", self.path.display()))
        })?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));
        }
        Ok(())
    }
}

/// How the effective trust decision was reached (for logs and warnings).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrustSource {
    /// The workspace declares nothing that could execute code.
    NoSurface,
    /// `--trust` on the command line (persisted).
    CliFlag,
    /// `trustAllWorkspaces` in the global settings (not persisted).
    TrustAllConfig,
    /// `PI_WORKSPACE_TRUST` environment override (not persisted).
    EnvOverride,
    /// A stored decision whose digest still matches.
    Store,
    /// The interactive first-use prompt (persisted).
    Prompt,
    /// Non-interactive launch with no stored decision: fail closed.
    NonInteractive,
}

/// The effective trust state for this launch.
#[derive(Debug)]
pub struct WorkspaceTrustState {
    pub trusted: bool,
    pub source: TrustSource,
    pub surface: Option<WorkspaceTrustSurface>,
}

/// Inputs to [`establish`] that the caller resolves from CLI/config/env.
#[derive(Debug, Clone)]
pub struct TrustInputs {
    /// `--trust` was passed on the command line.
    pub cli_trust: bool,
    /// `trustAllWorkspaces` from the *global* settings file.
    pub trust_all_workspaces: bool,
    /// Value of [`TRUST_ENV_VAR`], if set.
    pub env_override: Option<String>,
    /// Whether an interactive first-use prompt may be shown.
    pub interactive: bool,
}

#[cfg(unix)]
fn encoded_workspace_key(canonical: &Path) -> String {
    // The tag is part of the persistence contract. Changing it deliberately
    // invalidates older decisions and causes a safe re-prompt instead of
    // interpreting path bytes with a different platform/toolchain encoding.
    use std::os::unix::ffi::OsStrExt as _;

    format!(
        "path-v3:unix:{}",
        crate::package_manager::hex_encode(canonical.as_os_str().as_bytes())
    )
}

#[cfg(windows)]
fn encoded_workspace_key(canonical: &Path) -> String {
    use std::os::windows::ffi::OsStrExt as _;

    let bytes = canonical
        .as_os_str()
        .encode_wide()
        .flat_map(u16::to_le_bytes)
        .collect::<Vec<_>>();
    format!(
        "path-v3:windows-utf16le:{}",
        crate::package_manager::hex_encode(&bytes)
    )
}

#[cfg(not(any(unix, windows)))]
fn encoded_workspace_key(canonical: &Path) -> String {
    format!(
        "path-v3:platform-encoded:{}",
        crate::package_manager::hex_encode(canonical.as_os_str().as_encoded_bytes())
    )
}

/// Canonical store key for a workspace path.
#[must_use]
pub fn workspace_key(cwd: &Path) -> String {
    let canonical = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
    encoded_workspace_key(&canonical)
}

/// Decide whether the workspace at `cwd` is trusted, prompting via `prompt`
/// when allowed and necessary. `prompt` returns `Ok(true)` to trust.
pub fn establish(
    cwd: &Path,
    store_path: &Path,
    inputs: &TrustInputs,
    prompt: impl FnOnce(&WorkspaceTrustSurface) -> Result<bool>,
) -> Result<WorkspaceTrustState> {
    let Some(surface) = WorkspaceTrustSurface::scan(cwd)? else {
        return Ok(WorkspaceTrustState {
            trusted: true,
            source: TrustSource::NoSurface,
            surface: None,
        });
    };

    let key = workspace_key(cwd);
    let mut store = WorkspaceTrustStore::load(store_path);

    if let Some(value) = inputs.env_override.as_deref() {
        let trusted = match value.trim().to_ascii_lowercase().as_str() {
            "1" | "true" | "trusted" => true,
            "0" | "false" | "untrusted" => false,
            other => {
                return Err(Error::config(format!(
                    "Invalid {TRUST_ENV_VAR} value '{other}': expected trusted or untrusted"
                )));
            }
        };
        return Ok(WorkspaceTrustState {
            trusted,
            source: TrustSource::EnvOverride,
            surface: Some(surface),
        });
    }

    if inputs.cli_trust {
        store.record(&key, &surface.digest, TrustDecision::Trusted)?;
        return Ok(WorkspaceTrustState {
            trusted: true,
            source: TrustSource::CliFlag,
            surface: Some(surface),
        });
    }

    if inputs.trust_all_workspaces {
        return Ok(WorkspaceTrustState {
            trusted: true,
            source: TrustSource::TrustAllConfig,
            surface: Some(surface),
        });
    }

    match store.decision(&key, &surface.digest) {
        Some(TrustDecision::Trusted) => Ok(WorkspaceTrustState {
            trusted: true,
            source: TrustSource::Store,
            surface: Some(surface),
        }),
        Some(TrustDecision::Untrusted) => Ok(WorkspaceTrustState {
            trusted: false,
            source: TrustSource::Store,
            surface: Some(surface),
        }),
        None if inputs.interactive => {
            let granted = prompt(&surface)?;
            let decision = if granted {
                TrustDecision::Trusted
            } else {
                TrustDecision::Untrusted
            };
            store.record(&key, &surface.digest, decision)?;
            Ok(WorkspaceTrustState {
                trusted: granted,
                source: TrustSource::Prompt,
                surface: Some(surface),
            })
        }
        None => Ok(WorkspaceTrustState {
            trusted: false,
            source: TrustSource::NonInteractive,
            surface: Some(surface),
        }),
    }
}

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

    fn write(path: &Path, content: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("create parent");
        }
        std::fs::write(path, content).expect("write fixture");
    }

    fn no_prompt(_: &WorkspaceTrustSurface) -> Result<bool> {
        // Surfaces as an `establish` Err, failing the test's expect().
        Err(Error::config("prompt must not run in this scenario"))
    }

    fn inputs() -> TrustInputs {
        TrustInputs {
            cli_trust: false,
            trust_all_workspaces: false,
            env_override: None,
            interactive: false,
        }
    }

    #[test]
    fn scan_treats_a_file_where_a_surface_directory_is_expected_as_absent() {
        // A stray regular file named `.codex` (this repository carried one)
        // used to abort startup with "Failed to inspect .codex/config.toml:
        // Not a directory"; a file cannot contain a trust surface.
        let dir = tempfile::tempdir().expect("tempdir"); // ubs:ignore test fixture
        std::fs::write(dir.path().join(".codex"), b"").expect("write .codex file"); // ubs:ignore test fixture
        assert!(
            WorkspaceTrustSurface::scan(dir.path())
                .expect("scan") // ubs:ignore test assertion
                .is_none()
        );
    }

    #[test]
    fn scan_returns_none_without_project_surfaces() {
        let dir = tempfile::tempdir().expect("tempdir");
        assert!(
            WorkspaceTrustSurface::scan(dir.path())
                .expect("scan")
                .is_none()
        );
        // An unrelated .pi file (e.g. session artifacts) still yields None.
        write(&dir.path().join(".pi/notes.txt"), "not a surface");
        assert!(
            WorkspaceTrustSurface::scan(dir.path())
                .expect("scan")
                .is_none()
        );
    }

    #[test]
    fn scan_digest_is_stable_and_tracks_content() {
        let dir = tempfile::tempdir().expect("tempdir");
        write(
            &dir.path().join(".pi/settings.json"),
            r#"{"packages":["npm:left-pad"],"theme":"dark"}"#,
        );
        write(&dir.path().join(".pi/extensions/hook.js"), "export {}\n");
        write(
            &dir.path().join(".pi/extensions/nested/util.ts"),
            "export const x = 1\n",
        );

        let first = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        let second = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_eq!(first.digest, second.digest, "digest must be deterministic");
        assert!(first.has_project_settings);
        assert_eq!(first.package_count, 1);
        assert_eq!(
            first.extension_entries,
            vec![
                ".pi/extensions/hook.js".to_string(),
                ".pi/extensions/nested/util.ts".to_string(),
            ]
        );
        assert!(first.mcp_config_entries.is_empty());

        // Settings edit changes the digest.
        write(
            &dir.path().join(".pi/settings.json"),
            r#"{"packages":["npm:left-pad","npm:evil"],"theme":"dark"}"#,
        );
        let settings_changed = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_ne!(first.digest, settings_changed.digest);
        assert_eq!(settings_changed.package_count, 2);

        // Extension content edit changes the digest.
        write(
            &dir.path().join(".pi/extensions/hook.js"),
            "export const changed = true\n",
        );
        let extension_changed = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_ne!(settings_changed.digest, extension_changed.digest);

        // A new extension file changes the digest.
        write(&dir.path().join(".pi/extensions/new.js"), "export {}\n");
        let extension_added = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_ne!(extension_changed.digest, extension_added.digest);
    }

    #[test]
    fn scan_tracks_project_mcp_configuration_as_executable_surface() {
        let dir = tempfile::tempdir().expect("tempdir");
        let project_mcp = dir.path().join(".pi/mcp.json");
        write(
            &project_mcp,
            r#"{"mcpServers":{"local":{"command":"first"}}}"#,
        );

        let first = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("MCP-only workspace must have a trust surface");
        assert!(!first.has_project_settings);
        assert!(first.extension_entries.is_empty());
        assert_eq!(first.mcp_config_entries, vec![".pi/mcp.json"]);

        write(
            &project_mcp,
            r#"{"mcpServers":{"local":{"command":"second"}}}"#,
        );
        let changed = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_ne!(
            first.digest, changed.digest,
            "changing an MCP execution target must invalidate workspace trust"
        );

        write(
            &dir.path().join(".codex/config.toml"),
            "[mcp_servers.foreign]\ncommand = \"foreign\"\n",
        );
        let foreign_added = WorkspaceTrustSurface::scan(dir.path())
            .expect("scan")
            .expect("surface");
        assert_eq!(
            foreign_added.mcp_config_entries,
            vec![".codex/config.toml", ".pi/mcp.json"]
        );
        assert_ne!(changed.digest, foreign_added.digest);
    }

    #[test]
    fn scan_rejects_non_regular_and_oversized_trust_surfaces() {
        let non_regular = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(non_regular.path().join(".pi/mcp.json"))
            .expect("create non-regular MCP surface");
        let err = WorkspaceTrustSurface::scan(non_regular.path())
            .expect_err("directories must not be read as trust surfaces");
        assert!(err.to_string().contains("not a regular file"));

        let oversized = tempfile::tempdir().expect("tempdir");
        write(
            &oversized.path().join(".pi/mcp.json"),
            &"x".repeat(MAX_TRUST_CONFIG_BYTES + 1),
        );
        let err = WorkspaceTrustSurface::scan(oversized.path())
            .expect_err("oversized configs must fail before allocation grows unbounded");
        assert!(err.to_string().contains("exceeds 1048576 bytes"));
    }

    #[cfg(unix)]
    #[test]
    fn scan_rejects_device_symlinks_and_escapes_untrusted_names() {
        use std::os::unix::fs::symlink;

        let device = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(device.path().join(".pi")).expect("create project dir");
        symlink("/dev/zero", device.path().join(".pi/mcp.json")).expect("create device symlink");
        let err = WorkspaceTrustSurface::scan(device.path())
            .expect_err("device symlinks must be rejected before opening");
        assert!(err.to_string().contains("not a regular file"));

        let controls = tempfile::tempdir().expect("tempdir");
        write(
            &controls.path().join(".pi/extensions/evil\n\u{1b}[2J.js"),
            "export {}\n",
        );
        let surface = WorkspaceTrustSurface::scan(controls.path())
            .expect("scan")
            .expect("surface");
        let displayed = surface.extension_entries.join(" ");
        assert!(!displayed.contains('\n'));
        assert!(!displayed.contains('\u{1b}'));
        assert!(displayed.contains("\\n"));
        assert!(displayed.contains("\\u{1b}"));
    }

    #[test]
    fn store_roundtrip_and_digest_mismatch() {
        let dir = tempfile::tempdir().expect("tempdir");
        let store_path = dir.path().join("workspace-trust.json");

        let mut store = WorkspaceTrustStore::load(&store_path);
        assert!(store.decision("/ws", "d1").is_none());
        store
            .record("/ws", "d1", TrustDecision::Trusted)
            .expect("record");

        let reloaded = WorkspaceTrustStore::load(&store_path);
        assert_eq!(reloaded.decision("/ws", "d1"), Some(TrustDecision::Trusted));
        assert_eq!(
            reloaded.decision("/ws", "d2"),
            None,
            "a digest change must invalidate the stored decision"
        );
        assert_eq!(reloaded.decision("/other", "d1"), None);
    }

    #[cfg(unix)]
    #[test]
    fn workspace_keys_preserve_non_utf8_canonical_path_identity() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt as _;

        let dir = tempfile::tempdir().expect("tempdir");
        let first = dir
            .path()
            .join(OsString::from_vec(vec![b'w', b's', b'-', 0x80]));
        let second = dir
            .path()
            .join(OsString::from_vec(vec![b'w', b's', b'-', 0x81]));
        std::fs::create_dir_all(&first).expect("create first workspace");
        std::fs::create_dir_all(&second).expect("create second workspace");

        let first_key = workspace_key(&first);
        let second_key = workspace_key(&second);
        assert_ne!(
            first_key, second_key,
            "distinct raw canonical paths must never share trust decisions"
        );
        assert!(first_key.starts_with("path-v3:unix:"));
        assert!(first_key.is_ascii(), "store keys must remain JSON-safe");
    }

    #[cfg(windows)]
    #[test]
    fn workspace_keys_use_tagged_utf16le_path_encoding() {
        use std::os::windows::ffi::OsStrExt as _;

        let dir = tempfile::tempdir().expect("tempdir");
        let canonical = std::fs::canonicalize(dir.path()).expect("canonical workspace");
        let expected_bytes = canonical
            .as_os_str()
            .encode_wide()
            .flat_map(u16::to_le_bytes)
            .collect::<Vec<_>>();
        assert_eq!(
            workspace_key(dir.path()),
            format!(
                "path-v3:windows-utf16le:{}",
                crate::package_manager::hex_encode(&expected_bytes)
            )
        );
    }

    #[test]
    fn corrupt_store_is_treated_as_empty() {
        let dir = tempfile::tempdir().expect("tempdir");
        let store_path = dir.path().join("workspace-trust.json");
        write(&store_path, "{not json");
        let store = WorkspaceTrustStore::load(&store_path);
        assert!(store.decision("/ws", "d1").is_none());
    }

    fn seeded_workspace() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        write(
            &dir.path().join(".pi/settings.json"),
            r#"{"packages":["npm:left-pad"]}"#,
        );
        write(&dir.path().join(".pi/extensions/hook.js"), "export {}\n");
        dir
    }

    #[test]
    fn establish_trivially_trusts_workspaces_without_surfaces() {
        let dir = tempfile::tempdir().expect("tempdir");
        let store_path = dir.path().join("store.json");
        let state = establish(dir.path(), &store_path, &inputs(), no_prompt).expect("establish");
        assert!(state.trusted);
        assert_eq!(state.source, TrustSource::NoSurface);
        assert!(!store_path.exists(), "no-surface runs must not persist");
    }

    #[test]
    fn establish_non_interactive_mcp_only_workspace_fails_closed() {
        let dir = tempfile::tempdir().expect("tempdir");
        write(
            &dir.path().join(".agents/mcp.json"),
            r#"{"mcpServers":{"project":{"command":"project-server"}}}"#,
        );
        let store_path = dir.path().join("store.json");

        let state = establish(dir.path(), &store_path, &inputs(), no_prompt).expect("establish");
        assert!(!state.trusted);
        assert_eq!(state.source, TrustSource::NonInteractive);
        assert_eq!(
            state.surface.as_ref().expect("surface").mcp_config_entries,
            vec![".agents/mcp.json"]
        );
        assert!(!store_path.exists());
    }

    #[test]
    fn establish_cli_flag_trusts_and_persists() {
        let dir = seeded_workspace();
        let store_path = dir.path().join("store.json");
        let state = establish(
            dir.path(),
            &store_path,
            &TrustInputs {
                cli_trust: true,
                ..inputs()
            },
            no_prompt,
        )
        .expect("establish");
        assert!(state.trusted);
        assert_eq!(state.source, TrustSource::CliFlag);

        // A later plain run reuses the stored decision.
        let followup = establish(dir.path(), &store_path, &inputs(), no_prompt).expect("establish");
        assert!(followup.trusted);
        assert_eq!(followup.source, TrustSource::Store);
    }

    #[test]
    fn establish_trust_all_config_trusts_without_persisting() {
        let dir = seeded_workspace();
        let store_path = dir.path().join("store.json");
        let state = establish(
            dir.path(),
            &store_path,
            &TrustInputs {
                trust_all_workspaces: true,
                ..inputs()
            },
            no_prompt,
        )
        .expect("establish");
        assert!(state.trusted);
        assert_eq!(state.source, TrustSource::TrustAllConfig);
        assert!(!store_path.exists());
    }

    #[test]
    fn establish_env_override_wins_without_persisting() {
        let dir = seeded_workspace();
        let store_path = dir.path().join("store.json");
        for (value, expected) in [("trusted", true), ("0", false)] {
            let state = establish(
                dir.path(),
                &store_path,
                &TrustInputs {
                    env_override: Some(value.to_string()),
                    // Env must win even over --trust.
                    cli_trust: true,
                    ..inputs()
                },
                no_prompt,
            )
            .expect("establish");
            assert_eq!(state.trusted, expected, "env value {value}");
            assert_eq!(state.source, TrustSource::EnvOverride);
        }
        assert!(!store_path.exists());

        let err = establish(
            dir.path(),
            &store_path,
            &TrustInputs {
                env_override: Some("maybe".to_string()),
                ..inputs()
            },
            no_prompt,
        )
        .expect_err("invalid env value must fail");
        assert!(err.to_string().contains(TRUST_ENV_VAR));
    }

    #[test]
    fn establish_prompt_answers_persist_both_ways() {
        for (answer, expected) in [(true, true), (false, false)] {
            let dir = seeded_workspace();
            let store_path = dir.path().join("store.json");
            let state = establish(
                dir.path(),
                &store_path,
                &TrustInputs {
                    interactive: true,
                    ..inputs()
                },
                |_| Ok(answer),
            )
            .expect("establish");
            assert_eq!(state.trusted, expected);
            assert_eq!(state.source, TrustSource::Prompt);

            // The decision is remembered; the prompt must not run again.
            let followup =
                establish(dir.path(), &store_path, &inputs(), no_prompt).expect("establish");
            assert_eq!(followup.trusted, expected);
            assert_eq!(followup.source, TrustSource::Store);
        }
    }

    #[test]
    fn establish_reprompts_after_content_change() {
        let dir = seeded_workspace();
        let store_path = dir.path().join("store.json");
        establish(
            dir.path(),
            &store_path,
            &TrustInputs {
                interactive: true,
                ..inputs()
            },
            |_| Ok(true),
        )
        .expect("establish");

        write(
            &dir.path().join(".pi/extensions/hook.js"),
            "export const changed = 1\n",
        );
        let state = establish(
            dir.path(),
            &store_path,
            &TrustInputs {
                interactive: true,
                ..inputs()
            },
            |_| Ok(false),
        )
        .expect("establish");
        assert!(!state.trusted, "digest change must invalidate stored trust");
        assert_eq!(state.source, TrustSource::Prompt);
    }

    #[test]
    fn establish_non_interactive_fails_closed_without_persisting() {
        let dir = seeded_workspace();
        let store_path = dir.path().join("store.json");
        let state = establish(dir.path(), &store_path, &inputs(), no_prompt).expect("establish");
        assert!(!state.trusted);
        assert_eq!(state.source, TrustSource::NonInteractive);
        assert!(
            !store_path.exists(),
            "non-interactive denial must stay ephemeral so a later interactive run prompts"
        );
    }
}