agentplane 0.10.0

Durable, replayable agent runtime — the journal is the plan of record
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
//! Information-flow labels.
//!
//! Payloads are opaque to the engine (it never parses business data) but they
//! are never *unlabeled*: policy over unlabeled blobs is policy over nothing.
//!
//! Every value carries provenance, a trust level, and a sensitivity level.
//! Combining values joins their labels on a bounded semilattice — trust degrades
//! to the worse, sensitivity escalates to the higher, provenance accumulates.
//! The single rule most systems get wrong, and the one that makes the dual-LLM
//! guarantee real rather than nominal:
//!
//! > **Model output derived from untrusted input stays untrusted.**

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::{Deserialize, Serialize};

/// Where a value came from. Free-form so the engine stays domain-agnostic; the
/// runtime stamps tool refs, peer ids, and collection names.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SourceId(pub String);

impl SourceId {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

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

/// Whether a value may influence control flow.
///
/// Ordered so that `max` is the correct join: `Untrusted > Trusted`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Trust {
    /// From the operator, the manifest, or the run's own trusted input.
    Trusted,
    /// From a tool, document, peer, or any model that consumed an untrusted
    /// value. Never influences control flow.
    Untrusted,
}

/// How much damage disclosure would do.
///
/// Ordered so that `max` is the correct join, and so a sink can declare a
/// ceiling: an effect refuses arguments above its `max_sensitivity`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Sensitivity {
    Public,
    Internal,
    Confidential,
    Secret,
}

/// A value's position in the information-flow lattice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Label {
    pub provenance: BTreeSet<SourceId>,
    pub trust: Trust,
    pub sensitivity: Sensitivity,
}

/// A stricter information-flow rule for one JSON field sent to a sink.
///
/// Paths use RFC 6901 JSON Pointer syntax. An operator can require a protected
/// field to remain trusted, or permit it only when every contributing source is
/// in an explicit set. Ordinary content fields may remain untrusted without
/// granting them influence over recipient, amount, command, path, URL, tenant,
/// audience, model, or tool selectors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtectedField {
    path: String,
    #[serde(default)]
    require_trusted: bool,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    allowed_sources: BTreeSet<SourceId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    max_sensitivity: Option<Sensitivity>,
}

/// A typed request to improve labels on a whole value or selected JSON fields.
///
/// Every release names its basis, destination, field scope, and evidence. The
/// runtime supplies the releaser identity, asks policy, and journals all of it.
/// This prevents a reason string from serving as an unstructured universal
/// escape hatch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Release {
    scope: ReleaseScope,
    basis: String,
    destination: String,
    fields: BTreeSet<String>,
    evidence: BTreeSet<String>,
}

/// Which label dimensions an authorized release may improve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReleaseScope {
    trust: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    sensitivity: Option<Sensitivity>,
}

impl ReleaseScope {
    /// Improve trust to `trusted` while retaining provenance and sensitivity.
    #[must_use]
    pub const fn trust() -> Self {
        Self {
            trust: true,
            sensitivity: None,
        }
    }

    /// Lower sensitivity to the named classification while retaining trust.
    #[must_use]
    pub const fn sensitivity(target: Sensitivity) -> Self {
        Self {
            trust: false,
            sensitivity: Some(target),
        }
    }

    /// Improve trust and lower sensitivity in one indivisible policy decision.
    #[must_use]
    pub const fn trust_and_sensitivity(target: Sensitivity) -> Self {
        Self {
            trust: true,
            sensitivity: Some(target),
        }
    }
}

impl Release {
    /// Release an entire value.
    ///
    /// # Panics
    ///
    /// If basis, destination, or evidence is empty.
    #[must_use]
    pub fn whole(
        scope: ReleaseScope,
        basis: impl Into<String>,
        destination: impl Into<String>,
        evidence: impl IntoIterator<Item = String>,
    ) -> Self {
        Self::new(scope, [String::new()], basis, destination, evidence)
    }

    /// Release selected fields identified by absolute JSON Pointers.
    ///
    /// # Panics
    ///
    /// If the field set, basis, destination, or evidence is empty; a field is
    /// not an absolute RFC 6901 JSON Pointer; or whole-value and field scopes
    /// are mixed.
    #[must_use]
    pub fn fields(
        scope: ReleaseScope,
        fields: impl IntoIterator<Item = String>,
        basis: impl Into<String>,
        destination: impl Into<String>,
        evidence: impl IntoIterator<Item = String>,
    ) -> Self {
        Self::new(scope, fields, basis, destination, evidence)
    }

    /// The one constructor, and it is checked by the one rule set.
    ///
    /// It used to restate [`validate`](Self::validate)'s five rules as asserts,
    /// which is the *two representations of one fact* shape this crate treats as
    /// a defect everywhere else: the constructor and the deserialization gate
    /// could drift, and only the second has a mutation holding it. There is now
    /// one list of rules, consulted from both directions — a safe constructor
    /// panics on a programmer error, a deserialized value is refused as an
    /// input, and neither can start disagreeing about which releases are legal.
    fn new(
        scope: ReleaseScope,
        fields: impl IntoIterator<Item = String>,
        basis: impl Into<String>,
        destination: impl Into<String>,
        evidence: impl IntoIterator<Item = String>,
    ) -> Self {
        let release = Self {
            scope,
            basis: basis.into(),
            destination: destination.into(),
            fields: fields.into_iter().collect::<BTreeSet<_>>(),
            evidence: evidence.into_iter().collect::<BTreeSet<_>>(),
        };
        assert!(
            release.validate().is_ok(),
            "invalid release: {}",
            release.validate().unwrap_err()
        );
        release
    }

