roteiro 1.13.0

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
//! Layered project/user configuration (ADR-0007).
//!
//! Reads an optional **project** `roteiro.toml` (at the repository root — the
//! nearest ancestor holding a `.git` entry) and an optional **user**
//! `~/.roteiro/config.toml`, then
//! merges them so that, per value, the precedence is
//! **CLI flag > project > user > built-in default**. This module resolves the
//! *config* layers (project over user); the CLI-vs-config precedence is applied
//! at each call site (a flag, when present, wins over the resolved config).
//!
//! Every field is optional and every consumer has a built-in default, so **no
//! config is a working default**. TOML only (YAML is intentionally unsupported —
//! `serde_yaml` is unmaintained). Unknown keys are ignored (forward-compatible);
//! a malformed file is a hard error, never a silent partial parse.

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

use serde::{Deserialize, Serialize};

/// The merged configuration plus the layers it came from (for provenance).
#[derive(Debug, Default)]
pub struct Loaded {
    /// The effective, merged config used at run time (project over user).
    pub effective: Config,
    /// The user-layer config (`~/.roteiro/config.toml`), for provenance.
    pub user: Config,
    /// The project-layer config (`roteiro.toml`), for provenance.
    pub project: Config,
    /// Path the user config was read from, if present.
    pub user_path: Option<PathBuf>,
    /// Path the project config was read from, if present.
    pub project_path: Option<PathBuf>,
}

impl Loaded {
    /// The effective `[debt] ignore` patterns, each tagged with the layer it came
    /// from (`"project"`, `"user"`, or `"project, user"` when both name it).
    ///
    /// Because this list **merges** across layers ([`merge_ignore`]), one label
    /// per key would be a lie — the effective list can hold patterns from both
    /// layers at once — so provenance is reported per *pattern*. `roteiro config`
    /// prints this, which is what makes the merge legible instead of magic.
    #[must_use]
    pub fn debt_ignore_sources(&self) -> Vec<(&str, &'static str)> {
        let contains = |c: &Config, pattern: &str| {
            c.debt
                .ignore
                .as_deref()
                .is_some_and(|ps| ps.iter().any(|p| p == pattern))
        };
        self.effective
            .debt
            .ignore
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(|pattern| {
                let layer = match (
                    contains(&self.project, pattern),
                    contains(&self.user, pattern),
                ) {
                    (true, true) => "project, user",
                    (true, false) => "project",
                    (false, true) => "user",
                    // Unreachable while the effective list is built from the two
                    // layers; reported honestly rather than asserted away.
                    (false, false) => "unknown",
                };
                (pattern.as_str(), layer)
            })
            .collect()
    }

    /// Whether the **user** layer asked for an `ignore_reset` that did nothing.
    ///
    /// A reset drops what a layer inherits, and the user layer is the bottom of
    /// the two ([`DebtConfig::ignore_reset`]), so its flag never reaches
    /// [`merge_ignore`]. Reporting that is the point: a key whose whole argument
    /// is "a reset cannot fail quietly" must not itself fail quietly, and
    /// `roteiro config` is where a reader goes to find out what their
    /// configuration did.
    ///
    /// False when a reset *is* in force, even though the user's own flag was
    /// still individually inert: the project layer reset, patterns really were
    /// dropped, and `roteiro config` says so. Adding "…and your reset did
    /// nothing" beside that would be true but unreadable, and the user got the
    /// behaviour they asked for either way.
    #[must_use]
    pub fn debt_ignore_reset_was_inert(&self) -> bool {
        self.user.debt.ignore_reset == Some(true) && self.effective.debt.ignore_reset != Some(true)
    }

    /// The user-layer `[debt] ignore` patterns that `ignore_reset` discarded, so
    /// the reset is *visible* rather than merely effective. Empty when no reset is
    /// in force.
    ///
    /// Empty in practice unless the project layer both reset **and** declined to
    /// restate a user pattern, since the kept list is otherwise a superset of the
    /// user's. That is why this could never have exposed the inherited-flag defect
    /// on its own — with no reset in force the kept list is the union, so every
    /// user pattern is present and the filter yields nothing. The false claim was
    /// the unconditional headline in `roteiro config`, not this list.
    #[must_use]
    pub fn debt_ignore_discarded(&self) -> Vec<&str> {
        if self.effective.debt.ignore_reset != Some(true) {
            return Vec::new();
        }
        let kept = self.effective.debt.ignore.as_deref().unwrap_or_default();
        self.user
            .debt
            .ignore
            .as_deref()
            .unwrap_or_default()
            .iter()
            .filter(|p| !kept.iter().any(|k| k == *p))
            .map(String::as_str)
            .collect()
    }
}

/// Roteiro configuration. All fields optional; see the module docs.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct Config {
    /// Per-project model picks (override the tier defaults).
    pub models: ModelsConfig,
    /// `roteiro infer` tuning.
    pub infer: InferConfig,
    /// `roteiro duplicates` tuning.
    pub duplicates: DuplicatesConfig,
    /// `roteiro sync` content-ingestion toggles.
    pub ingest: IngestConfig,
    /// `roteiro media build`'s pre-generation gate.
    pub media: MediaConfig,
    /// `roteiro serve --models` local endpoint settings.
    pub serve: ServeConfig,
    /// `roteiro debt` tuning (paths excluded from the intent-debt scan).
    pub debt: DebtConfig,
    /// Filesystem locations (the model store).
    pub paths: PathsConfig,
    /// `[telemetry]` — opt-in structured file logging (ADR-0011). Unset ⇒ stdout
    /// only, unchanged.
    pub telemetry: TelemetryConfig,
    /// `roteiro serve --workspace` — repos a single server can host (ADR-0008).
    /// The legacy **single** workspace; still fully supported and, when it names
    /// any repos, folded in as the `default` linked workspace (see
    /// [`Config::resolved_workspaces`]).
    pub workspace: WorkspaceConfig,
    /// `[[workspaces]]` — additional **named**, linked workspaces (each a multi-repo
    /// graph whose cross-repo links resolve), the named form of the legacy single
    /// `[workspace]` (ADR-0008 multi-workspace).
    pub workspaces: Vec<NamedWorkspace>,
    /// `[standalone]` — repos each served as their **own** single-repo graph, with
    /// no cross-repo links. Discovered like `[workspace]` (roots scanned + explicit
    /// repos) but partitioned one-workspace-per-repo (ADR-0008 multi-workspace).
    pub standalone: WorkspaceConfig,
    /// `[[links]]` — authored cross-repo links to other workspace repos (ADR-0009).
    pub links: Vec<LinkDecl>,
    /// `[pins]` — how to map a deployed artifact to a hub git ref when the default
    /// tag guess doesn't fit this project's scheme (ADR-0009 step 8c). Keyed by the
    /// hub/image name; value is a ref template with a `{tag}` placeholder, e.g.
    /// `app = "release-{tag}"` maps image `app:1.2` → git ref `release-1.2`.
    pub pins: std::collections::BTreeMap<String, String>,
}

