tix-tracker 0.10.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
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
//! The stable view registry and its scope metadata (WP01).
//!
//! # Storage
//!
//! View definitions live in `tix.toml` under `[views.<view-id>]`, beside
//! `[teams.<label>]`, `[cycles.<name>]` and `[kanban.<name>]` — the existing
//! repository-owned, ordered registries (C-001, research R5). The section is
//! **omitted when empty**, so a repository that has never saved a view keeps
//! round-tripping its legacy `tix.toml` unchanged. Record *order* is restored
//! from the document's header order, exactly as the other registries do it
//! (D-02: declaration order is the order a surface lists them in).
//!
//! ```toml
//! [views.v-1f0c9a3d5b7e2411]
//! id = "v-1f0c9a3d5b7e2411"
//! name = "Platform active"
//!
//! [views.v-1f0c9a3d5b7e2411.scope]
//! kind = "project"
//! project_id = "p-platform"
//!
//! [views.v-1f0c9a3d5b7e2411.plan]
//! sort = "due"
//! ```
//!
//! # Identity
//!
//! The **id is the identity**; the name is a display label (C-002). An id is
//! allocated once — [`ViewId::generate`] for a new definition, or an explicit id
//! a caller chooses — and never changes afterwards. Renaming a view is a label
//! change: [`ViewRegistry::rename`] cannot touch the id, the scope, or the plan,
//! and a test pins that (T001/T006). Generated ids are 64 random bits drawn from
//! the process hasher (`std::collections::hash_map::RandomState`), so no new
//! dependency and no counter to lose: an id cannot be handed to a second view,
//! because there is no allocator that could hand it out twice.
//!
//! A record's `id` and its `[views.<id>]` key must agree. The key *is* the table
//! address, so a disagreement is an identity that points two ways; the registry
//! refuses to deserialize it rather than pick a winner.
//!
//! # Scope
//!
//! `scope.kind` is a closed family (data-model §2):
//!
//! | kind | required metadata | precedence |
//! |---|---|---|
//! | `repository` | none | 1 |
//! | `project` | `project_id`, resolved through [`ProjectDirectory`] | 2 |
//! | `user_share` | `owner` and/or `shared_with` | 3 |
//!
//! Selection by name uses "most specific explicit scope wins": user/share over
//! project over repository. Two candidates tied at the winning rank are a
//! **conflict**, reported with both ids in a deterministic order — the caller
//! selects by stable id instead (decision `01M3C93KZVGS0RCSY93E1B3NXY`). A scope
//! whose own metadata contradicts itself (`kind = "repository"` carrying a
//! `project_id`) is refused on the write path **and** at load: `tix.toml` never
//! becomes a registry holding a view this build cannot describe, and the read-only
//! [`ViewRegistry::diagnostics`] pass names the same conflicts for a registry a
//! caller built in memory.
//!
//! A project id that the project registry does not know is **missing**, not
//! corrupt: it loads (a deleted project leaves dangling references by design, so a
//! view must survive it) and it is refused when a caller tries to *write* the
//! registry, because writing a view that cannot resolve is what the atomicity
//! rule in C-008 is about.
//!
//! # Unknown metadata
//!
//! A record carries [`SavedView::extensions`], and a scope carries
//! [`ViewScope::extensions`]: every key the typed fields do not name. They are
//! preserved verbatim through load/save (NFR-002) and reported as
//! [`ViewDiagnosticKind::UnknownMetadata`] diagnostics — preserved *and*
//! diagnosed, never silently discarded (data-model §7). The typed `plan` table is
//! opaque here for the same reason: WP02 interprets it, the registry only keeps
//! it byte-for-byte.
//!
//! # The write path
//!
//! [`ViewRegistry::commit`] is the only writer: it validates the complete
//! candidate registry (structure, then scope resolution through the caller's
//! project directory), validates the whole config, and only then calls the
//! existing atomic `Config::save`. A rejection ([`ViewWriteError::Refused`])
//! writes no `tix.toml` and appends no History; the caller's `Config` is not
//! mutated either, because the assignment happens after the file is durable. An
//! accepted change is idempotent — committing the same registry twice produces the
//! same bytes.

use std::collections::BTreeSet;
use std::fmt;
use std::hash::{BuildHasher, Hash, Hasher};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::config::Config;
use crate::error::TixError;

/// The result of a view-registry operation that can be **refused**.
///
/// A refusal is a decision, not a failure: the input was checked and rejected,
/// with the diagnostics that say why. Every operation that returns this type
/// guarantees the rejection left the registry it was given unchanged, and that no
/// file was written.
pub type ViewResult<T> = std::result::Result<T, ViewRefusal>;

/// The result of a view-registry **write**.
///
/// Two genuinely different outcomes, kept apart because a caller reports them
/// differently: [`ViewWriteError::Refused`] is the registry declining the
/// candidate (nothing was written, and the diagnostics explain it), while
/// [`ViewWriteError::Failed`] is infrastructure — the config could not be
/// validated or the atomic save could not complete. Both leave `tix.toml` and the
/// caller's in-memory `Config` untouched.
pub type ViewWriteResult<T> = std::result::Result<T, ViewWriteError>;

/// A write that was refused or that failed for an infrastructure reason.
#[derive(Debug)]
pub enum ViewWriteError {
    /// The candidate registry was rejected before any write.
    Refused(ViewRefusal),
    /// The config could not be validated or written; the previous file is intact.
    Failed(TixError),
}

impl ViewWriteError {
    /// The refusal, when this was a decision rather than a failure.
    #[must_use]
    pub fn refusal(&self) -> Option<&ViewRefusal> {
        match self {
            Self::Refused(refusal) => Some(refusal),
            Self::Failed(_) => None,
        }
    }

    /// The infrastructure error, when this was not a refusal.
    #[must_use]
    pub fn failure(&self) -> Option<&TixError> {
        match self {
            Self::Refused(_) => None,
            Self::Failed(error) => Some(error),
        }
    }
}

impl From<ViewRefusal> for ViewWriteError {
    fn from(refusal: ViewRefusal) -> Self {
        Self::Refused(refusal)
    }
}

impl From<TixError> for ViewWriteError {
    fn from(error: TixError) -> Self {
        Self::Failed(error)
    }
}