    #[must_use]
    pub fn basis(&self) -> &str {
        &self.basis
    }

    #[must_use]
    pub const fn scope(&self) -> ReleaseScope {
        self.scope
    }

    #[must_use]
    pub fn destination(&self) -> &str {
        &self.destination
    }

    #[must_use]
    pub fn fields_scope(&self) -> &BTreeSet<String> {
        &self.fields
    }

    #[must_use]
    pub fn evidence(&self) -> &BTreeSet<String> {
        &self.evidence
    }

    #[must_use]
    pub fn is_whole_value(&self) -> bool {
        self.fields.contains("")
    }

    /// Validate a release deserialized from outside the safe constructors.
    pub fn validate(&self) -> Result<(), &'static str> {
        if !self.scope.trust && self.scope.sensitivity.is_none() {
            return Err("scope must improve trust, sensitivity, or both");
        }
        if self.basis.trim().is_empty() || self.destination.trim().is_empty() {
            return Err("basis and destination must be non-empty");
        }
        if self.fields.is_empty()
            || (self.fields.len() > 1 && self.fields.contains(""))
            || self
                .fields
                .iter()
                .any(|path| !path.is_empty() && !is_json_pointer(path))
        {
            return Err("field scope is not a valid whole-value or JSON Pointer selection");
        }
        if self.evidence.is_empty() || self.evidence.iter().any(|item| item.trim().is_empty()) {
            return Err("evidence must contain at least one non-empty reference");
        }
        Ok(())
    }
}

impl ProtectedField {
    /// Require a field to derive only from trusted data.
    ///
    /// # Panics
    ///
    /// If `path` is not an absolute JSON Pointer.
    #[must_use]
    pub fn trusted(path: impl Into<String>) -> Self {
        let path = path.into();
        assert_json_pointer(&path);
        Self {
            path,
            require_trusted: true,
            allowed_sources: BTreeSet::new(),
            max_sensitivity: None,
        }
    }

    /// Permit an untrusted field only when all of its provenance is drawn from
    /// the named sources.
    ///
    /// An empty source set would permit nothing while looking configured, so it
    /// is rejected at construction.
    ///
    /// # Panics
    ///
    /// If `path` is not an absolute JSON Pointer or `sources` is empty.
    #[must_use]
    pub fn from_sources(
        path: impl Into<String>,
        sources: impl IntoIterator<Item = SourceId>,
    ) -> Self {
        let path = path.into();
        assert_json_pointer(&path);
        let allowed_sources = sources.into_iter().collect::<BTreeSet<_>>();
        assert!(
            !allowed_sources.is_empty(),
            "a protected field source constraint must name at least one source"
        );
        Self {
            path,
            require_trusted: false,
            allowed_sources,
            max_sensitivity: None,
        }
    }

    /// Apply a field-specific sensitivity ceiling stricter than the sink-wide
    /// ceiling.
    #[must_use]
    pub const fn max_sensitivity(mut self, sensitivity: Sensitivity) -> Self {
        self.max_sensitivity = Some(sensitivity);
        self
    }

    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    #[must_use]
    pub const fn requires_trusted(&self) -> bool {
        self.require_trusted
    }

    #[must_use]
    pub fn allowed_sources(&self) -> &BTreeSet<SourceId> {
        &self.allowed_sources
    }

    #[must_use]
    pub const fn sensitivity_ceiling(&self) -> Option<Sensitivity> {
        self.max_sensitivity
    }

    /// Validate a rule deserialized from an external declaration.
    ///
    /// Constructors enforce these invariants for Rust callers; manifests and
    /// other serialized inputs must prove them after deserialization.
    pub fn validate(&self) -> Result<(), &'static str> {
        if !is_json_pointer(&self.path) {
            return Err("path must be a non-empty absolute RFC 6901 JSON Pointer");
        }
        if self.require_trusted && !self.allowed_sources.is_empty() {
            return Err("require_trusted and allowed_sources are mutually exclusive");
        }
        if !self.require_trusted
            && self.allowed_sources.is_empty()
            && self.max_sensitivity.is_none()
        {
            return Err("at least one trust, source, or sensitivity constraint is required");
        }
        Ok(())
    }
}

fn assert_json_pointer(path: &str) {
    assert!(
        is_json_pointer(path),
        "a protected field path must be a non-empty absolute RFC 6901 JSON Pointer"
    );
}

fn is_json_pointer(path: &str) -> bool {
    if !path.starts_with('/') {
        return false;
    }
    let bytes = path.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'~' {
            index += 1;
            if index == bytes.len() || !matches!(bytes[index], b'0' | b'1') {
                return false;
            }
        }
        index += 1;
    }
    true
}

impl Label {
    /// The lattice bottom: trusted, public, no provenance.
    #[must_use]
    pub fn trusted() -> Self {
        Self {
            provenance: BTreeSet::new(),
            trust: Trust::Trusted,
            sensitivity: Sensitivity::Public,
        }
    }

    /// A value that crossed a trust boundary — every tool result, every
    /// retrieval, every peer response, *including from first-party services*.
    /// A compromised internal service is exactly what this exists for.
    #[must_use]
    pub fn untrusted(source: SourceId) -> Self {
        Self {
            provenance: BTreeSet::from([source]),
            trust: Trust::Untrusted,
            sensitivity: Sensitivity::Internal,
        }
    }

    #[must_use]
    pub fn with_sensitivity(mut self, s: Sensitivity) -> Self {
        self.sensitivity = s;
        self
    }

