croft-software 0.2.132

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
//! The workspace's root-folder set (multi-root Phase 1a, #143).
//!
//! croft historically held ONE workspace root as a bare `PathBuf` threaded
//! through every subsystem. Multi-root workspaces (VS Code's ordered
//! "workspace folders") need the set to be a first-class value with two
//! distinct questions answered explicitly:
//!
//! - [`WorkspaceRoots::primary`] — the FIRST root: the launch identity.
//!   Session sockets, the collab relay, pair records, and the window title
//!   stay keyed on it (the drop-relay precedent in `remote.rs`: identity
//!   follows the launch argument, never the mutable folder set).
//! - [`WorkspaceRoots::owning_root`] — which root contains a given file:
//!   the longest-prefix match, the base every per-root subsystem (watcher,
//!   git worker, Cmd+P index, label rule) resolves against once more than
//!   one root exists.
//!
//! The set is never empty: croft always opens SOMETHING, and "no folder"
//! has no meaning anywhere in the app, so the type makes the invariant
//! unrepresentable instead of sprinkling `Option` through ~40 call sites.

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

/// An ordered, never-empty set of workspace root folders. Order is the
/// user's: the first entry is the primary root, later entries render (and
/// resolve) in the order they were added.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceRoots {
    roots: Vec<PathBuf>,
}

impl WorkspaceRoots {
    /// The single-root workspace every croft session starts as.
    pub fn single(root: PathBuf) -> Self {
        Self { roots: vec![root] }
    }

    /// The first root: the workspace's launch identity, and — while the
    /// set holds one entry — exactly what `workspace_root` meant before
    /// this type existed.
    pub fn primary(&self) -> &Path {
        &self.roots[0]
    }

    /// The root that owns `path`, by LONGEST prefix match — with nested
    /// roots (a repo and a crate inside it both added), the deeper root
    /// wins, matching VS Code's resolution for overlapping folders. `None`
    /// for a path outside every root (out-of-root files keep their
    /// existing behavior: absolute-path display, no per-root features).
    pub fn owning_root(&self, path: &Path) -> Option<&Path> {
        self.roots
            .iter()
            .filter(|r| path.starts_with(r))
            .max_by_key(|r| r.components().count())
            .map(PathBuf::as_path)
    }

    /// Replace the whole set with one root: what a single-root re-root
    /// (Make Root, the zoxide jump, post-clone) means today. Once
    /// add/remove-folder exists this stays the semantic for those
    /// gestures — they change what the window IS, not the folder list.
    pub fn replace_primary(&mut self, root: PathBuf) {
        self.roots = vec![root];
    }

    /// Append `root` to the folder set (Add Folder to Workspace, #147).
    /// A root already present is a no-op; returns whether the set grew.
    pub fn add(&mut self, root: PathBuf) -> bool {
        if self.roots.contains(&root) {
            return false;
        }
        self.roots.push(root);
        true
    }

    /// Drop `root` from the set (Remove Folder from Workspace, #147).
    /// The PRIMARY root is refused — it is the launch identity everything
    /// session-shaped is keyed on; changing it is `replace_primary`'s
    /// job (a re-root), never a removal. Returns whether the set shrank.
    pub fn remove(&mut self, root: &Path) -> bool {
        if self.primary() == root {
            return false;
        }
        let before = self.roots.len();
        self.roots.retain(|r| r != root);
        self.roots.len() < before
    }

    /// Every root in user order; the first is always the primary.
    pub fn iter(&self) -> impl Iterator<Item = &Path> {
        self.roots.iter().map(PathBuf::as_path)
    }

    /// More than one folder: the point where the multi-root label rule
    /// (root-name prefixes) and per-root fan-outs engage.
    pub fn is_multi(&self) -> bool {
        self.roots.len() > 1
    }
}

/// Display labels for a root set, disambiguated: the folder name alone
/// when unique; colliding names gain their parent (`api (work)` vs
/// `api (archive)`), and a still-colliding pair falls back to the full
/// path — so Quick Open / search prefixes never render two different
/// roots identically (#148 review).
pub fn root_display_labels(roots: &[PathBuf]) -> Vec<String> {
    let names: Vec<String> = roots
        .iter()
        .map(|r| {
            r.file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| r.display().to_string())
        })
        .collect();
    names
        .iter()
        .enumerate()
        .map(|(i, name)| {
            if names.iter().filter(|n| *n == name).count() == 1 {
                return name.clone();
            }
            let with_parent = |idx: usize| {
                roots[idx]
                    .parent()
                    .and_then(|p| p.file_name())
                    .map(|s| format!("{} ({})", names[idx], s.to_string_lossy()))
            };
            let mine = with_parent(i);
            let unique = mine.as_ref().is_some_and(|label| {
                names
                    .iter()
                    .enumerate()
                    .filter(|(j, n)| *j != i && *n == name)
                    .all(|(j, _)| with_parent(j).as_ref() != Some(label))
            });
            match mine {
                Some(label) if unique => label,
                _ => roots[i].display().to_string(),
            }
        })
        .collect()
}