impl fmt::Display for ViewWriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Refused(refusal) => write!(f, "{refusal}"),
            Self::Failed(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for ViewWriteError {}

/// The stable names of a view diagnostic (data-model §7).
///
/// The set is the vocabulary surfaces render and match on, so the names are
/// pinned by tests. `invalid_filter`, `invalid_sort`, `invalid_group` and
/// `invalid_visibility` are plan-field diagnostics — WP02's `views::plan`
/// constructs them, and they live here because a surface must not have to learn a
/// second vocabulary for the plan half of the same record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ViewDiagnosticKind {
    /// A record that cannot be a view at all: a blank or ill-formed id, a blank
    /// name.
    ///
    /// WP01 adds this name to data-model §7's vocabulary because that list names
    /// *field* problems (a filter, a sort key, a scope) and has no name for the
    /// record-level checks T001 requires. Nothing else is folded in here: an id
    /// problem is not a scope problem, and reporting it as one would make the kind
    /// useless for matching.
    InvalidView,
    /// A filter criterion the existing grammar does not accept.
    InvalidFilter,
    /// A sort key outside the existing vocabulary.
    InvalidSort,
    /// A group key outside the existing vocabulary.
    InvalidGroup,
    /// A board visibility setting that does not exist.
    InvalidVisibility,
    /// Scope metadata that contradicts itself, or a tie selection cannot resolve.
    ScopeConflict,
    /// No view matches the selection.
    UnknownView,
    /// A field the registry does not interpret, preserved for the caller.
    UnknownMetadata,
}

impl ViewDiagnosticKind {
    /// The contract name of this kind (data-model §7).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidView => "invalid_view",
            Self::InvalidFilter => "invalid_filter",
            Self::InvalidSort => "invalid_sort",
            Self::InvalidGroup => "invalid_group",
            Self::InvalidVisibility => "invalid_visibility",
            Self::ScopeConflict => "scope_conflict",
            Self::UnknownView => "unknown_view",
            Self::UnknownMetadata => "unknown_metadata",
        }
    }
}

impl fmt::Display for ViewDiagnosticKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One problem with one view, field, or scope.
///
/// `field` is the **record-relative** path the problem sits at (`"name"`,
/// `"scope.project_id"`, `"extensions.colour"`), because the record the caller
/// asked about is already known from `view_id`; the message is self-contained so
/// a surface can render it without rebuilding the path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ViewDiagnostic {
    kind: ViewDiagnosticKind,
    view_id: Option<ViewId>,
    field: Option<String>,
    message: String,
    remedy: Option<String>,
}

impl ViewDiagnostic {
    /// A diagnostic about a view as a whole.
    #[must_use]
    pub fn for_view(
        kind: ViewDiagnosticKind,
        view_id: &ViewId,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            view_id: Some(view_id.clone()),
            field: None,
            message: message.into(),
            remedy: None,
        }
    }

    /// A diagnostic about a definition that is not in the registry (yet).
    #[must_use]
    pub fn new(kind: ViewDiagnosticKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            view_id: None,
            field: None,
            message: message.into(),
            remedy: None,
        }
    }

    /// Name the record-relative field this diagnostic is about.
    #[must_use]
    pub fn with_field(mut self, field: impl Into<String>) -> Self {
        self.field = Some(field.into());
        self
    }

    /// State what the caller can do about it.
    #[must_use]
    pub fn with_remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    /// The contract name of this diagnostic.
    #[must_use]
    pub const fn kind(&self) -> ViewDiagnosticKind {
        self.kind
    }

    /// The view this is about, when the registry knows it.
    #[must_use]
    pub fn view_id(&self) -> Option<&ViewId> {
        self.view_id.as_ref()
    }

    /// The record-relative field, when the problem is field-shaped.
    #[must_use]
    pub fn field(&self) -> Option<&str> {
        self.field.as_deref()
    }

    /// The human-readable part.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The actionable part, when there is one.
    #[must_use]
    pub fn remedy(&self) -> Option<&str> {
        self.remedy.as_deref()
    }
}

/// One or more diagnostics, gathered as a refusal.
///
/// A refusal renders **every** diagnostic through
/// [`crate::error::render_diagnostics`], the one renderer `tix link` and
/// `tix parent set` already share, so a user who learned one refusal format does
/// not have to learn a second.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ViewRefusal {
    diagnostics: Vec<ViewDiagnostic>,
}

impl ViewRefusal {
    /// Gather a non-empty diagnostic set.
    ///
    /// # Panics
    ///
    /// Panics on an empty set: a refusal with no diagnostic cannot explain
    /// itself, and the callers that build one always have at least one reason.
    #[must_use]
    pub fn from_diagnostics(diagnostics: Vec<ViewDiagnostic>) -> Self {
        assert!(
            !diagnostics.is_empty(),
            "a refusal carries at least one diagnostic"
        );
        Self { diagnostics }
    }

    /// Refuse with one diagnostic.
    #[must_use]
    pub fn from_diagnostic(diagnostic: ViewDiagnostic) -> Self {
        Self {
            diagnostics: vec![diagnostic],
        }
    }

    /// Every diagnostic, in the order the operation produced them.
    #[must_use]
    pub fn diagnostics(&self) -> &[ViewDiagnostic] {
        &self.diagnostics
    }

    /// The first diagnostic's kind — what a surface switches on for one line.
    #[must_use]
    pub fn kind(&self) -> ViewDiagnosticKind {
        self.diagnostics[0].kind()
    }

    /// The first diagnostic's message.
    #[must_use]
    pub fn message(&self) -> &str {
        self.diagnostics[0].message()
    }

    /// All diagnostics as one line, through the shared renderer.
    #[must_use]
    pub fn render(&self) -> String {
        crate::error::render_diagnostics(
            "E-tix-views",
            self.diagnostics
                .iter()
                .map(|diagnostic| (diagnostic.kind().as_str(), diagnostic.message())),
        )
    }
}

impl From<ViewDiagnostic> for ViewRefusal {
    fn from(diagnostic: ViewDiagnostic) -> Self {
        Self::from_diagnostic(diagnostic)
    }
}

impl fmt::Display for ViewRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.render())
    }
}

impl std::error::Error for ViewRefusal {}

/// A stable view identity.
///
/// Never blank, never containing whitespace or a TOML-structural character, and
/// never reused. The type exists so "this string is an id" is checked once, at
/// the boundary, instead of at every lookup (T001).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ViewId(String);

impl ViewId {
    /// The longest id the registry accepts. Long enough for a readable name, short
    /// enough that a typo cannot turn into a paragraph in a table header.
    pub const MAX_LEN: usize = 128;