    /// Bounded join-semilattice: trust degrades, sensitivity escalates,
    /// provenance accumulates.
    #[must_use]
    pub fn join(&self, other: &Self) -> Self {
        Self {
            provenance: self.provenance.union(&other.provenance).cloned().collect(),
            trust: self.trust.max(other.trust),
            sensitivity: self.sensitivity.max(other.sensitivity),
        }
    }

    #[must_use]
    pub fn is_untrusted(&self) -> bool {
        self.trust == Trust::Untrusted
    }
}

impl Default for Label {
    fn default() -> Self {
        Self::trusted()
    }
}

/// A value carrying its information-flow label.
///
/// Deliberately exposes no `DerefMut` and no infallible unwrap. Reading is
/// allowed — a skill that cannot look at data cannot do anything useful, and the
/// enforcement point is at *sinks*, not at reads. Producing an owned, unlabeled
/// value is intentionally not a public operation. `StepCtx::release` consults
/// policy and improves only the named label dimensions while retaining the
/// value in the lattice and writing a `Released` journal record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tainted<T> {
    value: T,
    label: Label,
    /// Labels for structured sub-values, keyed by RFC 6901 JSON Pointer.
    /// Missing paths conservatively inherit their nearest labeled ancestor,
    /// ultimately the whole-value label.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    fields: BTreeMap<String, Label>,
}

impl<T> Tainted<T> {
    /// Wrap a value the operator vouches for: manifest content, run input,
    /// constants.
    pub fn trusted(value: T) -> Self {
        Self {
            value,
            label: Label::trusted(),
            fields: BTreeMap::new(),
        }
    }

    /// Wrap a value that crossed a trust boundary.
    pub fn from_source(value: T, source: SourceId) -> Self {
        Self {
            value,
            label: Label::untrusted(source),
            fields: BTreeMap::new(),
        }
    }

    pub fn with_label(value: T, label: Label) -> Self {
        Self {
            value,
            label,
            fields: BTreeMap::new(),
        }
    }

    pub fn label(&self) -> &Label {
        &self.label
    }

    /// Clone this value with an additional whole-value dependency.
    ///
    /// Structured field labels remain intact: a trusted selector such as a
    /// model instruction does not become untrusted merely because another
    /// provider-visible part of the same request contains tool output. The
    /// whole-value label still joins, so egress ceilings see that dependency.
    #[cfg(feature = "manifest")]
    pub(crate) fn with_joined_label(&self, other: &Label) -> Self
    where
        T: Clone,
    {
        Self {
            value: self.value.clone(),
            label: self.label.join(other),
            fields: self.fields.clone(),
        }
    }

    /// Read without unwrapping. Safe by design: the lattice governs where a
    /// value may *go*, not whether it may be inspected.
    /// Take the value, dropping the label.
    ///
    /// Deliberately *not* named `unwrap` or `into_inner`: this is the one
    /// operation that leaves the lattice without a journal record, and it should
    /// read like something you had to mean. The sanctioned exit for anything
    /// derived from the outside world is
    /// [`StepCtx::release`](crate::runtime::StepCtx::release), which records
    /// the typed scope, destination, evidence, and label it left with.
    ///
    /// Legitimate here only when the value never entered the lattice — the
    /// runtime unwrapping its own journaled clock, for instance.
    pub(crate) fn into_unlabelled(self) -> T {
        self.value
    }

    pub fn peek(&self) -> &T {
        &self.value
    }

    /// Transform in place; the whole-value label rides along.
    ///
    /// Arbitrary transforms invalidate JSON Pointer paths, so structured field
    /// labels are deliberately discarded. Use [`Tainted::object`] or
    /// [`Tainted::array`] when assembling structured values whose field-level
    /// provenance must survive to a sink.
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Tainted<U> {
        Tainted {
            value: f(self.value),
            label: self.label,
            fields: BTreeMap::new(),
        }
    }

    /// Combine two labeled values. Labels join, which is how untrust
    /// propagates: mixing anything with an untrusted value yields untrusted.
    /// Arbitrary tuple construction invalidates structured JSON paths, so any
    /// field maps are deliberately discarded.
    pub fn zip<U>(self, other: Tainted<U>) -> Tainted<(T, U)> {
        let label = self.label.join(&other.label);
        Tainted {
            value: (self.value, other.value),
            label,
            fields: BTreeMap::new(),
        }
    }
}

impl Tainted<serde_json::Value> {
    /// Build a JSON object without flattening the labels of its fields.
    pub fn object(fields: impl IntoIterator<Item = (String, Self)>) -> Self {
        let mut value = serde_json::Map::new();
        let mut label = Label::trusted();
        let mut field_labels = BTreeMap::new();

        for (name, field) in fields {
            let base = format!("/{}", escape_pointer_token(&name));
            label = label.join(&field.label);
            field_labels.insert(base.clone(), field.label);
            for (path, nested) in field.fields {
                field_labels.insert(format!("{base}{path}"), nested);
            }
            value.insert(name, field.value);
        }

        Self {
            value: serde_json::Value::Object(value),
            label,
            fields: field_labels,
        }
    }

    /// Build a JSON array without flattening the labels of its elements.
    pub fn array(elements: impl IntoIterator<Item = Self>) -> Self {
        let mut value = Vec::new();
        let mut label = Label::trusted();
        let mut field_labels = BTreeMap::new();

        for (index, element) in elements.into_iter().enumerate() {
            let base = format!("/{index}");
            label = label.join(&element.label);
            field_labels.insert(base.clone(), element.label);
            for (path, nested) in element.fields {
                field_labels.insert(format!("{base}{path}"), nested);
            }
            value.push(element.value);
        }

        Self {
            value: serde_json::Value::Array(value),
            label,
            fields: field_labels,
        }
    }