/// The persisted folder-set store (#153): `~/.config/croft/
/// workspace_folders.json`, a map from the PRIMARY root's display path to
/// its secondary folders — the `terminal_session.rs` model exactly. An
/// empty list prunes its key, so plain single-folder workspaces never
/// grow the file.
pub fn folders_store_path() -> PathBuf {
    crate::paths::config_dir().join("workspace_folders.json")
}

/// Load the whole map for READING: a missing file is an empty map (the
/// normal first-run state); any other failure also reads empty, since a
/// read-only consumer can do nothing better.
pub fn load_folders(path: &Path) -> std::collections::HashMap<String, Vec<PathBuf>> {
    load_folders_checked(path).unwrap_or_default()
}

/// Load for WRITING: a missing file is `Ok(empty)`, but an unreadable or
/// unparsable one is an error — the read-modify-write in
/// [`save_folders_for_root`] must never treat a corrupt store as empty
/// and silently replace every other workspace's saved arrangement with
/// just the current one (#156 review).
fn load_folders_checked(
    path: &Path,
) -> Result<std::collections::HashMap<String, Vec<PathBuf>>, String> {
    let raw = match std::fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Default::default()),
        Err(e) => return Err(format!("read {}: {e}", path.display())),
    };
    serde_json::from_str(&raw).map_err(|e| format!("parse {}: {e}", path.display()))
}

/// Read-modify-write one primary root's secondary-folder list; an empty
/// list removes the key. Runs under [`update_json_store`]'s exclusive
/// lock: refuses a store it cannot parse and writes atomically.
pub fn save_folders_for_root(
    path: &Path,
    primary: &str,
    folders: Vec<PathBuf>,
) -> Result<(), String> {
    update_json_store::<Vec<PathBuf>, _>(path, |map| {
        if folders.is_empty() {
            map.remove(primary);
        } else {
            map.insert(primary.to_string(), folders.clone());
        }
    })
}

/// The shared read-modify-write for croft's per-workspace JSON stores
/// (`workspace_folders.json`, `terminal_sessions.json`): the whole
/// load→mutate→rename transaction holds an exclusive lock on a sibling
/// `.lock` file, so two croft windows saving concurrently serialize
/// instead of overwriting each other's keys (#158 review); the write
/// lands through a per-process-unique temp file renamed into place; a
/// store that exists but cannot be read or parsed refuses the update
/// and keeps its bytes, while a missing store is the normal first run.
pub(crate) fn update_json_store<V, F>(path: &Path, mutate: F) -> Result<(), String>
where
    V: serde::Serialize + serde::de::DeserializeOwned,
    F: FnOnce(&mut std::collections::HashMap<String, V>),
{
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
    }
    let lock_path = path.with_extension("lock");
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(&lock_path)
        .map_err(|e| format!("open {}: {e}", lock_path.display()))?;
    lock.lock()
        .map_err(|e| format!("lock {}: {e}", lock_path.display()))?;
    // Held to end of scope; unlock on drop covers every early return.
    let mut map: std::collections::HashMap<String, V> = match std::fs::read_to_string(path) {
        Ok(raw) => {
            serde_json::from_str(&raw).map_err(|e| format!("parse {}: {e}", path.display()))?
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Default::default(),
        Err(e) => return Err(format!("read {}: {e}", path.display())),
    };
    mutate(&mut map);
    let json = serde_json::to_string_pretty(&map).map_err(|e| e.to_string())?;
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let tmp = path.with_extension(format!(
        "tmp.{}.{}",
        std::process::id(),
        SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    // Owner-only: these stores hold per-workspace state, the terminal one a
    // transcript of each pane's last lines, and a plain write left them at
    // the umask's 0644 for any other user to read.
    let write = || -> std::io::Result<()> {
        use std::io::Write;
        // Created fresh (O_EXCL), never opened through a symlink someone
        // planted at the temp name.
        let _ = std::fs::remove_file(&tmp);
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts.open(&tmp)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
        }
        f.write_all(json.as_bytes())
    };
    write().map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        format!("write {}: {e}", tmp.display())
    })?;
    std::fs::rename(&tmp, path).map_err(|e| format!("rename {}: {e}", path.display()))
}

