croft-software 0.2.3

VSCode-style TUI written in Rust
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! Layered settings (#251): one merged view over a chain of config files.
//!
//! [`crate::prefs`] knows a single `~/.config/croft/config.json`. This module
//! stacks layers over it, later layers winning per key:
//!
//! 1. built-in defaults (what `Prefs::default()` says)
//! 2. `~/.config/croft/config.json` — user, then
//!    `~/.config/croft/config.synced.json` — what config sync brought from
//!    the machine the user connected from (#262): only the appearance and
//!    editor keys a workspace may set, never trust state
//! 3. `~/.config/croft/config.local.json` — machine-local user overrides,
//!    dotfile-repo friendly
//! 4. `<root>/.vscode/settings.json` — a small mapped subset, so existing
//!    repos behave sensibly (never broad VS Code compatibility)
//! 5. `<root>/.croft/config.json` — workspace, committed
//! 6. `<root>/.croft/config.local.json` — workspace-local, gitignored
//!
//! Mechanics: every layer may `extends` other JSON files (relative to itself
//! or `~`-expanded; cycles warn and stop), and may carry `"macos"` /
//! `"linux"` / `"android"` blocks that merge over its flat keys on the
//! matching platform. Objects deep-merge; arrays and scalars replace.
//!
//! Workspace layers (4–6) are repo-controlled input, so they pass an explicit
//! allowlist: keys that change trust posture or execute things
//! (`mcp_consented`, `disabled_extensions`, …) are refused with a visible
//! warning and never merged. The user layers can set everything.
//!
//! Everything here is pure over the filesystem (paths in, merged view +
//! warnings out); the App owns applying the result and watching the chain.

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

use serde_json::{Map, Value};

use crate::prefs::Prefs;

/// Which layer a value came from, for provenance display in the settings hub.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum LayerKind {
    Default,
    User,
    Synced,
    UserLocal,
    VsCodeWorkspace,
    Workspace,
    WorkspaceLocal,
}

impl LayerKind {
    pub fn label(self) -> &'static str {
        match self {
            LayerKind::Default => "default",
            LayerKind::User => "user",
            LayerKind::Synced => "synced",
            LayerKind::UserLocal => "user-local",
            LayerKind::VsCodeWorkspace => ".vscode",
            LayerKind::Workspace => "workspace",
            LayerKind::WorkspaceLocal => "workspace-local",
        }
    }

    /// Layers written by something other than this machine's user get the
    /// allowlist: repo-controlled ones, and what config sync brought from
    /// another machine. The user's own layers do not.
    fn is_allowlisted(self) -> bool {
        matches!(
            self,
            LayerKind::Synced
                | LayerKind::VsCodeWorkspace
                | LayerKind::Workspace
                | LayerKind::WorkspaceLocal
        )
    }
}

/// The merged result: the effective preferences, which layer won each
/// top-level key, every file that participated (for hot-reload watching),
/// and human-readable warnings (parse failures, refused keys, cycles).
#[derive(Debug, Clone)]
pub struct MergedConfig {
    pub prefs: Prefs,
    pub provenance: BTreeMap<String, LayerKind>,
    /// Layer files and their `extends` targets, existing or not, in merge
    /// order. A save to any of these should trigger a re-merge.
    pub chain: Vec<PathBuf>,
    pub warnings: Vec<String>,
}

/// The layer that set `key` per a provenance map, defaulting to
/// [`LayerKind::Default`]. Free function so the App can query the map it
/// stored without keeping the whole merged view around.
pub fn layer_of(provenance: &BTreeMap<String, LayerKind>, key: &str) -> LayerKind {
    provenance.get(key).copied().unwrap_or(LayerKind::Default)
}

/// Keys a repo-controlled layer may set: appearance and editor/terminal
/// behavior toggles. Everything else — extension enablement, MCP consent and
/// fingerprints, host accents, machine-state flags — is user-config only,
/// because a cloned repo must not be able to change what croft trusts or
/// executes. Extending this list is a deliberate review decision.
pub const WORKSPACE_ALLOWED_KEYS: &[&str] = &[
    "theme",
    "format_on_save",
    "format_on_type",
    "auto_save",
    "auto_save_on_focus_change",
    "render_whitespace",
    "disable_inline_blame",
    "disable_auto_close_pairs",
    "disable_inline_values",
    "disable_bracket_colors",
    "disable_indent_guides",
    "disable_inlay_hints",
    "copy_on_select",
    "disable_log_highlight",
    "explorer_views",
];

/// The synced layer's file name (#262). Config sync pushes the projection
/// of the connecting machine's `config.json` here: a file of its own, so
/// the push can never overwrite consent or fingerprints the remote keeps in
/// its own `config.json`, and above that `config.json` in the merge, so the
/// theme follows the user. `config.local.json` still wins on the box.
pub const SYNCED_CONFIG_NAME: &str = "config.synced.json";

