repograph-core 0.4.0

Core library for repograph: registering, grouping, and exposing local git repositories as structured context for AI agents.
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
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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! Config model and TOML persistence.

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

use serde::{Deserialize, Serialize};

use crate::agents::AgentId;
use crate::error::RepographError;

/// On-disk file name within the config directory.
pub const CONFIG_FILE_NAME: &str = "config.toml";

/// Maximum length of a workspace name (RFC 1123 label rule).
pub const MAX_WORKSPACE_NAME_LEN: usize = 63;

/// Reserved workspace names. These collide with future filter ergonomics
/// (e.g. `--workspace all`) and are rejected at write time.
pub const RESERVED_WORKSPACE_NAMES: &[&str] = &["default", "all", "none"];

/// A registered local git repository. The `name` is the map key in
/// [`Config::repos`] — it does not appear as a field on this struct.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Repo {
    pub path: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stack: Vec<String>,
}

/// A set of in-place changes to apply to a registered repo via
/// [`Config::edit_repo`]. Every field is opt-in: `None` (or the outer `None`
/// for `description`) leaves the current value untouched.
///
/// - `new_name`: rename the entry; workspace memberships are rewritten so
///   groupings survive the rename.
/// - `description`: `Some(Some(text))` sets it, `Some(None)` clears it, `None`
///   leaves it unchanged.
/// - `stack`: `Some(vec)` replaces the stack wholesale; `None` leaves it.
/// - `path`: a pre-validated, canonicalized path; `Some(p)` replaces it.
#[derive(Debug, Default, Clone)]
pub struct RepoEdit {
    pub new_name: Option<String>,
    pub description: Option<Option<String>>,
    pub stack: Option<Vec<String>>,
    pub path: Option<PathBuf>,
}

/// A named grouping of registered repositories.
///
/// The `name` is the map key in [`Config::workspaces`] — it does not appear
/// as a field on this struct. `members` holds bare repo names (keys into
/// [`Config::repos`]) and is kept sorted on write for round-trip stability.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Workspace {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub members: Vec<String>,
}

/// Result of resolving a workspace's `members` against the repo registry:
/// `(live, dangling)`. Live entries borrow the repo's name and its
/// [`Repo`] entry; dangling entries borrow only the orphaned name.
pub type WorkspaceResolution<'a> = (Vec<(&'a String, &'a Repo)>, Vec<&'a String>);

/// The `[agents]` section of the on-disk config. Presence of this section
/// signals that `repograph init` has been run; absence triggers the first-run
/// prompt the next time an agent-consuming command runs.
///
/// `selected` preserves the order the user chose at init time so the rendered
/// config and any downstream agent prompt have stable, predictable output.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Agents {
    #[serde(default)]
    pub selected: Vec<AgentId>,
}

/// The `[settings]` section of the on-disk config. User-tunable knobs that
/// don't fit naturally under `[agents]`, `[repo.*]`, or `[workspace.*]`.
///
/// All fields are optional; absent values fall back to either an env var
/// (where one exists, e.g. `REPOGRAPH_PROJECT_ROOT` for `projects_root`) or
/// to "ask the user next time they need it" semantics.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Settings {
    /// User-declared root folder for git projects (e.g. `~/IdeaProjects`,
    /// `~/code`). When set, `repograph init`'s repo-registration step scans
    /// this directly instead of probing the filesystem for common
    /// conventions. `None` means "ask the user next time they need it" or
    /// "fall back to free-form input with autocomplete."
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub projects_root: Option<PathBuf>,
}

/// Top-level config aggregating all registered repos, workspaces, and the
/// user's agent selection.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default, rename = "repo", skip_serializing_if = "BTreeMap::is_empty")]
    repos: BTreeMap<String, Repo>,
    #[serde(
        default,
        rename = "workspace",
        skip_serializing_if = "BTreeMap::is_empty"
    )]
    workspaces: BTreeMap<String, Workspace>,
    /// User's agent toolchain selection. `None` means init has not been run;
    /// `Some(Agents { selected: vec![] })` means init was run and the user
    /// explicitly opted out of agent docs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    agents: Option<Agents>,
    /// Persistent user preferences (project root, …). Omitted from
    /// serialization when empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    settings: Option<Settings>,
}

impl Config {
    /// Read-only view of the registered repos.
    #[must_use]
    pub const fn repos(&self) -> &BTreeMap<String, Repo> {
        &self.repos
    }

    /// Read-only view of the registered workspaces.
    #[must_use]
    pub const fn workspaces(&self) -> &BTreeMap<String, Workspace> {
        &self.workspaces
    }