    /// Validate an explicit id.
    ///
    /// Ids are chosen by a caller (a `--id` flag) or generated. Either way the
    /// same rules apply, because the id ends up as a TOML table header:
    /// `restore_section_order` reads `[views.<id>]`, and an id containing `.` or a
    /// bracket would read as a nested table or malformed document.
    pub fn new(raw: &str) -> ViewResult<Self> {
        if raw.trim().is_empty() {
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                "a view id must not be blank",
            )
            .with_field("id")
            .with_remedy(
                "choose an id such as `platform-active`, or omit it and let tix generate one",
            )
            .into());
        }
        if raw.trim() != raw {
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                format!("view id `{raw}` has leading or trailing whitespace"),
            )
            .with_field("id")
            .into());
        }
        if raw.chars().count() > Self::MAX_LEN {
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                format!(
                    "view id is {} characters; the limit is {}",
                    raw.chars().count(),
                    Self::MAX_LEN
                ),
            )
            .with_field("id")
            .into());
        }
        if let Some(bad) = raw.chars().find(|c| is_structural(*c)) {
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                format!("view id `{raw}` contains `{bad}`"),
            )
            .with_field("id")
            .with_remedy("use letters, digits, `-`, `_`, or `:`")
            .into());
        }
        Ok(Self(raw.to_string()))
    }

    /// Allocate a new id: 64 random bits from the process hasher, `v-`-prefixed.
    ///
    /// No dependency and no counter in `tix.toml`, so there is no allocator whose
    /// state a delete could reset: two calls cannot collide in practice, and
    /// [`ViewRegistry::allocate_id`] additionally re-draws against the ids already
    /// present. The id is stable from the moment it is returned — persistence only
    /// stores it, and no operation rewrites it.
    #[must_use]
    pub fn generate() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
        std::process::id().hash(&mut hasher);
        COUNTER.fetch_add(1, Ordering::Relaxed).hash(&mut hasher);
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| since.as_nanos())
            .hash(&mut hasher);
        let bits = hasher.finish();
        // `v-` plus 16 hex digits is a valid id by construction, so the private
        // constructor is used directly rather than re-validating the format.
        Self(format!("v-{bits:016x}"))
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Characters that cannot appear in an id: whitespace, and the TOML/table syntax
/// characters an id would otherwise be able to break out of.
fn is_structural(c: char) -> bool {
    c.is_whitespace()
        || matches!(c, '.' | '"' | '\'' | '[' | ']' | '#' | '=' | '\\')
        || c.is_control()
}

impl TryFrom<String> for ViewId {
    type Error = ViewRefusal;

    fn try_from(raw: String) -> ViewResult<Self> {
        Self::new(&raw)
    }
}

impl From<ViewId> for String {
    fn from(id: ViewId) -> Self {
        id.0
    }
}

impl AsRef<str> for ViewId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for ViewId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The closed scope family (data-model §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ViewScopeKind {
    /// Visible to the whole repository. The default, so a legacy-shaped record
    /// without a scope table is a repository view.
    #[default]
    Repository,
    /// Visible to one project, resolved through the project registry.
    Project,
    /// Explicit owner/shared-with metadata. Metadata only — no permission model.
    UserShare,
}

impl ViewScopeKind {
    /// The serialized name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Repository => "repository",
            Self::Project => "project",
            Self::UserShare => "user_share",
        }
    }

    /// How specific this scope is when two views compete for one name. The higher
    /// rank wins; equal ranks are a conflict (decision
    /// `01M3C93KZVGS0RCSY93E1B3NXY`).
    #[must_use]
    pub const fn precedence(self) -> u8 {
        match self {
            Self::Repository => 1,
            Self::Project => 2,
            Self::UserShare => 3,
        }
    }
}

impl fmt::Display for ViewScopeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The derived state of a scope: whether it resolves, is missing a project, or
/// contradicts itself (data-model §2). Never persisted — a stored resolution would
/// be a second source of truth for a value that depends on the project registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeResolution {
    /// The scope's metadata is consistent and every reference exists.
    Resolved,
    /// The scope's project id is not in the project registry.
    Missing,
    /// The scope's own metadata contradicts itself.
    Conflict,
}

impl ScopeResolution {
    /// The contract name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Resolved => "resolved",
            Self::Missing => "missing",
            Self::Conflict => "conflict",
        }
    }
}

impl fmt::Display for ScopeResolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The project ids a view's project scope can be resolved against.
///
/// The seam exists because the project registry is **not this mission's to
/// own**: `first-class-projects` stores `[projects.<project-id>]` in the same
/// `tix.toml`, and when that lands its registry implements this trait. WP01 needs
/// the question ("is `p-platform` a project here?"), not the answer's storage.
/// Two implementations ship: the `[projects.<id>]` map shape, and a plain set for
/// callers and tests that have only ids.
pub trait ProjectDirectory {
    /// Whether `project_id` names a project in the active repository.
    fn contains(&self, project_id: &str) -> bool;
}

impl<T> ProjectDirectory for IndexMap<String, T> {
    fn contains(&self, project_id: &str) -> bool {
        self.contains_key(project_id)
    }
}

impl ProjectDirectory for BTreeSet<String> {
    fn contains(&self, project_id: &str) -> bool {
        self.contains(project_id)
    }
}

/// Explicit sharing/visibility metadata (data-model §2).
///
/// Every optional field is omitted from `tix.toml` when it is empty, so a
/// repository view is two lines and a project view names exactly one project.
/// Unknown keys are preserved in [`ViewScope::extensions`] rather than rejected:
/// a *newer* `tix` may have written a scope field this build does not know, and
/// dropping it would be the metadata loss the mission forbids (NFR-002).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ViewScope {
    /// Which scope family this is.
    pub kind: ViewScopeKind,
    /// The project this view belongs to; required for [`ViewScopeKind::Project`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// The identity a user/share scope belongs to. A label, not an account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
    /// Identities a user/share scope is shared with. Labels, not grants.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub shared_with: Vec<String>,
    /// Scope keys this build does not interpret, preserved verbatim.
    #[serde(flatten)]
    pub extensions: toml::Table,
}

impl ViewScope {
    /// A repository-wide scope: no sharing metadata at all.
    #[must_use]
    pub fn repository() -> Self {
        Self::default()
    }

    /// A project scope. The id is *not* resolved here — that needs the project
    /// registry, and [`ViewScope::conflicts`] is the structural check.
    #[must_use]
    pub fn project(project_id: impl Into<String>) -> Self {
        Self {
            kind: ViewScopeKind::Project,
            project_id: Some(project_id.into()),
            ..Self::default()
        }
    }