/// The keys of a `config.json` document that may travel to another machine
/// (#262): the [`WORKSPACE_ALLOWED_KEYS`] appearance and editor toggles,
/// read from the flat top level. `None` when the document has none of
/// them, so a machine with nothing to share pushes nothing.
pub fn synced_projection(doc: &Map<String, Value>) -> Option<Map<String, Value>> {
    let out: Map<String, Value> = doc
        .iter()
        .filter(|(k, _)| WORKSPACE_ALLOWED_KEYS.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    (!out.is_empty()).then_some(out)
}

/// Where the synced layer is read from: beside the user's `config.json`.
pub fn synced_config_path() -> PathBuf {
    user_layers_dir().join(SYNCED_CONFIG_NAME)
}

/// Path of the workspace layer files under a root.
pub fn workspace_config_path(root: &Path) -> PathBuf {
    root.join(".croft").join("config.json")
}

pub fn workspace_local_config_path(root: &Path) -> PathBuf {
    root.join(".croft").join("config.local.json")
}

/// Path of the machine-local user layer. Test builds read the user layers
/// from [`user_layers_dir`] instead, so this path is not in their chain.
pub fn user_local_config_path() -> PathBuf {
    crate::prefs::config_dir().join("config.local.json")
}

/// Load the full merged view for a workspace (or just the user layers when
/// `workspace_root` is `None`), reading the user layers from
/// [`user_layers_dir`].
pub fn load_merged(workspace_root: Option<&Path>) -> MergedConfig {
    load_merged_from(&user_layers_dir(), workspace_root, current_platform())
}

/// Where [`load_merged`] reads the user layers (`config.json` and
/// `config.local.json`). Test builds use a per-process dir nothing creates,
/// so the user's own settings never steer a test (#624).
fn user_layers_dir() -> PathBuf {
    if cfg!(test) {
        std::env::temp_dir().join(format!("croft-test-config-{}", std::process::id()))
    } else {
        // The active profile's dir (#618), which is where every settings
        // change is saved; reading the bare config dir dropped them all.
        crate::profiles::file("config.json")
            .parent()
            .map_or_else(crate::prefs::config_dir, Path::to_path_buf)
    }
}

/// The platform key active on this build, matching the scope-block names.
pub fn current_platform() -> &'static str {
    if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(target_os = "android") {
        "android"
    } else {
        "linux"
    }
}

const PLATFORM_KEYS: &[&str] = &["macos", "linux", "android"];

/// Testable core: explicit user config dir and platform.
pub fn load_merged_from(
    user_dir: &Path,
    workspace_root: Option<&Path>,
    platform: &str,
) -> MergedConfig {
    let mut layers: Vec<(LayerKind, PathBuf)> = vec![
        (LayerKind::User, user_dir.join("config.json")),
        (LayerKind::Synced, user_dir.join(SYNCED_CONFIG_NAME)),
        (LayerKind::UserLocal, user_dir.join("config.local.json")),
    ];
    if let Some(root) = workspace_root {
        layers.push((
            LayerKind::VsCodeWorkspace,
            root.join(".vscode").join("settings.json"),
        ));
        layers.push((LayerKind::Workspace, workspace_config_path(root)));
        layers.push((LayerKind::WorkspaceLocal, workspace_local_config_path(root)));
    }

    let mut warnings = Vec::new();
    let mut chain = Vec::new();
    let mut merged = Map::new();
    let mut provenance = BTreeMap::new();

    for (kind, path) in layers {
        chain.push(path.clone());
        let doc = if kind == LayerKind::VsCodeWorkspace {
            load_vscode_subset(&path, &mut warnings)
        } else {
            let mut visited = Vec::new();
            load_layer_document(&path, platform, &mut visited, &mut chain, &mut warnings)
        };
        let Some(doc) = doc else { continue };
        for (key, value) in doc {
            if kind.is_allowlisted() && !WORKSPACE_ALLOWED_KEYS.contains(&key.as_str()) {
                warnings.push(format!(
                    "{}: \"{key}\" is user-config only and was ignored ({} layers may set: appearance and editor toggles)",
                    path.display(),
                    kind.label()
                ));
                continue;
            }
            deep_merge(merged.entry(key.clone()).or_insert(Value::Null), &value);
            provenance.insert(key, kind);
        }
    }

    let prefs = deserialize_tolerantly(merged, &mut provenance, &mut warnings);
    MergedConfig {
        prefs,
        provenance,
        chain,
        warnings,
    }
}

/// Largest layer file croft will read: layers are hand-written settings, so
/// anything past this is a mistake (or a hostile `extends` target such as
/// `/dev/zero`) and refusing beats an unbounded read.
const LAYER_FILE_MAX: u64 = 1024 * 1024;

