memstead-base 0.3.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
//! Binding format **v1** — the additive format foundation for the projection
//! promotion (bundle plan `03-projection-promotion`, decisions D1/D5/D6).
//!
//! 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. The legacy
//! four-primitive `Projection` + flat-ingest store is parsed only by the
//! migrate/legacy path (via [`crate::pipeline_store::LegacyIngest`]); the
//! retired `Ingest` / `IngestMode` machinery is gone.
//!
//! Three things live here:
//!
//! 1. [`BindingV1`] — the versioned binding record (D1): one file per
//!    source→mem obligation, collapsing the projection + ingest split into a
//!    single record with an `operations { build, sync, verify }` block.
//! 2. [`hash_binding`] — `hash(D)` (D5): the lowercase-hex SHA-256 of the
//!    canonical JSON of a binding's *content-defining resolved projection*.
//!    Scheduling knobs (`trigger` / `batch_size` / `post_actions`) are
//!    excluded by construction; a facet selection pattern or a medium pointer
//!    changing — inputs *outside* the binding file — changes the hash.
//! 3. [`medium_capabilities`] + [`validate_binding`] — the medium-capability
//!    matrix (D6) and the validation entry point that generalizes the
//!    render-time preparation refusal to binding-validation time.
//!
//! The findings-store key + record (plan 03's schema stub, once here) now live
//! as the real, IO-backed store in [`crate::ingest::findings`] (group A of plan
//! 05): [`crate::ingest::findings::FindingKey`] keys it, `hash(D)` still
//! partitions its keyspace so a declaration edit invalidates prior findings.

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

use crate::ingest::resolve::ResolvedPrimarySource;
use crate::pipeline::{IngestTrigger, MediumType, PatternEntry};

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

/// The engine's current preparation-implementation version — the single
/// source of truth for "which preparation implementation is live".
///
/// No preparation implementation exists yet, so this is `0` ("none"). It
/// nonetheless participates in [`hash_binding`]: a future preparation
/// implementation bumps this constant, which — because the preparation
/// identifier + this version are both hashed — invalidates every prior
/// finding keyed on the old `hash(D)` by construction.
pub const PREPARATION_IMPL_VERSION: u32 = 0;

// ---------------------------------------------------------------------------
// D1 — Binding format v1
// ---------------------------------------------------------------------------

/// Coverage semantics — whether the binding claims to cover *everything* in
/// its declared scope (`exhaustive`) or a deliberately partial slice
/// (`curated`). Defaults to [`CoverageSemantics::Exhaustive`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CoverageSemantics {
    /// Every artifact in scope is expected to be accounted for.
    #[default]
    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** (D1) — 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 — read-only measurement. Optional: an absent
/// `verify` block means engine defaults, never a refusal (verify is
/// read-only). 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 (D1): 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 (D2), 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 (D3): 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 [`BindingV1`] (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 [`BindingV1`]: every operation is **optional**
/// (D1/D6). 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 is read-only — 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>,
}

/// A **binding**, format version 1 (D1). One versioned record per source→mem
/// obligation: the projection declaration (`intent`, `source_facets`,
/// `reference_mems`, `destination_mem`, `deny_paths`, `coverage_semantics`,
/// `rules`) plus an `operations { build, sync, verify }` block. Collapses the
/// legacy projection + flat-ingest split into one record.
///
/// 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 BindingV1 {
    /// Format version — required. v1 is [`BINDING_VERSION`]. A projection file
    /// without it is refused by the loader (integration deferred).
    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>,
    /// Source facets (by name) the binding consumes.
    #[serde(default)]
    pub source_facets: Vec<String>,
    /// 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).
    /// Moved **up** from the per-ingest record — strategy-invariant.
    #[serde(default)]
    pub deny_paths: Vec<String>,
    /// Whether the binding claims exhaustive or curated coverage.
    #[serde(default)]
    pub coverage_semantics: 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,
}

// ---------------------------------------------------------------------------
// D5 — hash(D)
// ---------------------------------------------------------------------------

