memstead-base 0.11.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, no API stability promise.
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
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
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
//! Binding format **v2** — one record per pipeline.
//!
//! This is the **live** binding shape: [`crate::pipeline_store::load_pipeline_configs`]
//! reads it (version-gated), the `projection` CLI tree writes it, and the
//! resolve / brief / status / advance paths consume it. A v2 [`Binding`]
//! alone fully defines a pipeline: intent, **inline sources** (each carrying
//! what the retired standalone medium + facet records carried), reference
//! mems, destination, deny paths, coverage semantics, and operations. The
//! 2026-07 consolidation (operator directive, 2026-07-18) removed the
//! three-file store: the engine reads only this format; `memstead projection
//! migrate` converts prior generations, and there is no compatibility layer.
//!
//! Three things live here:
//!
//! 1. [`Binding`] — the versioned record: one file per pipeline, collapsing
//!    the medium / facet / binding split into a single record with inline
//!    [`Source`] entries and an `operations { build, sync, verify }` block.
//! 2. [`hash_binding`] — `hash(D)`: the lowercase-hex SHA-256 of the
//!    canonical JSON of the binding's *content-defining* projection.
//!    Scheduling knobs (`trigger` / `batch_size` / `post_actions`, the
//!    sync/verify blocks, prune) are excluded by construction; a source's
//!    selection pattern or pointer changing — now inputs *inside* the one
//!    record — changes the hash.
//! 3. [`medium_capabilities`] + [`validate_binding`] — the medium-capability
//!    matrix (the medium *half* of a source description keeps the medium
//!    vocabulary) and the validation entry point: capability refusals,
//!    in-record source validation (empty / duplicate source names), and the
//!    preparation-registry check (a declared `preparation` must be one
//!    [`crate::preparation`] knows, over a medium it can apply to).
//!
//! The findings store ([`crate::ingest::findings`]) keys on `hash(D)`, so the
//! consolidation's shape change invalidates prior findings by construction —
//! accepted and disclosed (findings are re-derivable measurements).

use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};

use crate::pipeline::{IngestTrigger, MediumType, PatternEntry, Source};

/// The current binding format version. A v2 binding carries `version: 2`.
pub const BINDING_VERSION: u32 = 2;

/// The engine's current preparation-implementation version — the single
/// source of truth for "which preparation implementation is live".
///
/// `3` since the code-map flavour (`code-map`, touchpoint A on path grains)
/// landed; `2` was the delivery flavour (`dated-entries`, touchpoint B); `1`
/// the first registered preparation (`entity-load-bearing`, see
/// [`crate::preparation`]); `0` meant "none". It participates in
/// [`hash_binding`] for every source: because the declared identifier and
/// this version are both hashed, landing or changing an implementation
/// invalidates every prior finding keyed on the old `hash(D)` by
/// construction — the findings store keys on `hash(D)` alone, so the old
/// batch is segregated as superseded and never mixed into the current view
/// (pinned by `ingest::findings`'s
/// `impl_version_bump_invalidates_findings_by_construction`). Bump it once
/// per landed or changed implementation, never per registry entry that
/// merely exists.
pub const PREPARATION_IMPL_VERSION: u32 = 3;

// ---------------------------------------------------------------------------
// The v2 record
// ---------------------------------------------------------------------------

/// Coverage semantics — whether the binding claims to cover *everything* in
/// its declared scope (`exhaustive`) or a deliberately partial slice
/// (`curated`).
///
/// On the [`Binding`] record the field is **optional**: absent means "not
/// stated", which is a different fact from "stated as exhaustive". The
/// effective value is resolved per medium by
/// [`effective_coverage_semantics`] — there is deliberately no `Default`
/// impl, because a default is exactly the silence-as-assertion this
/// design retired.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CoverageSemantics {
    /// Every artifact in scope is expected to be accounted for.
    Exhaustive,
    /// A deliberately partial selection — an unaccounted artifact is
    /// information, not a defect.
    Curated,
}

/// How a [`BuildOperation`] engages its binding. **`refinement` is deleted
/// from the vocabulary** — it is neither a variant here nor migrated, so
/// deserializing `"mode": "refinement"` fails as an unknown value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BuildMode {
    /// Build out new coverage.
    Discovery,
    /// A single bounded pass.
    OneShot,
}

/// The **build** operation — the only operation carrying a mode. Grows new
/// coverage (or runs a one-shot lens). `trigger` / `batch_size` /
/// `post_actions` are scheduling attributes, excluded from [`hash_binding`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuildOperation {
    /// Discovery / one-shot. The one operation with a mode.
    pub mode: BuildMode,
    /// What sets this operation running (loop / manual / on-event).
    pub trigger: IngestTrigger,
    /// How many artifacts a single run processes.
    pub batch_size: u32,
    /// Free-form post-run actions (e.g. a one-shot `archive_source` flag).
    /// Opaque to the engine — consumed only by the one-shot brief renderer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_actions: Option<serde_json::Value>,
}

/// The **sync** operation — the (future) sole maintenance writer. Optional: an
/// absent `sync` block makes that *mutating* operation refuse at run time.
/// Carries no mode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncOperation {
    /// What sets a sync running.
    pub trigger: IngestTrigger,
    /// How many artifacts a single run processes.
    pub batch_size: u32,
}

/// Default per-run tier-3 adjudication cap (bundle plan `05-verify-sync-engine`,
/// D1/D4). Dogfood-tuned against the live `engine/graph` binding (524 source
/// artifacts): a fully-drifted mem of that scale clears its adjudication backlog
/// in ~11 verify runs while each run's asserted-drift work stays bounded and its
/// token cost predictable. `0` disables the cap (adjudicate every candidate).
pub const DEFAULT_ADJUDICATION_CAP: u32 = 50;

/// Default `full_resync_every` (bundle plan `05-verify-sync-engine`, D3/D4):
/// fire a guaranteed full-enumeration coverage sweep every N verify runs.
/// Dogfood-tuned against `engine/graph` (524 artifacts, sample batch 20 → a
/// rotation completes in ~27 runs): a sweep every 20 runs guarantees a complete
/// coverage picture without waiting on the rotation to happen to finish. `0`
/// disables scheduled full walks (rotating sample only).
pub const DEFAULT_FULL_RESYNC_EVERY: u32 = 20;

fn default_adjudication_cap() -> u32 {
    DEFAULT_ADJUDICATION_CAP
}

fn default_full_resync_every() -> u32 {
    DEFAULT_FULL_RESYNC_EVERY
}

/// The **verify** operation — measurement. Optional: an absent `verify`
/// block means engine defaults, never a refusal (verify has no mutating
/// operation to gate). Mutates no entity, but records findings, backfills
/// observed anchor hashes and writes a `#verified` baseline. Carries no mode.
///
/// `adjudication_cap` and `full_resync_every` are the tier-3 operations knobs
/// (bundle plan `05-verify-sync-engine`, group D): scheduling attributes on the
/// measurement side only — like `trigger` / `batch_size`, they never change what
/// the mem claims, so they are excluded from [`hash_binding`] (the whole
/// `verify` block is). Both are additive: an older `verify` block without them
/// deserializes to the dogfood-tuned defaults.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerifyOperation {
    /// What sets a verify running.
    pub trigger: IngestTrigger,
    /// How many artifacts a single run processes.
    pub batch_size: u32,
    /// Per-run tier-3 adjudication cap: the maximum number of hash-drift
    /// adjudications a single verify run asserts. Once the cap is reached the
    /// run **stops adjudicating** and queues the remaining drift candidates as
    /// `queued-for-adjudication` findings (the tier-3 backlog the fidelity
    /// report renders). Combined with the rotating sample, successive runs
    /// adjudicate different windows, so the whole anchor set is covered over a
    /// full rotation. `0` disables the cap. Defaults to
    /// [`DEFAULT_ADJUDICATION_CAP`].
    #[serde(default = "default_adjudication_cap")]
    pub adjudication_cap: u32,
    /// Scheduled full-enumeration walk cadence: every N verify runs, a full
    /// coverage sweep enumerates the whole source set (`S(D)`) for **enumerable**
    /// mediums, guaranteeing eventual complete coverage rather than relying on
    /// the rotating sample to finish. For a medium the capability matrix marks
    /// **non-enumerable**, the scheduled walk refuses with a typed signal — never
    /// a silent skip, never a fabricated full-coverage claim. `0` disables
    /// scheduled full walks. Defaults to [`DEFAULT_FULL_RESYNC_EVERY`].
    #[serde(default = "default_full_resync_every")]
    pub full_resync_every: u32,
}

/// The prune guarantee a binding **requests** (bundle plan
/// `05-verify-sync-engine`, F1). Prune produces deletion **proposals** surfaced
/// in the sync brief (it never mutates the mem); the guarantee governs how a
/// prune proposal treats a model-side edit that races a source removal.
///
/// The guarantee a medium can *support* is derived from its base-leg
/// retrievability ([`prune_guarantee_for_medium`]): a git-backed source can
/// retrieve the base leg for a real three-way merge ([`Self::NeverClobber`]);
/// everything else degrades to conflict-flagging ([`Self::ConflictFlag`]).
/// Requesting a guarantee the medium cannot support is refused at
/// **binding-validation** time (never at run time) via
/// [`CapabilityError::PruneGuaranteeUnsupported`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum PruneGuarantee {
    /// Full never-clobber three-way merge — only where the source **base leg is
    /// retrievable** (git-backed sources). The retrieved base lets the merge
    /// tell a model-side edit apart from a clean removal, so a divergence is
    /// never silently proposed as a clean delete.
    NeverClobber,
    /// Conflict-flag degradation (the default — always supportable): where the
    /// base leg is **not** retrievable, prune presents **both** sides and never
    /// auto-writes over a model-side edit. The decided posture for non-git
    /// sources (span-snapshot base legs are out of scope — no current payer).
    #[default]
    ConflictFlag,
}