/// Parse a VS Code-compatible `.code-workspace` file (#163): tolerant of
/// `//` comments (the keybindings.json treatment), `folders[].path`
/// resolved against the file's directory, `name` and `settings`/`launch`/
/// `tasks` sections ignored (croft's settings are global). Returns the
/// resolved folder list in file order; empty folders is an error — a
/// workspace names at least one folder.
pub fn parse_workspace_file(path: &Path) -> Result<Vec<PathBuf>, String> {
    let raw = std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
    // `crate::jsonc::strip_jsonc` walks CHARS. The copy that used to live
    // here walked BYTES and rebuilt every multi-byte character as mojibake,
    // so a workspace folder named "Caf\u{e9} Noir" arrived as "Café Noir"
    // with no error anywhere: the JSON still parsed (#396).
    //
    // The two treat comments, trailing commas and string literals alike, so
    // the swap changes what happens to non-ASCII input and nothing else.
    let stripped = crate::jsonc::strip_jsonc(&raw);
    let v: serde_json::Value =
        serde_json::from_str(&stripped).map_err(|e| format!("parse {}: {e}", path.display()))?;
    let base = path.parent().unwrap_or_else(|| Path::new("."));
    let folders = v
        .get("folders")
        .and_then(|f| f.as_array())
        .ok_or_else(|| format!("{}: no folders array", path.display()))?;
    let mut out = Vec::new();
    for f in folders {
        // An entry without a string `path` is a malformed FILE, not a
        // skippable row: silently dropping it would open a partial
        // workspace that looks complete (#164 review).
        let p = f
            .get("path")
            .and_then(|p| p.as_str())
            .ok_or_else(|| format!("{}: folder entry without a path", path.display()))?;
        out.push(resolve_folder(base, p));
    }
    if out.is_empty() {
        return Err(format!("{}: no folders", path.display()));
    }
    Ok(out)
}

/// A `folders[].path` as it opens: against the workspace file's directory
/// `base` unless absolute, canonicalised when it exists.
fn resolve_folder(base: &Path, p: &str) -> PathBuf {
    let p = Path::new(p);
    let abs = if p.is_absolute() {
        p.to_path_buf()
    } else {
        base.join(p)
    };
    abs.canonicalize().unwrap_or(abs)
}

/// Write the folder set as a `.code-workspace` (#163), or update the one
/// already at `path`, as [`workspace_file_update`] says. A file that
/// already lists exactly these folders is not touched.
pub fn write_workspace_file(path: &Path, folders: &[PathBuf]) -> Result<(), String> {
    let Some(text) = workspace_file_update(path, folders)? else {
        return Ok(());
    };
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
    }
    std::fs::write(path, text).map_err(|e| format!("write {}: {e}", path.display()))
}

/// The text that makes the `.code-workspace` at `path` list `folders`, or
/// `None` when it already does.
///
/// A new file names each folder relative to the file's directory where
/// possible (VS Code's recommendation, so the file survives being moved
/// with its folders), absolute otherwise.
///
/// An existing file is usually a team's committed one (#1012), so only its
/// `folders` array changes, edited in place by [`crate::jsonc_edit`]: its
/// settings, launch and task configs, recommended extensions and comments
/// stay as written, and a folder it already lists keeps its entry, `name`
/// and path spelling included, and its place: new folders go after the
/// listed ones, whatever order `folders` has. Rebuilt from scratch, the file lost all of
/// that. A file that is not a JSONC object, or cannot be edited in place,
/// is an error rather than replaced.
pub fn workspace_file_update(path: &Path, folders: &[PathBuf]) -> Result<Option<String>, String> {
    use serde_json::Value;
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => Some(text),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(format!("read {}: {e}", path.display())),
    };
    let left = |why: &str| format!("{} {why}; it was left as it is", path.display());
    let mut doc = match &existing {
        Some(text) => serde_json::from_str::<Value>(&crate::jsonc::strip_jsonc(text))
            .ok()
            .filter(Value::is_object)
            .ok_or_else(|| left("is not a workspace file"))?,
        None => serde_json::json!({}),
    };
    let base = path.parent().unwrap_or_else(|| Path::new("."));
    let base_canon = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    let listed = doc
        .get("folders")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let want: Vec<PathBuf> = folders
        .iter()
        .map(|f| f.canonicalize().unwrap_or_else(|_| f.clone()))
        .collect();
    let names = |e: &Value, w: &Path| {
        e.get("path")
            .and_then(Value::as_str)
            .is_some_and(|p| resolve_folder(base, p) == w)
    };
    // Entries the file already has keep its order, and new folders follow
    // them: the array editor keeps the text only of entries left in place,
    // so one moved would lose the comments inside it.
    let mut placed = vec![false; want.len()];
    let mut entries = Vec::new();
    for e in &listed {
        if let Some(i) = want.iter().position(|w| names(e, w))
            && !placed[i]
        {
            placed[i] = true;
            entries.push(e.clone());
        }
    }
    for (f, _) in folders.iter().zip(&placed).filter(|(_, placed)| !**placed) {
        entries.push(serde_json::json!({ "path": relative_to_base(base, &base_canon, f) }));
    }
    doc["folders"] = Value::Array(entries);
    let Some(text) = existing else {
        return serde_json::to_string_pretty(&doc)
            .map(Some)
            .map_err(|e| e.to_string());
    };
    let updated =
        crate::jsonc_edit::update(&text, &doc).ok_or_else(|| left("cannot be edited in place"))?;
    Ok((updated != text).then_some(updated))
}