/// A binding joined to its **resolved** primary sources — the shape
/// [`hash_binding`] and [`validate_binding`] consume. `reference_mems` are
/// carried on the [`BindingV1`] itself; only the primary facets need
/// resolving (each facet's selection patterns, preparation, and its medium's
/// type / pointer / change-detection).
///
/// This mirrors the resolution [`crate::ingest::resolve`] performs for the
/// legacy ingest, reusing [`ResolvedPrimarySource`], but is constructed
/// independently for these additive primitives — it is not produced by the
/// live resolve path yet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedBinding {
    /// The binding declaration.
    pub binding: BindingV1,
    /// The binding's primary sources, resolved (facet + medium), in
    /// `source_facets` order.
    pub primary_sources: Vec<ResolvedPrimarySource>,
}

/// One resolved facet's content-defining projection, in a fixed serde shape so
/// [`hash_binding`] hashes every content input (D5). Private — the hash is the
/// only consumer.
#[derive(Serialize)]
struct HashFacet<'a> {
    facet: &'a str,
    patterns: &'a [PatternEntry],
    preparation: &'a Option<String>,
    preparation_impl_version: u32,
    medium_type: MediumType,
    medium_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` blocks: scheduling
/// never changes what the mem claims.
#[derive(Serialize)]
struct HashInput<'a> {
    version: u32,
    intent: &'a Option<String>,
    source_facets: Vec<HashFacet<'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)` (D5) — the lowercase-hex SHA-256 of the canonical JSON of
/// a binding's content-defining resolved projection.
///
/// Hashed: `version`, `intent`, `source_facets` **resolved** (per facet: its
/// selection patterns, its preparation identifier + [`PREPARATION_IMPL_VERSION`],
/// and its medium's `type` / `pointer` / `change_detection`), `reference_mems`,
/// `destination_mem`, `deny_paths`, `coverage_semantics`, `rules`, and
/// `operations.build.mode`.
///
/// **Excluded:** `trigger`, `batch_size`, `post_actions`, and future tier
/// knobs — scheduling never changes what the mem claims. Because facet
/// selection and medium pointer participate (inputs *outside* the binding
/// file), a change to either invalidates the hash, and thus any findings
/// keyed on it.
pub fn hash_binding(resolved: &ResolvedBinding) -> String {
    let source_facets: Vec<HashFacet<'_>> = resolved
        .primary_sources
        .iter()
        .map(|p| HashFacet {
            facet: &p.facet_ref,
            patterns: &p.scope,
            preparation: &p.preparation,
            preparation_impl_version: PREPARATION_IMPL_VERSION,
            medium_type: p.medium_type,
            medium_pointer: &p.medium_pointer,
            change_detection: &p.declared_change_detection,
        })
        .collect();

    let input = HashInput {
        version: resolved.binding.version,
        intent: &resolved.binding.intent,
        source_facets,
        reference_mems: &resolved.binding.reference_mems,
        destination_mem: &resolved.binding.destination_mem,
        deny_paths: &resolved.binding.deny_paths,
        coverage_semantics: resolved.binding.coverage_semantics,
        rules: &resolved.binding.rules,
        build_mode: resolved.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());
    format!("{digest:x}")
}

// ---------------------------------------------------------------------------
// D6 — medium-capability matrix + validation
// ---------------------------------------------------------------------------