/// `[debt]` — intent-debt reporting.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct DebtConfig {
    /// Glob patterns whose matching files are excluded from the intent-debt
    /// report (e.g. `["vendor/**", "**/generated/*"]`). Patterns are matched
    /// anchored end-to-end against the whole repo-relative path (not a substring
    /// match): `*`/`?` match within a path segment, `**` matches across segments.
    ///
    /// **This list is additive across layers**: the project's patterns are
    /// appended to the user's rather than replacing them (see
    /// [`Config::overlaid_with`]). To start from nothing instead, set
    /// [`DebtConfig::ignore_reset`].
    pub ignore: Option<Vec<String>>,
    /// Drop every [`DebtConfig::ignore`] pattern inherited from a lower layer,
    /// so this layer's list stands alone.
    ///
    /// This is the deliberate answer to "if lists merge, how does a user *remove*
    /// an inherited pattern?" — an explicit, all-or-nothing reset rather than a
    /// per-pattern negation prefix such as `!vendor/**`. Two reasons, both about
    /// keeping failure loud:
    ///
    /// 1. **A reset cannot fail quietly; a negation can.** Mistype
    ///    `!vendour/**` and it matches no inherited pattern, removes nothing, and
    ///    says nothing — a wrong-but-quiet answer, the exact failure this key
    ///    exists to prevent. A reset is present or absent, with no third silent
    ///    state, and `roteiro config` prints the patterns it discarded.
    /// 2. **`!` already means something else.** In `.gitignore` — the syntax
    ///    every reader of a glob-exclusion list has in mind — a leading `!`
    ///    *re-includes a matching file*; it does not delete an inherited rule.
    ///    Borrowing a familiar sigil for an unfamiliar operation is worse than an
    ///    unfamiliar key that means exactly what it says.
    ///
    /// The cost is coarseness: you cannot drop one inherited pattern and keep the
    /// rest — you restate the ones you want. Exclusion lists are short, so that is
    /// cheap, and restating them is visible in review, which subtracting one
    /// invisibly would not be.
    ///
    /// # Effective in the project layer only (today)
    ///
    /// A reset drops what a layer **inherits**, so it means something only where
    /// there is a layer beneath it. There are exactly two layers — user
    /// (`~/.roteiro/config.toml`) then project (`roteiro.toml`), applied as
    /// `user.overlaid_with(&project)` — so the user layer is the bottom, and
    /// [`merge_ignore`] consults the *nearer* layer's flag and only that one.
    /// Setting this in the user config therefore resets nothing.
    ///
    /// That is an uncomfortable shape for a key whose entire argument is "a reset
    /// cannot fail quietly", so it is **not** left to this doc comment to carry.
    /// `roteiro config` reports an inert user-layer reset in so many words
    /// ([`Loaded::debt_ignore_reset_was_inert`]) — the same principle as the
    /// merge itself: the surface whose job is explaining the configuration says
    /// what happened, rather than expecting the reader to have found this
    /// paragraph.
    ///
    /// It is deliberately **not** a hard error. The key is inert because of
    /// today's layer *arrangement*, not because it is meaningless: add a built-in
    /// defaults layer beneath `user` — a plausible future — and a user-layer reset
    /// starts doing exactly what it says, with no config to migrate. Rejecting it
    /// permanently would encode a temporary fact as a rule.
    ///
    /// Accepted as `ignore_reset` (canonical, matching every other key in this
    /// file) or `ignore-reset`.
    #[serde(alias = "ignore-reset")]
    pub ignore_reset: Option<bool>,
}

/// `[paths]` — filesystem locations.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct PathsConfig {
    /// The model store directory (default `~/.roteiro/models`, or
    /// `$ROTEIRO_HOME/models`). A leading `~/` is expanded to the home directory.
    pub model_store: Option<String>,
}

/// `[telemetry]` — opt-in structured file logging, the groundwork for a future
/// OpenTelemetry exporter (ADR-0011). Every field is optional; with the whole
/// table absent, Roteiro logs exactly as it does today — human-readable text on
/// stdout, nothing written to disk. Setting `file` (or the `--log-file` flag /
/// `ROTEIRO_LOG_FILE` env var, or the `--log` flag for the default path) turns on
/// a **second**, structured sink to a rotating file, leaving stdout untouched.
///
/// The name is `telemetry`, not `log`, deliberately: this table is the seam for
/// the deferred OTLP logs **and** metrics/traces exporter (ADR-0011), so it
/// should read as "observability config", not "the log file". Precedence is the
/// usual CLI flag / env var > project > user > built-in default (ADR-0007).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct TelemetryConfig {
    /// Path to the rotating log file. **Unset ⇒ file logging is off** (stdout
    /// only). A leading `~/` is expanded to the home directory; a relative path is
    /// resolved under `$ROTEIRO_HOME` (else `~/.roteiro`). When file logging is
    /// enabled without an explicit path (the `--log` flag), the default is
    /// `$ROTEIRO_HOME/logs/roteiro.log`.
    pub file: Option<String>,
    /// Rotation cadence for the file appender: `daily` (default), `hourly`,
    /// `minutely`, or `never` (a single, unrotated file). Time-based only —
    /// size-based rotation is out of scope for `tracing-appender` and deferred to
    /// the OTLP step (ADR-0011).
    pub rotation: Option<String>,
    /// On-disk record format: `otel` (default) / `json` — one
    /// OpenTelemetry-shaped JSON object per line (see [`crate::telemetry`] for the
    /// field mapping) — or `text`, the same human-readable format stdout uses.
    pub format: Option<String>,
}

impl TelemetryConfig {
    /// Overlay `over` on top of `self` per field (the project layer over the user
    /// layer), taking `over`'s value wherever set.
    fn overlaid_with(&self, over: &Self) -> Self {
        Self {
            file: over.file.clone().or_else(|| self.file.clone()),
            rotation: over.rotation.clone().or_else(|| self.rotation.clone()),
            format: over.format.clone().or_else(|| self.format.clone()),
        }
    }
}

/// `[workspace]` — the repos one `roteiro serve` can host (ADR-0008). Naturally a
/// user-layer setting (machine-specific), but merged like any table. Combined
/// with `serve --workspace <root>`; empty ⇒ single-repo serve (the cwd's repo).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct WorkspaceConfig {
    /// Directories to scan for git repos (each immediate subdirectory that is a
    /// repo becomes a project, plus the root itself if it is one).
    pub roots: Option<Vec<String>>,
    /// Explicit repo paths to host, in addition to anything found under `roots`.
    pub repos: Option<Vec<String>>,
}

impl WorkspaceConfig {
    /// Whether this table names nothing to host (no roots and no repos) — used to
    /// decide whether the legacy `[workspace]` should fold in as `default`.
    fn is_empty(&self) -> bool {
        self.roots.as_ref().is_none_or(Vec::is_empty)
            && self.repos.as_ref().is_none_or(Vec::is_empty)
    }
}

/// One `[[workspaces]]` entry: a **named** linked workspace — a set of repos served
/// as a single multi-repo graph (their cross-repo links resolve), the named form of
/// the legacy single `[workspace]` (ADR-0008). Reuses the `roots`/`repos` discovery
/// rules of [`WorkspaceConfig`], plus a `name` (the `--workspace-name` selector).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct NamedWorkspace {
    /// The workspace name — the selector passed to `--workspace-name`.
    pub name: String,
    /// Directories to scan for member git repos (each immediate subdirectory that
    /// is a repo, plus the root itself if it is one), as `[workspace] roots`.
    pub roots: Option<Vec<String>>,
    /// Explicit member repo paths, in addition to anything found under `roots`.
    pub repos: Option<Vec<String>>,
}

/// One authored cross-repo link (ADR-0009): a `[[links]]` entry in a spoke repo's
/// `roteiro.toml` declaring that this repo references a project-qualified key in
/// another workspace repo. `roteiro links` resolves each against the workspace and
/// flags drift (targets that no longer exist).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
pub struct LinkDecl {
    /// The project-qualified target: `<project>::<key>`, e.g.
    /// `app::sym:rust:crates/roteiro/src/config.rs#ServeConfig`.
    pub to: String,
    /// Optional local anchor in *this* repo the link originates from, e.g.
    /// `file:values.prod.yaml`. Recorded for provenance and shown in the report;
    /// not currently resolved against this repo's graph.
    #[serde(default)]
    pub from: Option<String>,
    /// Relationship label for display (default `references`).
    #[serde(default)]
    pub kind: Option<String>,
}

/// `[models]` — override the registry tier defaults for this project.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ModelsConfig {
    /// Registry name of the embedding model `infer --model` defaults to.
    pub embedding: Option<String>,
    /// Registry name of the generative model `spec draft` defaults to.
    pub generative: Option<String>,
}

/// `[ingest]` — which blob content `roteiro sync` extracts for embedding. Each
/// toggle is `Some(false)` to disable a content class the binary supports; unset
/// (or `true`) leaves it on. A toggle cannot enable a class the binary was not
/// built with (the `pdf-text`/`image-ocr`/`image-vision`/`audio-transcribe`
/// features).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct IngestConfig {
    /// Embed the UTF-8 body of prose files (Markdown, plain text).
    pub prose: Option<bool>,
    /// Extract text from PDF documents.
    pub pdf: Option<bool>,
    /// OCR literal text from images.
    pub ocr: Option<bool>,
    /// Describe images with a vision model.
    pub vision: Option<bool>,
    /// Transcribe spoken-word audio.
    pub audio: Option<bool>,
}

impl IngestConfig {
    /// Resolve to the graph-layer [`rto_graph::IngestConfig`], defaulting each
    /// unset toggle to on.
    #[must_use]
    pub fn resolve(&self) -> rto_graph::IngestConfig {
        let default = rto_graph::IngestConfig::default();
        rto_graph::IngestConfig {
            prose: self.prose.unwrap_or(default.prose),
            pdf: self.pdf.unwrap_or(default.pdf),
            ocr: self.ocr.unwrap_or(default.ocr),
            vision: self.vision.unwrap_or(default.vision),
            audio: self.audio.unwrap_or(default.audio),
        }
    }
}