    /// The label at a JSON Pointer, inheriting conservatively from the nearest
    /// labeled ancestor when the value was not assembled field by field.
    #[must_use]
    pub fn label_at(&self, path: &str) -> Option<&Label> {
        self.value.pointer(path)?;
        if path.is_empty() {
            return Some(&self.label);
        }

        let mut candidate = path;
        loop {
            if let Some(label) = self.fields.get(candidate) {
                return Some(label);
            }
            let Some(split) = candidate.rfind('/') else {
                return Some(&self.label);
            };
            if split == 0 {
                return Some(&self.label);
            }
            candidate = &candidate[..split];
        }
    }

    /// Every explicitly tracked field label in stable pointer order.
    pub fn field_labels(&self) -> impl Iterator<Item = (&str, &Label)> {
        self.fields
            .iter()
            .map(|(path, label)| (path.as_str(), label))
    }

    /// Select a top-level object field while preserving and rebasing every
    /// tracked descendant label. Used by plan argument assembly; returning
    /// `None` distinguishes an absent field from a present JSON null.
    pub(crate) fn project_field(&self, name: &str) -> Option<Self> {
        self.project_pointer(&format!("/{}", escape_pointer_token(name)))
    }

    /// Select the value at a JSON Pointer while preserving and rebasing every
    /// tracked descendant label.
    ///
    /// The generalisation `project_field` delegates to — one implementation,
    /// because two copies of the rebase rule would agree everywhere except the
    /// nesting depth nobody probed. The projected value's own label comes from
    /// [`label_at`](Self::label_at), so a value that was never assembled field
    /// by field inherits conservatively from its nearest labelled ancestor.
    /// `None` distinguishes an absent path from a present JSON null.
    pub(crate) fn project_pointer(&self, pointer: &str) -> Option<Self> {
        if pointer.is_empty() {
            return Some(self.clone());
        }
        let value = self.value.pointer(pointer)?.clone();
        let label = self.label_at(pointer)?.clone();
        let prefix = format!("{pointer}/");
        let fields = self
            .fields
            .iter()
            .filter_map(|(path, label)| {
                path.strip_prefix(&prefix)
                    .map(|relative| (format!("/{relative}"), label.clone()))
            })
            .collect();
        Some(Self {
            value,
            label,
            fields,
        })
    }

    /// Apply an authorized release. The runtime owns the only call site.
    pub(crate) fn apply_release(mut self, release: &Release) -> Option<Self> {
        if release.is_whole_value() {
            self.label = apply_release_scope(&self.label, release.scope);
            for label in self.fields.values_mut() {
                *label = apply_release_scope(label, release.scope);
            }
            return Some(self);
        }

        // A field release requires explicit field lineage. Falling back to the
        // whole-value label would let a caller claim precision the runtime does
        // not actually possess.
        if release
            .fields
            .iter()
            .any(|path| !self.fields.contains_key(path) || self.value.pointer(path).is_none())
        {
            return None;
        }

        for released in &release.fields {
            let descendants = format!("{released}/");
            for (path, label) in &mut self.fields {
                if path == released || path.starts_with(&descendants) {
                    *label = apply_release_scope(label, release.scope);
                }
            }
        }
        self.label = self
            .fields
            .values()
            .fold(Label::trusted(), |joined, label| joined.join(label));
        Some(self)
    }
}

fn apply_release_scope(label: &Label, scope: ReleaseScope) -> Label {
    let mut released = label.clone();
    if scope.trust {
        released.trust = Trust::Trusted;
    }
    if let Some(target) = scope.sensitivity {
        released.sensitivity = label.sensitivity.min(target);
    }
    released
}