    /// A user/share scope. `owner` and `shared_with` are metadata only.
    #[must_use]
    pub fn user_share(owner: Option<String>, shared_with: Vec<String>) -> Self {
        Self {
            kind: ViewScopeKind::UserShare,
            project_id: None,
            owner,
            shared_with,
            extensions: toml::Table::new(),
        }
    }

    /// The structural problems with this scope, independent of any project
    /// registry. Empty when the scope is internally consistent.
    ///
    /// These are the rules a record cannot break *and* be meaningful under:
    /// a project scope with no project, a repository scope that names one, share
    /// metadata on a scope that is not a share, and blank or repeated identities.
    #[must_use]
    pub fn conflicts(&self) -> Vec<ViewDiagnostic> {
        let mut diagnostics = Vec::new();
        let mut conflict = |field: &str, message: String, remedy: &str| {
            diagnostics.push(
                ViewDiagnostic::new(ViewDiagnosticKind::ScopeConflict, message)
                    .with_field(format!("scope.{field}"))
                    .with_remedy(remedy),
            );
        };

        match self.kind {
            ViewScopeKind::Repository => {
                if self.project_id.is_some() {
                    conflict(
                        "project_id",
                        "a `repository` scope must not name a project".to_string(),
                        "use `kind = \"project\"` for a project scope, or drop `project_id`",
                    );
                }
            }
            ViewScopeKind::Project => match self.project_id.as_deref() {
                None => conflict(
                    "project_id",
                    "a `project` scope requires a project id".to_string(),
                    "set `project_id`, or use `kind = \"repository\"`",
                ),
                Some(project_id) if project_id.trim().is_empty() => conflict(
                    "project_id",
                    "a `project` scope has a blank project id".to_string(),
                    "set `project_id`, or use `kind = \"repository\"`",
                ),
                Some(project_id) if project_id.trim() != project_id => conflict(
                    "project_id",
                    format!("project id `{project_id}` has surrounding whitespace"),
                    "remove the whitespace",
                ),
                Some(_) => {}
            },
            ViewScopeKind::UserShare => {
                if self.project_id.is_some() {
                    conflict(
                        "project_id",
                        "a `user_share` scope must not name a project".to_string(),
                        "drop `project_id`, or use `kind = \"project\"`",
                    );
                }
                if self.owner.is_none() && self.shared_with.is_empty() {
                    conflict(
                        "owner",
                        "a `user_share` scope must name an owner or at least one shared-with identity"
                            .to_string(),
                        "set `owner` or `shared_with`, or use `kind = \"repository\"`",
                    );
                }
            }
        }

        if self.kind != ViewScopeKind::UserShare {
            if self.owner.is_some() {
                conflict(
                    "owner",
                    format!("a `{}` scope must not carry an owner", self.kind.as_str()),
                    "owner/shared-with metadata belongs to `kind = \"user_share\"`",
                );
            }
            if !self.shared_with.is_empty() {
                conflict(
                    "shared_with",
                    format!(
                        "a `{}` scope must not carry shared-with identities",
                        self.kind.as_str()
                    ),
                    "owner/shared-with metadata belongs to `kind = \"user_share\"`",
                );
            }
        }

        if let Some(owner) = self.owner.as_deref()
            && owner.trim().is_empty()
        {
            conflict(
                "owner",
                "`owner` is present but blank".to_string(),
                "remove `owner`, or name the identity it belongs to",
            );
        }

        let mut seen: Vec<&str> = Vec::new();
        for identity in &self.shared_with {
            if identity.trim().is_empty() {
                conflict(
                    "shared_with",
                    "`shared_with` contains a blank identity".to_string(),
                    "remove the blank entry",
                );
            } else if seen.contains(&identity.as_str()) {
                conflict(
                    "shared_with",
                    format!("`shared_with` names `{identity}` twice"),
                    "keep one entry per identity",
                );
            } else {
                seen.push(identity.as_str());
            }
        }

        diagnostics
    }

    /// Resolve this scope against the project registry (data-model §2).
    #[must_use]
    pub fn resolution<P: ProjectDirectory + ?Sized>(&self, projects: &P) -> ScopeResolution {
        if !self.conflicts().is_empty() {
            return ScopeResolution::Conflict;
        }
        match self.kind {
            ViewScopeKind::Project => {
                let known = self
                    .project_id
                    .as_deref()
                    .is_some_and(|project_id| projects.contains(project_id.trim()));
                if known {
                    ScopeResolution::Resolved
                } else {
                    ScopeResolution::Missing
                }
            }
            ViewScopeKind::Repository | ViewScopeKind::UserShare => ScopeResolution::Resolved,
        }
    }
}

/// One saved view definition (data-model §1).
///
/// `plan` is the **opaque** query plan table: WP02 owns its typed shape and
/// validation, and persists it here without this module having to know a single
/// field name. `extensions` holds record-level keys this build does not interpret.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SavedView {
    /// The stable identity. Set once; no operation in this module changes it.
    pub id: ViewId,
    /// The display label. Mutable — it is not the identity.
    pub name: String,
    /// The explicit scope metadata. Absent means a repository scope: a record
    /// without a `[views.<id>.scope]` table is the default, not an unknown.
    #[serde(default)]
    pub scope: ViewScope,
    /// The query/board plan, preserved verbatim until WP02 interprets it.
    #[serde(default, skip_serializing_if = "toml::Table::is_empty")]
    pub plan: toml::Table,
    /// Record-level fields this build does not interpret, preserved verbatim.
    #[serde(flatten)]
    pub extensions: toml::Table,
}

impl SavedView {
    /// A new definition with no plan. The name is trimmed, so "blank" means
    /// blank rather than "whitespace".
    pub fn new(id: ViewId, name: &str, scope: ViewScope) -> ViewResult<Self> {
        let view = Self {
            id,
            name: name.trim().to_string(),
            scope,
            plan: toml::Table::new(),
            extensions: toml::Table::new(),
        };
        view.check_structure()?;
        Ok(view)
    }

    /// Attach the plan table (WP02).
    #[must_use]
    pub fn with_plan(mut self, plan: toml::Table) -> Self {
        self.plan = plan;
        self
    }

    /// Whether this record is structurally sound on its own — the checks that need
    /// no registry and no project directory.
    pub fn check_structure(&self) -> ViewResult<()> {
        let mut diagnostics = Vec::new();
        if self.name.trim().is_empty() {
            diagnostics.push(
                ViewDiagnostic::for_view(
                    ViewDiagnosticKind::InvalidView,
                    &self.id,
                    format!("view `{}` has no name", self.id),
                )
                .with_field("name")
                .with_remedy("set `name`; the id is not a substitute for a label"),
            );
        }
        diagnostics.extend(
            self.scope
                .conflicts()
                .into_iter()
                .map(|diagnostic| attach_view(diagnostic, &self.id)),
        );
        if diagnostics.is_empty() {
            Ok(())
        } else {
            Err(ViewRefusal::from_diagnostics(diagnostics))
        }
    }

