farhand-core 0.2.10

FarHand core: config, secret guard, local allowlist, SSH/SFTP remote, transfers and audit log
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
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
1008
1009
1010
//! Configuration: where the remote is, what the local side may touch, and the
//! limits every operation runs under.
//!
//! Resolution order (first hit wins):
//! 1. an explicit path (`--config`),
//! 2. `$FARHAND_CONFIG`,
//! 3. `.farhand.toml` in the working directory,
//! 4. `~/.config/farhand/config.toml`.
//!
//! Whether FarHand is *active* in a directory — takes the agent's local
//! tools away and puts its remote ones in — depends on where the config
//! came from: a project file, an explicit path or the environment always
//! activate; the global file activates only when its `activation` is
//! `"always"` rather than the default `"project"`.
//!
//! A project file (any file named `.farhand.toml`, however it was found)
//! can arrive with a cloned repository, so it may only tighten what the
//! global config allows: it cannot loosen `[approval]`, allow local
//! folders outside its own directory, or move the audit log. Such settings
//! are ignored and reported in [`Loaded::notices`].

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// When the global config alone should make a session remote.
    #[serde(default)]
    pub activation: ActivationMode,
    pub remote: RemoteConfig,
    #[serde(default)]
    pub local: LocalConfig,
    #[serde(default)]
    pub limits: Limits,
    #[serde(default)]
    pub audit: AuditConfig,
    #[serde(default)]
    pub guard: GuardConfig,
    #[serde(default)]
    pub approval: ApprovalConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RemoteConfig {
    /// SSH destination: an alias from `~/.ssh/config`, or `user@host`.
    /// Authentication, jump hosts, ports and keys all come from the user's
    /// own OpenSSH configuration; FarHand never handles credentials itself.
    pub host: String,
    /// Directory relative paths resolve against and commands start in.
    /// Absolute (`/srv/app`, `C:\\work`), or `~` / `~/...` for the remote
    /// user's home.
    pub workdir: String,
    /// What the remote runs. Detected on connect from the SFTP root, so
    /// `auto` is fine; set it explicitly so the model is told before the
    /// first command which shell it is writing for.
    #[serde(default)]
    pub os: Os,
    /// Shell that runs every command, as argv. On a POSIX remote the
    /// command text is appended as one final argument, so the last element
    /// must accept a script (`-c`, `-lc`, ...). On Windows only the first
    /// element is used, as the PowerShell executable (`powershell.exe` by
    /// default; set `["pwsh"]` for PowerShell 7).
    #[serde(default = "default_shell")]
    pub shell: Vec<String>,
    #[serde(default = "default_connect_timeout")]
    pub connect_timeout_secs: u64,
    /// Passed to ssh as `ServerAliveInterval`; keeps NAT tables warm.
    #[serde(default = "default_alive_interval")]
    pub server_alive_interval_secs: u64,
}

pub fn default_shell() -> Vec<String> {
    vec!["bash".into(), "-lc".into()]
}