    /// Read-only view of the user's agent selection. Returns `None` when no
    /// `[agents]` section is present (init has not been run); `Some(_)` when
    /// init has run, even if `selected` is empty.
    #[must_use]
    pub const fn agents(&self) -> Option<&Agents> {
        self.agents.as_ref()
    }

    /// Replace the `[agents]` section with the given selection. Passing
    /// `Some(Agents { selected: vec![] })` writes a configured-but-empty
    /// section; passing `None` removes the section (and signals "not
    /// initialized" to consumers).
    pub fn set_agents(&mut self, agents: Option<Agents>) {
        self.agents = agents;
    }

    /// Read-only view of the user's persistent settings (project root,
    /// future preferences). Returns `None` when no `[settings]` section is
    /// present.
    #[must_use]
    pub const fn settings(&self) -> Option<&Settings> {
        self.settings.as_ref()
    }

    /// Replace the `[settings]` section. Pass `None` to remove the section.
    pub fn set_settings(&mut self, settings: Option<Settings>) {
        self.settings = settings;
    }

    /// Platform-default config directory: `dirs::config_dir() / "repograph"`.
    /// Returns `None` when no platform default exists (e.g. minimal envs); the
    /// binary surfaces this as a usage error guiding the user to `--config-dir`.
    #[must_use]
    pub fn default_dir() -> Option<PathBuf> {
        dirs::config_dir().map(|d| d.join("repograph"))
    }