    /// The registry keys this build does not interpret, recorded as diagnostics
    /// (data-model §7: unknown metadata is preserved *and* diagnosed).
    fn unknown_metadata(&self) -> Vec<ViewDiagnostic> {
        let mut diagnostics = Vec::new();
        for key in self.extensions.keys() {
            diagnostics.push(
                ViewDiagnostic::for_view(
                    ViewDiagnosticKind::UnknownMetadata,
                    &self.id,
                    format!(
                        "view `{}` carries an unknown field `{key}`, preserved as written",
                        self.id
                    ),
                )
                .with_field(format!("extensions.{key}")),
            );
        }
        for key in self.scope.extensions.keys() {
            diagnostics.push(
                ViewDiagnostic::for_view(
                    ViewDiagnosticKind::UnknownMetadata,
                    &self.id,
                    format!(
                        "view `{}` scope carries an unknown field `{key}`, preserved as written",
                        self.id
                    ),
                )
                .with_field(format!("scope.extensions.{key}")),
            );
        }
        diagnostics
    }
}

/// Re-point a diagnostic at the view it belongs to, keeping its field.
fn attach_view(diagnostic: ViewDiagnostic, view_id: &ViewId) -> ViewDiagnostic {
    let mut out = ViewDiagnostic::for_view(diagnostic.kind(), view_id, diagnostic.message());
    if let Some(field) = diagnostic.field() {
        out = out.with_field(field.to_string());
    }
    if let Some(remedy) = diagnostic.remedy() {
        out = out.with_remedy(remedy.to_string());
    }
    out
}

/// The selected view, refused if its scope does not resolve.
///
/// Free rather than a method because it needs nothing from the registry — only
/// the view it was handed and the project directory — and a method that ignores
/// its receiver invites the reader to look for hidden state.
fn selected<'a, P: ProjectDirectory + ?Sized>(
    view: &'a SavedView,
    projects: &P,
) -> ViewResult<&'a SavedView> {
    match view.scope.resolution(projects) {
        ScopeResolution::Resolved => Ok(view),
        ScopeResolution::Missing => Err(missing_project(view).into()),
        ScopeResolution::Conflict => {
            let diagnostics: Vec<ViewDiagnostic> = view
                .scope
                .conflicts()
                .into_iter()
                .map(|diagnostic| attach_view(diagnostic, &view.id))
                .collect();
            Err(ViewRefusal::from_diagnostics(diagnostics))
        }
    }
}

/// The one missing-project diagnostic: selection, the write check, and the
/// read-only pass all report this condition through here, so a user who saw it
/// once recognises it wherever it appears.
fn missing_project(view: &SavedView) -> ViewDiagnostic {
    ViewDiagnostic::for_view(
        ViewDiagnosticKind::ScopeConflict,
        &view.id,
        format!(
            "view `{}` is scoped to project `{}`, which is not in the project registry",
            view.id,
            view.scope.project_id.as_deref().unwrap_or("")
        ),
    )
    .with_field("scope.project_id")
    .with_remedy("create the project, or re-scope the view to the repository")
}

/// The repository-owned registry of saved views, keyed by stable id and stored in
/// declaration order.
///
/// Serialized transparently as the TOML table `[views.<id>]`, omitted when empty.
/// The key and [`SavedView::id`] must agree; a document where they disagree is
/// refused at parse time rather than resolved by preference.
#[derive(Debug, Clone, PartialEq)]
pub struct ViewRegistry {
    views: IndexMap<String, SavedView>,
}