/// The remote operating system family.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Os {
    #[default]
    Auto,
    /// Linux, macOS, BSD: a POSIX shell, `timeout(1)`, `base64(1)`.
    Posix,
    /// Windows with OpenSSH Server: commands run in PowerShell.
    Windows,
}
fn default_connect_timeout() -> u64 {
    20
}
fn default_alive_interval() -> u64 {
    30
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LocalConfig {
    /// The only local directories the model may list, read, upload from or
    /// download into. Empty means the local filesystem is fully closed.
    #[serde(default)]
    pub allowed_dirs: Vec<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    #[serde(default = "default_command_timeout")]
    pub command_timeout_secs: u64,
    #[serde(default = "default_max_command_timeout")]
    pub max_command_timeout_secs: u64,
    #[serde(default = "default_max_output_bytes")]
    pub max_output_bytes: usize,
    #[serde(default = "default_max_read_bytes")]
    pub max_read_bytes: usize,
    #[serde(default = "default_max_transfer_bytes")]
    pub max_transfer_bytes: u64,
    #[serde(default = "default_max_transfer_files")]
    pub max_transfer_files: usize,
}

fn default_command_timeout() -> u64 {
    120
}
fn default_max_command_timeout() -> u64 {
    1800
}
fn default_max_output_bytes() -> usize {
    100 * 1024
}
fn default_max_read_bytes() -> usize {
    512 * 1024
}
fn default_max_transfer_bytes() -> u64 {
    1024 * 1024 * 1024
}
fn default_max_transfer_files() -> usize {
    5000
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            command_timeout_secs: default_command_timeout(),
            max_command_timeout_secs: default_max_command_timeout(),
            max_output_bytes: default_max_output_bytes(),
            max_read_bytes: default_max_read_bytes(),
            max_transfer_bytes: default_max_transfer_bytes(),
            max_transfer_files: default_max_transfer_files(),
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuditConfig {
    /// Directory for the JSONL audit log. Defaults to
    /// `~/.local/share/farhand/audit`. There is deliberately no way to turn
    /// the log off: every remote action is recorded.
    pub log_dir: Option<PathBuf>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GuardConfig {
    /// Extra glob patterns (matched against the full local path and the
    /// basename) that may never be uploaded. Added to the built-in list.
    #[serde(default)]
    pub deny_globs: Vec<String>,
    /// Extra regular expressions that mark content as secret.
    #[serde(default)]
    pub deny_content: Vec<String>,
}

/// Whether the global config turns every session remote, or only the
/// projects that carry their own `.farhand.toml`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ActivationMode {
    /// Every session is remote.
    Always,
    /// Only directories with a `.farhand.toml` are remote; everywhere else
    /// the agent keeps its local tools and FarHand offers none. The
    /// default: installing FarHand must not take a machine's local tools
    /// away by surprise.
    #[default]
    Project,
}

/// Where a loaded config came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    Explicit,
    Env,
    Project,
    Global,
}

/// A config together with where it was found and whether it activates
/// FarHand in the directory it was resolved for.
#[derive(Debug, Clone)]
pub struct Loaded {
    pub config: Config,
    pub path: PathBuf,
    pub source: Source,
    /// Settings a project file tried and was not allowed to make, in words
    /// for the user. Empty for every other source.
    pub notices: Vec<String>,
}

impl Loaded {
    pub fn active(&self) -> bool {
        match self.source {
            Source::Explicit | Source::Env | Source::Project => true,
            Source::Global => self.config.activation == ActivationMode::Always,
        }
    }
}

/// Whether an agent should stop and ask the user before a mutating tool
/// runs. FarHand itself has no UI; this is the one knob every agent entry
/// translates into that agent's own permission system.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ApprovalMode {
    /// Prompt before every mutating tool; read-only tools run freely.
    /// The default.
    Ask,
    /// Run everything without prompting; the audit log is the only record.
    Auto,
    /// Prompt before every tool, read-only ones included.
    Strict,
}

impl ApprovalMode {
    pub fn as_str(self) -> &'static str {
        match self {
            ApprovalMode::Ask => "ask",
            ApprovalMode::Auto => "auto",
            ApprovalMode::Strict => "strict",
        }
    }
}

/// The tools that change something on the remote or in the outbox.
pub const MUTATING_TOOLS: &[&str] = &[
    "remote_shell",
    "remote_write",
    "remote_edit",
    "upload",
    "download",
];

/// The tools that only look.
pub const READ_ONLY_TOOLS: &[&str] = &[
    "remote_read",
    "remote_ls",
    "remote_glob",
    "remote_grep",
    "local_ls",
    "local_read",
    "remote_info",
];

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApprovalConfig {
    /// Default for every mutating tool.
    #[serde(default = "default_approval")]
    pub mode: ApprovalMode,
    /// Per-tool overrides, keyed by tool name; `ask` or `auto` only.
    #[serde(default)]
    pub tools: BTreeMap<String, ApprovalMode>,
}

fn default_approval() -> ApprovalMode {
    ApprovalMode::Ask
}

impl Default for ApprovalConfig {
    fn default() -> Self {
        Self {
            mode: default_approval(),
            tools: BTreeMap::new(),
        }
    }
}

impl ApprovalConfig {
    /// For every tool, whether it prompts (`Ask`) or runs (`Auto`),
    /// overrides applied. `Strict` never appears in the result.
    pub fn effective(&self) -> BTreeMap<&'static str, ApprovalMode> {
        let mutating = match self.mode {
            ApprovalMode::Auto => ApprovalMode::Auto,
            ApprovalMode::Ask | ApprovalMode::Strict => ApprovalMode::Ask,
        };
        let read_only = match self.mode {
            ApprovalMode::Strict => ApprovalMode::Ask,
            ApprovalMode::Ask | ApprovalMode::Auto => ApprovalMode::Auto,
        };
        MUTATING_TOOLS
            .iter()
            .map(|t| (*t, mutating))
            .chain(READ_ONLY_TOOLS.iter().map(|t| (*t, read_only)))
            .map(|(t, m)| (t, self.tools.get(t).copied().unwrap_or(m)))
            .collect()
    }
}