    /// Load config from `dir/config.toml`. Missing file → empty `Config`.
    /// Malformed TOML → `RepographError::ConfigParse`.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::Io`] for filesystem failures, or
    /// [`RepographError::ConfigParse`] when the file exists but is not valid TOML.
    pub fn load(dir: &Path) -> Result<Self, RepographError> {
        let path = dir.join(CONFIG_FILE_NAME);
        match fs_err::read_to_string(&path) {
            Ok(body) => Ok(toml::from_str(&body)?),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e.into()),
        }
    }

    /// Save config atomically to `dir/config.toml`, creating `dir` if missing.
    ///
    /// Atomicity: we serialize to a sibling temp file, then `rename` to the
    /// target. A crash mid-write cannot leave the target half-written.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::ConfigWrite`] when serialization fails,
    /// [`RepographError::PermissionDenied`] when the target dir or file is not
    /// writable, or [`RepographError::Io`] for other filesystem failures.
    pub fn save(&self, dir: &Path) -> Result<(), RepographError> {
        let body = toml::to_string_pretty(self)?;
        let target = dir.join(CONFIG_FILE_NAME);

        if let Err(e) = fs_err::create_dir_all(dir) {
            return Err(map_io_to_perm(e, dir));
        }

        let tmp = dir.join(format!(".{CONFIG_FILE_NAME}.tmp"));
        if let Err(e) = fs_err::write(&tmp, body.as_bytes()) {
            return Err(map_io_to_perm(e, &tmp));
        }
        if let Err(e) = fs_err::rename(&tmp, &target) {
            return Err(map_io_to_perm(e, &target));
        }
        Ok(())
    }

    /// Register a repo, enforcing both name and path uniqueness.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::Conflict`] with `kind = "name"` when `name`
    /// is already registered, or `kind = "path"` when `repo.path` is already
    /// registered under a different name.
    pub fn add_repo(&mut self, name: String, repo: Repo) -> Result<(), RepographError> {
        if self.repos.contains_key(&name) {
            return Err(RepographError::Conflict { kind: "name", name });
        }
        if let Some((existing_name, _)) = self.repos.iter().find(|(_, r)| r.path == repo.path) {
            return Err(RepographError::Conflict {
                kind: "path",
                name: existing_name.clone(),
            });
        }
        self.repos.insert(name, repo);
        Ok(())
    }

    /// Deregister a repo by name.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] when no repo by that name is registered.
    pub fn remove_repo(&mut self, name: &str) -> Result<Repo, RepographError> {
        self.repos
            .remove(name)
            .ok_or_else(|| RepographError::NotFound {
                kind: "repo",
                name: name.to_string(),
            })
    }

    /// Update a registered repo in place, returning the resulting `(name, repo)`.
    ///
    /// Unlike a remove-then-add, this preserves workspace memberships: a rename
    /// (`edit.new_name`) rewrites every `workspace.members` entry that pointed at
    /// the old name, so groupings survive with no dangling references. All
    /// validation runs before any mutation, so an error leaves the config
    /// untouched.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] with `kind = "repo"` when `name` is
    /// not registered; [`RepographError::Conflict`] with `kind = "name"` when
    /// `new_name` collides with a different existing repo, or `kind = "path"`
    /// when `edit.path` is already registered under a different name.
    pub fn edit_repo(
        &mut self,
        name: &str,
        edit: RepoEdit,
    ) -> Result<(String, Repo), RepographError> {
        if !self.repos.contains_key(name) {
            return Err(RepographError::NotFound {
                kind: "repo",
                name: name.to_string(),
            });
        }

        // A rename to the same name is a no-op rename, not a conflict.
        let rename_to = edit
            .new_name
            .as_deref()
            .filter(|n| *n != name)
            .map(ToString::to_string);

        // Validate before mutating: target name must be free.
        if let Some(new_name) = &rename_to {
            if self.repos.contains_key(new_name) {
                return Err(RepographError::Conflict {
                    kind: "name",
                    name: new_name.clone(),
                });
            }
        }
        // Validate before mutating: a new path must not collide with another repo.
        if let Some(new_path) = &edit.path {
            if let Some((existing, _)) = self
                .repos
                .iter()
                .find(|(k, r)| k.as_str() != name && &r.path == new_path)
            {
                return Err(RepographError::Conflict {
                    kind: "path",
                    name: existing.clone(),
                });
            }
        }

        // All checks passed — apply field updates to the (possibly soon-renamed) entry.
        // Safe to unwrap-free: presence was verified above.
        let mut repo = self
            .repos
            .remove(name)
            .ok_or_else(|| RepographError::NotFound {
                kind: "repo",
                name: name.to_string(),
            })?;
        if let Some(description) = edit.description {
            repo.description = description.filter(|s| !s.is_empty());
        }
        if let Some(stack) = edit.stack {
            repo.stack = stack;
        }
        if let Some(path) = edit.path {
            repo.path = path;
        }

        let final_name = rename_to.clone().unwrap_or_else(|| name.to_string());
        self.repos.insert(final_name.clone(), repo.clone());

        // Rewrite workspace memberships on rename so groupings don't dangle.
        if let Some(new_name) = &rename_to {
            for ws in self.workspaces.values_mut() {
                let mut touched = false;
                for member in &mut ws.members {
                    if member == name {
                        member.clone_from(new_name);
                        touched = true;
                    }
                }
                if touched {
                    ws.members.sort();
                    ws.members.dedup();
                }
            }
        }

        Ok((final_name, repo))
    }

    /// Create an empty workspace under `name` with an optional description.
    ///
    /// The name must satisfy [`validate_workspace_name`]. The workspace must
    /// not already exist.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::InvalidName`] when `name` violates the
    /// naming policy, or [`RepographError::Conflict`] with `kind = "workspace"`
    /// when a workspace by that name already exists.
    pub fn create_workspace(
        &mut self,
        name: String,
        description: Option<String>,
    ) -> Result<(), RepographError> {
        validate_workspace_name(&name)?;
        if self.workspaces.contains_key(&name) {
            return Err(RepographError::Conflict {
                kind: "workspace",
                name,
            });
        }
        self.workspaces.insert(
            name,
            Workspace {
                description: description.filter(|s| !s.is_empty()),
                members: Vec::new(),
            },
        );
        Ok(())
    }

    /// Delete a workspace by name. Registered repos are untouched.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] with `kind = "workspace"` when
    /// no workspace by that name is registered.
    pub fn remove_workspace(&mut self, name: &str) -> Result<Workspace, RepographError> {
        self.workspaces
            .remove(name)
            .ok_or_else(|| RepographError::NotFound {
                kind: "workspace",
                name: name.to_string(),
            })
    }

    /// Atomically attach one or more registered repos to a workspace.
    ///
    /// All `repos` must be registered before any mutation occurs; if even one
    /// is missing, the workspace is left unchanged. Already-member repos are
    /// silently ignored. On success the `members` list is sorted and
    /// deduplicated.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] with `kind = "workspace"` when
    /// the workspace does not exist, or `kind = "repo"` (naming the first
    /// missing repo) when any input repo is not registered.
    pub fn add_members(&mut self, workspace: &str, repos: &[String]) -> Result<(), RepographError> {
        // Workspace presence first, so the error message names the right thing
        // when neither workspace nor any of the repos exists.
        if !self.workspaces.contains_key(workspace) {
            return Err(RepographError::NotFound {
                kind: "workspace",
                name: workspace.to_string(),
            });
        }
        for name in repos {
            if !self.repos.contains_key(name) {
                return Err(RepographError::NotFound {
                    kind: "repo",
                    name: name.clone(),
                });
            }
        }
        // Re-fetch as mutable; we re-emit NotFound rather than expect() so a
        // future refactor that drops the contains_key guard can't introduce a panic.
        let ws = self
            .workspaces
            .get_mut(workspace)
            .ok_or_else(|| RepographError::NotFound {
                kind: "workspace",
                name: workspace.to_string(),
            })?;
        for name in repos {
            ws.members.push(name.clone());
        }
        ws.members.sort();
        ws.members.dedup();
        Ok(())
    }

    /// Detach one or more repos from a workspace. Non-members are silently
    /// ignored. The repo registry is not modified.
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] with `kind = "workspace"` when
    /// the workspace does not exist.
    pub fn remove_members(
        &mut self,
        workspace: &str,
        repos: &[String],
    ) -> Result<(), RepographError> {
        let ws = self
            .workspaces
            .get_mut(workspace)
            .ok_or_else(|| RepographError::NotFound {
                kind: "workspace",
                name: workspace.to_string(),
            })?;
        ws.members.retain(|m| !repos.iter().any(|r| r == m));
        Ok(())
    }

    /// Walk a workspace's members and partition them into live entries
    /// (resolved against the repo registry) and dangling names (tombstoned
    /// references to repos that are no longer registered). The order in each
    /// returned vector matches the workspace's stored `members` order
    /// (alphabetical after sort-on-write).
    ///
    /// # Errors
    ///
    /// Returns [`RepographError::NotFound`] with `kind = "workspace"` when
    /// the workspace does not exist.
    pub fn resolve_workspace<'a>(
        &'a self,
        workspace: &str,
    ) -> Result<WorkspaceResolution<'a>, RepographError> {
        let ws = self
            .workspaces
            .get(workspace)
            .ok_or_else(|| RepographError::NotFound {
                kind: "workspace",
                name: workspace.to_string(),
            })?;
        let mut live = Vec::with_capacity(ws.members.len());
        let mut dangling = Vec::new();
        for name in &ws.members {
            if let Some((key, repo)) = self.repos.get_key_value(name) {
                live.push((key, repo));
            } else {
                dangling.push(name);
            }
        }
        Ok((live, dangling))
    }
}