impl PruneGuarantee {
    /// Stable wire form.
    pub fn as_wire(&self) -> &'static str {
        match self {
            PruneGuarantee::NeverClobber => "never-clobber",
            PruneGuarantee::ConflictFlag => "conflict-flag",
        }
    }
}

/// The **prune** configuration of a [`Binding`] (F1) — additive, optional. An
/// absent `prune` block means prune is not enabled for the binding (no deletion
/// proposals are produced). Prune has no independent schedule: it rides the sync
/// brief (the sole maintenance-writer channel), so it carries no `trigger` /
/// `batch_size` — only the requested [`PruneGuarantee`]. Like the `sync` /
/// `verify` blocks it is **excluded from [`hash_binding`]**: a maintenance
/// policy never changes what the mem claims.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PruneConfig {
    /// The guarantee level the binding requests. Validated against the medium's
    /// base-leg retrievability at binding-validation time (F1 refusal).
    /// Defaults to [`PruneGuarantee::ConflictFlag`] when absent.
    #[serde(default)]
    pub guarantee: PruneGuarantee,
}

/// The operations block of a [`Binding`]: every operation is **optional**.
/// An absent `build` / `sync` block makes that *mutating* operation
/// refuse at run time with a `projection enable <op>` remedy; an absent
/// `verify` block means engine defaults (verify has no mutating operation to
/// gate — never a refusal). `build` is optional in serde so an absent block yields the
/// remedy-bearing refusal rather than a generic "missing field" parse error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Operations {
    /// The build operation (optional — absent = mutating op refuses with the
    /// `projection enable build` remedy at run time).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildOperation>,
    /// The sync operation (optional — absent = mutating op refuses with the
    /// `projection enable sync` remedy at run time).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sync: Option<SyncOperation>,
    /// The verify operation (optional — absent = engine defaults, never a refusal).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verify: Option<VerifyOperation>,
}

/// Default `deny_paths` scaffolded onto a fresh enumerable
/// (`codebase` / `filesystem`) binding: ordinary platform/tooling
/// debris that would otherwise flood a first denominator. A default,
/// not an invariant — the scaffold materialises the list into the
/// binding record, so an author who wants one of these in scope
/// deletes the entry and gets the files back; bindings created before
/// the default existed keep their recorded (empty) list. Engine state
/// (`.memstead/`, `.memstead.cache/`, mount storage) is NOT on this
/// list — its exclusion is unconditional in the strategy layer, never
/// a deletable record entry.
pub const DEFAULT_SCAFFOLD_DENY_PATHS: &[&str] = &[
    "**/.DS_Store",
    "**/.git/**",
    "**/node_modules/**",
    "**/Thumbs.db",
];

/// A **binding**, format version 2 — one record per pipeline. The single
/// versioned file at `projections/<mem>/<name>.json` that alone fully defines
/// the obligation: `intent`, inline [`Source`] entries (each carrying the
/// medium and facet halves the retired standalone records held),
/// `reference_mems`, `destination_mem`, `deny_paths`, `coverage_semantics`,
/// `rules`, `prune`, and the `operations { build, sync, verify }` block.
///
/// This is the live store record — [`crate::pipeline_store::load_pipeline_configs`]
/// reads it version-gated and the `projection` CLI tree writes it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Binding {
    /// Format version — required. v2 is [`BINDING_VERSION`]. A projection file
    /// without it (or with a prior version) is refused by the loader with a
    /// typed error naming `memstead projection migrate`.
    pub version: u32,
    /// What the binding is trying to accomplish — prose for the agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<String>,
    /// The inline sources the binding consumes, in declaration order.
    /// Each `name` is unique within the record and keys per-source state.
    #[serde(default)]
    pub sources: Vec<Source>,
    /// Read-only reference mems that supply cross-mem context.
    #[serde(default)]
    pub reference_mems: Vec<String>,
    /// The mem this binding writes into.
    pub destination_mem: String,
    /// Paths excluded from the binding's scope (workspace-relative globs).
    #[serde(default)]
    pub deny_paths: Vec<String>,
    /// Whether the binding claims exhaustive or curated coverage.
    /// Optional: `None` means **not stated** — a different fact from
    /// "stated as exhaustive". Consumers never read this raw; they read
    /// [`effective_coverage_semantics`], which resolves `None` per
    /// medium (all sources enumerable → exhaustive; any non-enumerable
    /// source → curated). An explicit `exhaustive` over a
    /// non-enumerable source is refused by [`validate_binding`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coverage_semantics: Option<CoverageSemantics>,
    /// Free-form binding rules (e.g. a one-shot lens `routing` string).
    /// Opaque to the engine — consumed only by the one-shot brief renderer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rules: Option<serde_json::Value>,
    /// The **prune** policy (bundle plan `05-verify-sync-engine`, F1) — additive,
    /// optional. Absent = prune disabled (no deletion proposals). Present = prune
    /// produces deletion proposals in the sync brief under the requested
    /// [`PruneGuarantee`], validated against the medium's base-leg
    /// retrievability at binding-validation time. Excluded from [`hash_binding`]
    /// (a maintenance policy, not content-defining).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prune: Option<PruneConfig>,
    /// The operations this binding declares (build required; sync/verify optional).
    pub operations: Operations,
}

// ---------------------------------------------------------------------------
// hash(D)
// ---------------------------------------------------------------------------

/// One source's content-defining projection, in a fixed serde shape so
/// [`hash_binding`] hashes every content input. Private — the hash is the
/// only consumer.
#[derive(Serialize)]
struct HashSource<'a> {
    source: &'a str,
    patterns: &'a [PatternEntry],
    preparation: &'a Option<String>,
    preparation_impl_version: u32,
    medium_type: MediumType,
    pointer: &'a str,
    change_detection: &'a Option<String>,
}

/// The content-defining projection of a binding, in a fixed serde shape.
/// Private — serialized to canonical JSON for hashing. Excludes `trigger`,
/// `batch_size`, `post_actions`, and the `sync` / `verify` / `prune` blocks:
/// scheduling and maintenance policy never change what the mem claims. The
/// `engagement` slot is likewise excluded (an engagement contract shapes how
/// an agent works, not what the mem claims — the pre-consolidation exclusion
/// carried forward).
#[derive(Serialize)]
struct HashInput<'a> {
    version: u32,
    intent: &'a Option<String>,
    sources: Vec<HashSource<'a>>,
    reference_mems: &'a [String],
    destination_mem: &'a str,
    deny_paths: &'a [String],
    coverage_semantics: CoverageSemantics,
    rules: &'a Option<serde_json::Value>,
    /// The build mode participates in `hash(D)`; an absent build block simply
    /// does not contribute it (skipped from the canonical JSON).
    #[serde(skip_serializing_if = "Option::is_none")]
    build_mode: Option<BuildMode>,
}

/// Serialize a JSON value with **recursively sorted object keys** and no
/// insignificant whitespace — the canonical form. serde_json's map is a
/// sorted `BTreeMap` today; this rebuild makes the canonicalization explicit
/// and robust even if the `preserve_order` feature is ever enabled build-wide.
fn canonical_json(value: &serde_json::Value) -> String {
    fn sorted(v: &serde_json::Value) -> serde_json::Value {
        match v {
            serde_json::Value::Object(map) => {
                let mut keys: Vec<&String> = map.keys().collect();
                keys.sort();
                let mut out = serde_json::Map::new();
                for k in keys {
                    out.insert(k.clone(), sorted(&map[k]));
                }
                serde_json::Value::Object(out)
            }
            serde_json::Value::Array(items) => {
                serde_json::Value::Array(items.iter().map(sorted).collect())
            }
            other => other.clone(),
        }
    }
    serde_json::to_string(&sorted(value)).expect("canonical JSON serializes")
}

/// Compute `hash(D)` — the lowercase-hex SHA-256 of the canonical JSON of a
/// binding's content-defining projection.
///
/// Hashed: `version`, `intent`, `sources` (per source: its name, selection
/// patterns, preparation identifier + [`PREPARATION_IMPL_VERSION`], and its
/// medium half's `type` / `pointer` / `change_detection`), `reference_mems`,
/// `destination_mem`, `deny_paths`, `coverage_semantics`, `rules`, and
/// `operations.build.mode`.
///
/// **Excluded:** `trigger`, `batch_size`, `post_actions`, the `sync` /
/// `verify` / `prune` blocks, and each source's `engagement` contract —
/// scheduling, maintenance policy, and engagement style never change what
/// the mem claims. The v2 record needs no external resolution: every content
/// input lives inside the one record, so a selection or pointer edit
/// invalidates the hash — and thus any findings keyed on it — directly.
pub fn hash_binding(binding: &Binding) -> String {
    hash_binding_at_impl_version(binding, PREPARATION_IMPL_VERSION)
}

/// [`hash_binding`] under an explicit preparation-implementation version.
/// The live hash is always [`PREPARATION_IMPL_VERSION`]'s; this exists so a
/// caller can name the hash a prior engine generation keyed its findings on
/// (the invalidation-by-construction pin, a migration report) without
/// re-deriving the canonical projection.
pub fn hash_binding_at_impl_version(binding: &Binding, preparation_impl_version: u32) -> String {
    let sources: Vec<HashSource<'_>> = binding
        .sources
        .iter()
        .map(|s| HashSource {
            source: &s.name,
            patterns: &s.scope,
            preparation: &s.preparation,
            preparation_impl_version,
            medium_type: s.medium_type,
            pointer: &s.pointer,
            change_detection: &s.change_detection,
        })
        .collect();

    let input = HashInput {
        version: binding.version,
        intent: &binding.intent,
        sources,
        reference_mems: &binding.reference_mems,
        destination_mem: &binding.destination_mem,
        deny_paths: &binding.deny_paths,
        // The RESOLVED effective value, never the `Option`: a binding
        // over enumerable sources that never declared the field keeps
        // its pre-optionality hash byte-for-byte (resolved
        // `exhaustive` == the old default), so its findings survive. A
        // non-enumerable-source binding that declared nothing rehashes
        // exactly once — correct, its asserted coverage genuinely
        // changed.
        coverage_semantics: effective_coverage_semantics(binding).value,
        rules: &binding.rules,
        build_mode: binding.operations.build.as_ref().map(|b| b.mode),
    };

    let value = serde_json::to_value(&input).expect("hash input serializes to a JSON value");
    let canonical = canonical_json(&value);
    let digest = Sha256::digest(canonical.as_bytes());
    crate::hex_lower(&digest)
}