fn escape_pointer_token(token: &str) -> String {
    token.replace('~', "~0").replace('/', "~1")
}

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

    fn src(s: &str) -> SourceId {
        SourceId::new(s)
    }

    #[test]
    fn trust_join_degrades() {
        let t = Label::trusted();
        let u = Label::untrusted(src("tool://tool"));
        assert_eq!(t.join(&u).trust, Trust::Untrusted);
        assert_eq!(u.join(&t).trust, Trust::Untrusted, "join is commutative");
    }

    #[test]
    fn sensitivity_join_escalates() {
        let a = Label::trusted().with_sensitivity(Sensitivity::Public);
        let b = Label::trusted().with_sensitivity(Sensitivity::Secret);
        assert_eq!(a.join(&b).sensitivity, Sensitivity::Secret);
    }

    #[test]
    fn provenance_accumulates() {
        let a = Label::untrusted(src("a"));
        let b = Label::untrusted(src("b"));
        let j = a.join(&b);
        assert_eq!(j.provenance.len(), 2);
    }

    #[test]
    fn join_is_idempotent_and_associative() {
        let a = Label::untrusted(src("a"));
        let b = Label::trusted().with_sensitivity(Sensitivity::Confidential);
        let c = Label::untrusted(src("c")).with_sensitivity(Sensitivity::Secret);
        assert_eq!(a.join(&a), a, "idempotent");
        assert_eq!(a.join(&b).join(&c), a.join(&b.join(&c)), "associative");
    }

    /// The rule most systems get wrong: derived data inherits untrust.
    #[test]
    fn zip_propagates_untrust_to_derived_values() {
        let trusted = Tainted::trusted(1);
        let untrusted = Tainted::from_source(2, src("tool://tool"));
        let combined = trusted.zip(untrusted).map(|(a, b)| a + b);
        assert!(combined.label().is_untrusted());
        assert_eq!(*combined.peek(), 3);
    }

    #[test]
    fn map_preserves_label() {
        let t = Tainted::from_source("x", src("doc"));
        let mapped = t.map(str::to_uppercase);
        assert!(mapped.label().is_untrusted());
        assert_eq!(mapped.peek(), "X");
    }

    #[test]
    fn field_projection_preserves_only_the_selected_lineage() {
        let nested = Tainted::object([
            ("safe".to_owned(), Tainted::trusted(serde_json::json!("ok"))),
            (
                "body".to_owned(),
                Tainted::from_source(serde_json::json!("outside"), src("model")),
            ),
        ]);
        let value = Tainted::object([
            ("selected".to_owned(), nested),
            (
                "other".to_owned(),
                Tainted::from_source(serde_json::json!("noise"), src("tool")),
            ),
        ]);

        let selected = value.project_field("selected").unwrap();
        assert!(selected.label_at("/safe").unwrap().provenance.is_empty());
        assert_eq!(
            selected.label_at("/body").unwrap().provenance,
            BTreeSet::from([src("model")])
        );
        assert!(selected.label_at("/other").is_none());
    }

    #[test]
    fn field_release_improves_only_its_declared_scope() {
        let value = Tainted::object([
            (
                "recipient".to_owned(),
                Tainted::from_source(serde_json::json!("treasury"), src("model")),
            ),
            (
                "memo".to_owned(),
                Tainted::from_source(serde_json::json!("outside"), src("model")),
            ),
        ]);
        let release = Release::fields(
            ReleaseScope::trust(),
            ["/recipient".to_owned()],
            "operator verified account",
            "ledger.transfer",
            ["approval:42".to_owned()],
        );

        let released = value.apply_release(&release).unwrap();
        let recipient = released.label_at("/recipient").unwrap();
        assert_eq!(recipient.trust, Trust::Trusted);
        assert_eq!(recipient.sensitivity, Sensitivity::Internal);
        assert_eq!(recipient.provenance, BTreeSet::from([src("model")]));
        assert!(released.label_at("/memo").unwrap().is_untrusted());
        assert!(
            released.label().is_untrusted(),
            "unreleased content still taints"
        );
    }

    /// Each of the three scopes moves the dimensions it names, and no others.
    ///
    /// Only `trust()` had a test. The other two were reachable public API with
    /// nothing that could tell a correct implementation from one that set the
    /// wrong field — and these are the declassification primitives, so a scope
    /// that quietly improved trust when it was asked for sensitivity would be
    /// granting authority nobody wrote down.
    #[test]
    fn each_release_scope_moves_exactly_what_it_names() {
        let secret = Label::untrusted(src("model")).with_sensitivity(Sensitivity::Secret);

        let trust_only = apply_release_scope(&secret, ReleaseScope::trust());
        assert_eq!(trust_only.trust, Trust::Trusted);
        assert_eq!(
            trust_only.sensitivity,
            Sensitivity::Secret,
            "improving trust must not also declassify"
        );

        let sensitivity_only =
            apply_release_scope(&secret, ReleaseScope::sensitivity(Sensitivity::Internal));
        assert_eq!(
            sensitivity_only.trust,
            Trust::Untrusted,
            "lowering sensitivity must not also confer belief"
        );
        assert_eq!(sensitivity_only.sensitivity, Sensitivity::Internal);

        let both = apply_release_scope(
            &secret,
            ReleaseScope::trust_and_sensitivity(Sensitivity::Internal),
        );
        assert_eq!(both.trust, Trust::Trusted);
        assert_eq!(both.sensitivity, Sensitivity::Internal);
    }

    /// A release declassifies; it never reclassifies upward.
    ///
    /// The scope names a *ceiling*, not an assignment. Handing a `Public` value
    /// to a release written for `Secret` data must leave it `Public` — an
    /// assignment would silently relabel ordinary data as secret and trip every
    /// egress ceiling downstream, which reads as the gate working and is not.
    #[test]
    fn a_release_never_raises_sensitivity() {
        let public = Label::untrusted(src("model")).with_sensitivity(Sensitivity::Public);

        let released = apply_release_scope(&public, ReleaseScope::sensitivity(Sensitivity::Secret));

        assert_eq!(
            released.sensitivity,
            Sensitivity::Public,
            "a release named a higher classification and the label followed it upward"
        );
    }

    /// Provenance survives every scope.
    ///
    /// Trust and sensitivity are judgements a policy may revise. Where the value
    /// came from is a fact, and a release that dropped it would erase the
    /// evidence that the release was needed in the first place.
    #[test]
    fn no_release_scope_erases_provenance() {
        let from_model = Label::untrusted(src("model")).with_sensitivity(Sensitivity::Secret);

        for scope in [
            ReleaseScope::trust(),
            ReleaseScope::sensitivity(Sensitivity::Public),
            ReleaseScope::trust_and_sensitivity(Sensitivity::Public),
        ] {
            assert_eq!(
                apply_release_scope(&from_model, scope).provenance,
                BTreeSet::from([src("model")]),
                "a release dropped the provenance it was granted against"
            );
        }
    }

    /// A descendant inherits from its nearest labelled ancestor, not the join.
    ///
    /// Split from the test above only for length. The fixture has to make the
    /// two answers observably different, or the assertion passes either way.
    #[test]
    fn an_untracked_descendant_inherits_its_nearest_labelled_ancestor() {
        let nested = Tainted::object([
            (
                "recipient".to_owned(),
                Tainted::with_label(
                    serde_json::json!({ "addr": "ops@example.com" }),
                    Label::trusted(),
                ),
            ),
            (
                "note".to_owned(),
                Tainted::with_label(
                    serde_json::json!("n"),
                    Label::untrusted(src("tool://mail")).with_sensitivity(Sensitivity::Secret),
                ),
            ),
        ]);

        assert_eq!(
            nested.label_at("/recipient/addr").map(|l| l.sensitivity),
            Some(Sensitivity::Public),
            "a descendant of a tracked field inherited the whole-value label \
             instead of its own ancestor's, so a field-scoped ceiling reads as \
             the join of everything beside it"
        );
        assert_eq!(
            nested.label().sensitivity,
            Sensitivity::Secret,
            "the fixture no longer distinguishes the two, so the assertion \
             above would pass under either reading"
        );
    }

    /// The three field-provenance accessors, each pinned by what it returns.
    ///
    /// A sweep replaced `field_labels` with `std::iter::empty()`, flipped
    /// `label_at`'s pointer comparison, and turned `apply_release`'s lineage
    /// check from `||` into `&&` — all three survived. Together they *are*
    /// field-level provenance: what an auditor reads, what a protected field
    /// checks, and what stops a release claiming precision the runtime does not
    /// have. Every test around them asserted whole-value behaviour, which is why
    /// emptying the field map changed nothing any check could see.
    #[test]
    fn field_provenance_is_reported_rebased_and_required() {
        let value = Tainted::object([
            (
                "recipient".to_owned(),
                Tainted::with_label(
                    serde_json::json!("ops@example.com"),
                    Label::untrusted(src("tool://mail")),
                ),
            ),
            (
                "amount".to_owned(),
                Tainted::with_label(serde_json::json!(10), Label::trusted()),
            ),
        ]);

        // `field_labels` reports both, so emptying it is observable.
        let reported: Vec<&str> = value.field_labels().map(|(p, _)| p).collect();
        assert_eq!(
            reported,
            vec!["/amount", "/recipient"],
            "field labels are not reported in stable pointer order, so an audit \
             of who influenced which field reads differently run to run"
        );

        // `label_at` answers per field, and an exact hit is not the parent's.
        assert_eq!(
            value.label_at("/recipient").map(|l| l.trust),
            Some(Trust::Untrusted),
            "the tracked field's own label was not returned"
        );
        assert_eq!(
            value.label_at("/amount").map(|l| l.trust),
            Some(Trust::Trusted),
            "a trusted sibling inherited its untrusted neighbour's label"
        );
        assert!(
            value.label_at("/absent").is_none(),
            "a path that is not in the value reported a label, so a sink would \
             check a field that is not being sent"
        );

        // `apply_release` requires lineage for *every* named field: one that is
        // tracked and one that is not must still be refused.
        let release = Release {
            scope: ReleaseScope {
                trust: true,
                sensitivity: None,
            },
            basis: "reviewed".to_owned(),
            destination: "tool://ledger/post".to_owned(),
            fields: ["/recipient".to_owned(), "/absent".to_owned()]
                .into_iter()
                .collect(),
            evidence: ["ticket:1".to_owned()].into_iter().collect(),
        };
        assert!(
            value.clone().apply_release(&release).is_none(),
            "a release naming one tracked field and one untracked field was \
             applied, so the untracked half was promoted on the strength of the \
             whole-value label — precision the runtime does not have"
        );

        // The half that separates the two conditions. A value assembled whole
        // carries no per-field lineage, so `/a` is **present in the value and
        // untracked** — which `||` refuses and `&&` would allow, promoting a
        // field on the strength of the whole-value label alone.
        let untracked = Tainted::with_label(
            serde_json::json!({ "a": "x" }),
            Label::untrusted(src("tool://mail")),
        );
        let over_untracked = Release {
            scope: ReleaseScope {
                trust: true,
                sensitivity: None,
            },
            basis: "reviewed".to_owned(),
            destination: "tool://ledger/post".to_owned(),
            fields: ["/a".to_owned()].into_iter().collect(),
            evidence: ["ticket:1".to_owned()].into_iter().collect(),
        };
        assert!(
            untracked.apply_release(&over_untracked).is_none(),
            "a field present in the value but with no tracked lineage was \
             released, so the promotion rests on the whole-value label while \
             the decision reads as field-scoped"
        );

        // And the positive half, so a refuse-everything change cannot pass.
        let ok = Release {
            fields: ["/recipient".to_owned()].into_iter().collect(),
            ..release
        };
        let good = value
            .clone()
            .apply_release(&ok)
            .expect("a release over a field with real lineage was refused");
        assert_eq!(
            good.label_at("/recipient").map(|l| l.trust),
            Some(Trust::Trusted),
            "the released field was not promoted"
        );
    }
}