/// Read a layer file's text, refusing non-regular files (a FIFO would block
/// startup, a device file would read forever) and oversized ones, both with
/// a warning. A missing file stays silent — absent layers are normal.
fn read_layer_file(path: &Path, warnings: &mut Vec<String>) -> Option<String> {
    let meta = std::fs::metadata(path).ok()?;
    if !meta.is_file() {
        warnings.push(format!(
            "{}: not a regular file — layer ignored",
            path.display()
        ));
        return None;
    }
    if meta.len() > LAYER_FILE_MAX {
        warnings.push(format!(
            "{}: larger than {LAYER_FILE_MAX} bytes — layer ignored",
            path.display()
        ));
        return None;
    }
    std::fs::read_to_string(path).ok()
}

/// Read one croft layer file: JSONC-tolerant parse, `extends` resolution
/// (depth-first, cycles warn and stop), then this platform's scope block
/// merged over the flat keys. `None` when the file is absent or unreadable.
///
/// `visited` is the ACTIVE recursion stack, not a set of everything ever
/// loaded: a base popped here may legitimately load again from a sibling
/// branch (diamond inheritance re-applies the shared base at its later
/// position); only a file already on the current stack is a true cycle.
fn load_layer_document(
    path: &Path,
    platform: &str,
    visited: &mut Vec<PathBuf>,
    chain: &mut Vec<PathBuf>,
    warnings: &mut Vec<String>,
) -> Option<Map<String, Value>> {
    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    if visited.contains(&canonical) {
        warnings.push(format!(
            "{}: extends cycle detected — this file is already in the chain and was skipped",
            path.display()
        ));
        return None;
    }
    visited.push(canonical);
    let doc = load_layer_document_inner(path, platform, visited, chain, warnings);
    visited.pop();
    doc
}

fn load_layer_document_inner(
    path: &Path,
    platform: &str,
    visited: &mut Vec<PathBuf>,
    chain: &mut Vec<PathBuf>,
    warnings: &mut Vec<String>,
) -> Option<Map<String, Value>> {
    let text = read_layer_file(path, warnings)?;
    let parsed: Value = match serde_json::from_str(&crate::tasks::strip_jsonc(&text)) {
        Ok(v) => v,
        Err(e) => {
            warnings.push(format!(
                "{}: not valid JSON ({e}) — layer ignored",
                path.display()
            ));
            return None;
        }
    };
    let Value::Object(mut doc) = parsed else {
        warnings.push(format!(
            "{}: expected a JSON object at the top level — layer ignored",
            path.display()
        ));
        return None;
    };

    // `extends`: bases merge first (in listed order), then this file's own
    // keys over them.
    let mut acc = Map::new();
    if let Some(ext) = doc.remove("extends") {
        let bases: Vec<String> = match ext {
            Value::String(s) => vec![s],
            Value::Array(a) => a
                .into_iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect(),
            _ => {
                warnings.push(format!(
                    "{}: \"extends\" must be a path or an array of paths — ignored",
                    path.display()
                ));
                Vec::new()
            }
        };
        for base in bases {
            let base_path = resolve_extends_path(&base, path);
            chain.push(base_path.clone());
            if !base_path.exists() {
                warnings.push(format!(
                    "{}: extends {} which does not exist",
                    path.display(),
                    base_path.display()
                ));
                continue;
            }
            if let Some(base_doc) =
                load_layer_document(&base_path, platform, visited, chain, warnings)
            {
                for (k, v) in base_doc {
                    deep_merge(acc.entry(k).or_insert(Value::Null), &v);
                }
            }
        }
    }

    // Platform scope blocks: strip all three, merge the matching one over
    // the flat keys.
    let mut scoped = None;
    for key in PLATFORM_KEYS {
        let block = doc.remove(*key);
        if *key == platform {
            scoped = block;
        }
    }
    for (k, v) in doc {
        deep_merge(acc.entry(k).or_insert(Value::Null), &v);
    }
    if let Some(Value::Object(block)) = scoped {
        for (k, v) in block {
            deep_merge(acc.entry(k).or_insert(Value::Null), &v);
        }
    }
    Some(acc)
}

/// Resolve an `extends` target: `~/` expands to the home directory, absolute
/// paths are taken as written, relative paths resolve against the extending
/// file's own directory.
fn resolve_extends_path(target: &str, extending_file: &Path) -> PathBuf {
    if let Some(rest) = target.strip_prefix("~/") {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("."));
        return home.join(rest);
    }
    let p = PathBuf::from(target);
    if p.is_absolute() {
        p
    } else {
        extending_file.parent().unwrap_or(Path::new(".")).join(p)
    }
}