// ---------------------------------------------------------------------------
// Medium-capability matrix + validation
// ---------------------------------------------------------------------------

/// What a medium can support — the row of the capability matrix for a
/// [`MediumType`] (the medium *half* of a source description). Pure data;
/// [`validate_binding`] reads it to refuse operations a medium cannot support.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MediumCapabilities {
    /// Can the medium's scope be enumerated (`S(D)` computable)?
    pub enumerable: bool,
    /// Does the medium provide a change signal?
    pub change_signal: bool,
    /// Can a base version be retrieved (for three-way merge)?
    pub base_version_retrievable: bool,
    /// The medium's anchor namespace (`path`, `path+commit`, `entity`, `url`).
    pub anchor_namespace: &'static str,
    /// Is a glob `deny_paths` list legal (i.e. is the namespace path-shaped)?
    pub glob_deny_legal: bool,
}

/// The capability-matrix row for a medium type. The single source of
/// truth the fidelity report also renders.
pub fn medium_capabilities(medium_type: MediumType) -> MediumCapabilities {
    match medium_type {
        MediumType::Codebase => MediumCapabilities {
            enumerable: true,
            change_signal: true,
            base_version_retrievable: true,
            anchor_namespace: "path",
            glob_deny_legal: true,
        },
        MediumType::Filesystem => MediumCapabilities {
            enumerable: true,
            change_signal: true,
            base_version_retrievable: true,
            anchor_namespace: "path",
            glob_deny_legal: true,
        },
        MediumType::Git => MediumCapabilities {
            enumerable: true,
            change_signal: true,
            base_version_retrievable: true,
            anchor_namespace: "path+commit",
            glob_deny_legal: true,
        },
        MediumType::Graph => MediumCapabilities {
            enumerable: true,
            change_signal: true,
            base_version_retrievable: true,
            anchor_namespace: "entity",
            glob_deny_legal: false,
        },
        MediumType::Web => MediumCapabilities {
            // Web enumeration / change detection / base retrieval are all
            // deferred this cycle (operator decision 7).
            enumerable: false,
            change_signal: false,
            base_version_retrievable: false,
            anchor_namespace: "url",
            glob_deny_legal: false,
        },
    }
}

/// The effective coverage of a binding plus its provenance — whether the
/// value was declared by the author or resolved from the sources' media.
/// The fidelity report renders the distinction; every other consumer
/// reads only [`Self::value`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EffectiveCoverage {
    /// The coverage every consumer acts on.
    pub value: CoverageSemantics,
    /// `true` when the binding declared the field; `false` when the
    /// value was resolved from the medium capabilities.
    pub declared: bool,
}

/// Resolve a binding's **effective** coverage semantics. A declared value
/// wins (validation has already refused an illegal `exhaustive`). An
/// undeclared value resolves per binding, not per source: all sources on
/// enumerable media → `exhaustive`; at least one non-enumerable source →
/// `curated` — a mixed binding can only honestly claim the weaker of its
/// parts, because coverage is an obligation of the binding as a whole
/// (the artifact that is measured, reported, and keyed).
pub fn effective_coverage_semantics(binding: &Binding) -> EffectiveCoverage {
    if let Some(declared) = binding.coverage_semantics {
        return EffectiveCoverage {
            value: declared,
            declared: true,
        };
    }
    let all_enumerable = binding
        .sources
        .iter()
        .all(|s| medium_capabilities(s.medium_type).enumerable);
    EffectiveCoverage {
        value: if all_enumerable {
            CoverageSemantics::Exhaustive
        } else {
            CoverageSemantics::Curated
        },
        declared: false,
    }
}

/// The strongest prune guarantee a medium can **support** (F1), derived from
/// the capability matrix: a base-leg-retrievable medium (git-backed —
/// codebase / filesystem / git / graph) supports the full never-clobber
/// three-way merge; a non-retrievable medium (`web`) supports only conflict-flag
/// degradation. Validation refuses a request that exceeds this.
pub fn prune_guarantee_for_medium(medium_type: MediumType) -> PruneGuarantee {
    if medium_capabilities(medium_type).base_version_retrievable {
        PruneGuarantee::NeverClobber
    } else {
        PruneGuarantee::ConflictFlag
    }
}

/// A binding operation subject to capability validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation {
    /// The sync (maintenance-write) operation.
    Sync,
    /// The verify (measurement) operation.
    Verify,
}

impl Operation {
    /// The lowercase name used in refusal messages.
    fn name(self) -> &'static str {
        match self {
            Operation::Sync => "sync",
            Operation::Verify => "verify",
        }
    }
}

/// A validation-time refusal: a capability the source's medium half cannot
/// support, or a malformed in-record source declaration. Every refusal names
/// the offending source so it is diagnosable without re-reading the store.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CapabilityError {
    /// A source has an empty `name` — the name keys per-source sync/verify
    /// state, so it must be present.
    #[error("a source has an empty name: every source names itself (the name keys its state)")]
    EmptySourceName,
    /// Two sources in the record share a name — per-source state keys would
    /// collide.
    #[error(
        "duplicate source name '{name}': source names are unique within a binding \
         (they key per-source sync/verify state)"
    )]
    DuplicateSourceName {
        /// The colliding name.
        name: String,
    },
    /// A `sync` / `verify` operation is declared over a medium that cannot
    /// support it this cycle (a `web` source — operator decision 7). The
    /// out-of-scope statement is said out loud, never a silent mtime-over-URL.
    #[error(
        "operation '{operation}' is out of scope for source '{source_name}' over a '{medium_type}' \
         medium: this medium has no change signal this cycle (deferred — operator decision 7)"
    )]
    OperationOutOfScope {
        /// The offending operation.
        operation: &'static str,
        /// The source declaring it.
        source_name: String,
        /// The medium type that cannot support the operation.
        medium_type: String,
    },
    /// A `graph` source's scope carries a pattern the entity-namespace
    /// vocabulary does not define. Refused at declaration rather than
    /// silently selecting nothing: a scope that looks like selection but
    /// reaches nothing is the defect this rule exists to prevent.
    #[error(
        "scope pattern '{pattern}' on source '{source_name}' is not a legal entity selector: a \
         graph medium selects entities, not paths — write '*' for the whole mem, \
         'type:<entity_type>', or 'id:<glob>'"
    )]
    GraphScopeNotEntitySelector {
        /// The source declaring it.
        source_name: String,
        /// The offending pattern, verbatim.
        pattern: String,
    },
    /// A source's scope carries a pattern its medium has no vocabulary to
    /// express at all, so nothing anywhere can interpret it. Distinct from
    /// [`Self::GraphScopeNotEntitySelector`], which names the legal forms
    /// because a legal form exists; here there is none, so the only honest
    /// scope is no scope.
    #[error(
        "scope pattern '{pattern}' on source '{source_name}' cannot be interpreted: a \
         '{medium_type}' medium has no scope vocabulary, so the pattern would select \
         nothing while looking like selection — remove the scope rule"
    )]
    ScopeNotInterpretable {
        /// The source declaring it.
        source_name: String,
        /// The offending pattern, verbatim.
        pattern: String,
        /// The medium with no scope vocabulary.
        medium_type: String,
    },
    /// Glob `deny_paths` are declared over a medium whose namespace is not
    /// path-shaped (`graph`, `web`) — a glob cannot select in that namespace.
    #[error(
        "glob deny_paths are illegal for source '{source_name}' over a '{medium_type}' medium: its \
         '{anchor_namespace}' namespace is not path-shaped"
    )]
    GlobDenyIllegal {
        /// The offending source.
        source_name: String,
        /// The medium type whose namespace is not path-shaped.
        medium_type: String,
        /// That medium's anchor namespace.
        anchor_namespace: &'static str,
    },
    /// A source declares a preparation identifier the engine's preparation
    /// registry ([`crate::preparation`]) does not know. The refusal is
    /// exactly "not in this engine's registry": a registered identifier
    /// validates clean, an unknown one refuses, and the message names the
    /// registered set.
    ///
    /// Raised by [`validate_binding`], which the edit/validate paths call —
    /// NOT `projection init` (which has no `--preparation` flag). The brief
    /// renderer mirrors the same rule for a record that acquired an unknown
    /// identifier by hand (accepted at rest, reported unsupported and
    /// skipped at run time with exit 0; see `GLOSSARY.md` and
    /// `crate::pipeline::Source::preparation`), so both refusal paths carry
    /// one semantics and move together.
    #[error(
        "source '{source_name}' declares preparation '{preparation}', which is not in this \
         engine's preparation registry (registered: {}; preparation impl version {impl_version})",
        crate::preparation::registered_identifiers().join(", ")
    )]
    PreparationUnsupported {
        /// The offending source.
        source_name: String,
        /// The declared preparation identifier.
        preparation: String,
        /// The current preparation-implementation version.
        impl_version: u32,
    },
    /// A registered preparation is declared over a medium whose anchor
    /// namespace admits none of the grains it prepares (`entity-load-bearing`
    /// over a `codebase` source). It would never meet an anchor it applies
    /// to, so the declaration is refused at validation rather than accepted
    /// and silently never applying.
    #[error(
        "source '{source_name}' declares preparation '{preparation}' over a '{medium_type}' \
         medium whose '{anchor_namespace}' anchor namespace admits none of the grains it \
         prepares"
    )]
    PreparationGrainMismatch {
        /// The offending source.
        source_name: String,
        /// The declared (registered) preparation identifier.
        preparation: String,
        /// The medium type it was declared over.
        medium_type: String,
        /// That medium's anchor namespace.
        anchor_namespace: &'static str,
    },
    /// The binding declares `coverage_semantics: exhaustive` while at least
    /// one source sits on a medium whose scope the engine cannot enumerate
    /// (`web`) — `S(D)` is not computable, so exhaustive coverage cannot be
    /// asserted over it. Refused at binding-validation time with `curated`
    /// as the remedy. An *undeclared* field never trips this: it resolves
    /// per medium via [`effective_coverage_semantics`].
    #[error(
        "coverage_semantics 'exhaustive' is unsupported for source '{source_name}' over a \
         '{medium_type}' medium: its scope is not enumerable (S(D) is not computable), so \
         exhaustive coverage cannot be asserted — declare 'curated', or omit the field to \
         resolve per medium"
    )]
    CoverageExhaustiveUnsupported {
        /// The offending source.
        source_name: String,
        /// The medium type whose scope is not enumerable.
        medium_type: String,
    },
    /// The binding requests a `prune` guarantee the source's medium cannot
    /// support (F1) — `never-clobber` over a medium whose base leg is not
    /// retrievable (`web`). Refused at binding-validation time with the
    /// downgrade remedy, never discovered at run time.
    #[error(
        "prune guarantee '{requested}' is unsupported for source '{source_name}' over a \
         '{medium_type}' medium: its base leg is not retrievable, so only '{supported}' \
         degradation is possible — set the binding's prune guarantee to '{supported}', or \
         point the source at a git-backed medium"
    )]
    PruneGuaranteeUnsupported {
        /// The offending source.
        source_name: String,
        /// The medium type that cannot support the requested guarantee.
        medium_type: String,
        /// The requested guarantee wire string.
        requested: &'static str,
        /// The strongest guarantee this medium supports (the downgrade remedy).
        supported: &'static str,
    },
}