/// Every rule `Release::validate` enforces, each with the case it rejects.
///
/// It had none. A mutation sweep replaced the whole function with `Ok(())` and
/// the suite stayed green — so all five rules were, as far as any check knew,
/// decoration. That matters more here than in most validators: this is the gate
/// on a request to **raise a label**, the one operation that turns untrusted
/// data into trusted data, and the constructors are not the only way in. A
/// `Release` deserialized from a config or a request body reaches `validate`
/// and nothing else.
#[cfg(test)]
mod release_validation_tests {
    use std::collections::BTreeSet;

    use super::{ProtectedField, Release, ReleaseScope, Sensitivity, SourceId, is_json_pointer};

    /// A release that the rules accept, which each case below then breaks in
    /// exactly one way. Without this baseline a rejection proves nothing — it
    /// could be failing for a reason the case did not intend.
    fn sound() -> Release {
        Release::fields(
            ReleaseScope::trust(),
            ["/recipient".to_owned()],
            "operator matched the account to settlement SET-42",
            "tool://ledger/transfer",
            ["approval:SET-42".to_owned()],
        )
    }

    #[test]
    fn the_baseline_is_accepted() {
        sound()
            .validate()
            .expect("the baseline must pass, or every case below rejects for the wrong reason");
    }

    /// A release that improves nothing is a decision record for a non-decision.
    #[test]
    fn a_scope_that_improves_nothing_is_refused() {
        let mut r = sound();
        r.scope = ReleaseScope {
            trust: false,
            sensitivity: None,
        };
        assert!(r.validate().is_err(), "a no-op release was accepted");
    }