impl Config {
    pub fn example() -> &'static str {
        EXAMPLE
    }

    /// Load following the resolution order in the module docs, with the
    /// project file looked for in the process's working directory.
    pub fn load(explicit: Option<&Path>) -> Result<(Self, PathBuf)> {
        let l = Self::load_in(None, explicit)?;
        Ok((l.config, l.path))
    }

    /// Load following the resolution order, with the project file looked
    /// for in `cwd` (default: the process's working directory).
    pub fn load_in(cwd: Option<&Path>, explicit: Option<&Path>) -> Result<Loaded> {
        let (path, source) = match explicit {
            // An agent entry may hand the project file over by path; it is
            // still a project file and gets no more trust for that.
            Some(p) if p.file_name() == Some(".farhand.toml".as_ref()) => {
                (p.to_path_buf(), Source::Project)
            }
            Some(p) => (p.to_path_buf(), Source::Explicit),
            None => Self::locate(cwd)?,
        };
        let text = std::fs::read_to_string(&path)
            .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?;
        // Relative `allowed_dirs` entries are resolved against the file's own
        // directory, but only for a per-project file: the global config
        // belongs to no directory, so `"."` would mean nothing there.
        let base = match source {
            Source::Global => None,
            _ => path.parent().map(Path::to_path_buf),
        };
        let (config, notices) = if source == Source::Project {
            let global = Self::global_path();
            let mut notices = Vec::new();
            // The global config is the floor a project file is measured
            // against and the source of the user's own deny lists. One that
            // exists but does not load stops FarHand: falling back to the
            // defaults would quietly drop both.
            let baseline = if global.symlink_metadata().is_ok() {
                let c = std::fs::read_to_string(&global)
                    .map_err(Error::from)
                    .and_then(|t| Self::parse(&t))
                    .map_err(|e| {
                        Error::Config(format!(
                            "the global config {} does not load ({e}); fix or remove it",
                            global.display()
                        ))
                    })?;
                Some(c)
            } else {
                None
            };
            let (config, more) = Self::parse_project(&text, base.as_deref(), baseline.as_ref())?;
            notices.extend(more);
            (config, notices)
        } else {
            (Self::parse_at(&text, base.as_deref())?, Vec::new())
        };
        Ok(Loaded {
            config,
            path,
            source,
            notices,
        })
    }

    /// Parse a project file living in `base`, measured against `baseline`
    /// (the global config, if there is one): settings that would loosen it
    /// are dropped, and each drop is described in the returned notices.
    pub fn parse_project(
        text: &str,
        base: Option<&Path>,
        baseline: Option<&Config>,
    ) -> Result<(Self, Vec<String>)> {
        let mut cfg: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
        let mut notices = Vec::new();
        let requested = std::mem::take(&mut cfg.local.allowed_dirs);
        for d in requested {
            if d.is_absolute() || d.to_string_lossy().starts_with('~') {
                notices.push(format!(
                    "local.allowed_dirs entry `{}` ignored: a project .farhand.toml may only \
                     allow folders inside its own directory (`\".\"`, `\"assets\"`); put other \
                     folders in the global config",
                    d.display()
                ));
            } else {
                cfg.local.allowed_dirs.push(d);
            }
        }
        if let Some(d) = cfg.audit.log_dir.take() {
            notices.push(format!(
                "audit.log_dir `{}` ignored: only the global config may move the audit log",
                d.display()
            ));
        }
        cfg.validate(base)?;
        // A relative entry is only inside the project as written. A cloned
        // repository can carry `assets -> ~/Documents` next to its
        // `.farhand.toml`, so each entry must still be inside the project
        // folder once symlinks are resolved, and it is kept in that resolved
        // form so a link swapped in later changes nothing.
        let project = base
            .map(|b| {
                if b.as_os_str().is_empty() {
                    Path::new(".")
                } else {
                    b
                }
            })
            .and_then(|b| b.canonicalize().ok());
        for d in std::mem::take(&mut cfg.local.allowed_dirs) {
            match (d.canonicalize(), &project) {
                (Ok(c), Some(p)) if c.starts_with(p) && c.is_dir() => {
                    cfg.local.allowed_dirs.push(c)
                }
                (Ok(_), _) => notices.push(format!(
                    "local.allowed_dirs entry `{}` ignored: it is not a folder inside the \
                     project directory once symlinks are resolved",
                    d.display()
                )),
                (Err(e), _) => notices.push(format!(
                    "local.allowed_dirs entry `{}` ignored: {e}",
                    d.display()
                )),
            }
        }
        cfg.audit.log_dir = baseline.and_then(|b| b.audit.log_dir.clone());

        let floor = baseline.map(|b| b.approval.clone()).unwrap_or_default();
        let floor = floor.effective();
        let mut loosened = Vec::new();
        let mut tools = BTreeMap::new();
        for (tool, mode) in cfg.approval.effective() {
            let mode = if mode == ApprovalMode::Auto && floor[tool] == ApprovalMode::Ask {
                loosened.push(tool);
                ApprovalMode::Ask
            } else {
                mode
            };
            tools.insert(tool.to_string(), mode);
        }
        if !loosened.is_empty() {
            notices.push(format!(
                "[approval] `auto` ignored for {}: a project .farhand.toml may make approval \
                 stricter, not looser; set it in the global config",
                loosened.join(", ")
            ));
            // Every tool spelled out, so `effective()` no longer depends
            // on the mode.
            cfg.approval.tools = tools;
        }

        // The global deny lists stay in force; a project can only add.
        if let Some(b) = baseline {
            for g in &b.guard.deny_globs {
                if !cfg.guard.deny_globs.contains(g) {
                    cfg.guard.deny_globs.push(g.clone());
                }
            }
            for r in &b.guard.deny_content {
                if !cfg.guard.deny_content.contains(r) {
                    cfg.guard.deny_content.push(r.clone());
                }
            }
        }
        Ok((cfg, notices))
    }

    /// Parse a config that belongs to no directory: `allowed_dirs` entries
    /// must be absolute or `~/...`.
    pub fn parse(text: &str) -> Result<Self> {
        Self::parse_at(text, None)
    }

    /// Parse a config file that lives in `base`; relative `allowed_dirs`
    /// entries (`"."`, `"assets"`) are resolved against it.
    pub fn parse_at(text: &str, base: Option<&Path>) -> Result<Self> {
        let mut cfg: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
        cfg.validate(base)?;
        Ok(cfg)
    }

    fn locate(cwd: Option<&Path>) -> Result<(PathBuf, Source)> {
        if let Some(p) = std::env::var_os("FARHAND_CONFIG") {
            return Ok((PathBuf::from(p), Source::Env));
        }
        let local = match cwd {
            Some(d) => d.join(".farhand.toml"),
            None => PathBuf::from(".farhand.toml"),
        };
        if local.is_file() {
            return Ok((local, Source::Project));
        }
        let p = Self::global_path();
        if p.is_file() {
            return Ok((p, Source::Global));
        }
        Err(Error::NoConfig)
    }

    pub fn global_path() -> PathBuf {
        xdg_dir("XDG_CONFIG_HOME", ".config")
            .join("farhand")
            .join("config.toml")
    }

    fn validate(&mut self, base: Option<&Path>) -> Result<()> {
        if self.remote.host.trim().is_empty() {
            return Err(Error::Config("remote.host is empty".into()));
        }
        if self.remote.host.starts_with('-') {
            return Err(Error::Config("remote.host may not start with '-'".into()));
        }
        let raw = self.remote.workdir.trim();
        let w = raw.trim_end_matches(['/', '\\']);
        let w = if w.is_empty() && raw.starts_with('/') {
            "/".to_string()
        } else if is_drive_root(raw) {
            // `C:\` keeps its separator; `C:` alone would be drive-relative.
            format!("{}\\", &raw[..2])
        } else {
            w.to_string()
        };
        let windows_abs = w.len() >= 3
            && w.as_bytes()[0].is_ascii_alphabetic()
            && w.as_bytes()[1] == b':'
            && (w.as_bytes()[2] == b'\\' || w.as_bytes()[2] == b'/');
        if !(w.starts_with('/')
            || w == "~"
            || w.starts_with("~/")
            || w.starts_with("~\\")
            || windows_abs)
        {
            return Err(Error::Config(
                "remote.workdir must be an absolute path (`/srv/app`, `C:\\work`) or start with `~` \
                 (the remote home)"
                    .into(),
            ));
        }
        self.remote.workdir = w;
        if self.remote.shell.is_empty() {
            return Err(Error::Config("remote.shell is empty".into()));
        }
        if self.limits.command_timeout_secs == 0 || self.limits.max_command_timeout_secs == 0 {
            return Err(Error::Config("timeouts must be positive".into()));
        }
        let mut dirs = Vec::with_capacity(self.local.allowed_dirs.len());
        let home = dirs::home_dir();
        let home_canon = home.as_deref().and_then(|h| h.canonicalize().ok());
        for d in &self.local.allowed_dirs {
            let mut expanded = expand_home(d);
            // `..` would let an entry reach above what it names: above the
            // project folder for a relative entry, anywhere for `~/../x`.
            if expanded
                .components()
                .any(|c| matches!(c, std::path::Component::ParentDir))
            {
                return Err(Error::Config(format!(
                    "local.allowed_dirs entry `{}` may not contain `..`",
                    d.display()
                )));
            }
            if !expanded.is_absolute() {
                // A relative entry names the project folder itself or
                // something inside it.
                let Some(base) = base else {
                    return Err(Error::Config(format!(
                        "local.allowed_dirs entry `{}` is relative; only a project \
                         .farhand.toml may use relative entries (`\".\"` for its own folder)",
                        d.display()
                    )));
                };
                expanded = base.join(expanded);
            }
            // The allowlist is for a folder the user set aside, never the
            // home directory or anything above it: that would hand every
            // non-credential file to the model.
            let canon = expanded.canonicalize().ok();
            let covers_home = |h: &Path| {
                h.starts_with(&expanded) || canon.as_deref().is_some_and(|c| h.starts_with(c))
            };
            if expanded.parent().is_none()
                || home.as_deref().is_some_and(covers_home)
                || home_canon.as_deref().is_some_and(covers_home)
            {
                return Err(Error::Config(format!(
                    "local.allowed_dirs may not contain `/`, the home directory or a folder \
                     above it ({}); allow a specific folder instead",
                    d.display()
                )));
            }
            dirs.push(expanded);
        }
        self.local.allowed_dirs = dirs;
        if let Some(d) = &self.audit.log_dir {
            self.audit.log_dir = Some(expand_home(d));
        }
        for (t, m) in &self.approval.tools {
            if t == "remote_bash" {
                return Err(Error::Config(
                    "approval.tools: `remote_bash` was renamed to `remote_shell` in 0.2.1".into(),
                ));
            }
            if !MUTATING_TOOLS.contains(&t.as_str()) && !READ_ONLY_TOOLS.contains(&t.as_str()) {
                return Err(Error::Config(format!(
                    "approval.tools: `{t}` is not a tool (one of {}, {})",
                    MUTATING_TOOLS.join(", "),
                    READ_ONLY_TOOLS.join(", ")
                )));
            }
            if *m == ApprovalMode::Strict {
                return Err(Error::Config(format!(
                    "approval.tools.{t}: use `ask` or `auto` (`strict` is a global mode)"
                )));
            }
        }
        Ok(())
    }

    pub fn audit_dir(&self) -> PathBuf {
        self.audit.log_dir.clone().unwrap_or_else(|| {
            xdg_dir("XDG_DATA_HOME", ".local/share")
                .join("farhand")
                .join("audit")
        })
    }
}