/// Enforce the workspace naming policy: lowercase ASCII alphanumerics and
/// hyphens, must start alphanumeric, length 1..=63, and not one of the
/// reserved words.
///
/// # Errors
///
/// Returns [`RepographError::InvalidName`] with `kind = "workspace"` when the
/// name violates the policy. The `reason` text is a short, user-facing phrase.
pub fn validate_workspace_name(name: &str) -> Result<(), RepographError> {
    if name.is_empty() {
        return Err(invalid_workspace_name(name, "must not be empty"));
    }
    if name.len() > MAX_WORKSPACE_NAME_LEN {
        return Err(invalid_workspace_name(
            name,
            "must be at most 63 characters",
        ));
    }
    if RESERVED_WORKSPACE_NAMES.contains(&name) {
        return Err(invalid_workspace_name(name, "is a reserved name"));
    }
    for (i, c) in name.chars().enumerate() {
        let alnum_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
        if i == 0 {
            if !alnum_lower {
                return Err(invalid_workspace_name(
                    name,
                    "must start with a lowercase letter or digit",
                ));
            }
        } else if !alnum_lower && c != '-' {
            return Err(invalid_workspace_name(
                name,
                "must contain only lowercase letters, digits, and hyphens",
            ));
        }
    }
    Ok(())
}

fn invalid_workspace_name(name: &str, reason: &'static str) -> RepographError {
    RepographError::InvalidName {
        kind: "workspace",
        name: name.to_string(),
        reason,
    }
}