/// `[media]` — the **pre-generation gate** `roteiro media build` applies before
/// loading a model (ADR-0015).
///
/// The gate is a cheap, deterministic refusal of blobs with nothing to read:
/// digital silence, flat-colour images. It is on by default at thresholds that
/// sit at the digital noise floor, because **a false skip is worse than a false
/// pass** now that generated output is clearly labelled — so raising a threshold
/// is a deliberate act, taken here, and never something the tool does for you.
///
/// Every setting is `Option`, and unset means the built-in default
/// ([`rto_graph::GateThresholds::default`]).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct MediaConfig {
    /// Apply the gate at all. `false` sends every blob to the model, which is
    /// what `--force` does for a single run.
    pub gate: Option<bool>,
    /// RMS amplitude (full scale `1.0`) at or below which an audio clip counts
    /// as silent. Default `0.0001` (≈ -80 dBFS).
    pub silence_rms: Option<f64>,
    /// Luma variance (a pixel is `0.0`…`1.0`) at or below which an image counts
    /// as uniform. Default `0.00001`.
    pub image_variance: Option<f64>,
}

impl MediaConfig {
    /// Resolve to the graph-layer thresholds, defaulting each unset value.
    ///
    /// `gate = false` resolves to [`rto_graph::GateThresholds::disabled`] rather
    /// than to a separate flag: the two settings would otherwise have to be read
    /// together everywhere, and a disabled gate is exactly a gate nothing can
    /// fall below.
    #[must_use]
    pub fn resolve(&self) -> rto_graph::GateThresholds {
        if self.gate == Some(false) {
            return rto_graph::GateThresholds::disabled();
        }
        let default = rto_graph::GateThresholds::default();
        rto_graph::GateThresholds {
            silence_rms: self.silence_rms.unwrap_or(default.silence_rms),
            image_variance: self.image_variance.unwrap_or(default.image_variance),
        }
    }
}

/// `[serve]` — the opt-in local OpenAI-compatible model endpoint (ADR-0006).
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ServeConfig {
    /// Bind address for `roteiro serve --models` (default `127.0.0.1:8017`).
    pub addr: Option<String>,
    /// Restrict which installed generative models to serve (default: all
    /// installed generative models).
    pub models: Option<Vec<String>>,
    /// Auto-register the graph tools so the served model can query the codebase
    /// (ADR-0006). Default `true`.
    pub tools: Option<bool>,
    /// Approximate memory budget (MiB) for models kept resident at once. The
    /// engine loads models on demand and unloads the least-recently-used once the
    /// resident set (proxied by GGUF size) exceeds this. Unset/`0` keeps a single
    /// model resident — set it higher to keep several warm and swap in real time.
    pub memory_budget_mb: Option<u64>,
    /// PEM certificate-chain file for in-app TLS. Set **both** this and `tls_key`
    /// and `serve --models` terminates HTTPS itself (needs `--features serve`);
    /// set **neither** and it serves plain HTTP (front with a proxy for TLS).
    /// Setting exactly one is a startup error.
    pub tls_cert: Option<String>,
    /// PEM private-key file paired with `tls_cert` (PKCS#8 or RSA).
    pub tls_key: Option<String>,
}

/// `[infer]` — defaults for the similarity-inference command.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct InferConfig {
    /// Minimum cosine similarity for a suggested edge (`0.0..=1.0`).
    pub min_confidence: Option<f64>,
    /// Maximum suggestions per node.
    pub top_k: Option<usize>,
}

/// `[duplicates]` — defaults for the duplicate-detection command.
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct DuplicatesConfig {
    /// Minimum cosine similarity for a near-duplicate pair (`0.0..=1.0`).
    pub min_similarity: Option<f64>,
    /// Maximum pairs to report.
    pub limit: Option<usize>,
}

/// The `[debt] ignore` exclusion globs that govern `project` within `ws` — read
/// from **that project's own repository**, not from the repo the process was
/// started in.
///
/// This is ADR-0009's per-repo config resolution applied to scanning: *a
/// repository's own configuration governs how it is scanned, whoever is asking.*
/// `roteiro links` already reads each spoke's config with a per-repo
/// [`load`]; a multi-repo server that skips it scans repo B from repo A under
/// A's exclusions, so B's own `[debt] ignore` never applies and B's operators
/// cannot explain the number they are shown.
///
/// Returns no exclusions when the project has no repository on disk to consult —
/// a pre-opened store ([`rto_graph::Workspace::from_stores`], the in-memory
/// tests). Substituting the invoking repo's config there would be precisely the
/// mix-up this function exists to prevent.
///
/// # Errors
/// The project name not resolving in `ws`, or that repository's `roteiro.toml`
/// being unreadable or malformed. Both are surfaced rather than swallowed: a
/// fallback to "no exclusions" answers with a silently different number, which is
/// the defect, not a graceful degradation.
// The two callers are the graph API (`explorer`) and the MCP `debt` tool
// (`serve`); a default build has neither, so gate it or dead-code warns.
#[cfg(any(feature = "explorer", feature = "serve"))]
pub fn debt_ignore_for(
    ws: &rto_graph::Workspace,
    project: Option<&str>,
) -> anyhow::Result<Vec<String>> {
    let Some(root) = ws.project_root(project)? else {
        return Ok(Vec::new());
    };
    let loaded = load(&root).map_err(|e| {
        anyhow::anyhow!(
            "reading the configuration of the repository at {}: {e}",
            root.display()
        )
    })?;
    Ok(loaded.effective.debt.ignore.unwrap_or_default())
}

/// Overlay the `[debt] ignore` **exclusion list**: `over`'s patterns are
/// *appended* to `base`'s (de-duplicated, inherited first), unless `over` sets
/// `ignore_reset`, in which case `base` is dropped entirely.
///
/// Replace is right for a scalar — one `model`, one `addr`, and the nearer layer
/// names it. It is wrong for an exclusion list, where the intent is nearly always
/// additive: a user who globally ignores `vendor/**` and then adds one
/// project-specific `thirdparty/**` wants both, and getting the union silently
/// narrowed to one pattern is a trap that reports debt the user believed excluded
/// — or, worse, hides it.
///
/// Only this list merges. The other list-valued keys stay replace-wins, and that
/// is a decision rather than an oversight:
///
/// - `[workspace]`/`[standalone]` `roots`/`repos` are **discovery** lists: a
///   merge would silently serve repos the project never named, which is a
///   surprise with a security surface, not a convenience.
/// - `[serve] models` is a **selection** ("serve exactly these"), where the
///   nearer layer narrowing the set is the whole point.
/// - `[[links]]`/`[[workspaces]]` are already whole-entry overlays with their own
///   documented rule, and `[pins]` already merges per key.
///
/// The distinguishing question is whether adding an entry *widens* something
/// harmless (an exclusion) or *changes what is reached* (discovery, selection).
fn merge_ignore(base: Option<&[String]>, over: &DebtConfig) -> Option<Vec<String>> {
    if over.ignore_reset == Some(true) {
        return over.ignore.clone();
    }
    match (base, over.ignore.as_deref()) {
        (None, None) => None,
        (Some(only), None) | (None, Some(only)) => Some(only.to_vec()),
        (Some(base), Some(over)) => {
            // Inherited first, then the nearer layer's, each pattern once — the
            // order `roteiro config` prints them in.
            let mut merged: Vec<String> = base.to_vec();
            for pattern in over {
                if !merged.iter().any(|p| p == pattern) {
                    merged.push(pattern.clone());
                }
            }
            Some(merged)
        }
    }
}