/// One folder's entry for the workspace file: relative to the file's own
/// directory when the two really are related, absolute when they are not.
///
/// Tries the caller's spelling first, so a folder the user deliberately
/// added through a symlink (`~/work` → `~/projects/alpha`) is persisted as
/// they named it — this file is shareable, and resolving the link would
/// bake in a target the user never typed and cannot recover from the file.
/// Only when that spelling shares no useful prefix does it retry through
/// canonical forms, which is what rescues the case where the two name one
/// directory differently (macOS hands croft `/var/…` for `/private/var/…`).
/// A folder that does not exist on disk cannot be canonicalised and simply
/// keeps the first answer.
fn relative_to_base(base: &Path, base_canon: &Path, target: &Path) -> String {
    let direct = relative_or_absolute(base, target);
    let target_canon = target.canonicalize().ok();
    if !Path::new(&direct).is_absolute() {
        // A `..` walk is resolved by the OS AFTER following any symlink in
        // `base`: from `~/link/ws` (link -> /data/x), `../../other` opens
        // `/data/other`, not `~/other`. Keep the spelling only when it
        // reopens the same directory; otherwise save the folder absolute.
        let reopens = match &target_canon {
            Some(want) => base.join(&direct).canonicalize().ok().as_ref() == Some(want),
            // A folder not on disk cannot be checked; keep its spelling.
            None => true,
        };
        return if reopens {
            direct
        } else {
            target.display().to_string()
        };
    }
    let Some(target_canon) = target_canon else {
        return direct;
    };
    let via_canon = relative_or_absolute(base_canon, &target_canon);
    if Path::new(&via_canon).is_absolute() {
        // Genuinely unrelated (different mount points): keep the caller's
        // spelling rather than swapping in a resolved one for no gain.
        return direct;
    }
    via_canon
}

/// `target` relative to `base` with `..` steps where they help (the
/// file's own directory becomes `.`), or the absolute path when the two
/// share no useful prefix (different mount points, or a walk that would
/// be all `..`): VS Code's recommendation is relative folders so a
/// workspace file survives moving with its folders.
fn relative_or_absolute(base: &Path, target: &Path) -> String {
    let base: Vec<_> = base.components().collect();
    let tgt: Vec<_> = target.components().collect();
    let common = base
        .iter()
        .zip(tgt.iter())
        .take_while(|(a, b)| a == b)
        .count();
    if common <= 1 {
        // Only the root (or nothing) shared: relative would be noise.
        return target.display().to_string();
    }
    let ups = base.len() - common;
    let mut out = PathBuf::new();
    for _ in 0..ups {
        out.push("..");
    }
    for c in &tgt[common..] {
        out.push(c.as_os_str());
    }
    if out.as_os_str().is_empty() {
        return String::from(".");
    }
    out.display().to_string()
}