impl Default for ViewRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ViewRegistry {
    /// An empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            views: IndexMap::new(),
        }
    }

    /// How many views are stored.
    #[must_use]
    pub fn len(&self) -> usize {
        self.views.len()
    }

    /// Whether the registry is empty — the condition that omits the section.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.views.is_empty()
    }

    /// The views in declaration order.
    pub fn iter(&self) -> impl Iterator<Item = &SavedView> {
        self.views.values()
    }

    /// One view by stable id.
    #[must_use]
    pub fn get(&self, id: &ViewId) -> Option<&SavedView> {
        self.views.get(id.as_str())
    }

    /// Whether the registry already holds this id.
    #[must_use]
    pub fn contains(&self, id: &ViewId) -> bool {
        self.views.contains_key(id.as_str())
    }

    /// Allocate an id that no stored view uses.
    ///
    /// The loop is the belt to [`ViewId::generate`]'s braces: a generated id is
    /// 64 random bits, and this re-draws in the (astronomically unlikely) event of
    /// a collision with a stored id, so "never reused" holds against the ids this
    /// repository actually has.
    #[must_use]
    pub fn allocate_id(&self) -> ViewId {
        loop {
            let candidate = ViewId::generate();
            if !self.contains(&candidate) {
                return candidate;
            }
        }
    }

    /// Add a validated definition. A duplicate id is a refusal, never an
    /// overwrite: identity is immutable, so "insert the same id" is a conflict
    /// rather than a silent replacement (T001).
    pub fn insert(&mut self, view: SavedView) -> ViewResult<()> {
        if let Some(existing) = self.views.get(view.id.as_str()) {
            return Err(ViewDiagnostic::for_view(
                ViewDiagnosticKind::InvalidView,
                &view.id,
                format!(
                    "view id `{}` is already taken by `{}`; ids are never reused",
                    view.id, existing.name
                ),
            )
            .with_field("id")
            .with_remedy("choose a different id, or edit the view that owns it")
            .into());
        }
        view.check_structure()?;
        self.views.insert(view.id.as_str().to_string(), view);
        Ok(())
    }

    /// Change the display label. The id, the scope, and the plan are untouched —
    /// the rename contract is that identity survives (C-002, T001).
    pub fn rename(&mut self, id: &ViewId, name: &str) -> ViewResult<()> {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            return Err(ViewDiagnostic::for_view(
                ViewDiagnosticKind::InvalidView,
                id,
                format!("view `{id}` cannot be renamed to a blank name"),
            )
            .with_field("name")
            .into());
        }
        let view = self.views.get_mut(id.as_str()).ok_or_else(|| {
            ViewDiagnostic::new(
                ViewDiagnosticKind::UnknownView,
                format!("no saved view with id `{id}`"),
            )
            .with_field("id")
        })?;
        view.name = trimmed.to_string();
        Ok(())
    }

    /// Replace the scope metadata, refusing a scope that contradicts itself.
    pub fn set_scope(&mut self, id: &ViewId, scope: ViewScope) -> ViewResult<()> {
        let diagnostics: Vec<ViewDiagnostic> = scope
            .conflicts()
            .into_iter()
            .map(|diagnostic| attach_view(diagnostic, id))
            .collect();
        if !diagnostics.is_empty() {
            return Err(ViewRefusal::from_diagnostics(diagnostics));
        }
        let view = self.views.get_mut(id.as_str()).ok_or_else(|| {
            ViewDiagnostic::new(
                ViewDiagnosticKind::UnknownView,
                format!("no saved view with id `{id}`"),
            )
            .with_field("id")
        })?;
        view.scope = scope;
        Ok(())
    }

    /// Replace the opaque plan table (WP02 hands one in after validating it).
    pub fn set_plan(&mut self, id: &ViewId, plan: toml::Table) -> ViewResult<()> {
        let view = self.views.get_mut(id.as_str()).ok_or_else(|| {
            ViewDiagnostic::new(
                ViewDiagnosticKind::UnknownView,
                format!("no saved view with id `{id}`"),
            )
            .with_field("id")
        })?;
        view.plan = plan;
        Ok(())
    }

    /// Drop a definition. Removing an unknown id is `None`, not an error: the
    /// caller decides whether that is a no-op or a refusal, which is how WP03's
    /// idempotent delete is expressible without a second lookup.
    ///
    /// The id is not remembered afterwards. There is no tombstone because
    /// data-model §1 stores none, so a caller that re-adds a *deleted explicit*
    /// id is declaring that identity again — a decision for the create surface
    /// (WP04), which can refuse it. A [`ViewId::generate`]d id cannot recur at
    /// all, which is what "never reused" rests on.
    pub fn remove(&mut self, id: &ViewId) -> Option<SavedView> {
        self.views.shift_remove(id.as_str())
    }

    /// Select one view by **reference** — its stable id, or its display name.
    ///
    /// An id wins over a name, because ids are unique and unambiguous by
    /// construction. A name may be shared, and that is where scope precedence
    /// applies: the most specific scope wins, and a tie at the winning rank is a
    /// conflict naming every candidate in a deterministic (id-sorted) order. The
    /// caller then selects by stable id.
    ///
    /// **Sharing is never inferred.** There is no "current user" argument: the
    /// registry cannot prefer a `user_share` view because its `owner` happens to
    /// match whoever is running the command (C-003). `owner` and `shared_with` are
    /// stored data; they take no part in matching, ranking, or filtering.
    pub fn select<P: ProjectDirectory + ?Sized>(
        &self,
        reference: &str,
        projects: &P,
    ) -> ViewResult<&SavedView> {
        let reference = reference.trim();
        if let Some(view) = self.views.get(reference) {
            return selected(view, projects);
        }

        let mut candidates: Vec<&SavedView> = self
            .views
            .values()
            .filter(|view| view.name == reference)
            .collect();
        if candidates.is_empty() {
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::UnknownView,
                format!("no saved view matches `{reference}`"),
            )
            .with_field("id")
            .with_remedy("list the saved views and select one by id")
            .into());
        }

        candidates.sort_by(|left, right| left.id.cmp(&right.id));
        let best = candidates
            .iter()
            .map(|view| view.scope.kind.precedence())
            .max()
            .unwrap_or(ViewScopeKind::Repository.precedence());
        let winners: Vec<&SavedView> = candidates
            .into_iter()
            .filter(|view| view.scope.kind.precedence() == best)
            .collect();

        if winners.len() > 1 {
            let ids = winners
                .iter()
                .map(|view| format!("`{}`", view.id))
                .collect::<Vec<_>>()
                .join(", ");
            let kinds = winners
                .iter()
                .map(|view| view.scope.kind.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            return Err(ViewDiagnostic::new(
                ViewDiagnosticKind::ScopeConflict,
                format!(
                    "view name `{reference}` is ambiguous: {ids} are all {} scope",
                    kinds
                ),
            )
            .with_field("name")
            .with_remedy("select the view by its stable id")
            .into());
        }

        // `winners` is non-empty: `candidates` was, and `best` came from it.
        selected(winners[0], projects)
    }

    /// Everything structurally wrong with this registry, before any project
    /// lookup — what `Config` validation can check without a project registry.
    pub fn check_structure(&self) -> ViewResult<()> {
        let mut diagnostics = Vec::new();
        for view in self.views.values() {
            if let Err(refusal) = view.check_structure() {
                diagnostics.extend(refusal.diagnostics().iter().cloned());
            }
        }
        if diagnostics.is_empty() {
            Ok(())
        } else {
            Err(ViewRefusal::from_diagnostics(diagnostics))
        }
    }

    /// The full write-path check: structure plus project resolution.
    ///
    /// A view whose project does not exist cannot be written (C-008) but can be
    /// *loaded*: a deleted project leaves references that must stay diagnosable
    /// rather than unloadable, so resolution is deliberately not part of
    /// `Config` validation.
    pub fn check<P: ProjectDirectory + ?Sized>(&self, projects: &P) -> ViewResult<()> {
        let mut diagnostics = Vec::new();
        if let Err(refusal) = self.check_structure() {
            diagnostics.extend(refusal.diagnostics().iter().cloned());
        }
        for view in self.views.values() {
            if let ScopeResolution::Missing = view.scope.resolution(projects) {
                diagnostics.push(missing_project(view));
            }
        }
        if diagnostics.is_empty() {
            Ok(())
        } else {
            Err(ViewRefusal::from_diagnostics(diagnostics))
        }
    }

    /// Read-only diagnostics for every stored view: scope conflicts, missing
    /// projects, and preserved-but-uninterpreted fields.
    ///
    /// Ordered by declaration order, then by the order a view's own problems were
    /// found, so two runs over the same file report the same list. This is what a
    /// surface shows *without* refusing anything — unknown metadata is reported
    /// here precisely so it is never silent, while writing it back stays allowed.
    #[must_use]
    pub fn diagnostics<P: ProjectDirectory + ?Sized>(&self, projects: &P) -> Vec<ViewDiagnostic> {
        let mut diagnostics = Vec::new();
        for view in self.views.values() {
            let conflicts = view.scope.conflicts();
            if conflicts.is_empty() {
                if let ScopeResolution::Missing = view.scope.resolution(projects) {
                    diagnostics.push(missing_project(view));
                }
            } else {
                // A conflicting scope also cannot be judged against the project
                // registry, so resolution is not attempted for it.
                diagnostics.extend(
                    conflicts
                        .into_iter()
                        .map(|diagnostic| attach_view(diagnostic, &view.id)),
                );
            }
            diagnostics.extend(view.unknown_metadata());
        }
        diagnostics
    }

    /// The one write path for view definitions (C-008, T005).
    ///
    /// The order is the guarantee:
    ///
    /// 1. the **complete candidate registry** is checked — structure, then scope
    ///    resolution through `projects`. A refusal returns before any write;
    /// 2. the whole candidate `Config` is validated, so the existing config
    ///    invariants hold for what is about to be written;
    /// 3. the existing atomic `Config::save` writes it (temp file, fsync, rename);
    /// 4. only then is the caller's `Config` updated.
    ///
    /// So a rejected operation writes no `tix.toml` and appends no History, and a
    /// failed save leaves both the file and the caller's in-memory config as they
    /// were. Committing the same registry twice writes the same bytes, which is
    /// what makes an accepted change idempotent; the audit event for an accepted
    /// change is the caller's to append (WP03), because this path touches no issue
    /// file.
    pub fn commit<P: ProjectDirectory + ?Sized>(
        &self,
        config: &mut Config,
        projects: &P,
        path: &Path,
    ) -> ViewWriteResult<()> {
        self.check(projects).map_err(ViewWriteError::Refused)?;

        let mut candidate = config.clone();
        candidate.views = self.clone();
        candidate.validate().map_err(ViewWriteError::Failed)?;
        candidate.save(path).map_err(ViewWriteError::Failed)?;

        *config = candidate;
        Ok(())
    }

    /// Restore the declaration order of `[views.<id>]` headers, which the TOML
    /// parser loses (it sorts table keys). Same D-02 rule as `[cycles]`/`[teams]`.
    pub(crate) fn restore_declaration_order(&mut self, contents: &str) {
        crate::config::restore_section_order(&mut self.views, contents, "views");
    }
}