    /// Basis and destination are what make the record answerable later.
    #[test]
    fn an_unexplained_or_undirected_release_is_refused() {
        for (field, broken) in [
            ("basis", {
                let mut r = sound();
                r.basis = "   ".to_owned();
                r
            }),
            ("destination", {
                let mut r = sound();
                r.destination = String::new();
                r
            }),
        ] {
            assert!(
                broken.validate().is_err(),
                "a release with an empty {field} was accepted, so the journal \
                 would record a decision that answers nothing"
            );
        }
    }

    /// Whole-value and field selection are alternatives, not a mixture.
    ///
    /// `""` means the whole value. Listing it *beside* paths asks for both at
    /// once, and the wider one silently wins — which is a broad release wearing
    /// a narrow one's declaration.
    #[test]
    fn a_field_scope_that_is_neither_whole_nor_valid_pointers_is_refused() {
        let empty = {
            let mut r = sound();
            r.fields.clear();
            r
        };
        assert!(
            empty.validate().is_err(),
            "a release selecting nothing was accepted"
        );

        let both = {
            let mut r = sound();
            r.fields.insert(String::new());
            r
        };
        assert!(
            both.validate().is_err(),
            "whole-value and field selection were accepted together, so the \
             broader one applies while the declaration reads narrow"
        );

        let malformed = {
            let mut r = sound();
            r.fields.clear();
            r.fields.insert("recipient".to_owned()); // no leading slash
            r
        };
        assert!(
            malformed.validate().is_err(),
            "a path that is not a JSON Pointer was accepted, so it would match \
             no field and release nothing while reading as a release"
        );
    }

    /// RFC 6901 escapes, from both sides of every branch.
    ///
    /// `is_json_pointer` decides which declared field paths are real, and its
    /// escape handling had no test at all: a sweep flipped `+= 1` to `-= 1`,
    /// `==` to `!=`, and dropped the `!` in the escape check, and every one
    /// survived. A pointer parser that accepts `~2` matches no field, so a
    /// protected-field rule written with one silently guards nothing while the
    /// manifest reads as if it does.
    #[test]
    fn a_json_pointer_is_judged_by_rfc_6901_escapes() {
        for good in [
            "/a", "/a/b", "/",     // the whole-document child, a legal pointer
            "/a~0b", // escaped tilde
            "/a~1b", // escaped solidus
            "/a~0",  // escape as the final token
            "/a~1", "/~0~1",  // adjacent escapes
            "/a~01b", // `~0` followed by an ordinary `1`
        ] {
            assert!(
                is_json_pointer(good),
                "{good} is a valid RFC 6901 pointer and was refused, so a \
                 legitimate protected field would be rejected at parse"
            );
        }

        for bad in [
            "",  // empty
            "a", // no leading solidus
            "a/b", "/a~", // trailing tilde: an escape with nothing after it
            "/~", "/a~2b", // `~` may only be followed by 0 or 1
            "/a~xb", "/~9",
        ] {
            assert!(
                !is_json_pointer(bad),
                "{bad:?} is not a valid RFC 6901 pointer and was accepted, so a \
                 rule written with it would match no field and guard nothing"
            );
        }
    }

    /// The two rules that decide whether a protected field constrains anything.
    ///
    /// Both are conjunctions, and a sweep turning either `&&` into `||` survived
    /// — so the gate on a rule arriving from a manifest was, as far as any check
    /// knew, decoration. Each case below is paired with an acceptance, because a
    /// refuse-everything mutation passes a file of refusals perfectly.
    #[test]
    fn a_protected_field_must_constrain_something_and_not_contradict_itself() {
        let trusted_and_sources = ProtectedField {
            path: "/recipient".to_owned(),
            require_trusted: true,
            allowed_sources: BTreeSet::from([SourceId::new("crm")]),
            max_sensitivity: None,
        };
        assert!(
            trusted_and_sources.validate().is_err(),
            "require_trusted beside allowed_sources was accepted; one demands \
             the lattice's top and the other names who may supply it, so a \
             reviewer cannot tell which is in force"
        );

        let constrains_nothing = ProtectedField {
            path: "/recipient".to_owned(),
            require_trusted: false,
            allowed_sources: BTreeSet::new(),
            max_sensitivity: None,
        };
        assert!(
            constrains_nothing.validate().is_err(),
            "a rule with no trust, source or sensitivity constraint was \
             accepted, so a field reads as protected while permitting anything"
        );

        // The three acceptances, one per constraint, so a refuse-everything
        // change cannot pass this test.
        for (label, field) in [
            (
                "trust alone",
                ProtectedField {
                    path: "/recipient".to_owned(),
                    require_trusted: true,
                    allowed_sources: BTreeSet::new(),
                    max_sensitivity: None,
                },
            ),
            (
                "sources alone",
                ProtectedField {
                    path: "/recipient".to_owned(),
                    require_trusted: false,
                    allowed_sources: BTreeSet::from([SourceId::new("crm")]),
                    max_sensitivity: None,
                },
            ),
            (
                "a sensitivity ceiling alone",
                ProtectedField {
                    path: "/recipient".to_owned(),
                    require_trusted: false,
                    allowed_sources: BTreeSet::new(),
                    max_sensitivity: Some(Sensitivity::Internal),
                },
            ),
        ] {
            assert!(
                field.validate().is_ok(),
                "{label} is a legitimate rule and was refused"
            );
        }

        let bad_path = ProtectedField {
            path: "recipient".to_owned(),
            require_trusted: true,
            allowed_sources: BTreeSet::new(),
            max_sensitivity: None,
        };
        assert!(
            bad_path.validate().is_err(),
            "a path that is not a JSON Pointer was accepted"
        );
    }