/// Deep-merge `over` into `base`: objects merge key-wise, everything else
/// (arrays included) replaces. The documented rule — arrays replace so a
/// workspace can *narrow* a list rather than only ever append.
fn deep_merge(base: &mut Value, over: &Value) {
    match (base, over) {
        (Value::Object(b), Value::Object(o)) => {
            for (k, v) in o {
                deep_merge(b.entry(k.clone()).or_insert(Value::Null), v);
            }
        }
        (slot, v) => *slot = v.clone(),
    }
}

/// The mapped `.vscode/settings.json` subset: only settings with an exact
/// croft equivalent, silently ignoring the rest (broad VS Code settings
/// compatibility is explicitly a non-goal). A missing file is silent, but a
/// present-yet-unparsable one warns — otherwise a malformed file is
/// indistinguishable from an absent one.
fn load_vscode_subset(path: &Path, warnings: &mut Vec<String>) -> Option<Map<String, Value>> {
    let text = read_layer_file(path, warnings)?;
    let parsed: Value = match serde_json::from_str(&crate::tasks::strip_jsonc(&text)) {
        Ok(v) => v,
        Err(e) => {
            warnings.push(format!(
                "{}: not valid JSON ({e}) — layer ignored",
                path.display()
            ));
            return None;
        }
    };
    let Some(obj) = parsed.as_object() else {
        warnings.push(format!(
            "{}: expected a JSON object at the top level — layer ignored",
            path.display()
        ));
        return None;
    };
    // ONE mapping, shared with `croft import-vscode`
    // (`crate::import_vscode::map_settings`). Keeping a second table here is
    // how the two came to disagree: this one ignored
    // `files.autoSave: "onWindowChange"` while the importer mapped it, so the
    // same file meant different things depending on which path read it.
    //
    // A workspace layer may only set the appearance and editor toggles in
    // `WORKSPACE_ALLOWED_KEYS`, so the shared result is filtered to those
    // here rather than warning about keys the user never wrote.
    let (mapped, _unmapped, _warnings) = crate::import_vscode::map_settings(obj);
    let out: Map<String, Value> = mapped
        .into_iter()
        .filter(|(k, _)| WORKSPACE_ALLOWED_KEYS.contains(&k.as_str()))
        .collect();
    (!out.is_empty()).then_some(out)
}

/// Deserialize the merged map into [`Prefs`]. A single mistyped key must not
/// nuke every other setting, so on failure each top-level key is re-tried in
/// isolation and the offenders are dropped with a warning.
fn deserialize_tolerantly(
    merged: Map<String, Value>,
    provenance: &mut BTreeMap<String, LayerKind>,
    warnings: &mut Vec<String>,
) -> Prefs {
    match serde_json::from_value(Value::Object(merged.clone())) {
        Ok(p) => p,
        Err(_) => {
            let mut clean = Map::new();
            for (key, value) in merged {
                let mut probe = Map::new();
                probe.insert(key.clone(), value.clone());
                if serde_json::from_value::<Prefs>(Value::Object(probe)).is_ok() {
                    clean.insert(key, value);
                } else {
                    warnings.push(format!(
                        "setting \"{key}\" has the wrong type and was ignored"
                    ));
                    provenance.remove(&key);
                }
            }
            serde_json::from_value(Value::Object(clean)).unwrap_or_default()
        }
    }
}