/// Validate a binding against the medium-capability matrix and the in-record
/// source rules, returning **every** refusal (empty `Err` never returned —
/// `Ok` means clean). The v2 record needs no external resolution: everything
/// validated lives inside the one record.
///
/// Refuses:
/// - an empty or duplicate source `name`
///   ([`CapabilityError::EmptySourceName`] /
///   [`CapabilityError::DuplicateSourceName`]) — names key per-source state;
/// - a declared `sync` / `verify` operation over a `web` source
///   ([`CapabilityError::OperationOutOfScope`]);
/// - a glob `deny_paths` list over a non-path-namespace medium
///   ([`CapabilityError::GlobDenyIllegal`]);
/// - a source preparation the engine's registry does not know
///   ([`CapabilityError::PreparationUnsupported`]), or a registered one
///   over a medium whose anchor namespace admits none of its grains
///   ([`CapabilityError::PreparationGrainMismatch`]);
/// - a declared `coverage_semantics: exhaustive` over a non-enumerable
///   medium ([`CapabilityError::CoverageExhaustiveUnsupported`]);
/// - a `prune` block requesting `never-clobber` over a non-base-retrievable
///   medium ([`CapabilityError::PruneGuaranteeUnsupported`], F1).
pub fn validate_binding(binding: &Binding) -> Result<(), Vec<CapabilityError>> {
    let mut refusals = Vec::new();
    let has_deny = !binding.deny_paths.is_empty();
    let sync_declared = binding.operations.sync.is_some();
    let verify_declared = binding.operations.verify.is_some();
    // F1: a `prune` block requesting `never-clobber` needs a base-retrievable
    // medium on every source; refuse per-source where it cannot be honoured.
    let requested_prune = binding
        .prune
        .as_ref()
        .map(|p| p.guarantee)
        .filter(|g| *g == PruneGuarantee::NeverClobber);

    let mut seen_names: Vec<&str> = Vec::new();
    for source in &binding.sources {
        if source.name.is_empty() {
            refusals.push(CapabilityError::EmptySourceName);
        } else if seen_names.contains(&source.name.as_str()) {
            refusals.push(CapabilityError::DuplicateSourceName {
                name: source.name.clone(),
            });
        } else {
            seen_names.push(&source.name);
        }

        let caps = medium_capabilities(source.medium_type);
        let medium_type = serde_json::to_value(source.medium_type)
            .ok()
            .and_then(|v| v.as_str().map(str::to_string))
            .unwrap_or_default();

        // A declared preparation must be one the registry knows — the
        // touchpoints consult the registry by identifier, so an unknown one
        // could never be applied — and one that can apply over this medium's
        // anchor namespace.
        if let Some(prep) = &source.preparation {
            match crate::preparation::lookup(prep) {
                None => refusals.push(CapabilityError::PreparationUnsupported {
                    source_name: source.name.clone(),
                    preparation: prep.clone(),
                    impl_version: PREPARATION_IMPL_VERSION,
                }),
                Some(registered)
                    if !crate::preparation::applies_to_namespace(
                        registered,
                        caps.anchor_namespace,
                    ) =>
                {
                    refusals.push(CapabilityError::PreparationGrainMismatch {
                        source_name: source.name.clone(),
                        preparation: prep.clone(),
                        medium_type: medium_type.clone(),
                        anchor_namespace: caps.anchor_namespace,
                    });
                }
                Some(_) => {}
            }
        }

        // sync / verify over a medium with no change signal (web) is out of scope.
        if !caps.change_signal {
            for (declared, op) in [
                (sync_declared, Operation::Sync),
                (verify_declared, Operation::Verify),
            ] {
                if declared {
                    refusals.push(CapabilityError::OperationOutOfScope {
                        operation: op.name(),
                        source_name: source.name.clone(),
                        medium_type: medium_type.clone(),
                    });
                }
            }
        }

        // A scope rule must be one its medium's namespace can express. The
        // engine used to accept any string here and interpret none of them,
        // so `**/*` scaffolded onto a graph facet looked like scope and
        // selected nothing. Refuse the undefined form at declaration.
        //
        // Checked for every medium whose namespace is not path-shaped, not for
        // graph alone: `web` has no selector vocabulary either, and gating on
        // one medium is how the class survived a round — fixed where it had
        // been demonstrated and left standing one row over.
        match source.medium_type {
            MediumType::Graph => {
                for rule in &source.scope {
                    if crate::ingest::cursor::parse_entity_selector(&rule.path).is_none() {
                        refusals.push(CapabilityError::GraphScopeNotEntitySelector {
                            source_name: source.name.clone(),
                            pattern: rule.path.clone(),
                        });
                    }
                }
            }
            MediumType::Web => {
                for rule in &source.scope {
                    refusals.push(CapabilityError::ScopeNotInterpretable {
                        source_name: source.name.clone(),
                        pattern: rule.path.clone(),
                        medium_type: medium_type.clone(),
                    });
                }
            }
            MediumType::Codebase | MediumType::Filesystem | MediumType::Git => {}
        }

        // Glob deny_paths over a non-path-shaped namespace is illegal.
        if has_deny && !caps.glob_deny_legal {
            refusals.push(CapabilityError::GlobDenyIllegal {
                source_name: source.name.clone(),
                medium_type: medium_type.clone(),
                anchor_namespace: caps.anchor_namespace,
            });
        }

        // A declared `exhaustive` over a non-enumerable medium is refused —
        // the engine cannot compute S(D) there, so the claim is unassertable.
        // Fires only on what the author actually wrote (`Some(Exhaustive)`);
        // an undeclared field resolves per medium instead of refusing.
        if binding.coverage_semantics == Some(CoverageSemantics::Exhaustive) && !caps.enumerable {
            refusals.push(CapabilityError::CoverageExhaustiveUnsupported {
                source_name: source.name.clone(),
                medium_type: medium_type.clone(),
            });
        }

        // F1: requested `never-clobber` prune over a non-base-retrievable medium
        // is refused with the downgrade remedy — at validation, not run time.
        if requested_prune.is_some() && !caps.base_version_retrievable {
            refusals.push(CapabilityError::PruneGuaranteeUnsupported {
                source_name: source.name.clone(),
                medium_type: medium_type.clone(),
                requested: PruneGuarantee::NeverClobber.as_wire(),
                supported: prune_guarantee_for_medium(source.medium_type).as_wire(),
            });
        }
    }

    if refusals.is_empty() {
        Ok(())
    } else {
        Err(refusals)
    }
}

/// What a caller wants scaffolded: one binding over one source. Everything
/// else — deny defaults, the capability-matrix filter, the prune block — is
/// the engine's to decide, so that every front door that scaffolds a binding
/// scaffolds the same one.
#[derive(Debug, Clone)]
pub struct ScaffoldParams<'a> {
    /// The mem the binding writes into — the `<mem>` half of the binding id.
    pub destination_mem: &'a str,
    /// The single source's `name` (unique within the record; keys per-source
    /// state). Conventionally the binding stem.
    pub source_name: &'a str,
    /// The medium pointer — workspace-relative path, mem id, or URL.
    pub pointer: &'a str,
    /// The medium type, which decides the capability matrix.
    pub medium_type: MediumType,
    /// Intent prose for the agent, or `None`.
    pub intent: Option<String>,
    /// Deny globs to add beyond [`DEFAULT_SCAFFOLD_DENY_PATHS`], for a caller
    /// that knows something about the tree the engine cannot infer. Materialised
    /// into the record exactly like the defaults — visible, editable, deletable.
    /// Engine state and mount storage locations never belong here: their
    /// exclusion is unconditional in the strategy layer.
    pub additional_deny_paths: Vec<String>,
}

/// A scaffolded binding, ready to write: the record, the operations it ended
/// up declaring, and the warnings the caller must surface.
#[derive(Debug, Clone)]
pub struct ScaffoldedBinding {
    /// The record to write.
    pub binding: Binding,
    /// The operation names the record declares, in `build, sync, verify` order
    /// — the matrix may have stripped some.
    pub operations: Vec<&'static str>,
    /// Capability refusals the scaffold resolved by stripping an operation,
    /// rendered for the caller's output. Never a failure: a scaffold that
    /// declares less than asked says so rather than refusing.
    pub warnings: Vec<String>,
}