impl Config {
    /// Overlay `over` on top of `self`, taking `over`'s value wherever set — used
    /// to apply the project layer on top of the user layer.
    ///
    /// Scalars replace; the `[debt] ignore` exclusion list **merges** (see
    /// [`merge_ignore`]).
    fn overlaid_with(&self, over: &Config) -> Config {
        Config {
            models: ModelsConfig {
                embedding: over
                    .models
                    .embedding
                    .clone()
                    .or(self.models.embedding.clone()),
                generative: over
                    .models
                    .generative
                    .clone()
                    .or(self.models.generative.clone()),
            },
            infer: InferConfig {
                min_confidence: over.infer.min_confidence.or(self.infer.min_confidence),
                top_k: over.infer.top_k.or(self.infer.top_k),
            },
            duplicates: DuplicatesConfig {
                min_similarity: over
                    .duplicates
                    .min_similarity
                    .or(self.duplicates.min_similarity),
                limit: over.duplicates.limit.or(self.duplicates.limit),
            },
            ingest: IngestConfig {
                prose: over.ingest.prose.or(self.ingest.prose),
                pdf: over.ingest.pdf.or(self.ingest.pdf),
                ocr: over.ingest.ocr.or(self.ingest.ocr),
                vision: over.ingest.vision.or(self.ingest.vision),
                audio: over.ingest.audio.or(self.ingest.audio),
            },
            media: MediaConfig {
                gate: over.media.gate.or(self.media.gate),
                silence_rms: over.media.silence_rms.or(self.media.silence_rms),
                image_variance: over.media.image_variance.or(self.media.image_variance),
            },
            serve: ServeConfig {
                addr: over.serve.addr.clone().or(self.serve.addr.clone()),
                models: over.serve.models.clone().or(self.serve.models.clone()),
                tools: over.serve.tools.or(self.serve.tools),
                memory_budget_mb: over.serve.memory_budget_mb.or(self.serve.memory_budget_mb),
                tls_cert: over.serve.tls_cert.clone().or(self.serve.tls_cert.clone()),
                tls_key: over.serve.tls_key.clone().or(self.serve.tls_key.clone()),
            },
            // `[debt] ignore` is the one list-valued key that **merges** rather
            // than replaces; see `merge_ignore` for why, and why the other lists
            // deliberately do not.
            debt: DebtConfig {
                ignore: merge_ignore(self.debt.ignore.as_deref(), &over.debt),
                // NOT inherited with `.or(self.debt.ignore_reset)`, unlike every
                // scalar above. Those are *values* the run consumes afterwards, so
                // falling back to the lower layer is right. This is a **directive
                // to the merge**, already consumed by `merge_ignore` — which reads
                // `over`'s flag and only `over`'s. After the overlay it is no
                // longer an input to anything; it is the *record* of what the
                // merge did. Inheriting it made the record disagree with the
                // event: a user-layer reset (inert, since `merge_ignore` never
                // consults it) surfaced in `effective`, and `roteiro config` — the
                // command whose whole job is explaining what the config did —
                // announced "inherited patterns dropped" over a list where every
                // inherited pattern was plainly still present.
                ignore_reset: over.debt.ignore_reset,
            },
            paths: PathsConfig {
                model_store: over
                    .paths
                    .model_store
                    .clone()
                    .or(self.paths.model_store.clone()),
            },
            telemetry: self.telemetry.overlaid_with(&over.telemetry),
            workspace: WorkspaceConfig {
                roots: over
                    .workspace
                    .roots
                    .clone()
                    .or(self.workspace.roots.clone()),
                repos: over
                    .workspace
                    .repos
                    .clone()
                    .or(self.workspace.repos.clone()),
            },
            // `[[workspaces]]` overlay like `links`: the project layer wins outright
            // when it declares any, else the user layer's survive.
            workspaces: if over.workspaces.is_empty() {
                self.workspaces.clone()
            } else {
                over.workspaces.clone()
            },
            // `[standalone]` merges per field (project over user), like `workspace`.
            standalone: WorkspaceConfig {
                roots: over
                    .standalone
                    .roots
                    .clone()
                    .or(self.standalone.roots.clone()),
                repos: over
                    .standalone
                    .repos
                    .clone()
                    .or(self.standalone.repos.clone()),
            },
            // Links are per-repo (a spoke declares its own); the project layer wins
            // outright when it has any, else the user layer's (rare).
            links: if over.links.is_empty() {
                self.links.clone()
            } else {
                over.links.clone()
            },
            // Pins merge per key: the project layer overrides the user layer.
            pins: {
                let mut m = self.pins.clone();
                m.extend(over.pins.clone());
                m
            },
        }
    }

    /// Normalise the workspace configuration into a flat list of resolved groups
    /// (ADR-0008 multi-workspace), the input to [`rto_graph::WorkspaceSet`]:
    ///
    /// - the legacy `[workspace]` table, **when it names any roots/repos**, folds in
    ///   as a linked group named `default`;
    /// - each `[[workspaces]]` entry is a linked group under its own name;
    /// - `[standalone]` expands — by discovering the repos under its roots plus its
    ///   explicit repos — into one **unlinked**, single-repo group per repo, named
    ///   after the repo directory (deduped `-2`/`-3` on collision, as the workspace
    ///   registry does).
    ///
    /// **Linked** workspace names (`default` and every `[[workspaces]]`) must be
    /// **unique** — a collision is a config error, never a silent rename, because
    /// renaming a user-named linked workspace would resolve its cross-repo links
    /// against the wrong repos. Only the auto-generated **standalone** names (derived
    /// from repo directory names) take a `-2`/`-3` suffix on collision, including
    /// against a linked name.
    ///
    /// Fully backward-compatible: a config with only `[workspace]` yields exactly one
    /// `default` linked group with the same membership as before; a config naming no
    /// workspaces at all yields an empty list.
    ///
    /// # Errors
    /// A duplicate **linked** workspace name, or a discovery failure (an unreadable
    /// `[standalone]` root).
    pub fn resolved_workspaces(&self) -> anyhow::Result<Vec<rto_graph::ResolvedWorkspace>> {
        use std::collections::HashSet;

        let mut out: Vec<rto_graph::ResolvedWorkspace> = Vec::new();
        let mut used: HashSet<String> = HashSet::new();

        // Legacy `[workspace]` → the `default` linked group (only if it names any
        // repos), so today's single-workspace configs keep working unchanged.
        if !self.workspace.is_empty() {
            used.insert("default".to_owned());
            out.push(rto_graph::ResolvedWorkspace {
                name: "default".to_owned(),
                roots: expand_tilde_all(self.workspace.roots.clone().unwrap_or_default()),
                repos: expand_tilde_all(self.workspace.repos.clone().unwrap_or_default()),
                linked: true,
            });
        }

        // Each `[[workspaces]]` → a named linked group. A collision with `default`
        // or another `[[workspaces]]` is a config error (never a silent rename).
        for nw in &self.workspaces {
            if !used.insert(nw.name.clone()) {
                anyhow::bail!(
                    "duplicate workspace name `{}` — `[[workspaces]]` names (and the legacy \
                     `[workspace]`, which folds in as `default`) must each be unique",
                    nw.name
                );
            }
            out.push(rto_graph::ResolvedWorkspace {
                name: nw.name.clone(),
                roots: expand_tilde_all(nw.roots.clone().unwrap_or_default()),
                repos: expand_tilde_all(nw.repos.clone().unwrap_or_default()),
                linked: true,
            });
        }

        // `[standalone]` → one unlinked, single-repo group per discovered repo.
        for repo in self.standalone_repo_paths()? {
            let base = repo
                .file_name()
                .map_or_else(|| "repo".to_owned(), |s| s.to_string_lossy().into_owned());
            let name = dedupe_workspace_name(&mut used, base);
            out.push(rto_graph::ResolvedWorkspace {
                name,
                roots: Vec::new(),
                repos: vec![repo.to_string_lossy().into_owned()],
                linked: false,
            });
        }

        Ok(out)
    }

    /// Every standalone repo: those discovered under each `[standalone] roots` entry
    /// plus each explicit `[standalone] repos` path, order-stable and de-duplicated
    /// by path.
    fn standalone_repo_paths(&self) -> anyhow::Result<Vec<PathBuf>> {
        use std::collections::HashSet;
        let mut seen: HashSet<PathBuf> = HashSet::new();
        let mut out: Vec<PathBuf> = Vec::new();
        for root in self.standalone.roots.iter().flatten() {
            for repo in rto_graph::discover_repos_under(&expand_tilde(root))? {
                if seen.insert(repo.clone()) {
                    out.push(repo);
                }
            }
        }
        for repo in self.standalone.repos.iter().flatten() {
            let p = expand_tilde(repo).into_owned();
            if seen.insert(p.clone()) {
                out.push(p);
            }
        }
        Ok(out)
    }
}

/// Expand a leading `~/` (or a bare `~`) to the user's home directory in every
/// path string, returning owned strings. The workspace-resolution boundary
/// ([`Config::resolved_workspaces`]): `rto_graph` receives real paths, never a
/// literal `~` it would hand straight to git. A path without a leading `~` is
/// unchanged. Env-var expansion (`$HOME`) is intentionally out of scope.
fn expand_tilde_all(paths: Vec<String>) -> Vec<String> {
    paths
        .into_iter()
        .map(|p| expand_tilde(&p).to_string_lossy().into_owned())
        .collect()
}