    /// Exactly one field is a field selection, not a whole-value one.
    ///
    /// `fields.len() > 1` guards the "whole value and named fields together"
    /// contradiction. A sweep relaxing it to `>=` survived, which would refuse
    /// the ordinary single-field release — the common case — while the
    /// contradiction it exists to catch still needs two entries.
    #[test]
    fn a_single_named_field_is_a_release_and_not_a_contradiction() {
        let one = {
            let mut r = sound();
            r.fields.clear();
            r.fields.insert("/recipient".to_owned());
            r
        };
        assert!(
            one.validate().is_ok(),
            "releasing exactly one named field was refused, which is the \
             ordinary shape of a field-scoped release"
        );
    }

    /// The accessors an audit reads report what was decided, not a constant.
    ///
    /// `AuditReport::releases` names the releaser, basis, **destination**,
    /// **fields** and **evidence** of every discretionary label change — the one
    /// discretionary act in the system. A sweep replaced `destination`,
    /// `fields_scope` and `evidence` with fabricated values and all three
    /// survived, including under a feature set that compiles the integration
    /// tests: every test around them asserted that a release was *refused* or
    /// *applied*, and none read back what it said it was for. An audit listing
    /// a destination nobody chose is worse than no listing, because it reads as
    /// corroboration.
    ///
    /// The values below are deliberately unalike, so a getter returning any
    /// fixed string or any other field's value is caught rather than
    /// coincidentally right.
    #[test]
    fn a_release_reports_the_decision_it_was_given() {
        let release = Release::fields(
            ReleaseScope::trust(),
            ["/recipient".to_owned()],
            "four-eyes approval AC-1",
            "tool://ledger/post_entry",
            ["ticket:AC-1".to_owned(), "reviewer:sam".to_owned()],
        );

        assert_eq!(
            release.basis(),
            "four-eyes approval AC-1",
            "the basis an audit reports is not the one the releaser gave"
        );
        assert_eq!(
            release.destination(),
            "tool://ledger/post_entry",
            "the destination an audit reports is not the sink the release named"
        );
        assert_eq!(
            release.fields_scope(),
            &["/recipient".to_owned()].into_iter().collect(),
            "the field scope an audit reports is not what was released"
        );
        assert_eq!(
            release.evidence(),
            &["reviewer:sam".to_owned(), "ticket:AC-1".to_owned()]
                .into_iter()
                .collect(),
            "the evidence an audit reports is not what was supplied — evidence \
             is the difference between a decision and an assertion"
        );
        assert!(
            !release.is_whole_value(),
            "a field-scoped release reported itself as whole-value, which is a \
             broader claim than was authorized"
        );

        let whole = Release::whole(
            ReleaseScope::trust(),
            "operator override",
            "tool://ledger/post_entry",
            ["ticket:AC-2".to_owned()],
        );
        assert!(
            whole.is_whole_value(),
            "a whole-value release did not report itself as one"
        );
    }

    /// The safe constructors refuse a path that is not a JSON Pointer.
    ///
    /// `assert_json_pointer` replaced with `()` survived. The first attempt at
    /// this test aimed at `Release::fields`, which panics through `validate`
    /// rather than through the assert — so it passed with the mutation applied
    /// and proved nothing. The assert's only callers are the two
    /// `ProtectedField` constructors, and those are what a mutation of it must
    /// be caught by.
    #[test]
    fn a_protected_field_constructor_refuses_a_path_that_is_not_a_pointer() {
        for build in [
            (|| ProtectedField::trusted("recipient")) as fn() -> ProtectedField,
            || ProtectedField::from_sources("recipient", [SourceId::new("crm")]),
        ] {
            let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(build));
            assert!(
                refused.is_err(),
                "a path with no leading solidus was accepted, so the rule would \
                 match no field and guard nothing"
            );
        }

        // The acceptance, so a panic-on-everything change cannot pass.
        let ok = ProtectedField::trusted("/recipient");
        assert_eq!(ok.path(), "/recipient");
    }

    /// Evidence is the difference between a decision and an assertion.
    #[test]
    fn a_release_with_no_usable_evidence_is_refused() {
        let none = {
            let mut r = sound();
            r.evidence.clear();
            r
        };
        assert!(
            none.validate().is_err(),
            "an evidence-free release was accepted"
        );

        let blank = {
            let mut r = sound();
            r.evidence.clear();
            r.evidence.insert("  ".to_owned());
            r
        };
        assert!(
            blank.validate().is_err(),
            "blank evidence was accepted, which passes the count and says nothing"
        );
    }

    /// A sensitivity-only release is legitimate, so the first rule must not
    /// over-reject. The negative cases above would all still pass if `validate`
    /// simply refused everything.
    #[test]
    fn improving_sensitivity_alone_is_accepted() {
        let mut r = sound();
        r.scope = ReleaseScope {
            trust: false,
            sensitivity: Some(Sensitivity::Internal),
        };
        r.validate()
            .expect("a sensitivity-only release is a legitimate decision");
    }
}