/// `$VAR` if set, else `~/<fallback>`. The XDG layout is used on every
/// platform so the documented paths (`~/.config/farhand`,
/// `~/.local/share/farhand`) are the real ones on macOS too.
fn xdg_dir(var: &str, fallback: &str) -> PathBuf {
    if let Some(v) = std::env::var_os(var) {
        if !v.is_empty() {
            return PathBuf::from(v);
        }
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(fallback)
}

/// `~` and `~/x` expand to the home directory; anything else is returned as-is.
/// `C:\`, `C:/` or `C:` — a Windows drive root, with or without separator.
fn is_drive_root(s: &str) -> bool {
    let b = s.as_bytes();
    (b.len() == 2 || b.len() == 3)
        && b[0].is_ascii_alphabetic()
        && b[1] == b':'
        && (b.len() == 2 || b[2] == b'\\' || b[2] == b'/')
}

pub fn expand_home(p: &Path) -> PathBuf {
    let s = p.to_string_lossy();
    if s == "~" {
        return dirs::home_dir().unwrap_or_else(|| p.to_path_buf());
    }
    if let Some(rest) = s.strip_prefix("~/") {
        if let Some(home) = dirs::home_dir() {
            return home.join(rest);
        }
    }
    p.to_path_buf()
}

const EXAMPLE: &str = r#"# FarHand configuration.
# As .farhand.toml in a project root, it makes that project remote.
# As ~/.config/farhand/config.toml it is optional: only needed for
# activation = "always" (or as the target of --config / FARHAND_CONFIG).

# "project" (default): only directories that carry a .farhand.toml are
#            remote; anywhere else the agent keeps its local tools and FarHand
#            stays out of the way.
# "always":  every agent session on this machine is remote, using the
#            [remote] section below.
# Only meaningful in this global file; a project's .farhand.toml is always
# active in its own directory.
# activation = "project"

[remote]
# An alias from ~/.ssh/config or user@host. Keys, ports, jump hosts and
# agent forwarding all come from your OpenSSH config.
host = "devbox"
# Directory on the remote where every command starts and relative paths
# resolve. Absolute, or `~/...` for the remote user's home. Created on
# first connection if it does not exist.
workdir = "~/project"
# os = "auto"              # "posix" or "windows"; detected on connect, but set it so
#                          # the model knows which shell it is writing for
# shell = ["bash", "-lc"]  # Windows: ["powershell"] (default) or ["pwsh"]
# connect_timeout_secs = 20
# server_alive_interval_secs = 30

[local]
# The only local directories the model may list, read from, upload from or
# download into. Leave empty to close the local filesystem completely.
# In a project .farhand.toml, "." means this folder: drop files here to
# upload them, and downloads land here. A project file may only name this
# folder or folders inside it; absolute and `~` entries belong in the
# global config. Never allow your home directory or anything above it.
allowed_dirs = ["."]

[limits]
# command_timeout_secs = 120
# max_command_timeout_secs = 1800
# max_output_bytes = 102400
# max_read_bytes = 524288
# max_transfer_bytes = 1073741824
# max_transfer_files = 5000

[audit]
# Global config only; a project file cannot move the log.
# log_dir = "~/.local/share/farhand/audit"

[guard]
# Extra globs that may never leave this machine (added to the built-in list).
# deny_globs = ["*.internal"]
# Extra regexes that mark content as secret.
# deny_content = ["ACME-[0-9]{12}"]

[approval]
# "ask":    the agent prompts you before remote_shell, remote_write,
#           remote_edit, upload and download; read-only tools run freely.
# "auto":   nothing prompts; the audit log is your record.
# "strict": every tool prompts, reads and searches included.
# A project .farhand.toml can make this stricter than the global config,
# never looser: `auto` there only holds where the global config allows it.
mode = "ask"
# Per-tool overrides (`ask` or `auto`), any tool name:
# tools = { remote_write = "auto", remote_edit = "auto", remote_read = "ask" }
"#;

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

    #[test]
    fn example_parses() {
        // `farhand init` writes the example as a project file; its `"."`
        // is that file's folder, and is meaningless in the global config.
        let cfg = Config::parse_at(Config::example(), Some(Path::new("/proj"))).unwrap();
        assert_eq!(cfg.remote.host, "devbox");
        assert_eq!(cfg.remote.shell, vec!["bash", "-lc"]);
        assert_eq!(cfg.local.allowed_dirs, vec![PathBuf::from("/proj")]);
        assert!(Config::parse(Config::example()).is_err());
    }

    #[test]
    fn rejects_home_and_root_as_allowed_dirs() {
        for d in ["/", "~"] {
            let err = Config::parse(&format!(
                "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['{d}']"
            ))
            .unwrap_err();
            assert!(err.to_string().contains("home directory"), "{d}: {err}");
        }
        assert!(
            Config::parse("[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['~/out']")
                .is_ok()
        );
    }

    #[test]
    fn relative_allowed_dirs_resolve_against_the_project_file() {
        let text = "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['.', 'assets']";
        let err = Config::parse(text).unwrap_err();
        assert!(err.to_string().contains("relative"), "{err}");
        let cfg = Config::parse_at(text, Some(Path::new("/proj"))).unwrap();
        assert_eq!(
            cfg.local.allowed_dirs,
            vec![PathBuf::from("/proj"), PathBuf::from("/proj/assets")]
        );
        let err = Config::parse_at(
            "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['../x']",
            Some(Path::new("/proj")),
        )
        .unwrap_err();
        assert!(err.to_string().contains(".."), "{err}");
    }

    #[test]
    fn old_tool_name_points_at_the_new_one() {
        let err = Config::parse(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ remote_bash='ask' }",
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("renamed to `remote_shell`"),
            "{err}"
        );
    }

    #[test]
    fn rejects_relative_workdir() {
        let err = Config::parse("[remote]\nhost='h'\nworkdir='rel'").unwrap_err();
        assert!(err.to_string().contains("absolute"));
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='~/'").unwrap();
        assert_eq!(cfg.remote.workdir, "~");
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='/srv/app/'").unwrap();
        assert_eq!(cfg.remote.workdir, "/srv/app");
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='C:\\work\\'").unwrap();
        assert_eq!(cfg.remote.workdir, "C:\\work");
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='D:/'").unwrap();
        assert_eq!(cfg.remote.workdir, "D:\\");
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='C:'").unwrap();
        assert_eq!(cfg.remote.workdir, "C:\\");
        assert!(Config::parse("[remote]\nhost='h'\nworkdir='work'").is_err());
        let cfg = Config::parse("[remote]\nhost='h'\nworkdir='/'\nos='windows'").unwrap();
        assert_eq!(cfg.remote.os, Os::Windows);
    }

    #[test]
    fn approval_overrides_apply() {
        let cfg = Config::parse(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'\ntools={ remote_shell='ask' }",
        )
        .unwrap();
        let e = cfg.approval.effective();
        assert_eq!(e["remote_shell"], ApprovalMode::Ask);
        assert_eq!(e["remote_write"], ApprovalMode::Auto);
        assert_eq!(e["remote_read"], ApprovalMode::Auto);
        assert_eq!(e.len(), MUTATING_TOOLS.len() + READ_ONLY_TOOLS.len());

        let strict = Config::parse(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='strict'\ntools={ remote_info='auto' }",
        )
        .unwrap();
        let e = strict.approval.effective();
        assert_eq!(e["remote_read"], ApprovalMode::Ask);
        assert_eq!(e["remote_shell"], ApprovalMode::Ask);
        assert_eq!(e["remote_info"], ApprovalMode::Auto);

        let default = Config::parse("[remote]\nhost='h'\nworkdir='/'").unwrap();
        assert_eq!(
            default.approval.effective()["remote_read"],
            ApprovalMode::Auto
        );
        assert!(Config::parse(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ nope='auto' }"
        )
        .is_err());
        assert!(Config::parse(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ upload='strict' }"
        )
        .is_err());
    }

    #[test]
    fn activation_depends_on_source() {
        let mk = |activation: &str, source: Source| Loaded {
            config: Config::parse(&format!(
                "activation='{activation}'\n[remote]\nhost='h'\nworkdir='/'"
            ))
            .unwrap(),
            path: PathBuf::new(),
            source,
            notices: Vec::new(),
        };
        assert!(mk("always", Source::Global).active());
        assert!(!mk("project", Source::Global).active());
        assert!(mk("project", Source::Project).active());
        assert!(mk("project", Source::Explicit).active());
        assert_eq!(
            Config::parse("[remote]\nhost='h'\nworkdir='/'")
                .unwrap()
                .activation,
            ActivationMode::Project
        );
    }

    #[test]
    fn allowed_dirs_refuse_home_ancestors_and_dotdot() {
        let home = dirs::home_dir().unwrap();
        let parent = home.parent().unwrap().display().to_string();
        for d in [parent.as_str(), "~/..", "~/../x", "/tmp/../etc"] {
            let err = Config::parse(&format!(
                "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['{d}']"
            ))
            .unwrap_err();
            assert!(err.to_string().contains("allowed_dirs"), "{d}: {err}");
        }
    }

    /// Parse `text` as the `.farhand.toml` of a fresh project folder.
    fn project(text: &str, baseline: Option<&str>) -> (Config, Vec<String>, tempfile::TempDir) {
        let d = tempfile::tempdir().unwrap();
        let baseline = baseline.map(|b| Config::parse(b).unwrap());
        let (cfg, notes) = Config::parse_project(text, Some(d.path()), baseline.as_ref()).unwrap();
        (cfg, notes, d)
    }

    #[test]
    fn project_file_cannot_loosen_approval() {
        let (cfg, notes, _d) = project(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'",
            None,
        );
        let e = cfg.approval.effective();
        assert_eq!(e["remote_shell"], ApprovalMode::Ask);
        assert_eq!(e["upload"], ApprovalMode::Ask);
        assert_eq!(e["remote_read"], ApprovalMode::Auto);
        assert_eq!(notes.len(), 1);
        assert!(notes[0].contains("remote_shell"), "{notes:?}");

        // The global config sets the floor: what it allows, a project may use.
        let global = "[remote]\nhost='g'\nworkdir='/'\n[approval]\nmode='auto'";
        let (cfg, notes, _d) = project(
            "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'\ntools={ upload='ask' }",
            Some(global),
        );
        assert!(notes.is_empty(), "{notes:?}");
        assert_eq!(cfg.approval.effective()["remote_shell"], ApprovalMode::Auto);
        assert_eq!(cfg.approval.effective()["upload"], ApprovalMode::Ask);

        // Tightening is always fine; loosening strict reads is not.
        let strict = "[remote]\nhost='g'\nworkdir='/'\n[approval]\nmode='strict'";
        let (cfg, notes, _d) = project("[remote]\nhost='h'\nworkdir='/'", Some(strict));
        assert_eq!(cfg.approval.effective()["remote_read"], ApprovalMode::Ask);
        assert!(notes[0].contains("remote_read"), "{notes:?}");
    }

    #[test]
    fn project_file_keeps_to_its_own_folder_and_the_global_log() {
        let (cfg, notes, d) = project(
            "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['.', '/Users', '~/x']\n\
             [audit]\nlog_dir='/dev'",
            Some("[remote]\nhost='g'\nworkdir='/'\n[audit]\nlog_dir='/var/log/fh'\n[guard]\ndeny_globs=['*.corp']"),
        );
        assert_eq!(
            cfg.local.allowed_dirs,
            vec![d.path().canonicalize().unwrap()]
        );
        assert_eq!(cfg.audit.log_dir, Some(PathBuf::from("/var/log/fh")));
        assert_eq!(cfg.guard.deny_globs, vec!["*.corp".to_string()]);
        assert_eq!(notes.len(), 3, "{notes:?}");
        let err = Config::parse_project(
            "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['../x']",
            Some(Path::new("/proj")),
            None,
        )
        .unwrap_err();
        assert!(err.to_string().contains(".."), "{err}");
    }

    #[cfg(unix)]
    #[test]
    fn project_folders_may_not_leave_the_project_through_a_symlink() {
        let d = tempfile::tempdir().unwrap();
        let proj = d.path().join("proj");
        let outside = d.path().join("outside");
        std::fs::create_dir_all(proj.join("real/sub")).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        std::os::unix::fs::symlink(&outside, proj.join("assets")).unwrap();
        std::os::unix::fs::symlink(proj.join("real/sub"), proj.join("inner")).unwrap();
        let (cfg, notes) = Config::parse_project(
            "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['assets', 'inner', 'missing', 'real']",
            Some(&proj),
            None,
        )
        .unwrap();
        let real = proj.join("real").canonicalize().unwrap();
        assert_eq!(cfg.local.allowed_dirs, vec![real.join("sub"), real]);
        assert_eq!(notes.len(), 2, "{notes:?}");
        assert!(notes[0].contains("/assets`"), "{notes:?}");
        assert!(notes[1].contains("/missing`"), "{notes:?}");
    }

    #[test]
    fn a_farhand_toml_passed_by_path_is_still_a_project_file() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join(".farhand.toml");
        std::fs::write(
            &p,
            "[remote]\nhost='h'\nworkdir='/'\n[audit]\nlog_dir='/dev'",
        )
        .unwrap();
        let l = Config::load_in(None, Some(&p)).unwrap();
        assert_eq!(l.source, Source::Project);
        assert!(
            l.notices.iter().any(|n| n.contains("log_dir")),
            "{:?}",
            l.notices
        );
        let other = d.path().join("fh.toml");
        std::fs::copy(&p, &other).unwrap();
        let l = Config::load_in(None, Some(&other)).unwrap();
        assert_eq!(l.source, Source::Explicit);
        assert_eq!(l.config.audit.log_dir, Some(PathBuf::from("/dev")));
    }

    #[test]
    fn rejects_unknown_fields() {
        assert!(Config::parse("[remote]\nhost='h'\nworkdir='/'\nbogus=1").is_err());
    }
}