/// Map an [`std::io::Error`] to a typed permission-denied error when the kind
/// matches; otherwise pass it through as `Io`.
fn map_io_to_perm(e: std::io::Error, path: &Path) -> RepographError {
    if e.kind() == std::io::ErrorKind::PermissionDenied {
        RepographError::PermissionDenied {
            path: path.to_path_buf(),
        }
    } else {
        RepographError::Io(e)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    use super::*;
    use tempfile::TempDir;

    fn make(path: &str) -> Repo {
        Repo {
            path: PathBuf::from(path),
            description: None,
            stack: vec![],
        }
    }

    #[test]
    fn load_missing_returns_empty() {
        let tmp = TempDir::new().unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert!(cfg.repos.is_empty());
    }

    #[test]
    fn save_then_load_round_trip() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        cfg.add_repo(
            "bar".into(),
            Repo {
                path: PathBuf::from("/tmp/bar"),
                description: Some("hi".into()),
                stack: vec!["rust".into()],
            },
        )
        .unwrap();

        cfg.save(tmp.path()).unwrap();
        let loaded = Config::load(tmp.path()).unwrap();
        assert_eq!(loaded.repos.len(), 2);
        assert_eq!(
            loaded.repos.get("bar").unwrap().description.as_deref(),
            Some("hi")
        );
    }

    #[test]
    fn name_conflict_blocks_insert() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/a")).unwrap();
        let err = cfg.add_repo("foo".into(), make("/b")).unwrap_err();
        assert!(matches!(err, RepographError::Conflict { kind: "name", .. }));
        assert_eq!(cfg.repos.get("foo").unwrap().path, PathBuf::from("/a"));
    }

    #[test]
    fn path_conflict_blocks_insert() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/shared")).unwrap();
        let err = cfg.add_repo("bar".into(), make("/shared")).unwrap_err();
        assert!(matches!(err, RepographError::Conflict { kind: "path", .. }));
        assert!(!cfg.repos.contains_key("bar"));
    }

    #[test]
    fn remove_missing_returns_not_found() {
        let mut cfg = Config::default();
        let err = cfg.remove_repo("ghost").unwrap_err();
        assert!(matches!(err, RepographError::NotFound { .. }));
    }

    #[test]
    fn unknown_field_in_toml_is_tolerated() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[repo.foo]\npath = \"/tmp/foo\"\nfuture = \"yes\"\n",
        )
        .unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert!(cfg.repos.contains_key("foo"));
    }

    // --- Workspace tests ---

    #[test]
    fn validate_workspace_name_accepts_simple_lowercase() {
        assert!(validate_workspace_name("acme").is_ok());
        assert!(validate_workspace_name("acme-rebuild-2026").is_ok());
        assert!(validate_workspace_name("a").is_ok());
        assert!(validate_workspace_name("0").is_ok());
        assert!(validate_workspace_name("0acme").is_ok());
    }

    #[test]
    fn validate_workspace_name_rejects_empty() {
        let err = validate_workspace_name("").unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn validate_workspace_name_rejects_uppercase() {
        let err = validate_workspace_name("AcmeRebuild").unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
    }

    #[test]
    fn validate_workspace_name_rejects_leading_hyphen() {
        let err = validate_workspace_name("-acme").unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
    }

    #[test]
    fn validate_workspace_name_rejects_underscore() {
        let err = validate_workspace_name("ac_me").unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
    }

    #[test]
    fn validate_workspace_name_rejects_spaces() {
        let err = validate_workspace_name("ac me").unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
    }

    #[test]
    fn validate_workspace_name_rejects_overlength() {
        let name = "a".repeat(MAX_WORKSPACE_NAME_LEN + 1);
        let err = validate_workspace_name(&name).unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
    }

    #[test]
    fn validate_workspace_name_accepts_exact_max_length() {
        let name = "a".repeat(MAX_WORKSPACE_NAME_LEN);
        assert!(validate_workspace_name(&name).is_ok());
    }

    #[test]
    fn validate_workspace_name_rejects_reserved_words() {
        for reserved in RESERVED_WORKSPACE_NAMES {
            let err = validate_workspace_name(reserved).unwrap_err();
            assert!(
                matches!(err, RepographError::InvalidName { .. }),
                "reserved `{reserved}` must be rejected"
            );
        }
    }

    #[test]
    fn create_workspace_inserts_empty_entry() {
        let mut cfg = Config::default();
        cfg.create_workspace("acme".into(), None).unwrap();
        let ws = cfg.workspaces.get("acme").unwrap();
        assert!(ws.description.is_none());
        assert!(ws.members.is_empty());
    }

    #[test]
    fn create_workspace_persists_description() {
        let mut cfg = Config::default();
        cfg.create_workspace("acme".into(), Some("rebuild".into()))
            .unwrap();
        assert_eq!(
            cfg.workspaces.get("acme").unwrap().description.as_deref(),
            Some("rebuild")
        );
    }

    #[test]
    fn create_workspace_conflict_returns_conflict() {
        let mut cfg = Config::default();
        cfg.create_workspace("acme".into(), None).unwrap();
        let err = cfg.create_workspace("acme".into(), None).unwrap_err();
        assert!(matches!(
            err,
            RepographError::Conflict {
                kind: "workspace",
                ..
            }
        ));
        assert_eq!(err.exit_code(), 5);
    }

    #[test]
    fn create_workspace_invalid_name_returns_invalid_name() {
        let mut cfg = Config::default();
        let err = cfg.create_workspace("Bad Name".into(), None).unwrap_err();
        assert!(matches!(err, RepographError::InvalidName { .. }));
        assert_eq!(err.exit_code(), 2);
        assert!(cfg.workspaces.is_empty());
    }

    #[test]
    fn remove_workspace_missing_returns_not_found() {
        let mut cfg = Config::default();
        let err = cfg.remove_workspace("ghost").unwrap_err();
        assert!(matches!(
            err,
            RepographError::NotFound {
                kind: "workspace",
                ..
            }
        ));
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn remove_workspace_does_not_touch_repos() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        cfg.remove_workspace("acme").unwrap();
        assert!(cfg.repos.contains_key("api"));
        assert!(!cfg.workspaces.contains_key("acme"));
    }

    #[test]
    fn add_members_atomic_when_one_repo_missing() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.add_repo("ui".into(), make("/tmp/ui")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        let err = cfg
            .add_members("acme", &["api".into(), "ghost".into(), "ui".into()])
            .unwrap_err();
        assert!(matches!(
            err,
            RepographError::NotFound { kind: "repo", ref name } if name == "ghost"
        ));
        // No partial application.
        assert!(cfg.workspaces.get("acme").unwrap().members.is_empty());
    }

    #[test]
    fn add_members_sorts_and_deduplicates() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.add_repo("ui".into(), make("/tmp/ui")).unwrap();
        cfg.add_repo("libs".into(), make("/tmp/libs")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["ui".into(), "api".into(), "libs".into()])
            .unwrap();
        assert_eq!(
            cfg.workspaces.get("acme").unwrap().members,
            vec!["api", "libs", "ui"]
        );
        // Idempotent.
        cfg.add_members("acme", &["api".into()]).unwrap();
        assert_eq!(
            cfg.workspaces.get("acme").unwrap().members,
            vec!["api", "libs", "ui"]
        );
    }

    #[test]
    fn add_members_missing_workspace_returns_not_found() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        let err = cfg.add_members("ghost", &["api".into()]).unwrap_err();
        assert!(matches!(
            err,
            RepographError::NotFound {
                kind: "workspace",
                ..
            }
        ));
    }

    #[test]
    fn remove_members_is_idempotent_for_non_members() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        cfg.remove_members("acme", &["ghost".into()]).unwrap();
        assert_eq!(cfg.workspaces.get("acme").unwrap().members, vec!["api"]);
    }

    #[test]
    fn remove_members_does_not_deregister_repo() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        cfg.remove_members("acme", &["api".into()]).unwrap();
        assert!(cfg.repos.contains_key("api"));
        assert!(cfg.workspaces.get("acme").unwrap().members.is_empty());
    }

    #[test]
    fn resolve_workspace_partitions_live_and_dangling() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.add_repo("ui".into(), make("/tmp/ui")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into(), "ui".into()])
            .unwrap();
        // Tombstone: forcibly drop `ui` from the registry without touching the workspace.
        cfg.remove_repo("ui").unwrap();
        let (live, dangling) = cfg.resolve_workspace("acme").unwrap();
        assert_eq!(live.len(), 1);
        assert_eq!(live[0].0, "api");
        assert_eq!(dangling.len(), 1);
        assert_eq!(dangling[0], "ui");
    }

    #[test]
    fn resolve_workspace_recovers_after_reregistration() {
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        cfg.remove_repo("api").unwrap();
        let (_, dangling) = cfg.resolve_workspace("acme").unwrap();
        assert_eq!(dangling, vec!["api"]);
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        let (live, dangling) = cfg.resolve_workspace("acme").unwrap();
        assert_eq!(live.len(), 1);
        assert!(dangling.is_empty());
    }

    #[test]
    fn round_trip_with_mixed_repos_and_workspaces() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.add_repo("ui".into(), make("/tmp/ui")).unwrap();
        cfg.create_workspace("acme".into(), Some("Rebuild".into()))
            .unwrap();
        cfg.add_members("acme", &["ui".into(), "api".into()])
            .unwrap();
        cfg.create_workspace("billing".into(), None).unwrap();
        cfg.save(tmp.path()).unwrap();

        let body_first = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        let loaded = Config::load(tmp.path()).unwrap();
        loaded.save(tmp.path()).unwrap();
        let body_second = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert_eq!(body_first, body_second, "byte-identical round trip");

        assert_eq!(loaded.workspaces.len(), 2);
        let acme = loaded.workspaces.get("acme").unwrap();
        assert_eq!(acme.description.as_deref(), Some("Rebuild"));
        assert_eq!(acme.members, vec!["api", "ui"]);
        let billing = loaded.workspaces.get("billing").unwrap();
        assert!(billing.description.is_none());
        assert!(billing.members.is_empty());
    }

    // --- Agents schema tests ---

    #[test]
    fn config_without_agents_section_loads_as_none() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[repo.foo]\npath = \"/tmp/foo\"\n",
        )
        .unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert!(cfg.agents().is_none());
        assert!(cfg.repos.contains_key("foo"));
    }

    #[test]
    fn config_with_empty_agents_is_some_with_empty_selection() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[agents]\nselected = []\n",
        )
        .unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        let agents = cfg.agents().expect("agents present");
        assert!(agents.selected.is_empty());
    }

    #[test]
    fn save_with_agents_none_omits_section() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        // agents remains None.
        cfg.save(tmp.path()).unwrap();
        let body = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert!(
            !body.contains("[agents]"),
            "no [agents] section when agents is None, got:\n{body}"
        );
    }

    #[test]
    fn save_with_empty_agents_writes_section_header() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_agents(Some(Agents { selected: vec![] }));
        cfg.save(tmp.path()).unwrap();
        let body = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert!(
            body.contains("[agents]"),
            "configured-but-empty still writes section header, got:\n{body}"
        );
    }

    #[test]
    fn agents_selection_order_round_trips() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::Cursor, AgentId::ClaudeCode, AgentId::AgentsMd],
        }));
        cfg.save(tmp.path()).unwrap();
        let body = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        let cursor = body.find("\"cursor\"").expect("cursor present");
        let claude = body.find("\"claude-code\"").expect("claude-code present");
        let agents_md = body.find("\"agents-md\"").expect("agents-md present");
        assert!(cursor < claude && claude < agents_md, "order preserved");

        let reloaded = Config::load(tmp.path()).unwrap();
        assert_eq!(
            reloaded.agents().unwrap().selected,
            vec![AgentId::Cursor, AgentId::ClaudeCode, AgentId::AgentsMd]
        );
    }

    #[test]
    fn agents_round_trip_with_repos_and_workspaces_is_byte_stable() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["api".into()]).unwrap();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::ClaudeCode],
        }));
        cfg.save(tmp.path()).unwrap();
        let body_first = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();

        let loaded = Config::load(tmp.path()).unwrap();
        loaded.save(tmp.path()).unwrap();
        let body_second = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert_eq!(
            body_first, body_second,
            "round-trip byte-identical with [agents]"
        );
    }

    #[test]
    fn unknown_agent_id_in_config_produces_parse_error() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[agents]\nselected = [\"claude-code\", \"bogus\"]\n",
        )
        .unwrap();
        let err = Config::load(tmp.path()).unwrap_err();
        assert!(
            matches!(err, RepographError::ConfigParse(_)),
            "expected ConfigParse, got {err:?}"
        );
        assert_eq!(err.exit_code(), 1);
    }

    // --- Settings schema tests ---

    #[test]
    fn config_without_settings_section_loads_as_none() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[agents]\nselected = []\n",
        )
        .unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert!(cfg.settings().is_none());
    }

    #[test]
    fn save_with_settings_none_omits_section() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::ClaudeCode],
        }));
        // settings remains None.
        cfg.save(tmp.path()).unwrap();
        let body = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert!(
            !body.contains("[settings]"),
            "no [settings] section when settings is None, got:\n{body}"
        );
    }

    #[test]
    fn settings_projects_root_round_trip() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_settings(Some(Settings {
            projects_root: Some(PathBuf::from("/home/dev/IdeaProjects")),
        }));
        cfg.save(tmp.path()).unwrap();
        let reloaded = Config::load(tmp.path()).unwrap();
        assert_eq!(
            reloaded.settings().unwrap().projects_root.as_deref(),
            Some(Path::new("/home/dev/IdeaProjects"))
        );
    }

    #[test]
    fn settings_with_none_projects_root_still_writes_section_header() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.set_settings(Some(Settings::default()));
        cfg.save(tmp.path()).unwrap();
        let body = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert!(
            body.contains("[settings]"),
            "configured-but-empty settings still writes header, got:\n{body}"
        );
        assert!(
            !body.contains("projects_root"),
            "absent field is omitted, got:\n{body}"
        );
    }

    #[test]
    fn settings_round_trip_with_agents_and_repos_is_byte_stable() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = Config::default();
        cfg.add_repo("api".into(), make("/tmp/api")).unwrap();
        cfg.set_agents(Some(Agents {
            selected: vec![AgentId::ClaudeCode],
        }));
        cfg.set_settings(Some(Settings {
            projects_root: Some(PathBuf::from("/home/dev/IdeaProjects")),
        }));
        cfg.save(tmp.path()).unwrap();
        let body_first = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();

        let loaded = Config::load(tmp.path()).unwrap();
        loaded.save(tmp.path()).unwrap();
        let body_second = fs_err::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).unwrap();
        assert_eq!(
            body_first, body_second,
            "round-trip byte-identical with [settings]"
        );
    }

    #[test]
    fn unknown_field_on_workspace_is_tolerated() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path()).unwrap();
        std::fs::write(
            tmp.path().join(CONFIG_FILE_NAME),
            "[workspace.acme]\nmembers = []\nfuture = \"yes\"\n",
        )
        .unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert!(cfg.workspaces.contains_key("acme"));
    }

    #[test]
    fn edit_repo_updates_description_and_stack_in_place() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        let (name, repo) = cfg
            .edit_repo(
                "foo",
                RepoEdit {
                    description: Some(Some("new".into())),
                    stack: Some(vec!["rust".into(), "cli".into()]),
                    ..RepoEdit::default()
                },
            )
            .unwrap();
        assert_eq!(name, "foo");
        assert_eq!(repo.description.as_deref(), Some("new"));
        assert_eq!(repo.stack, vec!["rust", "cli"]);
        assert_eq!(
            cfg.repos.get("foo").unwrap().path,
            PathBuf::from("/tmp/foo")
        );
    }

    #[test]
    fn edit_repo_empty_description_clears_it() {
        let mut cfg = Config::default();
        cfg.add_repo(
            "foo".into(),
            Repo {
                path: PathBuf::from("/tmp/foo"),
                description: Some("old".into()),
                stack: vec![],
            },
        )
        .unwrap();
        cfg.edit_repo(
            "foo",
            RepoEdit {
                description: Some(None),
                ..RepoEdit::default()
            },
        )
        .unwrap();
        assert!(cfg.repos.get("foo").unwrap().description.is_none());
    }

    #[test]
    fn edit_repo_rename_preserves_workspace_membership() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        cfg.create_workspace("acme".into(), None).unwrap();
        cfg.add_members("acme", &["foo".into()]).unwrap();

        let (name, _) = cfg
            .edit_repo(
                "foo",
                RepoEdit {
                    new_name: Some("bar".into()),
                    ..RepoEdit::default()
                },
            )
            .unwrap();
        assert_eq!(name, "bar");
        assert!(cfg.repos.contains_key("bar"));
        assert!(!cfg.repos.contains_key("foo"));
        // The workspace now references `bar` as a live member, no dangling.
        let (live, dangling) = cfg.resolve_workspace("acme").unwrap();
        assert!(dangling.is_empty(), "rename left a dangling member");
        assert_eq!(live.len(), 1);
        assert_eq!(live[0].0, "bar");
    }

    #[test]
    fn edit_repo_rename_to_existing_name_conflicts() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        cfg.add_repo("bar".into(), make("/tmp/bar")).unwrap();
        let err = cfg
            .edit_repo(
                "foo",
                RepoEdit {
                    new_name: Some("bar".into()),
                    ..RepoEdit::default()
                },
            )
            .unwrap_err();
        assert!(matches!(err, RepographError::Conflict { kind: "name", .. }));
        // No mutation: foo still present, bar untouched.
        assert!(cfg.repos.contains_key("foo"));
        assert_eq!(
            cfg.repos.get("bar").unwrap().path,
            PathBuf::from("/tmp/bar")
        );
    }

    #[test]
    fn edit_repo_nonexistent_returns_not_found() {
        let mut cfg = Config::default();
        let err = cfg
            .edit_repo(
                "ghost",
                RepoEdit {
                    description: Some(Some("x".into())),
                    ..RepoEdit::default()
                },
            )
            .unwrap_err();
        assert!(matches!(err, RepographError::NotFound { kind: "repo", .. }));
    }

    #[test]
    fn edit_repo_path_conflict_returns_conflict() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        cfg.add_repo("bar".into(), make("/tmp/bar")).unwrap();
        let err = cfg
            .edit_repo(
                "foo",
                RepoEdit {
                    path: Some(PathBuf::from("/tmp/bar")),
                    ..RepoEdit::default()
                },
            )
            .unwrap_err();
        assert!(matches!(err, RepographError::Conflict { kind: "path", .. }));
        assert_eq!(
            cfg.repos.get("foo").unwrap().path,
            PathBuf::from("/tmp/foo")
        );
    }

    #[test]
    fn edit_repo_rename_to_same_name_is_noop_not_conflict() {
        let mut cfg = Config::default();
        cfg.add_repo("foo".into(), make("/tmp/foo")).unwrap();
        let (name, _) = cfg
            .edit_repo(
                "foo",
                RepoEdit {
                    new_name: Some("foo".into()),
                    description: Some(Some("d".into())),
                    ..RepoEdit::default()
                },
            )
            .unwrap();
        assert_eq!(name, "foo");
        assert_eq!(
            cfg.repos.get("foo").unwrap().description.as_deref(),
            Some("d")
        );
    }
}