/// What a medium can support (D6) — the row of the capability matrix for a
/// [`MediumType`]. 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 (D6). The single source of
/// truth the fidelity report (E3b) will also render.
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 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 capability refusal (D6). Sibling to
/// [`crate::ingest::resolve::ResolveError`] (which refuses *dangling*
/// references); this refuses declared operations a medium cannot support.
/// Every refusal names the offending facet/medium so it is diagnosable
/// without re-reading the store.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CapabilityError {
    /// A `sync` / `verify` operation is declared over a medium that cannot
    /// support it this cycle (a `web` medium — 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 facet '{facet}' 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 facet.
        facet: String,
        /// The medium type that cannot support the operation.
        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 facet '{facet}' over a '{medium_type}' medium: its \
         '{anchor_namespace}' namespace is not path-shaped"
    )]
    GlobDenyIllegal {
        /// The source facet.
        facet: String,
        /// The medium type whose namespace is not path-shaped.
        medium_type: String,
        /// That medium's anchor namespace.
        anchor_namespace: &'static str,
    },
    /// A facet declares a deterministic preparation step. No preparation
    /// implementation exists ([`PREPARATION_IMPL_VERSION`] is `0`), so any
    /// declared preparation is unsupported — refused at validation time, not
    /// only at render time.
    #[error(
        "facet '{facet}' declares preparation '{preparation}', which has no implementation \
         (preparation impl version {impl_version})"
    )]
    PreparationUnsupported {
        /// The source facet.
        facet: String,
        /// The declared preparation identifier.
        preparation: String,
        /// The current preparation-implementation version (`0` = none).
        impl_version: u32,
    },
    /// The binding requests a `prune` guarantee the facet'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 facet '{facet}' 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 facet at a git-backed medium"
    )]
    PruneGuaranteeUnsupported {
        /// The source facet.
        facet: 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 resolved binding against the medium-capability matrix (D6),
/// returning **every** capability refusal (empty `Err` never returned — `Ok`
/// means clean). Generalizes the render-time preparation refusal to
/// binding-validation time.
///
/// Refuses, per D6:
/// - a declared `sync` / `verify` operation over a `web` medium
///   ([`CapabilityError::OperationOutOfScope`]);
/// - a glob `deny_paths` list over a non-path-namespace medium
///   ([`CapabilityError::GlobDenyIllegal`]);
/// - any declared facet preparation
///   ([`CapabilityError::PreparationUnsupported`]);
/// - a `prune` block requesting `never-clobber` over a non-base-retrievable
///   medium ([`CapabilityError::PruneGuaranteeUnsupported`], F1).
///
/// A binding whose every declared operation the matrix marks legal validates
/// clean (`Ok(())`). This is a new, callable entry point — it is not yet wired
/// into the live loader / resolve path.
pub fn validate_binding(resolved: &ResolvedBinding) -> Result<(), Vec<CapabilityError>> {
    let mut refusals = Vec::new();
    let has_deny = !resolved.binding.deny_paths.is_empty();
    let sync_declared = resolved.binding.operations.sync.is_some();
    let verify_declared = resolved.binding.operations.verify.is_some();
    // F1: a `prune` block requesting `never-clobber` needs a base-retrievable
    // medium on every facet; refuse per-facet where it cannot be honoured.
    let requested_prune = resolved
        .binding
        .prune
        .as_ref()
        .map(|p| p.guarantee)
        .filter(|g| *g == PruneGuarantee::NeverClobber);

    for source in &resolved.primary_sources {
        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 is always unsupported (no implementation).
        if let Some(prep) = &source.preparation {
            refusals.push(CapabilityError::PreparationUnsupported {
                facet: source.facet_ref.clone(),
                preparation: prep.clone(),
                impl_version: PREPARATION_IMPL_VERSION,
            });
        }

        // 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(),
                        facet: source.facet_ref.clone(),
                        medium_type: medium_type.clone(),
                    });
                }
            }
        }

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

        // 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 {
                facet: source.facet_ref.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)
    }
}