impl Serialize for ViewRegistry {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.views.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ViewRegistry {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let stored = IndexMap::<String, SavedView>::deserialize(deserializer)?;
        let mut registry = Self::new();
        for (key, view) in stored {
            if key != view.id.as_str() {
                return Err(serde::de::Error::custom(format!(
                    "the `[views.{key}]` record declares id `{}`: the table key is the stable \
                     identity and the two must agree",
                    view.id.as_str()
                )));
            }
            registry.views.insert(key, view);
        }
        Ok(registry)
    }
}

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

    fn projects(ids: &[&str]) -> BTreeSet<String> {
        ids.iter().map(|id| (*id).to_string()).collect()
    }

    fn view(id: &str, name: &str, scope: ViewScope) -> SavedView {
        SavedView::new(ViewId::new(id).unwrap(), name, scope).unwrap()
    }

    #[test]
    fn blank_and_ill_formed_ids_are_refused() {
        assert!(ViewId::new("").is_err());
        assert!(ViewId::new("   ").is_err());
        assert!(ViewId::new(" padded").is_err());
        assert!(ViewId::new("a.b").is_err());
        assert!(ViewId::new("a[b]").is_err());
        assert!(ViewId::new("a b").is_err());
        assert!(ViewId::new(&"x".repeat(ViewId::MAX_LEN + 1)).is_err());
        assert_eq!(
            ViewId::new("platform-active").unwrap().as_str(),
            "platform-active"
        );
    }

    #[test]
    fn generated_ids_are_unique_and_well_formed() {
        let first = ViewId::generate();
        let second = ViewId::generate();
        assert_ne!(first, second);
        assert!(first.as_str().starts_with("v-"));
        assert_eq!(first.as_str().len(), 18);
        assert!(ViewId::new(first.as_str()).is_ok());
    }

    #[test]
    fn allocate_id_skips_stored_ids() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view("taken", "Taken", ViewScope::repository()))
            .unwrap();
        for _ in 0..32 {
            assert!(!registry.contains(&registry.allocate_id()));
        }
    }

    #[test]
    fn duplicate_id_is_a_refusal_not_an_overwrite() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view("platform", "Platform", ViewScope::repository()))
            .unwrap();
        let refusal = registry
            .insert(view("platform", "Something else", ViewScope::repository()))
            .unwrap_err();
        assert_eq!(refusal.kind(), ViewDiagnosticKind::InvalidView);
        assert_eq!(
            registry
                .get(&ViewId::new("platform").unwrap())
                .unwrap()
                .name,
            "Platform",
            "an existing definition is never overwritten by a duplicate id"
        );
    }

    #[test]
    fn blank_names_are_refused_on_insert_and_rename() {
        let mut registry = ViewRegistry::new();
        let refusal = SavedView::new(
            ViewId::new("platform").unwrap(),
            "   ",
            ViewScope::repository(),
        )
        .unwrap_err();
        assert_eq!(refusal.kind(), ViewDiagnosticKind::InvalidView);

        registry
            .insert(view("platform", "Platform", ViewScope::repository()))
            .unwrap();
        let id = ViewId::new("platform").unwrap();
        assert!(registry.rename(&id, "  ").is_err());
        registry.rename(&id, "  Platform active  ").unwrap();
        assert_eq!(registry.get(&id).unwrap().name, "Platform active");
    }

    #[test]
    fn scope_kinds_rank_by_specificity() {
        assert!(ViewScopeKind::UserShare.precedence() > ViewScopeKind::Project.precedence());
        assert!(ViewScopeKind::Project.precedence() > ViewScopeKind::Repository.precedence());
    }

    #[test]
    fn repository_scope_must_not_name_a_project() {
        let scope = ViewScope {
            kind: ViewScopeKind::Repository,
            project_id: Some("p-platform".into()),
            ..ViewScope::default()
        };
        let conflicts = scope.conflicts();
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].field(), Some("scope.project_id"));
        assert_eq!(
            scope.resolution(&projects(&["p-platform"])),
            ScopeResolution::Conflict
        );
    }

    #[test]
    fn project_scope_requires_a_project_and_resolves_through_the_directory() {
        let empty = ViewScope::project("   ");
        assert_eq!(empty.conflicts().len(), 1);

        let scope = ViewScope::project("p-platform");
        assert_eq!(
            scope.resolution(&projects(&["p-platform"])),
            ScopeResolution::Resolved
        );
        assert_eq!(scope.resolution(&projects(&[])), ScopeResolution::Missing);
    }

    #[test]
    fn user_share_scope_needs_owner_or_shared_with_and_is_metadata_only() {
        assert_eq!(ViewScope::user_share(None, vec![]).conflicts().len(), 1);
        let scope = ViewScope::user_share(Some("alice".into()), vec!["bob".into()]);
        assert_eq!(
            scope.conflicts(),
            [] as [crate::views::registry::ViewDiagnostic; 0]
        );
        assert_eq!(scope.resolution(&projects(&[])), ScopeResolution::Resolved);
    }

    #[test]
    fn user_share_scope_must_not_name_a_project() {
        // Symmetric with the `repository` arm: a `user_share` scope carrying a
        // `project_id` is self-contradictory and must be refused, not silently
        // carried with the field left inert (WP01 review finding).
        let scope = ViewScope {
            kind: ViewScopeKind::UserShare,
            project_id: Some("p-platform".into()),
            owner: Some("alice".into()),
            ..ViewScope::default()
        };
        let conflicts = scope.conflicts();
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].field(), Some("scope.project_id"));
        assert_eq!(
            scope.resolution(&projects(&["p-platform"])),
            ScopeResolution::Conflict
        );
    }

    #[test]
    fn share_metadata_on_a_non_share_scope_is_a_conflict() {
        let scope = ViewScope {
            kind: ViewScopeKind::Repository,
            owner: Some("alice".into()),
            shared_with: vec!["bob".into()],
            ..ViewScope::default()
        };
        let conflicts = scope.conflicts();
        let fields: Vec<Option<&str>> = conflicts.iter().map(|d| d.field()).collect();
        assert_eq!(fields, vec![Some("scope.owner"), Some("scope.shared_with")]);
    }

    #[test]
    fn repeated_and_blank_shared_with_identities_are_refused() {
        let scope = ViewScope::user_share(Some("alice".into()), vec!["bob".into(), "bob".into()]);
        assert_eq!(scope.conflicts().len(), 1);
        let scope = ViewScope::user_share(Some("alice".into()), vec!["  ".into()]);
        assert_eq!(scope.conflicts().len(), 1);
    }

    #[test]
    fn select_prefers_the_id_and_then_the_most_specific_scope() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view("repo", "Active", ViewScope::repository()))
            .unwrap();
        registry
            .insert(view("proj", "Active", ViewScope::project("p-platform")))
            .unwrap();
        let known = projects(&["p-platform"]);
        assert_eq!(registry.select("proj", &known).unwrap().id.as_str(), "proj");
        assert_eq!(
            registry.select("Active", &known).unwrap().id.as_str(),
            "proj"
        );
    }

    #[test]
    fn user_share_tie_is_a_deterministic_conflict() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view(
                "zoe",
                "Mine",
                ViewScope::user_share(Some("zoe".into()), vec![]),
            ))
            .unwrap();
        registry
            .insert(view(
                "alice",
                "Mine",
                ViewScope::user_share(Some("alice".into()), vec![]),
            ))
            .unwrap();
        let known = projects(&[]);
        let first = registry.select("Mine", &known).unwrap_err();
        let second = registry.select("Mine", &known).unwrap_err();
        assert_eq!(first, second);
        assert_eq!(first.kind(), ViewDiagnosticKind::ScopeConflict);
        assert!(first.message().contains("`alice`"));
        assert!(first.message().contains("`zoe`"));
    }

    #[test]
    fn owner_metadata_never_influences_selection() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view(
                "shared",
                "Mine",
                ViewScope::user_share(Some("someone-else".into()), vec!["another".into()]),
            ))
            .unwrap();
        let selected = registry.select("Mine", &projects(&[])).unwrap();
        assert_eq!(selected.id.as_str(), "shared");

        // A second registry whose only difference is the owner value selects
        // exactly the same view: the metadata is inert as far as resolution goes.
        let mut other = ViewRegistry::new();
        other
            .insert(view(
                "shared",
                "Mine",
                ViewScope::user_share(Some("alice".into()), vec!["bob".into()]),
            ))
            .unwrap();
        assert_eq!(
            other.select("Mine", &projects(&[])).unwrap().id.as_str(),
            "shared"
        );
    }

    #[test]
    fn select_reports_unknown_references_and_missing_projects() {
        let mut registry = ViewRegistry::new();
        registry
            .insert(view("proj", "Platform", ViewScope::project("p-gone")))
            .unwrap();
        let refusal = registry.select("nope", &projects(&[])).unwrap_err();
        assert_eq!(refusal.kind(), ViewDiagnosticKind::UnknownView);

        let refusal = registry.select("proj", &projects(&[])).unwrap_err();
        assert_eq!(refusal.kind(), ViewDiagnosticKind::ScopeConflict);
        assert!(refusal.message().contains("p-gone"));
    }

    #[test]
    fn unknown_metadata_is_reported_not_refused() {
        let mut registry = ViewRegistry::new();
        let mut record = view("platform", "Platform", ViewScope::repository());
        record
            .extensions
            .insert("colour".into(), toml::Value::String("red".into()));
        record
            .scope
            .extensions
            .insert("visibility".into(), toml::Value::String("team".into()));
        registry.insert(record).unwrap();

        assert!(registry.check_structure().is_ok());
        let diagnostics = registry.diagnostics(&projects(&[]));
        let kinds: Vec<ViewDiagnosticKind> = diagnostics.iter().map(|d| d.kind()).collect();
        assert_eq!(
            kinds,
            vec![
                ViewDiagnosticKind::UnknownMetadata,
                ViewDiagnosticKind::UnknownMetadata
            ]
        );
        assert_eq!(registry.iter().next().unwrap().extensions.len(), 1);
    }

    #[test]
    fn rename_keeps_identity_scope_and_plan() {
        let mut registry = ViewRegistry::new();
        let mut record = view("platform", "Platform", ViewScope::project("p-platform"));
        let mut plan = toml::Table::new();
        plan.insert("sort".into(), toml::Value::String("due".into()));
        record.plan = plan.clone();
        registry.insert(record).unwrap();

        let id = ViewId::new("platform").unwrap();
        registry.rename(&id, "Platform active").unwrap();
        let stored = registry.get(&id).unwrap();
        assert_eq!(stored.id, id);
        assert_eq!(stored.name, "Platform active");
        assert_eq!(stored.scope, ViewScope::project("p-platform"));
        assert_eq!(stored.plan, plan);
    }
}