/// Make sure `<root>/.croft/.gitignore` ignores the workspace-local layer,
/// creating the directory and file as needed. Called before the local layer
/// is first opened for editing so it can never land in a commit by accident.
///
/// `.croft/` and `.gitignore` are repo-controlled paths, so a hostile clone
/// could make either a symlink into the user's own config
/// (`.croft/.gitignore → ~/.config/croft/config.json`) and turn this append
/// into config corruption. Both components are therefore refused as
/// symlinks, and the write itself opens with `O_NOFOLLOW` so a race cannot
/// swap one in between the check and the write.
pub fn ensure_workspace_local_ignored(root: &Path) -> std::io::Result<()> {
    use std::io::{Read, Write};

    let no_follow = |what: &Path| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!(
                "{} is a symlink — refusing to write through it",
                what.display()
            ),
        )
    };
    let dir = root.join(".croft");
    std::fs::create_dir_all(&dir)?;
    if std::fs::symlink_metadata(&dir)?.file_type().is_symlink() {
        return Err(no_follow(&dir));
    }
    let gi = dir.join(".gitignore");
    match std::fs::symlink_metadata(&gi) {
        Ok(m) if m.file_type().is_symlink() => return Err(no_follow(&gi)),
        Ok(_) | Err(_) => {}
    }
    let mut opts = std::fs::OpenOptions::new();
    opts.read(true).write(true).create(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.custom_flags(libc::O_NOFOLLOW);
    }
    let mut f = opts.open(&gi)?;
    let mut existing = String::new();
    f.read_to_string(&mut existing)?;
    if existing.lines().any(|l| l.trim() == "config.local.json") {
        return Ok(());
    }
    if !existing.is_empty() && !existing.ends_with('\n') {
        f.write_all(b"\n")?;
    }
    f.write_all(b"config.local.json\n")
}

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

    /// #624: a test build reads the user layers from a dir outside the
    /// user's config dir, so their own settings never reach a test.
    #[test]
    fn a_test_build_reads_the_user_layers_outside_the_config_dir() {
        let dir = user_layers_dir();
        assert!(
            !dir.starts_with(crate::prefs::config_dir()),
            "user layers read from the real config dir: {}",
            dir.display()
        );
        assert!(!dir.exists(), "nothing creates the test user dir");
    }

    fn write(path: &Path, text: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, text).unwrap();
    }

    /// A tempdir with a user config dir and a workspace root inside it.
    fn setup() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let tmp = tempfile::tempdir().unwrap();
        let user = tmp.path().join("user");
        let root = tmp.path().join("repo");
        std::fs::create_dir_all(&user).unwrap();
        std::fs::create_dir_all(&root).unwrap();
        (tmp, user, root)
    }

    #[test]
    fn later_layers_win_and_provenance_tracks_the_winner() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            r#"{"theme":"dark","format_on_save":true}"#,
        );
        write(&user.join("config.local.json"), r#"{"theme":"black"}"#);
        write(
            &root.join(".croft/config.json"),
            r#"{"theme":"nord","auto_save":true}"#,
        );
        write(
            &root.join(".croft/config.local.json"),
            r#"{"theme":"dracula"}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(m.prefs.theme, "dracula");
        assert!(
            m.prefs.format_on_save,
            "user layer survives under overrides"
        );
        assert!(m.prefs.auto_save, "workspace layer applies");
        assert_eq!(layer_of(&m.provenance, "theme"), LayerKind::WorkspaceLocal);
        assert_eq!(layer_of(&m.provenance, "format_on_save"), LayerKind::User);
        assert_eq!(layer_of(&m.provenance, "auto_save"), LayerKind::Workspace);
        assert_eq!(
            layer_of(&m.provenance, "copy_on_select"),
            LayerKind::Default
        );
        assert!(m.warnings.is_empty(), "{:?}", m.warnings);
    }

    #[test]
    fn workspace_layers_cannot_touch_trust_or_execution_settings() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            r#"{"disabled_extensions":["dap-python"],"fleet_groups":{"web":["web1","web2"]}}"#,
        );
        write(
            &root.join(".croft/config.json"),
            r#"{"theme":"nord","mcp_consented":["evil"],"disabled_extensions":[],"host_accents":[{"pattern":"*"}],"fleet_groups":{"all":["prod-db"]}}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(m.prefs.theme, "nord", "allowlisted key applies");
        assert!(
            m.prefs.mcp_consented.is_empty(),
            "a cloned repo must not grant MCP consent"
        );
        assert!(
            m.prefs.disabled_extensions.contains("dap-python"),
            "the user's own value survives the refused workspace override"
        );
        assert!(m.prefs.host_accents.is_empty());
        // A fleet group is a list of machines to run commands on (#363), so
        // a checked-out repo naming one could add a production box to a set
        // the user then broadcasts to.
        // The user's own group survives the refused workspace override, so
        // this proves refusal rather than the key simply never deserializing
        // - without a user-layer value, an inert feature would pass too.
        assert_eq!(
            m.prefs.fleet_groups.get("web").map(Vec::len),
            Some(2),
            "a user layer CAN name a fleet group"
        );
        assert!(
            !m.prefs.fleet_groups.contains_key("all"),
            "a cloned repo must not name hosts for a fleet run"
        );
        let joined = m.warnings.join("\n");
        assert!(joined.contains("mcp_consented"), "{joined}");
        assert!(joined.contains("disabled_extensions"), "{joined}");
        assert!(joined.contains("host_accents"), "{joined}");
        assert!(joined.contains("fleet_groups"), "{joined}");
    }

    #[test]
    fn extends_composes_and_cycles_warn_instead_of_hanging() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("base.json"),
            r#"{"format_on_save":true,"theme":"nord"}"#,
        );
        write(
            &user.join("config.json"),
            r#"{"extends":"base.json","theme":"black"}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(m.prefs.format_on_save, "inherited from the base");
        assert_eq!(m.prefs.theme, "black", "own keys beat the base");
        assert!(m.chain.iter().any(|p| p.ends_with("base.json")));

        // A cycle: a -> b -> a. Must terminate with a warning.
        write(
            &user.join("a.json"),
            r#"{"extends":"b.json","auto_save":true}"#,
        );
        write(&user.join("b.json"), r#"{"extends":"a.json"}"#);
        write(&user.join("config.json"), r#"{"extends":"a.json"}"#);
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(m.prefs.auto_save, "keys before the cycle still merge");
        assert!(
            m.warnings.iter().any(|w| w.contains("cycle")),
            "{:?}",
            m.warnings
        );
    }

    #[test]
    fn platform_blocks_apply_only_on_their_platform() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            r#"{"theme":"dark","linux":{"theme":"nord"},"macos":{"format_on_save":true}}"#,
        );
        let linux = load_merged_from(&user, Some(&root), "linux");
        assert_eq!(linux.prefs.theme, "nord");
        assert!(!linux.prefs.format_on_save);
        let mac = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(mac.prefs.theme, "dark");
        assert!(mac.prefs.format_on_save);
    }

    #[test]
    fn objects_deep_merge_and_arrays_replace() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            r#"{"explorer_views":{"timeline":false},"host_accents":[{"pattern":"prod-*"},{"pattern":"stage-*"}]}"#,
        );
        write(
            &user.join("config.local.json"),
            r#"{"explorer_views":{"outline":false},"host_accents":[{"pattern":"dev-*"}]}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(!m.prefs.explorer_views.timeline, "user key survives");
        assert!(!m.prefs.explorer_views.outline, "local key merges in");
        assert!(
            m.prefs.explorer_views.folders,
            "untouched keys keep defaults"
        );
        assert_eq!(
            m.prefs.host_accents.len(),
            1,
            "arrays replace wholesale, they never concatenate"
        );
        assert_eq!(m.prefs.host_accents[0].pattern, "dev-*");
    }

    /// An UNRECOGNISED `files.autoSave` value must change nothing.
    ///
    /// The mapper this layer used to carry matched three known values with a
    /// `_ => {}` arm. When the table was consolidated with the importer's,
    /// any string became authoritative, so a typo in a workspace file emitted
    /// `auto_save: false` and silently turned the user's own setting off.
    ///
    /// This goes through `load_merged_from`, the real chain. The test in
    /// `import_vscode` that names this agreement calls `map_settings`
    /// directly and never reaches this layer, so it would pass with the
    /// consolidation reverted entirely and could not see this regression.
    #[test]
    fn an_unrecognised_auto_save_value_does_not_override_the_user() {
        let (_tmp, user, root) = setup();
        write(&user.join("config.json"), r#"{ "auto_save": true }"#);
        write(
            &root.join(".vscode/settings.json"),
            r#"{ "files.autoSave": "afterDelayy" }"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.prefs.auto_save,
            "a typo in a workspace file must not turn the user's auto-save off"
        );
        assert_eq!(layer_of(&m.provenance, "auto_save"), LayerKind::User);
    }

    /// And `onWindowChange`, which VS Code does define, must reach this layer
    /// as a focus-change save. The two mappers disagreed on it before they
    /// were consolidated: the importer mapped it, this layer ignored it.
    #[test]
    fn on_window_change_reaches_the_workspace_layer() {
        let (_tmp, user, root) = setup();
        write(
            &root.join(".vscode/settings.json"),
            r#"{ "files.autoSave": "onWindowChange" }"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.prefs.auto_save_on_focus_change,
            "onWindowChange saves when the window loses focus"
        );
        assert_eq!(
            layer_of(&m.provenance, "auto_save_on_focus_change"),
            LayerKind::VsCodeWorkspace
        );
    }

    #[test]
    fn vscode_settings_map_a_small_subset_and_lose_to_croft_layers() {
        let (_tmp, user, root) = setup();
        write(
            &root.join(".vscode/settings.json"),
            r#"{
  // JSONC is fine here too
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  "files.autoSave": "afterDelay",
  "editor.fontSize": 13,
}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(m.prefs.format_on_save);
        assert!(m.prefs.format_on_type);
        assert_eq!(
            layer_of(&m.provenance, "format_on_type"),
            LayerKind::VsCodeWorkspace
        );
        assert!(m.prefs.auto_save);
        assert_eq!(
            layer_of(&m.provenance, "format_on_save"),
            LayerKind::VsCodeWorkspace
        );

        // The croft workspace layer sits above the mapped subset.
        write(
            &root.join(".croft/config.json"),
            r#"{"format_on_save":false}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(!m.prefs.format_on_save);
        assert_eq!(
            layer_of(&m.provenance, "format_on_save"),
            LayerKind::Workspace
        );
    }

    #[test]
    fn a_mistyped_key_is_dropped_alone_with_a_warning() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            r#"{"theme":"nord","terminal_scrollback":"lots"}"#,
        );
        // (terminal_scrollback is a user-layer key; the type check runs on
        // user layers too.)
        let m = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(m.prefs.theme, "nord", "healthy keys survive");
        assert_eq!(m.prefs.terminal_scrollback, 0, "offender falls to default");
        assert!(
            m.warnings.iter().any(|w| w.contains("terminal_scrollback")),
            "{:?}",
            m.warnings
        );
        assert_eq!(
            layer_of(&m.provenance, "terminal_scrollback"),
            LayerKind::Default
        );
    }

    #[test]
    fn parse_errors_and_comments_behave() {
        let (_tmp, user, root) = setup();
        write(
            &user.join("config.json"),
            "{\n  // comments are tolerated\n  \"theme\": \"nord\",\n}\n",
        );
        write(&root.join(".croft/config.json"), "not json at all");
        let m = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(m.prefs.theme, "nord");
        assert!(
            m.warnings.iter().any(|w| w.contains("not valid JSON")),
            "{:?}",
            m.warnings
        );
    }

    #[test]
    fn missing_files_merge_to_defaults_and_chain_lists_every_candidate() {
        let (_tmp, user, root) = setup();
        let m = load_merged_from(&user, Some(&root), "macos");
        assert_eq!(m.prefs, Prefs::default());
        assert_eq!(m.chain.len(), 6, "all six layer files are watch candidates");
        assert!(m.warnings.is_empty());
        // Without a workspace only the three user layers are in play.
        let m = load_merged_from(&user, None, "macos");
        assert_eq!(m.chain.len(), 3);
    }

    /// #262: the synced layer carries the connecting machine's appearance to
    /// this one. It wins over this machine's `config.json` (the theme follows
    /// the user) and loses to `config.local.json` (a box can still pin its
    /// own), and like a workspace layer it can set no trust state: a synced
    /// file naming MCP consent is refused with a warning, not merged.
    #[test]
    fn the_synced_layer_sits_between_user_and_local_and_sets_no_trust() {
        let (_tmp, user, _root) = setup();
        std::fs::write(
            user.join("config.json"),
            r#"{ "theme": "light", "format_on_save": false, "mcp_consented": ["local-srv"] }"#,
        )
        .unwrap();
        std::fs::write(
            user.join(SYNCED_CONFIG_NAME),
            r#"{ "theme": "solarized", "format_on_save": true, "mcp_consented": ["evil"] }"#,
        )
        .unwrap();
        let m = load_merged_from(&user, None, "linux");
        assert_eq!(
            m.prefs.theme, "solarized",
            "the synced theme wins over config.json"
        );
        assert!(m.prefs.format_on_save);
        assert_eq!(layer_of(&m.provenance, "theme"), LayerKind::Synced);
        assert!(
            m.prefs.mcp_consented.contains("local-srv") && !m.prefs.mcp_consented.contains("evil"),
            "consent comes from this machine only: {:?}",
            m.prefs.mcp_consented
        );
        assert!(
            m.warnings
                .iter()
                .any(|w| w.contains("mcp_consented") && w.contains("synced")),
            "{:?}",
            m.warnings
        );
        std::fs::write(user.join("config.local.json"), r#"{ "theme": "dark" }"#).unwrap();
        let m = load_merged_from(&user, None, "linux");
        assert_eq!(
            m.prefs.theme, "dark",
            "config.local.json still pins this box"
        );
    }

    /// #262: the projection that travels keeps the appearance and editor
    /// keys of a `config.json` and nothing that says what croft trusts.
    #[test]
    fn the_synced_projection_keeps_appearance_and_drops_trust() {
        let doc: Map<String, Value> = serde_json::from_str(
            r#"{ "theme": "light", "render_whitespace": "all",
                 "mcp_consented": ["a"], "mcp_tool_fingerprints": {"a": "x"},
                 "disabled_extensions": ["b"], "host_accents": [] }"#,
        )
        .unwrap();
        let p = synced_projection(&doc).unwrap();
        let keys: Vec<&str> = p.keys().map(String::as_str).collect();
        assert_eq!(keys, ["render_whitespace", "theme"]);
        let trust_only: Map<String, Value> =
            serde_json::from_str(r#"{ "mcp_consented": ["a"] }"#).unwrap();
        assert_eq!(synced_projection(&trust_only), None, "nothing to share");
    }

    #[test]
    fn gitignore_append_is_idempotent_and_preserves_content() {
        let (_tmp, _user, root) = setup();
        ensure_workspace_local_ignored(&root).unwrap();
        ensure_workspace_local_ignored(&root).unwrap();
        let gi = std::fs::read_to_string(root.join(".croft/.gitignore")).unwrap();
        assert_eq!(gi.matches("config.local.json").count(), 1);
        // Existing entries survive an append.
        std::fs::write(root.join(".croft/.gitignore"), "scratch/\n").unwrap();
        ensure_workspace_local_ignored(&root).unwrap();
        let gi = std::fs::read_to_string(root.join(".croft/.gitignore")).unwrap();
        assert!(gi.contains("scratch/"));
        assert!(gi.contains("config.local.json"));
    }

    /// Diamond inheritance is not a cycle: two siblings extending the same
    /// base both load it, so the shared base re-applies at its later
    /// position (`b`'s inherited copy wins over `a`'s override).
    #[test]
    fn diamond_extends_loads_the_shared_base_from_both_branches() {
        let (_tmp, user, root) = setup();
        write(&user.join("common.json"), r#"{"theme":"nord"}"#);
        write(
            &user.join("a.json"),
            r#"{"extends":"./common.json","theme":"black"}"#,
        );
        write(&user.join("b.json"), r#"{"extends":"./common.json"}"#);
        write(
            &user.join("config.json"),
            r#"{"extends":["./a.json","./b.json"]}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings.is_empty(),
            "a shared base is not a cycle: {:?}",
            m.warnings
        );
        assert_eq!(
            m.prefs.theme, "nord",
            "b's inherited base merges after a's override, exactly as if \
             its keys were written inline"
        );
        // A real cycle still warns and stops.
        write(&user.join("x.json"), r#"{"extends":"./y.json"}"#);
        write(&user.join("y.json"), r#"{"extends":"./x.json"}"#);
        write(&user.join("config.json"), r#"{"extends":"./x.json"}"#);
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings.iter().any(|w| w.contains("cycle")),
            "{:?}",
            m.warnings
        );
    }

    /// Layer reads are bounded and regular-file only: an `extends` target
    /// that is a directory (or FIFO, device, …) is refused with a warning
    /// instead of blocking or ballooning startup, and so is an absurdly
    /// large file.
    #[test]
    fn non_regular_and_oversized_layer_files_are_refused() {
        let (_tmp, user, root) = setup();
        std::fs::create_dir_all(user.join("adir")).unwrap();
        write(
            &user.join("config.json"),
            r#"{"extends":"./adir","theme":"black"}"#,
        );
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings.iter().any(|w| w.contains("not a regular file")),
            "{:?}",
            m.warnings
        );
        assert_eq!(m.prefs.theme, "black", "the file's own keys still apply");

        let huge = " ".repeat(LAYER_FILE_MAX as usize + 1);
        write(&user.join("huge.json"), &huge);
        write(&user.join("config.json"), r#"{"extends":"./huge.json"}"#);
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings.iter().any(|w| w.contains("larger than")),
            "{:?}",
            m.warnings
        );
    }

    /// A present-but-broken .vscode/settings.json warns; an absent one is
    /// silent (absent layers are the normal case).
    #[test]
    fn a_malformed_vscode_settings_file_warns_instead_of_vanishing() {
        let (_tmp, user, root) = setup();
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(m.warnings.is_empty(), "{:?}", m.warnings);
        write(&root.join(".vscode/settings.json"), "{ definitely not json");
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings
                .iter()
                .any(|w| w.contains("settings.json") && w.contains("not valid JSON")),
            "{:?}",
            m.warnings
        );
        write(&root.join(".vscode/settings.json"), "[1,2,3]");
        let m = load_merged_from(&user, Some(&root), "macos");
        assert!(
            m.warnings.iter().any(|w| w.contains("JSON object")),
            "{:?}",
            m.warnings
        );
    }

    /// Repo-controlled symlinks must not redirect the gitignore write into
    /// the user's own files (`.croft/.gitignore → ~/.config/croft/…`).
    #[cfg(unix)]
    #[test]
    fn the_gitignore_write_refuses_symlinked_components() {
        let (tmp, _user, root) = setup();
        let victim = tmp.path().join("victim.json");
        std::fs::write(&victim, "{\"precious\": true}\n").unwrap();
        std::fs::create_dir_all(root.join(".croft")).unwrap();
        std::os::unix::fs::symlink(&victim, root.join(".croft/.gitignore")).unwrap();
        let err = ensure_workspace_local_ignored(&root).unwrap_err();
        assert!(err.to_string().contains("symlink"), "{err}");
        assert_eq!(
            std::fs::read_to_string(&victim).unwrap(),
            "{\"precious\": true}\n",
            "the symlink target must be untouched"
        );

        // A symlinked .croft directory is refused the same way.
        let root2 = tmp.path().join("repo2");
        std::fs::create_dir_all(&root2).unwrap();
        let elsewhere = tmp.path().join("elsewhere");
        std::fs::create_dir_all(&elsewhere).unwrap();
        std::os::unix::fs::symlink(&elsewhere, root2.join(".croft")).unwrap();
        let err = ensure_workspace_local_ignored(&root2).unwrap_err();
        assert!(err.to_string().contains("symlink"), "{err}");
    }
}