/// Expand a leading `~/` (or a bare `~`) to the user's home directory; any other
/// path is borrowed back unchanged. The one home-relative expansion shared by
/// every config path — the model store (`[paths] model_store`) and workspace
/// `roots`/`repos` (new `[[workspaces]]`/`[standalone]` and legacy `[workspace]`).
/// Env-var expansion (`$HOME`) is intentionally out of scope — only `~`.
///
/// Fast path: a string that isn't exactly `~` and doesn't start with `~/` is
/// borrowed as-is — no `HOME`/`USERPROFILE` lookup and no allocation — so
/// resolving a large `roots`/`repos` list (serve startup, SIGHUP reload) costs
/// nothing beyond the borrow, as it did before tilde handling was added.
pub(crate) fn expand_tilde(path: &str) -> Cow<'_, Path> {
    if path != "~" && !path.starts_with("~/") {
        return Cow::Borrowed(Path::new(path));
    }
    let home = home_dir();
    Cow::Owned(expand_tilde_with(
        path,
        home.as_deref().map(std::path::Path::as_os_str),
    ))
}

/// The user's home directory: `$HOME`, else `$USERPROFILE` (Windows). The one home
/// lookup shared across the codebase — [`expand_tilde`]'s `~` expansion and
/// [`roteiro_home`]'s `~/.roteiro` fallback both resolve home through it. Returns
/// `None` when neither is set. Env-var expansion beyond `~` is out of scope.
pub(crate) fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

/// Core of [`expand_tilde`] with the home directory injected, so tests drive it
/// deterministically without mutating process-global env.
fn expand_tilde_with(path: &str, home: Option<&std::ffi::OsStr>) -> PathBuf {
    if path == "~"
        && let Some(h) = home
    {
        return PathBuf::from(h);
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(h) = home
    {
        return Path::new(h).join(rest);
    }
    PathBuf::from(path)
}

/// Make `base` unique against the names already handed out, appending `-2`, `-3`, …
/// on collision (mirrors the workspace registry's `dedupe_name`). Records the
/// chosen name in `used`.
fn dedupe_workspace_name(used: &mut std::collections::HashSet<String>, base: String) -> String {
    if used.insert(base.clone()) {
        return base;
    }
    let mut n = 2u32;
    loop {
        let candidate = format!("{base}-{n}");
        if used.insert(candidate.clone()) {
            return candidate;
        }
        n += 1;
    }
}

/// Load and merge the user and project config layers, starting the project
/// search from `cwd`.
///
/// # Errors
/// Returns an error if a config file exists but cannot be read or parsed
/// (malformed TOML is a hard error, never a silent partial parse).
pub fn load(cwd: &Path) -> anyhow::Result<Loaded> {
    let user_path = user_config_path().filter(|p| p.is_file());
    let project_path = find_project_config(cwd);
    load_from(user_path, project_path)
}

/// Read and merge explicit user/project config paths — the env-free core of
/// [`load`], so tests can exercise layering without mutating global state.
fn load_from(user_path: Option<PathBuf>, project_path: Option<PathBuf>) -> anyhow::Result<Loaded> {
    let user = read_config(user_path.as_deref())?;
    let project = read_config(project_path.as_deref())?;
    let effective = user.overlaid_with(&project);
    Ok(Loaded {
        effective,
        user,
        project,
        user_path,
        project_path,
    })
}

/// Parse a config file, or the default config if `path` is `None`.
fn read_config(path: Option<&Path>) -> anyhow::Result<Config> {
    let Some(path) = path else {
        return Ok(Config::default());
    };
    let text = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("reading config {}: {e}", path.display()))?;
    toml::from_str(&text).map_err(|e| anyhow::anyhow!("parsing config {}: {e}", path.display()))
}

/// Roteiro's home directory: `$ROTEIRO_HOME` when set, else `~/.roteiro`. The one
/// place the model store, the user config, and the default log path
/// ([`default_log_path`]) resolve their base, so they always agree. Returns
/// `None` only when neither `ROTEIRO_HOME` nor a home directory is discoverable.
pub(crate) fn roteiro_home() -> Option<PathBuf> {
    if let Some(home) = std::env::var_os("ROTEIRO_HOME") {
        return Some(PathBuf::from(home));
    }
    Some(home_dir()?.join(".roteiro"))
}

/// The default rotating-log path used when file logging is enabled without an
/// explicit path (`roteiro --log`): `$ROTEIRO_HOME/logs/roteiro.log`, else
/// `~/.roteiro/logs/roteiro.log`.
pub(crate) fn default_log_path() -> Option<PathBuf> {
    Some(roteiro_home()?.join("logs").join("roteiro.log"))
}

/// The user config path: `$ROTEIRO_HOME/config.toml`, else `~/.roteiro/config.toml`
/// (mirrors the model store's home resolution).
fn user_config_path() -> Option<PathBuf> {
    Some(roteiro_home()?.join("config.toml"))
}