/// Scaffold the default binding record for one source — the single
/// definition of "a fresh binding", shared by every front door that creates
/// one (`memstead projection init`, the guided `memstead quickstart` path,
/// any embedder).
///
/// The record: one inline [`Source`] scoped `**/*` (a scoped default — an
/// unscoped source refuses at run time), the enumerable-medium deny defaults
/// materialised into the record (see [`DEFAULT_SCAFFOLD_DENY_PATHS`] for why
/// they are recorded rather than injected), unstated `coverage_semantics`
/// (the scaffold asserts nothing), and `build` + `sync` + `verify` filtered
/// through the capability matrix — a `web` source loses sync/verify and the
/// deferral rides `warnings`. Prune is scaffolded wherever sync survived,
/// with the strongest guarantee the medium supports.
pub fn scaffold_binding(params: ScaffoldParams<'_>) -> ScaffoldedBinding {
    let ScaffoldParams {
        destination_mem,
        source_name,
        pointer,
        medium_type,
        intent,
        additional_deny_paths,
    } = params;

    let source = Source {
        name: source_name.to_string(),
        medium_type,
        pointer: pointer.to_string(),
        change_detection: None,
        // Scope is medium-shaped. A path glob over a graph source is not a
        // narrower scope — it is an uninterpreted string: nothing anywhere
        // matches globs against entity ids, so `**/*` scaffolded a facet that
        // looked scoped and selected nothing. The graph namespace gets its own
        // whole-mem selector; every path medium keeps `**/*` byte-for-byte.
        //
        // `web` gets no scope rule at all. Its namespace is `url`, nothing
        // enumerates it, and no selector vocabulary exists for it — so any
        // pattern scaffolded here would be decorative in exactly the way the
        // graph glob was, and the brief would print it at an agent as
        // selection. An absent scope is the honest scaffold: it renders as
        // unmonitored rather than as a scope that reaches nothing.
        scope: match medium_type {
            MediumType::Graph => vec![PatternEntry {
                path: "*".to_string(),
                mode: crate::pipeline::PatternMode::Allow,
            }],
            MediumType::Web => Vec::new(),
            _ => vec![PatternEntry {
                path: "**/*".to_string(),
                mode: crate::pipeline::PatternMode::Allow,
            }],
        },
        engagement: None,
        preparation: None,
    };

    let mut deny_paths: Vec<String> =
        if matches!(medium_type, MediumType::Codebase | MediumType::Filesystem) {
            DEFAULT_SCAFFOLD_DENY_PATHS
                .iter()
                .map(|s| s.to_string())
                .collect()
        } else {
            Vec::new()
        };
    for extra in additional_deny_paths {
        if !deny_paths.contains(&extra) {
            deny_paths.push(extra);
        }
    }

    let mut binding = Binding {
        version: BINDING_VERSION,
        intent,
        sources: vec![source],
        reference_mems: Vec::new(),
        destination_mem: destination_mem.to_string(),
        deny_paths,
        coverage_semantics: None,
        rules: None,
        prune: None,
        operations: Operations {
            build: Some(BuildOperation {
                mode: BuildMode::Discovery,
                trigger: IngestTrigger::Loop,
                batch_size: 20,
                post_actions: None,
            }),
            sync: Some(SyncOperation {
                trigger: IngestTrigger::Manual,
                batch_size: 20,
            }),
            verify: Some(VerifyOperation {
                trigger: IngestTrigger::Manual,
                batch_size: 20,
                adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
            }),
        },
    };

    let mut warnings: Vec<String> = Vec::new();
    if let Err(refusals) = validate_binding(&binding) {
        for r in &refusals {
            if let CapabilityError::OperationOutOfScope { operation, .. } = r {
                match *operation {
                    "sync" => binding.operations.sync = None,
                    "verify" => binding.operations.verify = None,
                    _ => {}
                }
            }
            warnings.push(r.to_string());
        }
    }

    if binding.operations.sync.is_some() {
        binding.prune = Some(PruneConfig {
            guarantee: prune_guarantee_for_medium(medium_type),
        });
    }

    let mut operations: Vec<&'static str> = vec!["build"];
    if binding.operations.sync.is_some() {
        operations.push("sync");
    }
    if binding.operations.verify.is_some() {
        operations.push("verify");
    }

    ScaffoldedBinding {
        binding,
        operations,
        warnings,
    }
}

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

    /// The scaffold is one definition, so every front door writes the same
    /// record: scoped source, materialised deny defaults, full operations.
    #[test]
    fn codebase_scaffold_carries_the_deny_defaults_and_every_operation() {
        let s = scaffold_binding(ScaffoldParams {
            destination_mem: "app",
            source_name: "app",
            pointer: ".",
            medium_type: MediumType::Codebase,
            intent: Some("model it".to_string()),
            additional_deny_paths: Vec::new(),
        });
        assert_eq!(s.operations, vec!["build", "sync", "verify"]);
        assert_eq!(s.warnings, Vec::<String>::new());
        assert_eq!(s.binding.deny_paths, DEFAULT_SCAFFOLD_DENY_PATHS);
        assert_eq!(s.binding.sources[0].scope[0].path, "**/*");
        assert_eq!(s.binding.sources[0].pointer, ".");
        assert!(s.binding.coverage_semantics.is_none(), "asserts nothing");
        assert!(
            s.binding.prune.is_some(),
            "sync survived, so prune rides it"
        );
    }

    /// A caller's extra deny entries are materialised alongside the
    /// defaults — visible, editable, and never silently deduplicated away
    /// into a different list.
    #[test]
    fn additional_deny_paths_are_appended_once() {
        let s = scaffold_binding(ScaffoldParams {
            destination_mem: "app",
            source_name: "app",
            pointer: ".",
            medium_type: MediumType::Codebase,
            intent: None,
            additional_deny_paths: vec!["build/**".to_string(), "**/.git/**".to_string()],
        });
        let expected: Vec<String> = DEFAULT_SCAFFOLD_DENY_PATHS
            .iter()
            .map(|s| s.to_string())
            .chain(std::iter::once("build/**".to_string()))
            .collect();
        assert_eq!(s.binding.deny_paths, expected);
    }

    /// A medium the matrix cannot serve loses the operation and says so,
    /// rather than scaffolding a record that refuses at run time.
    #[test]
    fn web_scaffold_loses_sync_and_verify_with_a_warning() {
        let s = scaffold_binding(ScaffoldParams {
            destination_mem: "app",
            source_name: "manual",
            pointer: "https://example.com/manual",
            medium_type: MediumType::Web,
            intent: None,
            additional_deny_paths: Vec::new(),
        });
        assert_eq!(s.operations, vec!["build"]);
        assert!(!s.warnings.is_empty(), "the deferral is named");
        assert!(s.binding.deny_paths.is_empty(), "no path denies over web");
        assert!(s.binding.prune.is_none(), "no sync, no prune");
    }
}

#[cfg(test)]
mod tests {

    /// Scaffolded scope is medium-shaped, and every rule it writes is one
    /// something interprets. The path mediums keep `**/*` byte-for-byte;
    /// `graph` gets the entity vocabulary; `web` gets NO rule, because its
    /// namespace has no selector vocabulary and a pattern there would be
    /// decorative in exactly the way the graph glob was — printed at an agent
    /// as selection while reaching nothing.
    #[test]
    fn scaffolded_scope_is_medium_shaped_and_never_decorative() {
        let scope_of = |medium: MediumType| {
            scaffold_binding(ScaffoldParams {
                destination_mem: "m",
                source_name: "s",
                pointer: "p",
                medium_type: medium,
                intent: None,
                additional_deny_paths: Vec::new(),
            })
            .binding
            .sources[0]
                .scope
                .iter()
                .map(|r| r.path.clone())
                .collect::<Vec<_>>()
        };

        // Unchanged, and asserted so a graph-shaped fix can never drift them.
        assert_eq!(scope_of(MediumType::Codebase), vec!["**/*".to_string()]);
        assert_eq!(scope_of(MediumType::Filesystem), vec!["**/*".to_string()]);
        assert_eq!(scope_of(MediumType::Git), vec!["**/*".to_string()]);

        // Entity namespace: a legal selector, and one the run time honours.
        assert_eq!(scope_of(MediumType::Graph), vec!["*".to_string()]);
        assert!(
            crate::ingest::cursor::parse_entity_selector("*").is_some(),
            "the graph scaffold writes a selector the parser accepts"
        );

        // No vocabulary exists, so no rule is written.
        assert!(
            scope_of(MediumType::Web).is_empty(),
            "a web facet carries no scope rather than one nothing interprets"
        );
    }
    use super::*;
    use crate::pipeline::PatternMode;

    // ---- builders -------------------------------------------------------

    fn build_op() -> BuildOperation {
        BuildOperation {
            mode: BuildMode::Discovery,
            trigger: IngestTrigger::Loop,
            batch_size: 20,
            post_actions: None,
        }
    }

    fn allow(path: &str) -> PatternEntry {
        PatternEntry {
            path: path.to_string(),
            mode: PatternMode::Allow,
        }
    }

    fn source(
        name: &str,
        medium_type: MediumType,
        pointer: &str,
        scope: Vec<PatternEntry>,
        preparation: Option<&str>,
        change_detection: Option<&str>,
    ) -> Source {
        Source {
            name: name.to_string(),
            medium_type,
            pointer: pointer.to_string(),
            change_detection: change_detection.map(str::to_string),
            scope,
            engagement: None,
            preparation: preparation.map(str::to_string),
        }
    }

    fn codebase_source() -> Source {
        source(
            "source-tree",
            MediumType::Codebase,
            "../public",
            vec![allow("../public/**/*.rs")],
            None,
            None,
        )
    }