/// True when `path` names a VS Code workspace file.
pub fn is_workspace_file(path: &Path) -> bool {
    path.extension().is_some_and(|e| e == "code-workspace")
}

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

    #[test]
    fn json_stores_are_written_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("store.json");
        std::fs::write(&path, "{}").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
        update_json_store::<String, _>(&path, |m| {
            m.insert("k".into(), "v".into());
        })
        .unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600);
    }

    #[cfg(unix)]
    #[test]
    fn a_relative_folder_is_not_saved_through_a_symlinked_base() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().canonicalize().unwrap();
        std::fs::create_dir_all(home.join("data/x/ws")).unwrap();
        std::fs::create_dir_all(home.join("other")).unwrap();
        std::os::unix::fs::symlink(home.join("data/x"), home.join("link")).unwrap();
        let base = home.join("link/ws");
        let saved = relative_to_base(&base, &base.canonicalize().unwrap(), &home.join("other"));
        let reopened = base.join(&saved).canonicalize().unwrap();
        assert_eq!(reopened, home.join("other"), "saved as {saved}");
    }

    #[test]
    fn a_single_root_set_answers_primary_with_it() {
        let ws = WorkspaceRoots::single(PathBuf::from("/w/a"));
        assert_eq!(ws.primary(), Path::new("/w/a"));
        assert_eq!(ws.roots, vec![PathBuf::from("/w/a")]);
    }

    #[test]
    fn owning_root_takes_the_longest_prefix_and_refuses_outside_paths() {
        let mut ws = WorkspaceRoots::single(PathBuf::from("/w/repo"));
        ws.roots.push(PathBuf::from("/w/repo/crates/foo"));
        assert_eq!(
            ws.owning_root(Path::new("/w/repo/crates/foo/src/lib.rs")),
            Some(Path::new("/w/repo/crates/foo")),
            "with nested roots the DEEPER root owns the file"
        );
        assert_eq!(
            ws.owning_root(Path::new("/w/repo/README.md")),
            Some(Path::new("/w/repo")),
        );
        assert_eq!(
            ws.owning_root(Path::new("/elsewhere/x.rs")),
            None,
            "a path outside every root belongs to none"
        );
        // Prefix matching is component-wise, never textual: /w/repo2 is
        // not inside /w/repo.
        assert_eq!(ws.owning_root(Path::new("/w/repo2/x.rs")), None);
    }

    #[test]
    fn add_grows_the_set_once_and_remove_refuses_the_primary() {
        let mut ws = WorkspaceRoots::single(PathBuf::from("/w/a"));
        assert!(ws.add(PathBuf::from("/w/b")), "a new folder grows the set");
        assert!(!ws.add(PathBuf::from("/w/b")), "adding it again is a no-op");
        assert!(ws.is_multi());
        assert_eq!(
            ws.iter().collect::<Vec<_>>(),
            vec![Path::new("/w/a"), Path::new("/w/b")]
        );
        assert!(
            !ws.remove(Path::new("/w/a")),
            "the primary root is the launch identity; removal is refused"
        );
        assert!(ws.remove(Path::new("/w/b")), "a secondary root removes");
        assert!(!ws.is_multi());
        assert_eq!(ws.primary(), Path::new("/w/a"));
    }

    /// A symlink the USER chose is theirs to keep. The file is shareable,
    /// so resolving `~/work` into `~/projects/alpha` would bake in a target
    /// they never typed and cannot recover from the file. Only a spelling
    /// that would otherwise go absolute gets retried through canonical
    /// forms.
    #[test]
    fn a_deliberate_folder_symlink_is_written_as_the_user_named_it() {
        let tmp = tempfile::tempdir().unwrap();
        let real = tmp.path().canonicalize().unwrap();
        let alpha = real.join("alpha");
        std::fs::create_dir(&alpha).unwrap();
        let work = real.join("work");
        std::os::unix::fs::symlink(&alpha, &work).unwrap();

        let file = real.join("proj.code-workspace");
        write_workspace_file(&file, std::slice::from_ref(&work)).unwrap();
        let raw = std::fs::read_to_string(&file).unwrap();
        assert!(
            raw.contains("\"work\""),
            "the user's own spelling is persisted, not the link target: {raw}"
        );
        assert!(
            !raw.contains("\"alpha\""),
            "the symlink is not resolved away: {raw}"
        );
    }

    /// A folder that is not on disk cannot be canonicalised. It must still
    /// relativise off the caller's spelling rather than falling back to an
    /// absolute path — the fix must not depend on the filesystem.
    #[test]
    fn a_missing_folder_still_relativises() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().canonicalize().unwrap();
        let file = base.join("proj.code-workspace");
        write_workspace_file(&file, &[base.join("ghost")]).unwrap();
        let raw = std::fs::read_to_string(&file).unwrap();
        assert!(
            raw.contains("\"ghost\""),
            "a folder that does not exist yet still writes relative: {raw}"
        );
    }

    /// The written entry must RESOLVE to the right directory, not merely
    /// look relative — including when the walk climbs out through a symlink
    /// with `..`, where a lexical reading and the filesystem's disagree.
    /// `parse_workspace_file` joins onto the file's own directory and then
    /// canonicalises, so the OS resolves `..` after traversing the link,
    /// which is what makes the round trip safe.
    #[test]
    fn a_relative_entry_resolves_through_a_symlinked_walk() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().canonicalize().unwrap();
        let deep = root.join("deep");
        std::fs::create_dir_all(deep.join("real")).unwrap();
        // `shallow` reaches `deep/real` from a different depth.
        let shallow = root.join("shallow");
        std::os::unix::fs::symlink(deep.join("real"), &shallow).unwrap();
        // Two same-named directories: the true target beside the link's
        // resolved location, and a decoy beside the link itself. A lexical
        // `..` would land on the decoy.
        std::fs::create_dir(deep.join("sibling")).unwrap();
        std::fs::write(deep.join("sibling").join("REAL"), "x").unwrap();
        std::fs::create_dir(root.join("sibling")).unwrap();
        std::fs::write(root.join("sibling").join("DECOY"), "x").unwrap();

        let file = shallow.join("w.code-workspace");
        write_workspace_file(&file, &[shallow.join("..").join("sibling")]).unwrap();
        let parsed = parse_workspace_file(&file).unwrap();
        assert!(
            parsed[0].join("REAL").exists(),
            "the entry resolves to the directory beside the link's TARGET: {parsed:?}"
        );
        assert!(
            !parsed[0].join("DECOY").exists(),
            "not the same-named one beside the link itself: {parsed:?}"
        );
    }

    /// A folder reached through a symlink must still relativise. macOS
    /// hands croft `/var/...` for a `/private/var/...` directory (and any
    /// symlinked home does the same), so canonicalising only the base left
    /// the two sharing just the root component — `relative_or_absolute`
    /// then wrote an ABSOLUTE path and the workspace file stopped being
    /// portable, which is the one thing it promises.
    #[test]
    fn a_symlinked_folder_still_writes_relative() {
        let tmp = tempfile::tempdir().unwrap();
        let real = tmp.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let alpha = real.join("alpha");
        std::fs::create_dir(&alpha).unwrap();
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        // The caller passes the path it holds — through the symlink, and
        // uncanonicalised, exactly as the primary workspace root arrives.
        let file = link.join("proj.code-workspace");
        write_workspace_file(&file, &[link.join("alpha")]).unwrap();
        let raw = std::fs::read_to_string(&file).unwrap();
        assert!(
            raw.contains("\"alpha\""),
            "a symlinked folder relativises like any other: {raw}"
        );
        assert!(
            !raw.contains("/alpha\""),
            "and is not written absolute: {raw}"
        );
        assert_eq!(
            parse_workspace_file(&file).unwrap(),
            vec![alpha.canonicalize().unwrap()],
            "and round-trips back to the real directory"
        );
    }

    /// A `.code-workspace` path carrying non-ASCII must survive the JSONC
    /// strip (#396).
    ///
    /// The stripper that used to live in this module walked BYTES and treated
    /// each as a char, so every multi-byte character was rebuilt as mojibake.
    /// Nothing errored: the JSON still parsed and the folder simply arrived
    /// under a mangled name.
    #[test]
    fn a_non_ascii_folder_path_survives_the_jsonc_strip() {
        let tmp = tempfile::tempdir().unwrap();
        // A directory whose name needs more than one byte per character, in
        // three scripts, since the corruption is per byte.
        for name in [
            "caf\u{e9}",
            "\u{4e2d}\u{6587}",
            "\u{444}\u{430}\u{439}\u{43b}",
        ] {
            std::fs::create_dir_all(tmp.path().join(name)).unwrap();
        }
        let ws = tmp.path().join("accents.code-workspace");
        std::fs::write(
            &ws,
            "{\n  // a comment, so the stripper definitely runs\n  \"folders\": [\n                 { \"path\": \"caf\u{e9}\" },\n    { \"path\": \"\u{4e2d}\u{6587}\" },\n                 { \"path\": \"\u{444}\u{430}\u{439}\u{43b}\" },\n  ],\n}\n",
        )
        .unwrap();

        let roots = parse_workspace_file(&ws).expect("a commented file with accents parses");
        let names: Vec<String> = roots
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            names,
            vec![
                "caf\u{e9}",
                "\u{4e2d}\u{6587}",
                "\u{444}\u{430}\u{439}\u{43b}"
            ],
            "the folder names must arrive intact rather than as mojibake"
        );
    }

    #[test]
    fn workspace_file_round_trips_with_relative_paths_and_tolerates_comments() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("alpha");
        let b = tmp.path().join("beta");
        std::fs::create_dir(&a).unwrap();
        std::fs::create_dir(&b).unwrap();
        let file = tmp.path().join("proj.code-workspace");
        write_workspace_file(&file, &[a.clone(), b.clone()]).unwrap();
        let raw = std::fs::read_to_string(&file).unwrap();
        assert!(
            raw.contains("\"alpha\"") && raw.contains("\"beta\""),
            "folders under the file's dir are written RELATIVE: {raw}"
        );
        let parsed = parse_workspace_file(&file).unwrap();
        assert_eq!(
            parsed,
            vec![a.canonicalize().unwrap(), b.canonicalize().unwrap()]
        );

        // A file INSIDE a folder still relativizes: itself as `.`, the
        // sibling through `..` — VS Code's shareable shape.
        let inside = a.join("self.code-workspace");
        write_workspace_file(
            &inside,
            &[a.canonicalize().unwrap(), b.canonicalize().unwrap()],
        )
        .unwrap();
        let raw2 = std::fs::read_to_string(&inside).unwrap();
        assert!(raw2.contains("\".\""), "own dir is '.': {raw2}");
        assert!(raw2.contains("../beta"), "sibling uses ..: {raw2}");
        assert_eq!(
            parse_workspace_file(&inside).unwrap(),
            vec![a.canonicalize().unwrap(), b.canonicalize().unwrap()]
        );

        // Comments and absolute paths parse too; order is preserved.
        let commented = tmp.path().join("c.code-workspace");
        std::fs::write(
            &commented,
            format!(
                "{{\n  // the arrangement\n  \"folders\": [\n    {{ \"path\": \"{}\" }},\n    {{ \"path\": \"alpha\" }}\n  ]\n}}\n",
                b.display()
            ),
        )
        .unwrap();
        let parsed = parse_workspace_file(&commented).unwrap();
        assert_eq!(
            parsed,
            vec![b.canonicalize().unwrap(), a.canonicalize().unwrap()]
        );

        // Malformed: a real error, never an empty default.
        let bad = tmp.path().join("bad.code-workspace");
        std::fs::write(&bad, "{ nope").unwrap();
        assert!(parse_workspace_file(&bad).is_err());
        assert!(is_workspace_file(&bad));
        assert!(!is_workspace_file(Path::new("x.rs")));

        // VS Code JSONC: block comments and trailing commas parse (#164
        // review), and an entry without a string path REJECTS the file
        // rather than opening a partial workspace.
        let jsonc = tmp.path().join("jsonc.code-workspace");
        std::fs::write(
            &jsonc,
            "{\n  /* block\n     comment */\n  \"folders\": [\n    { \"path\": \"alpha\" }, // tail\n    { \"path\": \"beta\" },\n  ],\n}\n",
        )
        .unwrap();
        assert_eq!(
            parse_workspace_file(&jsonc).unwrap(),
            vec![a.canonicalize().unwrap(), b.canonicalize().unwrap()]
        );
        let mixed = tmp.path().join("mixed.code-workspace");
        std::fs::write(
            &mixed,
            "{ \"folders\": [ { \"path\": \"alpha\" }, { \"name\": \"nope\" } ] }",
        )
        .unwrap();
        assert!(
            parse_workspace_file(&mixed).is_err(),
            "an entry without a path rejects the whole file"
        );
    }

    /// The issue's committed team file, with the comments a team leaves.
    const TEAM_FILE: &str = r#"{
  // Opened by the whole team: keep folder names short.
  "folders": [
    { "path": "." },
    // vendored helpers
    { "path": "../wsx_lib", "name": "shared lib" }
  ],
  "settings": {
    "python.defaultInterpreterPath": ".venv/bin/python", // the project venv
    "editor.formatOnSave": true
  },
  /* F5 runs the app */
  "launch": { "version": "0.2.0", "configurations": [ { "name": "Run app", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/app.py" } ] },
  "extensions": { "recommendations": ["ms-python.python"] }
}
"#;

    /// `wsx` holding the team file, beside `wsx_lib` and `extra`.
    fn team_workspace() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().canonicalize().unwrap();
        for d in ["wsx", "wsx_lib", "extra"] {
            std::fs::create_dir(root.join(d)).unwrap();
        }
        let file = root.join("wsx/wsx.code-workspace");
        std::fs::write(&file, TEAM_FILE).unwrap();
        (tmp, root, file)
    }

    /// #1012: saving the folders a team file already lists leaves it byte
    /// for byte; it was rewritten as `{"folders": [...]}` alone, deleting
    /// the settings, launch configs, extensions, names and comments.
    #[test]
    fn saving_the_same_folders_leaves_a_team_workspace_file_as_it_is() {
        let (_tmp, root, file) = team_workspace();
        let folders = [root.join("wsx"), root.join("wsx_lib")];
        assert_eq!(workspace_file_update(&file, &folders), Ok(None));
        write_workspace_file(&file, &folders).unwrap();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), TEAM_FILE);
    }

    /// The folders in another order move no entry: a moved one was
    /// rewritten from its parsed value, dropping the comments inside it.
    #[test]
    fn saving_the_folders_in_another_order_leaves_the_file_as_it_is() {
        let (_tmp, root, file) = team_workspace();
        let folders = [root.join("wsx_lib"), root.join("wsx")];
        assert_eq!(workspace_file_update(&file, &folders), Ok(None));
        let with_extra = [root.join("extra"), root.join("wsx_lib"), root.join("wsx")];
        write_workspace_file(&file, &with_extra).unwrap();
        let out = std::fs::read_to_string(&file).unwrap();
        assert!(
            out.starts_with(&TEAM_FILE[..TEAM_FILE.find("\"shared lib\" }").unwrap()]),
            "{out}"
        );
        assert!(out.contains("\"path\": \"../extra\""), "{out}");
    }

    /// #1012: an added folder changes only `folders`, and a removed one
    /// takes only its own entry; the rest of the file, comments included,
    /// stays as written.
    #[test]
    fn a_changed_folder_set_rewrites_only_the_folders_of_a_team_file() {
        let (_tmp, root, file) = team_workspace();
        let three = [root.join("wsx"), root.join("wsx_lib"), root.join("extra")];
        write_workspace_file(&file, &three).unwrap();
        let out = std::fs::read_to_string(&file).unwrap();
        assert_eq!(
            out,
            TEAM_FILE.replace(
                "\"shared lib\" }\n",
                "\"shared lib\" },\n    {\n      \"path\": \"../extra\"\n    }\n"
            )
        );
        assert_eq!(parse_workspace_file(&file).unwrap(), three);

        write_workspace_file(&file, &[root.join("wsx"), root.join("extra")]).unwrap();
        let out = std::fs::read_to_string(&file).unwrap();
        assert!(!out.contains("wsx_lib"), "{out}");
        assert!(out.contains("// the project venv"), "{out}");
        let mut want: serde_json::Value =
            serde_json::from_str(&crate::jsonc::strip_jsonc(TEAM_FILE)).unwrap();
        want["folders"] = serde_json::json!([{ "path": "." }, { "path": "../extra" }]);
        let got: serde_json::Value =
            serde_json::from_str(&crate::jsonc::strip_jsonc(&out)).unwrap();
        assert_eq!(got, want);
    }

    /// Negative (#1012): a file that is not a workspace is refused, never
    /// replaced by one.
    #[test]
    fn a_file_that_is_not_a_workspace_is_not_saved_over() {
        let (_tmp, root, _) = team_workspace();
        let notes = root.join("notes.code-workspace");
        std::fs::write(&notes, "my notes, not JSON").unwrap();
        let err = write_workspace_file(&notes, &[root.join("wsx")]).unwrap_err();
        assert!(err.contains("not a workspace file"), "{err}");
        assert_eq!(
            std::fs::read_to_string(&notes).unwrap(),
            "my notes, not JSON"
        );
    }

    #[test]
    fn concurrent_saves_serialize_instead_of_overwriting_each_other() {
        // #158 review: without the lock, two writers could each load the
        // pre-update map and the second rename would discard the first
        // writer's key.
        let tmp = tempfile::tempdir().unwrap();
        let store = tmp.path().join("folders.json");
        let handles: Vec<_> = (0..8)
            .map(|i| {
                let store = store.clone();
                std::thread::spawn(move || {
                    save_folders_for_root(
                        &store,
                        &format!("/w/root{i}"),
                        vec![PathBuf::from(format!("/w/extra{i}"))],
                    )
                    .unwrap();
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        let map = load_folders(&store);
        assert_eq!(map.len(), 8, "every writer's key survives: {map:?}");
    }

    #[test]
    fn a_corrupt_folders_store_is_refused_not_replaced() {
        // #156 review: treating a corrupt store as empty and writing over
        // it silently discarded EVERY other workspace's arrangement.
        let tmp = tempfile::tempdir().unwrap();
        let store = tmp.path().join("folders.json");
        std::fs::write(&store, "{ not valid json").unwrap();
        let err = save_folders_for_root(&store, "/w/a", vec![PathBuf::from("/w/b")]);
        assert!(err.is_err(), "a corrupt store must refuse the update");
        assert_eq!(
            std::fs::read_to_string(&store).unwrap(),
            "{ not valid json",
            "the corrupt bytes stay untouched for the user to inspect"
        );
        // A read-only load degrades to empty rather than erroring.
        assert!(load_folders(&store).is_empty());
        // And a MISSING file is the normal first-run state: the save
        // proceeds and round-trips.
        let fresh = tmp.path().join("fresh.json");
        save_folders_for_root(&fresh, "/w/a", vec![PathBuf::from("/w/b")]).unwrap();
        assert_eq!(
            load_folders(&fresh).get("/w/a"),
            Some(&vec![PathBuf::from("/w/b")])
        );
    }

    #[test]
    fn root_labels_disambiguate_same_named_folders() {
        let roots = vec![
            PathBuf::from("/work/api"),
            PathBuf::from("/archive/api"),
            PathBuf::from("/work/web"),
        ];
        assert_eq!(
            root_display_labels(&roots),
            vec!["api (work)", "api (archive)", "web"],
            "colliding folder names gain their parent; unique ones stay bare"
        );
        let twins = vec![PathBuf::from("/x/api"), PathBuf::from("/y/x/api")];
        let labels = root_display_labels(&twins);
        assert_ne!(
            labels[0], labels[1],
            "labels are never identical: {labels:?}"
        );
    }

    #[test]
    fn replace_primary_collapses_the_set_to_the_new_root() {
        let mut ws = WorkspaceRoots::single(PathBuf::from("/w/a"));
        ws.roots.push(PathBuf::from("/w/b"));
        ws.replace_primary(PathBuf::from("/w/c"));
        assert_eq!(ws.primary(), Path::new("/w/c"));
        assert_eq!(
            ws.roots,
            vec![PathBuf::from("/w/c")],
            "a re-root changes what the window IS"
        );
    }
}