#[cfg(test)]
mod tests {
    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 binding() -> BindingV1 {
        BindingV1 {
            version: BINDING_VERSION,
            intent: Some("prose for the agent".to_string()),
            source_facets: vec!["source-tree".to_string()],
            reference_mems: vec!["engine".to_string()],
            destination_mem: "plugin".to_string(),
            deny_paths: vec!["VISION.md".to_string(), "dev/**".to_string()],
            coverage_semantics: CoverageSemantics::Exhaustive,
            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,
                }),
            },
        }
    }

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

    fn primary(
        facet: &str,
        medium_type: MediumType,
        pointer: &str,
        scope: Vec<PatternEntry>,
        preparation: Option<&str>,
        change_detection: Option<&str>,
    ) -> ResolvedPrimarySource {
        ResolvedPrimarySource {
            facet_ref: facet.to_string(),
            medium: "m".to_string(),
            medium_type,
            medium_pointer: pointer.to_string(),
            declared_change_detection: change_detection.map(str::to_string),
            scope,
            preparation: preparation.map(str::to_string),
        }
    }

    fn resolved(binding: BindingV1, sources: Vec<ResolvedPrimarySource>) -> ResolvedBinding {
        ResolvedBinding {
            binding,
            primary_sources: sources,
        }
    }

    fn one_codebase_source() -> Vec<ResolvedPrimarySource> {
        vec![primary(
            "source-tree",
            MediumType::Codebase,
            "../public",
            vec![allow("../public/**/*.rs")],
            None,
            None,
        )]
    }

    // ---- D1: BindingV1 serde --------------------------------------------

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

    /// A real-shaped v1 binding JSON (the D1 example) deserializes, with the
    /// operations block and coverage semantics as declared.
    #[test]
    fn real_shaped_v1_json_deserializes() {
        let src = r#"{
          "version": 1,
          "intent": "prose for the agent",
          "source_facets": ["source-tree"],
          "reference_mems": ["engine"],
          "destination_mem": "plugin",
          "deny_paths": ["VISION.md", "dev/**"],
          "coverage_semantics": "exhaustive",
          "rules": { "routing": "…" },
          "operations": {
            "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20, "post_actions": { "archive_source": true } },
            "sync":  { "trigger": "manual", "batch_size": 20 },
            "verify": { "trigger": "manual", "batch_size": 20 }
          }
        }"#;
        let b: BindingV1 = serde_json::from_str(src).unwrap();
        assert_eq!(b.version, 1);
        assert_eq!(b.destination_mem, "plugin");
        assert_eq!(b.coverage_semantics, CoverageSemantics::Exhaustive);
        assert_eq!(
            b.operations.build.as_ref().unwrap().mode,
            BuildMode::Discovery
        );
        assert_eq!(
            b.operations.build.as_ref().unwrap().trigger,
            IngestTrigger::Loop
        );
        assert_eq!(
            b.operations.build.as_ref().unwrap().post_actions,
            Some(serde_json::json!({ "archive_source": true }))
        );
        assert!(b.operations.sync.is_some());
        assert!(b.operations.verify.is_some());
    }

    /// `coverage_semantics` defaults to exhaustive when absent, and `one-shot`
    /// is the kebab wire form.
    #[test]
    fn coverage_defaults_and_one_shot_wire_form() {
        let src = r#"{
          "version": 1,
          "destination_mem": "m",
          "operations": { "build": { "mode": "one-shot", "trigger": "manual", "batch_size": 5 } }
        }"#;
        let b: BindingV1 = serde_json::from_str(src).unwrap();
        assert_eq!(b.coverage_semantics, CoverageSemantics::Exhaustive);
        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""#
        );
    }

    /// D4 — the tier-3 knobs are additive: a `verify` block written before they
    /// existed (only `trigger` + `batch_size`) 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() {
        // Legacy verify block — no adjudication_cap / full_resync_every.
        let src = r#"{
          "version": 1,
          "destination_mem": "m",
          "operations": {
            "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
            "verify": { "trigger": "manual", "batch_size": 20 }
          }
        }"#;
        let b: BindingV1 = 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(&resolved(binding(), one_codebase_source()));
        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(&resolved(tuned, one_codebase_source())),
            "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": 1,
          "destination_mem": "m",
          "operations": { "build": { "mode": "refinement", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let err = serde_json::from_str::<BindingV1>(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::<BindingV1>(src).is_err());
    }

    // ---- D5: hash(D) ----------------------------------------------------

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

    /// Changing a facet selection pattern (an input *outside* the binding
    /// file) changes the hash.
    #[test]
    fn changing_a_facet_pattern_changes_the_hash() {
        let base = hash_binding(&resolved(binding(), one_codebase_source()));
        let changed = hash_binding(&resolved(
            binding(),
            vec![primary(
                "source-tree",
                MediumType::Codebase,
                "../public",
                vec![allow("../public/**/*.md")], // different pattern
                None,
                None,
            )],
        ));
        assert_ne!(base, changed);
    }

    /// Changing a medium pointer (an input *outside* the binding file) changes
    /// the hash.
    #[test]
    fn changing_a_medium_pointer_changes_the_hash() {
        let base = hash_binding(&resolved(binding(), one_codebase_source()));
        let changed = hash_binding(&resolved(
            binding(),
            vec![primary(
                "source-tree",
                MediumType::Codebase,
                "../elsewhere", // different pointer
                vec![allow("../public/**/*.rs")],
                None,
                None,
            )],
        ));
        assert_ne!(base, changed);
    }

    /// Changing `trigger`, `batch_size`, or `post_actions` does **not** change
    /// the hash — scheduling never changes what the mem claims.
    #[test]
    fn scheduling_knobs_do_not_change_the_hash() {
        let base = hash_binding(&resolved(binding(), one_codebase_source()));

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

        let mut b_batch = binding();
        b_batch.operations.build.as_mut().unwrap().batch_size = 999;
        assert_eq!(
            base,
            hash_binding(&resolved(b_batch, one_codebase_source())),
            "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(&resolved(b_post, one_codebase_source())),
            "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(&resolved(b_sync, one_codebase_source())),
            "sync block 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(&resolved(binding(), one_codebase_source()));
        let mut b = binding();
        b.operations.build.as_mut().unwrap().mode = BuildMode::OneShot;
        assert_ne!(base, hash_binding(&resolved(b, one_codebase_source())));
    }

    /// An absent `build` block deserializes (serde default) and still hashes —
    /// the build mode simply does not participate in `hash(D)` (D1/AC4).
    #[test]
    fn absent_build_deserializes_and_hashes() {
        let src = r#"{
          "version": 1,
          "destination_mem": "m",
          "operations": { "verify": { "trigger": "manual", "batch_size": 5 } }
        }"#;
        let b: BindingV1 = serde_json::from_str(src).unwrap();
        assert!(b.operations.build.is_none(), "absent build parses to None");
        // Hashes without panicking; build_mode is omitted from the canonical JSON.
        let h = hash_binding(&resolved(b, one_codebase_source()));
        assert_eq!(h.len(), 64);
    }

    // ---- D6: capability matrix + validate -------------------------------

    /// The matrix rows match D6's table.
    #[test]
    fn capability_matrix_matches_d6_table() {
        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"
        );
    }

    /// `sync` and `verify` over a `web` medium 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();
        let sources = vec![primary(
            "web-facet",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&resolved(b, sources)).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` medium refuses.
    #[test]
    fn glob_deny_over_graph_refuses() {
        // Graph binding with build-only (avoid the change-signal check; graph
        // *does* have a change signal anyway) and a glob deny list.
        let mut b = binding();
        b.operations.sync = None;
        b.operations.verify = None;
        b.deny_paths = vec!["some/**".to_string()];
        let sources = vec![primary(
            "graph-facet",
            MediumType::Graph,
            "home",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&resolved(b, sources)).unwrap_err();
        assert!(
            errs.iter()
                .any(|e| matches!(e, CapabilityError::GlobDenyIllegal { .. })),
            "expected GlobDenyIllegal, got {errs:?}"
        );
    }

    /// A declared facet preparation refuses at validation time.
    #[test]
    fn declared_preparation_refuses() {
        let mut b = binding();
        b.operations.sync = None;
        b.operations.verify = None;
        b.deny_paths.clear();
        let sources = vec![primary(
            "manual-pages",
            MediumType::Filesystem,
            "../docs",
            vec![],
            Some("pdf-to-markdown"),
            None,
        )];
        let errs = validate_binding(&resolved(b, sources)).unwrap_err();
        assert!(
            errs.iter().any(|e| matches!(
                e,
                CapabilityError::PreparationUnsupported { preparation, .. } if preparation == "pdf-to-markdown"
            )),
            "expected PreparationUnsupported, got {errs:?}"
        );
    }

    /// 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 sources = vec![primary(
                "f",
                ty,
                "../src",
                vec![allow("../src/**")],
                None,
                None,
            )];
            assert!(
                validate_binding(&resolved(binding(), sources)).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();
        let graph_sources = vec![primary("g", MediumType::Graph, "home", vec![], None, None)];
        assert!(
            validate_binding(&resolved(graph_binding, graph_sources)).is_ok(),
            "graph build+sync+verify with no glob deny should validate clean"
        );
    }

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

    /// F1 — the `prune` block is additive: a binding written before it existed
    /// 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() {
        // Legacy binding — no `prune`.
        let src = r#"{
          "version": 1,
          "destination_mem": "m",
          "operations": { "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let b: BindingV1 = 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": 1,
          "destination_mem": "m",
          "prune": {},
          "operations": { "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 } }
        }"#;
        let b: BindingV1 = 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(&resolved(binding(), one_codebase_source()));
        let mut pruned = binding();
        pruned.prune = Some(PruneConfig {
            guarantee: PruneGuarantee::NeverClobber,
        });
        assert_eq!(
            base,
            hash_binding(&resolved(pruned, one_codebase_source())),
            "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` medium (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,
        });
        let sources = vec![primary(
            "web-facet",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        let errs = validate_binding(&resolved(b, sources)).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 medium 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(&resolved(nc, one_codebase_source())).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,
        });
        let web = vec![primary(
            "web-facet",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        assert!(validate_binding(&resolved(cf, web)).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();
        let sources = vec![primary(
            "web-facet",
            MediumType::Web,
            "https://example.com",
            vec![],
            None,
            None,
        )];
        assert!(validate_binding(&resolved(b, sources)).is_ok());
    }
}