    fn binding() -> Binding {
        Binding {
            version: BINDING_VERSION,
            intent: Some("prose for the agent".to_string()),
            sources: vec![codebase_source()],
            reference_mems: vec!["engine".to_string()],
            destination_mem: "plugin".to_string(),
            deny_paths: vec!["VISION.md".to_string(), "dev/**".to_string()],
            coverage_semantics: None,
            rules: Some(serde_json::json!({ "routing": "" })),
            prune: None,
            operations: Operations {
                build: Some(build_op()),
                sync: Some(SyncOperation {
                    trigger: IngestTrigger::Manual,
                    batch_size: 20,
                }),
                verify: Some(VerifyOperation {
                    trigger: IngestTrigger::Manual,
                    batch_size: 20,
                    adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                    full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
                }),
            },
        }
    }

    // ---- Binding serde --------------------------------------------------

    /// A v2 binding round-trips: serialize → deserialize → equal.
    #[test]
    fn binding_round_trips() {
        let b = binding();
        let json = serde_json::to_string(&b).unwrap();
        let back: Binding = serde_json::from_str(&json).unwrap();
        assert_eq!(back, b);
    }

    /// The plan's v2 wire example deserializes: inline sources with both
    /// halves, the operations block, and coverage semantics as declared.
    #[test]
    fn plan_shaped_v2_json_deserializes() {
        let src = r#"{
          "version": 2,
          "intent": "prose the building agent reads before every run",
          "sources": [
            {
              "name": "source-tree",
              "type": "codebase",
              "pointer": "../public",
              "change_detection": "auto",
              "scope": [
                { "path": "../public/**/*.rs", "mode": "allow" },
                { "path": "../public/target/**", "mode": "deny" }
              ]
            }
          ],
          "reference_mems": ["engineering"],
          "destination_mem": "engine",
          "deny_paths": ["../dev/**"],
          "coverage_semantics": "exhaustive",
          "operations": {
            "build":  { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
            "sync":   { "trigger": "loop", "batch_size": 20 },
            "verify": { "trigger": "loop", "batch_size": 20,
                        "adjudication_cap": 50, "full_resync_every": 20 }
          }
        }"#;
        let b: Binding = serde_json::from_str(src).unwrap();
        assert_eq!(b.version, 2);
        assert_eq!(b.destination_mem, "engine");
        assert_eq!(b.sources.len(), 1);
        let s = &b.sources[0];
        assert_eq!(s.name, "source-tree");
        assert_eq!(s.medium_type, MediumType::Codebase);
        assert_eq!(s.pointer, "../public");
        assert_eq!(s.change_detection.as_deref(), Some("auto"));
        assert_eq!(s.scope.len(), 2);
        assert_eq!(b.reference_mems, vec!["engineering".to_string()]);
        assert_eq!(b.coverage_semantics, Some(CoverageSemantics::Exhaustive));
        assert_eq!(
            b.operations.build.as_ref().unwrap().mode,
            BuildMode::Discovery
        );
        assert!(b.operations.sync.is_some());
        assert_eq!(b.operations.verify.as_ref().unwrap().adjudication_cap, 50);
    }