/// Find the project `roteiro.toml` at the **repository root** — the nearest
/// ancestor of `start` that contains a `.git` entry (per ADR-0007, the project
/// config lives alongside the git dir). Bounding discovery to the repo root
/// keeps it from ascending into parent directories *outside* the repo and stops
/// a `roteiro.toml` in a nested subdirectory from shadowing the repo-level one.
/// Returns `None` when `start` is not inside a git repository, or the root has
/// no `roteiro.toml`.
fn find_project_config(start: &Path) -> Option<PathBuf> {
    let mut dir = Some(start);
    while let Some(d) = dir {
        // `.git` is a directory in a normal clone but a file in worktrees and
        // submodules, so test existence rather than `is_dir`.
        if d.join(".git").exists() {
            let candidate = d.join("roteiro.toml");
            return candidate.is_file().then_some(candidate);
        }
        dir = d.parent();
    }
    None
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::{
        Config, NamedWorkspace, WorkspaceConfig, expand_tilde_with, find_project_config, load_from,
    };

    #[test]
    fn project_config_is_repo_root_bounded() {
        let root = std::env::temp_dir().join(format!("roteiro-disc-{}", std::process::id()));
        std::fs::remove_dir_all(&root).ok();
        let repo = root.join("repo");
        let sub = repo.join("crate").join("src");
        std::fs::create_dir_all(&sub).expect("mkdir");
        std::fs::create_dir_all(repo.join(".git")).expect("mkdir .git");

        // A `roteiro.toml` above the repo (in `root`) must NOT be picked up when
        // running from inside the repo — discovery stops at the repo root.
        std::fs::write(root.join("roteiro.toml"), "[infer]\ntop_k = 1\n").expect("write outside");
        assert_eq!(
            find_project_config(&sub),
            None,
            "no repo-root config → None, never the parent-dir one"
        );

        // With a config at the repo root, running from a nested subdir finds it.
        let at_root = repo.join("roteiro.toml");
        std::fs::write(&at_root, "[infer]\ntop_k = 2\n").expect("write root");
        assert_eq!(find_project_config(&sub), Some(at_root));

        // Not inside a git repo at all → None (the outside config is ignored).
        assert_eq!(find_project_config(&root), None);

        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn config_layering_precedence_and_errors() {
        let dir = std::env::temp_dir().join(format!("roteiro-cfg-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let user = dir.join("config.toml");
        let project = dir.join("roteiro.toml");

        // No config files → all defaults.
        let loaded = load_from(None, None).expect("load");
        assert_eq!(loaded.effective, Config::default());
        assert!(loaded.project_path.is_none());

        // User layer sets both infer knobs and an embedding model; project layer
        // overrides min_confidence only.
        std::fs::write(
            &user,
            "[infer]\nmin_confidence = 0.3\ntop_k = 9\n[models]\nembedding = \"bge-base-en-v1.5\"\n",
        )
        .expect("write user");
        std::fs::write(&project, "[infer]\nmin_confidence = 0.7\n").expect("write project");

        let loaded = load_from(Some(user.clone()), Some(project.clone())).expect("load");
        // project wins for min_confidence; user's top_k + embedding survive.
        assert_eq!(loaded.effective.infer.min_confidence, Some(0.7));
        assert_eq!(loaded.effective.infer.top_k, Some(9));
        assert_eq!(
            loaded.effective.models.embedding.as_deref(),
            Some("bge-base-en-v1.5")
        );
        assert_eq!(loaded.user.infer.min_confidence, Some(0.3));
        assert_eq!(loaded.project.infer.min_confidence, Some(0.7));

        // Unknown keys are ignored (forward-compatible).
        std::fs::write(&project, "[future]\nwhatever = true\n[infer]\ntop_k = 2\n").expect("write");
        let loaded = load_from(None, Some(project.clone())).expect("unknown keys ignored");
        assert_eq!(loaded.effective.infer.top_k, Some(2));

        // A malformed file is a hard error.
        std::fs::write(&project, "[infer]\nmin_confidence = = =\n").expect("write");
        assert!(
            load_from(None, Some(project.clone())).is_err(),
            "malformed TOML must error"
        );

        // `[pins]` parses, and merges per key (project over user).
        std::fs::write(&user, "[pins]\napp = \"v{tag}\"\nother = \"user-{tag}\"\n").expect("write");
        std::fs::write(&project, "[pins]\napp = \"release-{tag}\"\n").expect("write");
        let loaded = load_from(Some(user), Some(project)).expect("load");
        assert_eq!(
            loaded.effective.pins.get("app").map(String::as_str),
            Some("release-{tag}")
        );
        assert_eq!(
            loaded.effective.pins.get("other").map(String::as_str),
            Some("user-{tag}")
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    /// `[debt] ignore` is the one list-valued key that **merges** across layers
    /// (issue #321c): a project pattern must not silently discard every global
    /// one, because the user then sees debt they believed excluded — or misses
    /// debt they believed counted — with nothing to indicate why.
    #[test]
    fn debt_ignore_merges_across_layers_instead_of_replacing() {
        let dir = std::env::temp_dir().join(format!("roteiro-cfg-debt-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let user = dir.join("config.toml");
        let project = dir.join("roteiro.toml");

        std::fs::write(&user, "[debt]\nignore = [\"vendor/**\", \"target/**\"]\n").expect("user");
        std::fs::write(&project, "[debt]\nignore = [\"thirdparty/**\"]\n").expect("project");
        let loaded = load_from(Some(user.clone()), Some(project.clone())).expect("load");

        // The union, inherited first — NOT just the project's one pattern.
        assert_eq!(
            loaded.effective.debt.ignore.as_deref(),
            Some(
                [
                    "vendor/**".to_owned(),
                    "target/**".to_owned(),
                    "thirdparty/**".to_owned()
                ]
                .as_slice()
            ),
        );

        // Every pattern reports the layer it came from, so the merge is legible.
        assert_eq!(
            loaded.debt_ignore_sources(),
            vec![
                ("vendor/**", "user"),
                ("target/**", "user"),
                ("thirdparty/**", "project"),
            ]
        );
        assert!(loaded.debt_ignore_discarded().is_empty(), "nothing dropped");

        // A pattern named by both layers appears once, tagged with both.
        std::fs::write(
            &project,
            "[debt]\nignore = [\"vendor/**\", \"thirdparty/**\"]\n",
        )
        .expect("project");
        let loaded = load_from(Some(user.clone()), Some(project.clone())).expect("load");
        assert_eq!(
            loaded.effective.debt.ignore.as_deref(),
            Some(
                [
                    "vendor/**".to_owned(),
                    "target/**".to_owned(),
                    "thirdparty/**".to_owned()
                ]
                .as_slice()
            ),
            "a duplicate pattern is not listed twice"
        );
        assert_eq!(
            loaded.debt_ignore_sources()[0],
            ("vendor/**", "project, user")
        );

        // One layer alone still works, in both directions.
        let only_user = load_from(Some(user.clone()), None).expect("load");
        assert_eq!(
            only_user.effective.debt.ignore.as_deref(),
            Some(["vendor/**".to_owned(), "target/**".to_owned()].as_slice())
        );
        let only_project = load_from(None, Some(project.clone())).expect("load");
        assert_eq!(
            only_project.effective.debt.ignore.as_deref(),
            Some(["vendor/**".to_owned(), "thirdparty/**".to_owned()].as_slice())
        );
        // Neither layer ⇒ unset, as before.
        assert!(
            load_from(None, None)
                .expect("load")
                .effective
                .debt
                .ignore
                .is_none()
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    /// The answer to "how do I remove an inherited pattern?": `ignore_reset`
    /// drops the inherited list wholesale, and `roteiro config` can name what it
    /// dropped — an explicit reset rather than a `!pattern` negation that would
    /// fail silently on a typo (see [`super::DebtConfig::ignore_reset`]).
    #[test]
    fn debt_ignore_reset_drops_the_inherited_list_visibly() {
        let dir = std::env::temp_dir().join(format!("roteiro-cfg-reset-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let user = dir.join("config.toml");
        let project = dir.join("roteiro.toml");
        std::fs::write(&user, "[debt]\nignore = [\"vendor/**\", \"target/**\"]\n").expect("user");

        // With the reset, only the project's own patterns remain…
        std::fs::write(
            &project,
            "[debt]\nignore_reset = true\nignore = [\"thirdparty/**\"]\n",
        )
        .expect("project");
        let loaded = load_from(Some(user.clone()), Some(project.clone())).expect("load");
        assert_eq!(
            loaded.effective.debt.ignore.as_deref(),
            Some(["thirdparty/**".to_owned()].as_slice())
        );
        // …and the drop is reportable, not merely effective.
        assert_eq!(
            loaded.debt_ignore_discarded(),
            vec!["vendor/**", "target/**"]
        );

        // The kebab-case spelling is accepted too.
        std::fs::write(
            &project,
            "[debt]\nignore-reset = true\nignore = [\"thirdparty/**\"]\n",
        )
        .expect("project");
        let kebab = load_from(Some(user.clone()), Some(project.clone())).expect("load");
        assert_eq!(kebab.effective.debt.ignore_reset, Some(true));
        assert_eq!(
            kebab.effective.debt.ignore.as_deref(),
            Some(["thirdparty/**".to_owned()].as_slice())
        );

        // A reset with no list of its own excludes nothing at all.
        std::fs::write(&project, "[debt]\nignore_reset = true\n").expect("project");
        let bare = load_from(Some(user.clone()), Some(project.clone())).expect("load");
        assert!(bare.effective.debt.ignore.is_none(), "inherits nothing");
        assert_eq!(bare.debt_ignore_discarded(), vec!["vendor/**", "target/**"]);

        // `ignore_reset = false` is not a reset: the merge stands.
        std::fs::write(
            &project,
            "[debt]\nignore_reset = false\nignore = [\"thirdparty/**\"]\n",
        )
        .expect("project");
        let off = load_from(Some(user), Some(project)).expect("load");
        assert_eq!(
            off.effective.debt.ignore.as_deref(),
            Some(
                [
                    "vendor/**".to_owned(),
                    "target/**".to_owned(),
                    "thirdparty/**".to_owned()
                ]
                .as_slice()
            )
        );
        assert!(off.debt_ignore_discarded().is_empty());

        std::fs::remove_dir_all(&dir).ok();
    }

    /// A **user-layer** `ignore_reset` must not surface in the effective config
    /// (PR #343 review). It governs nothing — [`super::merge_ignore`] reads only
    /// the nearer (project) layer's flag, and the user layer is the bottom — so
    /// inheriting it made `effective` claim a reset that never happened, and
    /// `roteiro config` announce "inherited patterns dropped" over a list where
    /// every inherited pattern was still present.
    #[test]
    fn an_inert_user_layer_reset_does_not_claim_a_reset_that_never_happened() {
        let dir = std::env::temp_dir().join(format!("roteiro-cfg-inert-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let user = dir.join("config.toml");
        let project = dir.join("roteiro.toml");

        // The scenario: the user asks for a reset, the project does not.
        std::fs::write(
            &user,
            "[debt]\nignore_reset = true\nignore = [\"vendor/**\", \"target/**\"]\n",
        )
        .expect("user");
        std::fs::write(&project, "[debt]\nignore = [\"thirdparty/**\"]\n").expect("project");
        let loaded = load_from(Some(user.clone()), Some(project.clone())).expect("load");

        // The effective flag records the merge that ran, which reset nothing.
        assert_ne!(
            loaded.effective.debt.ignore_reset,
            Some(true),
            "a user-layer reset governs nothing, so it must not appear as one in \
             the effective config — that is the claim `roteiro config` prints"
        );
        // The inert request is still *visible*, since a silent no-op is exactly
        // what this key was introduced to avoid.
        assert!(
            loaded.debt_ignore_reset_was_inert(),
            "the user asked for a reset that did nothing; that must be reportable"
        );

        // Nothing was discarded, and nothing claims to have been. (This list could
        // not have caught the defect on its own: with no reset in force the kept
        // list is the union, so it is a superset of the user's and filters empty.)
        assert!(
            loaded.debt_ignore_discarded().is_empty(),
            "no pattern was dropped, so none may be reported as dropped: {:?}",
            loaded.debt_ignore_discarded()
        );

        // And the inert flag did not accidentally start *resetting* anything:
        // both layers' patterns survive, in merge order.
        assert_eq!(
            loaded.effective.debt.ignore.as_deref(),
            Some(
                [
                    "vendor/**".to_owned(),
                    "target/**".to_owned(),
                    "thirdparty/**".to_owned()
                ]
                .as_slice()
            ),
            "the merge is unaffected — this was only ever a reporting defect"
        );

        // The project layer's reset is unaffected by the change: it governs, so it
        // is reported, and the user's flag is not what put it there.
        std::fs::write(
            &project,
            "[debt]\nignore_reset = true\nignore = [\"thirdparty/**\"]\n",
        )
        .expect("project");
        let both = load_from(Some(user.clone()), Some(project)).expect("load");
        assert_eq!(both.effective.debt.ignore_reset, Some(true));
        assert_eq!(both.debt_ignore_discarded(), vec!["vendor/**", "target/**"]);
        assert!(
            !both.debt_ignore_reset_was_inert(),
            "a reset really happened, so `roteiro config` reports the drop rather \
             than a second note saying the user's own flag was individually inert"
        );

        // With no project config at all, the user's reset is still inert.
        let alone = load_from(Some(user), None).expect("load");
        assert_ne!(alone.effective.debt.ignore_reset, Some(true));
        assert!(alone.debt_ignore_reset_was_inert());
        assert_eq!(
            alone.effective.debt.ignore.as_deref(),
            Some(["vendor/**".to_owned(), "target/**".to_owned()].as_slice()),
            "and it resets none of the user's own patterns"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    /// Merging is scoped to the **exclusion** list. Discovery and selection lists
    /// stay replace-wins, so a global `[workspace] roots` cannot silently add
    /// repos a project never named.
    #[test]
    fn other_list_keys_still_replace_rather_than_merge() {
        let dir = std::env::temp_dir().join(format!("roteiro-cfg-lists-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let user = dir.join("config.toml");
        let project = dir.join("roteiro.toml");
        std::fs::write(
            &user,
            "[workspace]\nroots = [\"/u/one\"]\n[serve]\nmodels = [\"a\"]\n",
        )
        .expect("user");
        std::fs::write(
            &project,
            "[workspace]\nroots = [\"/p/two\"]\n[serve]\nmodels = [\"b\"]\n",
        )
        .expect("project");
        let loaded = load_from(Some(user), Some(project)).expect("load");
        assert_eq!(
            loaded.effective.workspace.roots.as_deref(),
            Some(["/p/two".to_owned()].as_slice()),
            "discovery roots replace"
        );
        assert_eq!(
            loaded.effective.serve.models.as_deref(),
            Some(["b".to_owned()].as_slice()),
            "model selection replaces"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The `[telemetry]` block parses, and overlays per field (project over user)
    /// like the other tables: an unset field falls back to the user layer.
    #[test]
    fn telemetry_block_parses_and_overlays_per_field() {
        // Absent table ⇒ all fields None (file logging off by default).
        let none: Config = toml::from_str("[infer]\ntop_k = 1\n").expect("parse");
        assert_eq!(none.telemetry, super::TelemetryConfig::default());

        let user: Config = toml::from_str(
            "[telemetry]\nfile = \"~/.roteiro/logs/roteiro.log\"\nrotation = \"daily\"\nformat = \"otel\"\n",
        )
        .expect("parse user");
        assert_eq!(
            user.telemetry.file.as_deref(),
            Some("~/.roteiro/logs/roteiro.log")
        );
        assert_eq!(user.telemetry.rotation.as_deref(), Some("daily"));

        // Project overrides only `rotation`; user's `file`/`format` survive.
        let project: Config =
            toml::from_str("[telemetry]\nrotation = \"hourly\"\n").expect("parse project");
        let merged = user.overlaid_with(&project);
        assert_eq!(merged.telemetry.rotation.as_deref(), Some("hourly"));
        assert_eq!(
            merged.telemetry.file.as_deref(),
            Some("~/.roteiro/logs/roteiro.log")
        );
        assert_eq!(merged.telemetry.format.as_deref(), Some("otel"));
    }

    /// Backward compat: a legacy `[workspace]`-only config parses, merges, and
    /// resolves to exactly one `default` linked workspace — as before the
    /// multi-workspace fields existed.
    #[test]
    fn legacy_workspace_only_resolves_to_one_default_linked_group() {
        let cfg = Config {
            workspace: WorkspaceConfig {
                roots: Some(vec!["/code".to_owned()]),
                repos: Some(vec!["/code/extra".to_owned()]),
            },
            ..Default::default()
        };
        let resolved = cfg.resolved_workspaces().expect("resolve");
        assert_eq!(resolved.len(), 1);
        let d = &resolved[0];
        assert_eq!(d.name, "default");
        assert!(d.linked);
        assert_eq!(d.roots, vec!["/code".to_owned()]);
        assert_eq!(d.repos, vec!["/code/extra".to_owned()]);

        // A config naming no workspaces at all yields no groups.
        assert!(
            Config::default()
                .resolved_workspaces()
                .expect("resolve default")
                .is_empty()
        );

        // A user-layer `[workspace]` still survives an empty project overlay, and
        // the new fields default to empty (they don't perturb a legacy config).
        let user: Config = toml::from_str("[workspace]\nroots = [\"/code\"]\n").expect("parse");
        let merged = user.overlaid_with(&Config::default());
        assert_eq!(
            merged.workspace.roots.as_deref(),
            Some(&["/code".to_owned()][..])
        );
        assert!(merged.workspaces.is_empty());
        assert!(merged.standalone.is_empty());
    }

    /// A config with `[[workspaces]]` + `[standalone]` (and a legacy `[workspace]`)
    /// partitions into linked named groups first, then one unlinked single-repo
    /// group per discovered standalone repo, with the right names and flags.
    #[test]
    fn named_workspaces_and_standalone_partition_correctly() {
        let base = std::env::temp_dir().join(format!("roteiro-rw-{}", std::process::id()));
        std::fs::remove_dir_all(&base).ok();
        // Two synthetic standalone repos (a `.git` entry marks a repo) under a root.
        for name in ["docs", "tools"] {
            std::fs::create_dir_all(base.join("solo").join(name).join(".git")).expect("mkrepo");
        }

        let cfg = Config {
            workspace: WorkspaceConfig {
                roots: Some(vec!["/legacy".to_owned()]),
                repos: None,
            },
            workspaces: vec![
                NamedWorkspace {
                    name: "api".to_owned(),
                    roots: Some(vec!["/api".to_owned()]),
                    repos: None,
                },
                NamedWorkspace {
                    name: "web".to_owned(),
                    roots: None,
                    repos: Some(vec!["/web/app".to_owned()]),
                },
            ],
            standalone: WorkspaceConfig {
                roots: Some(vec![base.join("solo").to_string_lossy().into_owned()]),
                repos: None,
            },
            ..Default::default()
        };
        let resolved = cfg.resolved_workspaces().expect("resolve");
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();

        // Legacy `[workspace]` folds in as `default` first, then the named linked
        // groups, then the standalone singletons (discovered in sorted order).
        assert_eq!(names, vec!["default", "api", "web", "docs", "tools"]);

        let by_name = |n: &str| resolved.iter().find(|r| r.name == n).expect("group");
        assert!(by_name("default").linked);
        assert!(by_name("api").linked);
        assert!(by_name("web").linked);

        let docs = by_name("docs");
        assert!(!docs.linked, "standalone repos are unlinked");
        assert!(docs.roots.is_empty());
        assert_eq!(docs.repos.len(), 1, "a standalone group is a singleton");
        assert!(docs.repos[0].ends_with("docs"));
        assert!(!by_name("tools").linked);

        std::fs::remove_dir_all(&base).ok();
    }

    /// A standalone repo whose directory name collides with a linked workspace name
    /// takes a `-2` suffix (dedupe like the workspace registry); the linked group
    /// keeps its slot.
    #[test]
    fn standalone_names_dedupe_against_linked_names() {
        let base = std::env::temp_dir().join(format!("roteiro-rw-dedupe-{}", std::process::id()));
        std::fs::remove_dir_all(&base).ok();
        let repo = base.join("default");
        std::fs::create_dir_all(repo.join(".git")).expect("mkrepo");

        let cfg = Config {
            workspace: WorkspaceConfig {
                roots: Some(vec!["/legacy".to_owned()]),
                repos: None,
            },
            standalone: WorkspaceConfig {
                roots: None,
                repos: Some(vec![repo.to_string_lossy().into_owned()]),
            },
            ..Default::default()
        };
        let resolved = cfg.resolved_workspaces().expect("resolve");
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["default", "default-2"]);
        // The linked `default` keeps its slot; the standalone takes `default-2`.
        assert!(
            resolved
                .iter()
                .find(|r| r.name == "default")
                .unwrap()
                .linked
        );
        assert!(
            !resolved
                .iter()
                .find(|r| r.name == "default-2")
                .unwrap()
                .linked
        );

        std::fs::remove_dir_all(&base).ok();
    }

    /// The new fields parse from TOML and overlay like `links`: a project-layer
    /// `[[workspaces]]` wins outright, while an unset `[standalone]` falls back to
    /// the user layer.
    #[test]
    fn multi_workspace_fields_parse_and_overlay() {
        let user: Config = toml::from_str(
            "[[workspaces]]\nname = \"api\"\nroots = [\"/api\"]\n\
             [standalone]\nrepos = [\"/solo/x\"]\n",
        )
        .expect("parse user");
        assert_eq!(user.workspaces.len(), 1);
        assert_eq!(user.workspaces[0].name, "api");
        assert_eq!(
            user.standalone.repos.as_deref(),
            Some(&["/solo/x".to_owned()][..])
        );

        let project: Config =
            toml::from_str("[[workspaces]]\nname = \"web\"\n").expect("parse project");
        let merged = user.overlaid_with(&project);
        // `[[workspaces]]` from the project layer wins outright.
        assert_eq!(merged.workspaces.len(), 1);
        assert_eq!(merged.workspaces[0].name, "web");
        // `[standalone]` unset in the project layer ⇒ the user layer's survives.
        assert_eq!(
            merged.standalone.repos.as_deref(),
            Some(&["/solo/x".to_owned()][..])
        );
    }

    /// A **linked** workspace name collision is a config error (never a silent
    /// rename that would resolve links against the wrong repos) — both between two
    /// `[[workspaces]]` and between a `[[workspaces]]` and the folded-in `default`.
    #[test]
    fn duplicate_linked_workspace_names_are_a_config_error() {
        // Two `[[workspaces]]` sharing a name → error.
        let cfg = Config {
            workspaces: vec![
                NamedWorkspace {
                    name: "api".to_owned(),
                    roots: Some(vec!["/a".to_owned()]),
                    repos: None,
                },
                NamedWorkspace {
                    name: "api".to_owned(),
                    roots: Some(vec!["/b".to_owned()]),
                    repos: None,
                },
            ],
            ..Default::default()
        };
        let err = cfg
            .resolved_workspaces()
            .expect_err("duplicate [[workspaces]] name must error")
            .to_string();
        assert!(
            err.contains("duplicate workspace name") && err.contains("api"),
            "{err}"
        );

        // A `[[workspaces]]` named `default` collides with the legacy `[workspace]`
        // that folds in as `default` → error.
        let cfg = Config {
            workspace: WorkspaceConfig {
                roots: Some(vec!["/legacy".to_owned()]),
                repos: None,
            },
            workspaces: vec![NamedWorkspace {
                name: "default".to_owned(),
                roots: Some(vec!["/x".to_owned()]),
                repos: None,
            }],
            ..Default::default()
        };
        let err = cfg
            .resolved_workspaces()
            .expect_err("[[workspaces]] named `default` must collide with the legacy fold-in")
            .to_string();
        assert!(err.contains("default"), "{err}");
    }

    /// A `[standalone]` root holding several repos expands to one **single-repo**,
    /// unlinked group per repo — never one multi-repo unlinked group.
    #[test]
    fn standalone_root_yields_one_single_repo_group_per_repo() {
        let base = std::env::temp_dir().join(format!("roteiro-rw-solo-{}", std::process::id()));
        std::fs::remove_dir_all(&base).ok();
        for name in ["svc-a", "svc-b"] {
            std::fs::create_dir_all(base.join("pool").join(name).join(".git")).expect("mkrepo");
        }

        let cfg = Config {
            standalone: WorkspaceConfig {
                roots: Some(vec![base.join("pool").to_string_lossy().into_owned()]),
                repos: None,
            },
            ..Default::default()
        };
        let resolved = cfg.resolved_workspaces().expect("resolve");
        assert_eq!(resolved.len(), 2, "one group per repo: {resolved:?}");
        for rw in &resolved {
            assert!(!rw.linked, "standalone repos are unlinked: {rw:?}");
            assert_eq!(rw.repos.len(), 1, "each is a singleton: {rw:?}");
            assert!(rw.roots.is_empty(), "expanded, not a roots scan: {rw:?}");
        }
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["svc-a", "svc-b"],
            "named after repo dirs, sorted"
        );

        std::fs::remove_dir_all(&base).ok();
    }

    /// The shared `~` expansion (the seam every workspace path flows through):
    /// bare `~` and `~/rest` map onto the injected home; anything else is verbatim.
    #[test]
    fn expand_tilde_handles_bare_and_prefixed_and_passes_others_through() {
        let home = std::ffi::OsString::from("/home/alice");
        let h = Some(home.as_os_str());
        assert_eq!(expand_tilde_with("~", h), PathBuf::from("/home/alice"));
        assert_eq!(
            expand_tilde_with("~/foo/bar", h),
            PathBuf::from("/home/alice/foo/bar")
        );
        // No leading `~` → unchanged (absolute and relative alike).
        assert_eq!(
            expand_tilde_with("/abs/path", h),
            PathBuf::from("/abs/path")
        );
        assert_eq!(expand_tilde_with("rel/path", h), PathBuf::from("rel/path"));
        // `~user` (neither `~` nor `~/`) is not home-expansion — left verbatim.
        assert_eq!(expand_tilde_with("~bob/x", h), PathBuf::from("~bob/x"));
        // No home available → the `~` forms are left as-is rather than panicking.
        assert_eq!(expand_tilde_with("~/foo", None), PathBuf::from("~/foo"));
        assert_eq!(expand_tilde_with("~", None), PathBuf::from("~"));
    }

    /// A leading `~` in every workspace path input — legacy `[workspace]`,
    /// `[[workspaces]]`, and `[standalone]`, in both `roots` and `repos` — expands
    /// to the user's home at the resolution boundary, so `rto_graph` (and git)
    /// never see a literal `~`. A path without a leading `~` is passed through.
    #[test]
    fn resolved_workspaces_expand_leading_tilde_in_all_path_inputs() {
        // Home, from the same source `expand_tilde` reads, so the expectation is
        // deterministic wherever the test runs. With no home set, `expand_tilde`
        // documents that it leaves `~` unchanged — there is nothing to expand
        // against, so skip rather than assert against a home that doesn't exist
        // (keeps a sanitized-env run green, matching production behaviour).
        let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))
        else {
            return;
        };
        let home = Path::new(&home);
        let joined = |rest: &str| home.join(rest).to_string_lossy().into_owned();

        let cfg = Config {
            workspace: WorkspaceConfig {
                roots: Some(vec!["~/legacy/root".to_owned()]),
                repos: Some(vec!["~/legacy/repo".to_owned()]),
            },
            workspaces: vec![NamedWorkspace {
                name: "api".to_owned(),
                roots: Some(vec!["~/api/root".to_owned()]),
                repos: Some(vec!["~/api/repo".to_owned()]),
            }],
            standalone: WorkspaceConfig {
                roots: None,
                // Explicit standalone repos become their own single-repo groups
                // with no filesystem discovery, so the expanded path is directly
                // observable. `~` roots share the identical `expand_tilde` call
                // (covered by the pure-function test above).
                repos: Some(vec!["~/solo/repo".to_owned(), "/abs/solo".to_owned()]),
            },
            ..Default::default()
        };
        let resolved = cfg.resolved_workspaces().expect("resolve");
        let by_name = |n: &str| resolved.iter().find(|r| r.name == n).expect("group");

        // Legacy `[workspace]` → `default`: roots and repos expanded.
        let d = by_name("default");
        assert_eq!(d.roots, vec![joined("legacy/root")]);
        assert_eq!(d.repos, vec![joined("legacy/repo")]);

        // `[[workspaces]]`: roots and repos expanded.
        let api = by_name("api");
        assert_eq!(api.roots, vec![joined("api/root")]);
        assert_eq!(api.repos, vec![joined("api/repo")]);

        // `[standalone]` explicit repo: expanded, named after the repo dir; a
        // non-`~` absolute path is passed through unchanged.
        assert_eq!(by_name("repo").repos, vec![joined("solo/repo")]);
        assert_eq!(by_name("solo").repos, vec!["/abs/solo".to_owned()]);

        // No expanded path still carries a literal leading `~`.
        for rw in &resolved {
            for p in rw.roots.iter().chain(&rw.repos) {
                assert!(!p.starts_with('~'), "unexpanded tilde survived: {p}");
            }
        }
    }
}