    /// An absent `coverage_semantics` deserializes to `None` ("not
    /// stated" — resolved per medium, never a baked-in default), and
    /// `one-shot` is the kebab wire form.
    #[test]
    fn coverage_defaults_and_one_shot_wire_form() {
        let src = r#"{
          "version": 2,
          "destination_mem": "m",
          "operations": { "build": { "mode": "one-shot", "trigger": "manual", "batch_size": 5 } }
        }"#;
        let b: Binding = serde_json::from_str(src).unwrap();
        assert_eq!(b.coverage_semantics, None, "absent = not stated");
        assert_eq!(
            b.operations.build.as_ref().unwrap().mode,
            BuildMode::OneShot
        );
        assert!(b.operations.sync.is_none());
        assert!(b.operations.verify.is_none());
        // one-shot serializes to the kebab form.
        assert_eq!(
            serde_json::to_string(&BuildMode::OneShot).unwrap(),
            r#""one-shot""#
        );
    }

    /// The tier-3 knobs are additive: a `verify` block without them
    /// deserializes to the dogfood-tuned defaults, and a block that sets them
    /// round-trips its values.
    #[test]
    fn verify_tier3_knobs_default_and_round_trip() {
        let src = r#"{
          "version": 2,
          "destination_mem": "m",
          "operations": {
            "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
            "verify": { "trigger": "manual", "batch_size": 20 }
          }
        }"#;
        let b: Binding = serde_json::from_str(src).unwrap();
        let v = b.operations.verify.as_ref().unwrap();
        assert_eq!(v.adjudication_cap, DEFAULT_ADJUDICATION_CAP);
        assert_eq!(v.full_resync_every, DEFAULT_FULL_RESYNC_EVERY);

        // Explicit values round-trip.
        let explicit = VerifyOperation {
            trigger: IngestTrigger::Manual,
            batch_size: 10,
            adjudication_cap: 7,
            full_resync_every: 3,
        };
        let json = serde_json::to_string(&explicit).unwrap();
        let back: VerifyOperation = serde_json::from_str(&json).unwrap();
        assert_eq!(back, explicit);
        assert!(json.contains("adjudication_cap"));
        assert!(json.contains("full_resync_every"));
    }

    /// The tier-3 scheduling knobs never change `hash(D)` — they are excluded
    /// with the rest of the `verify` block (scheduling never changes the claim).
    #[test]
    fn tier3_knobs_do_not_change_the_hash() {
        let base = hash_binding(&binding());
        let mut tuned = binding();
        let v = tuned.operations.verify.as_mut().unwrap();
        v.adjudication_cap = 999;
        v.full_resync_every = 1;
        assert_eq!(
            base,
            hash_binding(&tuned),
            "tier-3 verify knobs are excluded from hash(D)"
        );
    }

    /// `"mode": "refinement"` is a deleted value — deserialization fails.
    #[test]
    fn refinement_mode_is_rejected() {
        let src = r#"{
          "version": 2,
          "destination_mem": "m",
          "operations": { "build": { "mode": "refinement", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let err = serde_json::from_str::<Binding>(src).unwrap_err();
        assert!(
            err.to_string().contains("refinement") || err.to_string().contains("unknown variant"),
            "unexpected error: {err}"
        );
    }

    /// `version` is required — a projection file without it refuses.
    #[test]
    fn version_is_required() {
        let src = r#"{
          "destination_mem": "m",
          "operations": { "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 } }
        }"#;
        assert!(serde_json::from_str::<Binding>(src).is_err());
    }

    // ---- hash(D) --------------------------------------------------------

    /// `hash(D)` is stable and recomputable: the same binding hashes
    /// identically, and the digest is 64 lowercase hex chars.
    #[test]
    fn hash_is_stable_and_recomputable() {
        let b = binding();
        let h1 = hash_binding(&b);
        let h2 = hash_binding(&b);
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 64);
        assert!(
            h1.chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        );
    }

    /// Changing a source's selection pattern — now an input *inside* the one
    /// record — changes the hash.
    #[test]
    fn changing_a_source_pattern_changes_the_hash() {
        let base = hash_binding(&binding());
        let mut changed = binding();
        changed.sources[0].scope = vec![allow("../public/**/*.md")];
        assert_ne!(base, hash_binding(&changed));
    }

    /// Changing a source's pointer changes the hash.
    #[test]
    fn changing_a_source_pointer_changes_the_hash() {
        let base = hash_binding(&binding());
        let mut changed = binding();
        changed.sources[0].pointer = "../elsewhere".to_string();
        assert_ne!(base, hash_binding(&changed));
    }

    /// Changing `trigger`, `batch_size`, or `post_actions` does **not** change
    /// the hash — scheduling never changes what the mem claims. Neither does a
    /// source's `engagement` contract (the pre-consolidation exclusion carried
    /// forward).
    #[test]
    fn scheduling_knobs_do_not_change_the_hash() {
        let base = hash_binding(&binding());

        let mut b_trigger = binding();
        b_trigger.operations.build.as_mut().unwrap().trigger = IngestTrigger::Manual;
        assert_eq!(base, hash_binding(&b_trigger), "trigger is excluded");

        let mut b_batch = binding();
        b_batch.operations.build.as_mut().unwrap().batch_size = 999;
        assert_eq!(base, hash_binding(&b_batch), "batch_size is excluded");

        let mut b_post = binding();
        b_post.operations.build.as_mut().unwrap().post_actions =
            Some(serde_json::json!({ "archive_source": false }));
        assert_eq!(base, hash_binding(&b_post), "post_actions is excluded");

        // The sync/verify blocks are excluded too.
        let mut b_sync = binding();
        b_sync.operations.sync = None;
        assert_eq!(base, hash_binding(&b_sync), "sync block is excluded");

        // A source's engagement contract is excluded.
        let mut b_engage = binding();
        b_engage.sources[0].engagement = Some(serde_json::json!({ "readVerb": "Study" }));
        assert_eq!(base, hash_binding(&b_engage), "engagement is excluded");
    }

    /// Changing `operations.build.mode` — a content-defining input — **does**
    /// change the hash.
    #[test]
    fn changing_build_mode_changes_the_hash() {
        let base = hash_binding(&binding());
        let mut b = binding();
        b.operations.build.as_mut().unwrap().mode = BuildMode::OneShot;
        assert_ne!(base, hash_binding(&b));
    }

    /// An absent `build` block deserializes (serde default) and still hashes —
    /// the build mode simply does not participate in `hash(D)`.
    #[test]
    fn absent_build_deserializes_and_hashes() {
        let src = r#"{
          "version": 2,
          "destination_mem": "m",
          "operations": { "verify": { "trigger": "manual", "batch_size": 5 } }
        }"#;
        let b: Binding = serde_json::from_str(src).unwrap();
        assert!(b.operations.build.is_none(), "absent build parses to None");
        let h = hash_binding(&b);
        assert_eq!(h.len(), 64);
    }

    // ---- capability matrix + validate -----------------------------------

    /// The matrix rows are unchanged by the consolidation.
    #[test]
    fn capability_matrix_rows() {
        let web = medium_capabilities(MediumType::Web);
        assert!(!web.enumerable && !web.change_signal && !web.base_version_retrievable);
        assert!(!web.glob_deny_legal);
        assert_eq!(web.anchor_namespace, "url");

        let graph = medium_capabilities(MediumType::Graph);
        assert!(graph.enumerable && graph.change_signal && graph.base_version_retrievable);
        assert!(!graph.glob_deny_legal, "graph namespace is not path-shaped");
        assert_eq!(graph.anchor_namespace, "entity");

        for ty in [
            MediumType::Codebase,
            MediumType::Filesystem,
            MediumType::Git,
        ] {
            let c = medium_capabilities(ty);
            assert!(c.enumerable && c.change_signal && c.base_version_retrievable);
            assert!(c.glob_deny_legal, "{ty:?} allows glob deny_paths");
        }
        assert_eq!(
            medium_capabilities(MediumType::Git).anchor_namespace,
            "path+commit"
        );
    }

    /// An empty source name refuses, and a duplicate source name refuses —
    /// per-source state keys must be present and collision-free.
    #[test]
    fn empty_and_duplicate_source_names_refuse() {
        let mut b = binding();
        b.deny_paths.clear();
        b.sources = vec![
            source("", MediumType::Codebase, "../a", vec![], None, None),
            source("dup", MediumType::Codebase, "../b", vec![], None, None),
            source("dup", MediumType::Codebase, "../c", vec![], None, None),
        ];
        let errs = validate_binding(&b).unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, CapabilityError::EmptySourceName)),
            "expected EmptySourceName, got {errs:?}"
        );
        assert!(
            errs.iter().any(|e| matches!(
                e,
                CapabilityError::DuplicateSourceName { name } if name == "dup"
            )),
            "expected DuplicateSourceName, got {errs:?}"
        );
    }

    /// `sync` and `verify` over a `web` source each refuse as out-of-scope.
    #[test]
    fn sync_and_verify_over_web_refuse() {
        // Web binding, no deny_paths (globs illegal), no prep — isolate the op refusal.
        let mut b = binding();
        b.deny_paths.clear();
        b.sources = vec![source(
            "web-source",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&b).unwrap_err();
        let ops: Vec<&str> = errs
            .iter()
            .filter_map(|e| match e {
                CapabilityError::OperationOutOfScope { operation, .. } => Some(*operation),
                _ => None,
            })
            .collect();
        assert!(ops.contains(&"sync"), "sync refused: {errs:?}");
        assert!(ops.contains(&"verify"), "verify refused: {errs:?}");
    }

    /// Glob `deny_paths` over a `graph` source refuses.
    #[test]
    fn glob_deny_over_graph_refuses() {
        let mut b = binding();
        b.operations.sync = None;
        b.operations.verify = None;
        b.deny_paths = vec!["some/**".to_string()];
        b.sources = vec![source(
            "graph-source",
            MediumType::Graph,
            "home",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&b).unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, CapabilityError::GlobDenyIllegal { .. })),
            "expected GlobDenyIllegal, got {errs:?}"
        );
    }

    /// A source preparation the registry does not know refuses at
    /// validation time — the narrowed refusal: same error shape, "not in
    /// this engine's registry" semantics, the registered set named.
    #[test]
    fn unregistered_preparation_refuses() {
        let mut b = binding();
        b.operations.sync = None;
        b.operations.verify = None;
        b.deny_paths.clear();
        b.sources = vec![source(
            "manual-pages",
            MediumType::Filesystem,
            "../docs",
            vec![],
            Some("pdf-to-markdown"),
            None,
        )];
        let errs = validate_binding(&b).unwrap_err();
        let refusal = errs
            .iter()
            .find(|e| matches!(
                e,
                CapabilityError::PreparationUnsupported { preparation, impl_version, .. }
                    if preparation == "pdf-to-markdown" && *impl_version == PREPARATION_IMPL_VERSION
            ))
            .unwrap_or_else(|| panic!("expected PreparationUnsupported, got {errs:?}"));
        let msg = refusal.to_string();
        assert!(
            msg.contains("not in this engine's preparation registry"),
            "{msg}"
        );
        assert!(
            msg.contains("entity-load-bearing"),
            "names the registered set: {msg}"
        );
        assert!(
            !msg.contains("facet"),
            "the retired noun stays retired: {msg}"
        );
    }

    /// A registered preparation validates clean over a medium whose anchor
    /// namespace admits its grain (`entity-load-bearing` over `graph`), and
    /// refuses over one that does not (the same identifier over `codebase`,
    /// where no entity-grain anchor could ever meet it).
    #[test]
    fn registered_preparation_validates_over_its_namespace_only() {
        let mut ok = binding();
        ok.deny_paths.clear();
        ok.sources = vec![source(
            "claims",
            MediumType::Graph,
            "home",
            vec![allow("*")],
            Some(crate::preparation::ENTITY_LOAD_BEARING),
            None,
        )];
        assert!(
            validate_binding(&ok).is_ok(),
            "registered preparation over its namespace validates clean: {:?}",
            validate_binding(&ok)
        );

        let mut mismatch = binding();
        mismatch.sources = vec![source(
            "source-tree",
            MediumType::Codebase,
            "../public",
            vec![allow("**/*.rs")],
            Some(crate::preparation::ENTITY_LOAD_BEARING),
            None,
        )];
        let errs = validate_binding(&mismatch).unwrap_err();
        assert!(
            errs.iter().any(|e| matches!(
                e,
                CapabilityError::PreparationGrainMismatch { preparation, anchor_namespace, .. }
                    if preparation == crate::preparation::ENTITY_LOAD_BEARING && *anchor_namespace == "path"
            )),
            "expected PreparationGrainMismatch, got {errs:?}"
        );
        assert!(
            !errs
                .iter()
                .any(|e| matches!(e, CapabilityError::PreparationUnsupported { .. })),
            "a registered identifier is never reported as unregistered"
        );
    }

    /// The impl version is hashed for EVERY source, with or without a
    /// declared preparation: the hash a prior engine generation computed
    /// (impl version 0) differs from the live one, so every finding keyed on
    /// it is invalidated by construction when the constant bumps.
    #[test]
    fn impl_version_is_hashed_into_every_binding() {
        let plain = binding();
        assert!(plain.sources.iter().all(|s| s.preparation.is_none()));
        let live = hash_binding(&plain);
        assert_eq!(
            live,
            hash_binding_at_impl_version(&plain, PREPARATION_IMPL_VERSION)
        );
        assert_ne!(
            live,
            hash_binding_at_impl_version(&plain, 0),
            "the pre-registry generation's hash differs from the live one"
        );
        assert_ne!(
            live,
            hash_binding_at_impl_version(&plain, PREPARATION_IMPL_VERSION + 1)
        );

        let mut prepared = plain.clone();
        prepared.sources[0].preparation = Some(crate::preparation::ENTITY_LOAD_BEARING.to_string());
        assert_ne!(
            hash_binding(&prepared),
            live,
            "the identifier is hashed too"
        );
    }

    /// Every combination the matrix marks legal validates clean:
    /// codebase / filesystem / git / graph bindings with build+sync+verify all
    /// pass (graph carries no glob deny_paths, none carry preparation).
    #[test]
    fn legal_combinations_validate_clean() {
        // codebase / filesystem / git — path-shaped, deny_paths legal.
        for ty in [
            MediumType::Codebase,
            MediumType::Filesystem,
            MediumType::Git,
        ] {
            let mut b = binding();
            b.sources = vec![source(
                "f",
                ty,
                "../src",
                vec![allow("../src/**")],
                None,
                None,
            )];
            assert!(
                validate_binding(&b).is_ok(),
                "{ty:?} build+sync+verify should validate clean"
            );
        }
        // graph — build+sync+verify legal, but only without glob deny_paths.
        let mut graph_binding = binding();
        graph_binding.deny_paths.clear();
        graph_binding.sources = vec![source("g", MediumType::Graph, "home", vec![], None, None)];
        assert!(
            validate_binding(&graph_binding).is_ok(),
            "graph build+sync+verify with no glob deny should validate clean"
        );
    }

    // ---- F1: prune guarantee -------------------------------------------

    /// F1 — the `prune` block is additive: a binding without it deserializes
    /// to `prune: None`, and a block that sets a guarantee round-trips
    /// (defaulting to `conflict-flag` when the guarantee is absent).
    #[test]
    fn prune_block_is_additive_and_round_trips() {
        let src = r#"{
          "version": 2,
          "destination_mem": "m",
          "operations": { "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let b: Binding = serde_json::from_str(src).unwrap();
        assert!(b.prune.is_none(), "absent prune parses to None");

        // A prune block with no guarantee defaults to conflict-flag.
        let with_default = r#"{
          "version": 2,
          "destination_mem": "m",
          "prune": {},
          "operations": { "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let b: Binding = serde_json::from_str(with_default).unwrap();
        assert_eq!(
            b.prune.as_ref().unwrap().guarantee,
            PruneGuarantee::ConflictFlag
        );

        // Explicit never-clobber round-trips.
        let explicit = PruneConfig {
            guarantee: PruneGuarantee::NeverClobber,
        };
        let json = serde_json::to_string(&explicit).unwrap();
        assert!(json.contains("never-clobber"));
        assert_eq!(
            serde_json::from_str::<PruneConfig>(&json).unwrap(),
            explicit
        );
    }

    /// F1 — the `prune` policy never changes `hash(D)` (it is a maintenance
    /// policy, excluded like the sync/verify blocks).
    #[test]
    fn prune_does_not_change_the_hash() {
        let base = hash_binding(&binding());
        let mut pruned = binding();
        pruned.prune = Some(PruneConfig {
            guarantee: PruneGuarantee::NeverClobber,
        });
        assert_eq!(
            base,
            hash_binding(&pruned),
            "prune policy is excluded from hash(D)"
        );
    }

    /// F1 — the strongest guarantee a medium supports is base-leg-retrievability:
    /// git-backed mediums support never-clobber; `web` supports only conflict-flag.
    #[test]
    fn prune_guarantee_per_medium_matches_capability_matrix() {
        for ty in [
            MediumType::Codebase,
            MediumType::Filesystem,
            MediumType::Git,
            MediumType::Graph,
        ] {
            assert_eq!(
                prune_guarantee_for_medium(ty),
                PruneGuarantee::NeverClobber,
                "{ty:?} can retrieve a base leg → never-clobber"
            );
        }
        assert_eq!(
            prune_guarantee_for_medium(MediumType::Web),
            PruneGuarantee::ConflictFlag,
            "web has no retrievable base leg → conflict-flag only"
        );
    }

    /// F1 REFUSAL — requesting `never-clobber` prune over a `web` source (no
    /// retrievable base leg) fails at binding validation with a remedy-bearing
    /// error naming the downgrade, never a runtime surprise.
    #[test]
    fn never_clobber_prune_over_web_refuses_with_remedy() {
        let mut b = binding();
        b.operations.sync = None; // isolate the prune refusal from op-out-of-scope
        b.operations.verify = None;
        b.deny_paths.clear();
        b.prune = Some(PruneConfig {
            guarantee: PruneGuarantee::NeverClobber,
        });
        b.sources = vec![source(
            "web-source",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&b).unwrap_err();
        let refusal = errs
            .iter()
            .find_map(|e| match e {
                CapabilityError::PruneGuaranteeUnsupported {
                    requested,
                    supported,
                    ..
                } => Some((*requested, *supported)),
                _ => None,
            })
            .expect("expected a PruneGuaranteeUnsupported refusal");
        assert_eq!(refusal, ("never-clobber", "conflict-flag"));
        // The message carries the concrete downgrade remedy.
        let msg = errs
            .iter()
            .find(|e| matches!(e, CapabilityError::PruneGuaranteeUnsupported { .. }))
            .unwrap()
            .to_string();
        assert!(
            msg.contains("conflict-flag"),
            "remedy names the downgrade: {msg}"
        );
    }

    /// F1 — `never-clobber` over a git-backed source validates clean, and
    /// `conflict-flag` (the always-supportable degradation) validates clean over
    /// `web` — the guarantee the matrix marks legal is accepted.
    #[test]
    fn prune_guarantee_supported_validates_clean() {
        // never-clobber over codebase — base retrievable, clean.
        let mut nc = binding();
        nc.prune = Some(PruneConfig {
            guarantee: PruneGuarantee::NeverClobber,
        });
        assert!(validate_binding(&nc).is_ok());

        // conflict-flag over web — always supportable (build-only to isolate).
        let mut cf = binding();
        cf.operations.sync = None;
        cf.operations.verify = None;
        cf.deny_paths.clear();
        cf.prune = Some(PruneConfig {
            guarantee: PruneGuarantee::ConflictFlag,
        });
        cf.sources = vec![source(
            "web-source",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        assert!(validate_binding(&cf).is_ok());
    }

    /// A `web` binding scaffolded build-only (no sync/verify, no deny, no prep)
    /// validates clean — the matrix-filtered default.
    #[test]
    fn web_build_only_validates_clean() {
        let mut b = binding();
        b.operations.sync = None;
        b.operations.verify = None;
        b.deny_paths.clear();
        b.sources = vec![source(
            "web-source",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        assert!(validate_binding(&b).is_ok());
    }

    // ---- coverage semantics: resolution / refusal / hash stability ------

    /// A clean web source carries NO scope: the medium has no scope
    /// vocabulary, so any rule on it is uninterpretable and refuses. This
    /// helper used to hand out `**/*` — which made every web fixture carry a
    /// decorative rule, and is why the defect went unnoticed here.
    fn web_source(name: &str) -> Source {
        source(
            name,
            MediumType::Web,
            "https://example.test",
            vec![],
            None,
            None,
        )
    }

    /// Resolution: an undeclared field resolves per binding — all
    /// sources enumerable → exhaustive; at least one non-enumerable
    /// source → curated (a mixed binding claims the weaker of its
    /// parts). An explicit `curated` validates over any medium and
    /// resolves to curated, declared.
    #[test]
    fn coverage_resolves_per_medium_when_undeclared() {
        let enumerable = binding();
        assert_eq!(enumerable.coverage_semantics, None);
        let eff = effective_coverage_semantics(&enumerable);
        assert_eq!(eff.value, CoverageSemantics::Exhaustive);
        assert!(!eff.declared, "resolved, not declared");
        validate_binding(&enumerable).expect("undeclared over enumerable validates");

        // Mixed: one enumerable + one web source → curated.
        let mut mixed = binding();
        mixed.sources.push(web_source("front"));
        // web has no change signal — drop sync/verify so only coverage
        // resolution is under test.
        mixed.operations.sync = None;
        mixed.operations.verify = None;
        mixed.deny_paths.clear();
        let eff = effective_coverage_semantics(&mixed);
        assert_eq!(eff.value, CoverageSemantics::Curated);
        assert!(!eff.declared);
        validate_binding(&mixed).expect("undeclared over web validates (resolves, never refuses)");

        // Explicit curated over any medium: validates, declared.
        let mut curated = mixed.clone();
        curated.coverage_semantics = Some(CoverageSemantics::Curated);
        validate_binding(&curated).expect("explicit curated validates over any medium");
        let eff = effective_coverage_semantics(&curated);
        assert_eq!(eff.value, CoverageSemantics::Curated);
        assert!(eff.declared);
    }

    /// Refusal: an explicit `exhaustive` with at least one
    /// non-enumerable source refuses, naming the source, the medium,
    /// and `curated` as the remedy — alongside other refusals of the
    /// same binding, not replacing them. Complements: a binding whose
    /// ONLY problem is this one still reports it; an explicit
    /// `exhaustive` over enumerable sources is NOT refused.
    #[test]
    fn explicit_exhaustive_over_non_enumerable_refuses() {
        // Only-problem case: clean web binding, explicit exhaustive.
        let mut only = binding();
        only.sources = vec![web_source("front")];
        only.operations.sync = None;
        only.operations.verify = None;
        only.deny_paths.clear();
        only.coverage_semantics = Some(CoverageSemantics::Exhaustive);
        let errs = validate_binding(&only).expect_err("must refuse");
        assert_eq!(errs.len(), 1, "only this refusal: {errs:?}");
        match &errs[0] {
            CapabilityError::CoverageExhaustiveUnsupported {
                source_name,
                medium_type,
            } => {
                assert_eq!(source_name, "front");
                assert_eq!(medium_type, "web");
            }
            other => panic!("expected CoverageExhaustiveUnsupported, got {other:?}"),
        }
        let msg = errs[0].to_string();
        assert!(
            msg.contains("'front'") && msg.contains("'web'") && msg.contains("curated"),
            "refusal names source, medium, and the curated remedy: {msg}"
        );

        // Alongside other refusals: keep sync declared (web has no change
        // signal) — both refusals must be reported together.
        let mut multi = binding();
        multi.sources = vec![web_source("front")];
        multi.operations.verify = None;
        multi.deny_paths.clear();
        multi.coverage_semantics = Some(CoverageSemantics::Exhaustive);
        assert!(multi.operations.sync.is_some(), "fixture declares sync");
        let errs = validate_binding(&multi).expect_err("must refuse");
        assert!(
            errs.iter()
                .any(|e| matches!(e, CapabilityError::CoverageExhaustiveUnsupported { .. })),
            "coverage refusal present: {errs:?}"
        );
        assert!(
            errs.iter()
                .any(|e| matches!(e, CapabilityError::OperationOutOfScope { .. })),
            "reported alongside the sync refusal, not replacing it: {errs:?}"
        );

        // Complement: explicit exhaustive over enumerable is NOT refused.
        let mut ok = binding();
        ok.coverage_semantics = Some(CoverageSemantics::Exhaustive);
        validate_binding(&ok).expect("explicit exhaustive over enumerable validates");
    }

    /// Hash stability: the hash serialises the RESOLVED value, never
    /// the `Option`. Over enumerable sources, an undeclared field
    /// hashes byte-identically to an explicit `exhaustive` (== the
    /// pre-optionality bytes, whose serialized projection was the
    /// same `"exhaustive"` value). Over a non-enumerable source, an
    /// undeclared field hashes identically to an explicit `curated`
    /// (the moved-once, stable-thereafter hash) and differently from
    /// the enumerable case's resolution.
    #[test]
    fn hash_serialises_the_resolved_coverage_value() {
        // Enumerable: None == Some(Exhaustive), byte-for-byte.
        let undeclared = binding();
        let mut declared = binding();
        declared.coverage_semantics = Some(CoverageSemantics::Exhaustive);
        assert_eq!(
            hash_binding(&undeclared),
            hash_binding(&declared),
            "undeclared over enumerable keeps the pre-optionality hash"
        );
        // ...and an explicit curated moves it (a genuine coverage change).
        let mut curated = binding();
        curated.coverage_semantics = Some(CoverageSemantics::Curated);
        assert_ne!(hash_binding(&undeclared), hash_binding(&curated));

        // Non-enumerable: None == Some(Curated) — the one-time move is
        // to the curated hash, stable thereafter.
        let mut web_undeclared = binding();
        web_undeclared.sources = vec![web_source("front")];
        let mut web_curated = web_undeclared.clone();
        web_curated.coverage_semantics = Some(CoverageSemantics::Curated);
        assert_eq!(
            hash_binding(&web_undeclared),
            hash_binding(&web_curated),
            "undeclared over web resolves (and hashes) as curated"
        );
    }
}