proofborne-core 0.1.0-alpha.3

Versioned contracts, events, provider types, and proof graph for Proofborne
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
use std::{collections::BTreeSet, path::Component};

use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;

use crate::{ActionClass, CriterionState, RunOutcome, SCHEMA_VERSION, TaskContract, hash_json};

/// Version of the proof-carrying parent/child delegation protocol.
pub const AGENT_PROTOCOL_VERSION: &str = "proofborne.agent.v1";

/// Runtime role of one authority in a delegated task.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum AgentRole {
    /// Owns the user contract and may accept reviewed handoffs.
    Coordinator,
    /// Executes a strict subset of the parent contract.
    Worker,
    /// Independently inspects a worker handoff without mutation authority.
    Reviewer,
    /// Attempts to falsify a proposed result without mutation authority.
    Adversary,
}

/// Secret-free, content-addressed authority assigned to one agent session.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AgentAuthority {
    /// Canonical digest over all remaining fields.
    pub authority_hash: String,
    /// Runtime-owned agent identity, distinct for every delegated session.
    pub agent_id: Uuid,
    /// Contract role for this authority.
    pub role: AgentRole,
    /// Explicit provider profile selected by the coordinator.
    pub profile: String,
    /// Provider adapter identifier.
    pub provider: String,
    /// Exact model selector.
    pub model: String,
    /// Public credential identity, never credential material.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credential_id: Option<String>,
}

impl AgentAuthority {
    /// Constructs and content-addresses a secret-free authority.
    pub fn new(
        role: AgentRole,
        profile: impl Into<String>,
        provider: impl Into<String>,
        model: impl Into<String>,
        credential_id: Option<String>,
    ) -> Result<Self, AgentError> {
        let mut authority = Self {
            authority_hash: String::new(),
            agent_id: Uuid::now_v7(),
            role,
            profile: profile.into(),
            provider: provider.into(),
            model: model.into(),
            credential_id,
        };
        authority.validate_material()?;
        authority.authority_hash = authority.material_digest()?;
        Ok(authority)
    }

    /// Computes the canonical digest over the authority material.
    pub fn material_digest(&self) -> Result<String, AgentError> {
        let value = serde_json::json!({
            "agentId": self.agent_id,
            "role": self.role,
            "profile": self.profile,
            "provider": self.provider,
            "model": self.model,
            "credentialId": self.credential_id,
        });
        Ok(hash_json(&value))
    }

    /// Validates identity fields and the content-addressed authority hash.
    pub fn validate(&self) -> Result<(), AgentError> {
        self.validate_material()?;
        if !valid_digest(&self.authority_hash) || self.authority_hash != self.material_digest()? {
            return Err(AgentError::AuthorityDigest);
        }
        Ok(())
    }

    fn validate_material(&self) -> Result<(), AgentError> {
        if self.profile.trim().is_empty()
            || self.provider.trim().is_empty()
            || self.model.trim().is_empty()
            || self
                .credential_id
                .as_deref()
                .is_some_and(|value| value.trim().is_empty())
        {
            return Err(AgentError::EmptyAuthority);
        }
        Ok(())
    }
}

/// Read/write scope delegated from one immutable parent workspace generation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkspaceLease {
    /// Parent workspace generation observed before the child workspace was created.
    pub input_workspace_generation: String,
    /// Digest of the material copied into the isolated child workspace.
    pub leased_input_hash: String,
    /// Normalized workspace-relative paths visible to the child.
    pub read_paths: BTreeSet<String>,
    /// Normalized workspace-relative paths the child may change.
    pub write_paths: BTreeSet<String>,
}

impl WorkspaceLease {
    /// Validates digests and requires every write scope to be contained by a read scope.
    pub fn validate(&self) -> Result<(), AgentError> {
        if !valid_digest(&self.input_workspace_generation) || !valid_digest(&self.leased_input_hash)
        {
            return Err(AgentError::WorkspaceDigest);
        }
        if self.read_paths.is_empty() {
            return Err(AgentError::EmptyLease);
        }
        for path in self.read_paths.iter().chain(&self.write_paths) {
            validate_scope_path(path)?;
        }
        for write_path in &self.write_paths {
            if !self
                .read_paths
                .iter()
                .any(|read_path| scope_contains(read_path, write_path))
            {
                return Err(AgentError::WriteOutsideReadScope(write_path.clone()));
            }
        }
        Ok(())
    }

    /// Returns whether a normalized path is visible to the child.
    pub fn permits_read(&self, path: &str) -> bool {
        self.read_paths
            .iter()
            .any(|scope| scope_contains(scope, path))
    }

    /// Returns whether a normalized path may be changed by the child.
    pub fn permits_write(&self, path: &str) -> bool {
        self.write_paths
            .iter()
            .any(|scope| scope_contains(scope, path))
    }
}

/// Hard runtime budget propagated from parent to child.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AgentBudget {
    /// Provider turns available to the worker.
    pub max_provider_turns: usize,
    /// Total provider-requested tool calls available to the worker.
    pub max_tool_calls: u64,
    /// Wall-clock ceiling for the child session.
    pub max_duration_ms: u64,
}

impl AgentBudget {
    /// Rejects zero-valued limits instead of silently granting an unbounded budget.
    pub fn validate(&self) -> Result<(), AgentError> {
        if self.max_provider_turns == 0 || self.max_tool_calls == 0 || self.max_duration_ms == 0 {
            return Err(AgentError::InvalidBudget);
        }
        Ok(())
    }
}

/// Proof-carrying plan for exactly one parent-to-child delegation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DelegationPlan {
    /// Public schema identifier.
    pub schema_version: String,
    /// Delegation protocol version.
    pub protocol_version: String,
    /// Unique delegation identity.
    pub delegation_id: Uuid,
    /// Parent session that owns the original contract.
    pub parent_session_id: Uuid,
    /// Parent contract identifier.
    pub parent_contract_id: Uuid,
    /// Derived, confirmed child contract.
    pub child_contract: TaskContract,
    /// Exact parent criterion IDs delegated to the child.
    pub delegated_criterion_ids: BTreeSet<String>,
    /// Child execution authority.
    pub authority: AgentAuthority,
    /// Immutable workspace lease.
    pub lease: WorkspaceLease,
    /// Hard child budget.
    pub budget: AgentBudget,
    /// Runtime-owned action classes available in the child session.
    pub allowed_action_classes: BTreeSet<ActionClass>,
    /// Parent proof/state binding at delegation time.
    pub parent_state_binding: String,
}

impl DelegationPlan {
    /// Builds a strict child contract from a criterion subset and additive constraints.
    #[allow(clippy::too_many_arguments)]
    pub fn derive(
        parent_session_id: Uuid,
        parent: &TaskContract,
        delegated_criterion_ids: BTreeSet<String>,
        added_constraints: Vec<String>,
        authority: AgentAuthority,
        lease: WorkspaceLease,
        budget: AgentBudget,
        allowed_action_classes: BTreeSet<ActionClass>,
        parent_state_binding: impl Into<String>,
    ) -> Result<Self, AgentError> {
        if delegated_criterion_ids.is_empty() {
            return Err(AgentError::EmptyCriterionSubset);
        }
        let mut criteria = Vec::new();
        for criterion in &parent.criteria {
            if delegated_criterion_ids.contains(&criterion.id) {
                let mut criterion = criterion.clone();
                criterion.state = CriterionState::Pending;
                criterion.evidence_ids.clear();
                criterion.waiver = None;
                criteria.push(criterion);
            }
        }
        if criteria.len() != delegated_criterion_ids.len() {
            return Err(AgentError::UnknownDelegatedCriterion);
        }
        let mut constraints = parent.constraints.clone();
        for constraint in added_constraints {
            if constraint.trim().is_empty() {
                return Err(AgentError::EmptyConstraint);
            }
            if !constraints.contains(&constraint) {
                constraints.push(constraint);
            }
        }
        let child_contract = TaskContract {
            schema_version: parent.schema_version.clone(),
            id: Uuid::now_v7(),
            goal: format!("Delegated subset of {}: {}", parent.id, parent.goal),
            claim_scope: parent.claim_scope,
            constraints,
            criteria,
            created_at: parent.created_at,
            confirmed: true,
        };
        let plan = Self {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_id: Uuid::now_v7(),
            parent_session_id,
            parent_contract_id: parent.id,
            child_contract,
            delegated_criterion_ids,
            authority,
            lease,
            budget,
            allowed_action_classes,
            parent_state_binding: parent_state_binding.into(),
        };
        plan.validate(parent)?;
        Ok(plan)
    }

    /// Validates version, subset, authority, lease, budget, and authority invariants.
    pub fn validate(&self, parent: &TaskContract) -> Result<(), AgentError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(AgentError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AGENT_PROTOCOL_VERSION {
            return Err(AgentError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        parent
            .validate()
            .map_err(|_| AgentError::InvalidParentContract)?;
        self.child_contract
            .validate()
            .map_err(|_| AgentError::InvalidChildContract)?;
        self.authority.validate()?;
        self.lease.validate()?;
        self.budget.validate()?;
        if self.parent_contract_id != parent.id || !parent.confirmed {
            return Err(AgentError::ParentBinding);
        }
        if self.authority.role != AgentRole::Worker {
            return Err(AgentError::InvalidWorkerRole);
        }
        if self.parent_state_binding.trim().is_empty() {
            return Err(AgentError::EmptyStateBinding);
        }
        if self.delegated_criterion_ids.is_empty()
            || self.child_contract.criteria.len() != self.delegated_criterion_ids.len()
        {
            return Err(AgentError::EmptyCriterionSubset);
        }
        if self.child_contract.claim_scope != parent.claim_scope || !self.child_contract.confirmed {
            return Err(AgentError::ChildContractWidened);
        }
        if parent
            .constraints
            .iter()
            .any(|constraint| !self.child_contract.constraints.contains(constraint))
        {
            return Err(AgentError::ChildContractWidened);
        }
        for child in &self.child_contract.criteria {
            if !self.delegated_criterion_ids.contains(&child.id) {
                return Err(AgentError::UnknownDelegatedCriterion);
            }
            let Some(parent_criterion) = parent
                .criteria
                .iter()
                .find(|criterion| criterion.id == child.id)
            else {
                return Err(AgentError::UnknownDelegatedCriterion);
            };
            let mut expected = parent_criterion.clone();
            expected.state = CriterionState::Pending;
            expected.evidence_ids.clear();
            expected.waiver = None;
            if child != &expected {
                return Err(AgentError::ChildContractWidened);
            }
        }
        if self.allowed_action_classes.is_empty()
            || self.allowed_action_classes.contains(&ActionClass::Delegate)
            || self
                .allowed_action_classes
                .contains(&ActionClass::Sensitive)
        {
            return Err(AgentError::InvalidActionAuthority);
        }
        Ok(())
    }

    /// Computes a canonical content digest over the validated plan.
    pub fn digest(&self, parent: &TaskContract) -> Result<String, AgentError> {
        self.validate(parent)?;
        let value = serde_json::to_value(self).map_err(|_| AgentError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Kind of one deterministic child-workspace change.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum HandoffChangeKind {
    /// A previously absent file was created.
    Created,
    /// An existing file changed content.
    Modified,
    /// An existing file was deleted.
    Deleted,
}

/// One content-addressed path change proposed by a child.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HandoffChange {
    /// Normalized workspace-relative path.
    pub path: String,
    /// Change classification.
    pub kind: HandoffChangeKind,
    /// Input digest for modifications/deletions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before_digest: Option<String>,
    /// Output digest for creations/modifications.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_digest: Option<String>,
}

impl HandoffChange {
    /// Validates path and digest shape for the selected change kind.
    pub fn validate(&self) -> Result<(), AgentError> {
        validate_scope_path(&self.path)?;
        let valid = match self.kind {
            HandoffChangeKind::Created => {
                self.before_digest.is_none()
                    && self.after_digest.as_deref().is_some_and(valid_digest)
            }
            HandoffChangeKind::Modified => {
                self.before_digest.as_deref().is_some_and(valid_digest)
                    && self.after_digest.as_deref().is_some_and(valid_digest)
                    && self.before_digest != self.after_digest
            }
            HandoffChangeKind::Deleted => {
                self.before_digest.as_deref().is_some_and(valid_digest)
                    && self.after_digest.is_none()
            }
        };
        if valid {
            Ok(())
        } else {
            Err(AgentError::InvalidChange(self.path.clone()))
        }
    }
}

/// Proof-carrying worker output, bound to one delegation plan and child session.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HandoffReceipt {
    /// Public schema identifier.
    pub schema_version: String,
    /// Delegation protocol version.
    pub protocol_version: String,
    /// Digest of the exact delegation plan.
    pub delegation_hash: String,
    /// Persisted child session.
    pub child_session_id: Uuid,
    /// Child authority copied from the plan.
    pub authority: AgentAuthority,
    /// Child workspace generation after execution.
    pub output_workspace_generation: String,
    /// Stable path-ordered changes.
    pub changes: Vec<HandoffChange>,
    /// Evidence IDs produced by the child proof graph.
    pub evidence_ids: Vec<Uuid>,
    /// Child proof-gated outcome.
    pub outcome: RunOutcome,
    /// Digest of the child provider's public output text.
    pub output_digest: String,
}

impl HandoffReceipt {
    /// Validates all plan bindings, evidence identity, change scope, and outcome.
    pub fn validate(&self, plan: &DelegationPlan, parent: &TaskContract) -> Result<(), AgentError> {
        plan.validate(parent)?;
        if self.schema_version != SCHEMA_VERSION {
            return Err(AgentError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AGENT_PROTOCOL_VERSION {
            return Err(AgentError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        if self.delegation_hash != plan.digest(parent)?
            || self.authority != plan.authority
            || !valid_digest(&self.output_workspace_generation)
            || !valid_digest(&self.output_digest)
        {
            return Err(AgentError::HandoffBinding);
        }
        if self.outcome != RunOutcome::Verified {
            return Err(AgentError::UnverifiedHandoff);
        }
        if self.evidence_ids.is_empty() {
            return Err(AgentError::MissingEvidence);
        }
        let mut paths = BTreeSet::new();
        for change in &self.changes {
            change.validate()?;
            if !paths.insert(&change.path) {
                return Err(AgentError::DuplicateChange(change.path.clone()));
            }
            if !plan.lease.permits_write(&change.path) {
                return Err(AgentError::ChangeOutsideLease(change.path.clone()));
            }
        }
        if !self
            .changes
            .windows(2)
            .all(|pair| pair[0].path < pair[1].path)
        {
            return Err(AgentError::UnsortedChanges);
        }
        Ok(())
    }

    /// Computes the canonical receipt digest after validation.
    pub fn digest(
        &self,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<String, AgentError> {
        self.validate(plan, parent)?;
        let value = serde_json::to_value(self).map_err(|_| AgentError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Independent reviewer disposition for one handoff.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecision {
    /// Reviewer found no blocking counterevidence.
    Approved,
    /// Reviewer found one or more blocking defects.
    Rejected,
}

/// One reviewer finding with explicit criterion/path scope.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReviewFinding {
    /// Stable machine-readable finding code.
    pub code: String,
    /// Human-readable detail.
    pub message: String,
    /// Delegated criterion implicated by this finding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub criterion_id: Option<String>,
    /// Workspace-relative path implicated by this finding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

/// Review receipt produced by a separately authorized reviewer session.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReviewReceipt {
    /// Public schema identifier.
    pub schema_version: String,
    /// Delegation protocol version.
    pub protocol_version: String,
    /// Digest of the exact handoff under review.
    pub handoff_hash: String,
    /// Persisted reviewer session.
    pub reviewer_session_id: Uuid,
    /// Reviewer authority; must differ from the worker authority.
    pub authority: AgentAuthority,
    /// Explicit disposition.
    pub decision: ReviewDecision,
    /// Stable findings; approval requires an empty set.
    pub findings: Vec<ReviewFinding>,
    /// Workspace paths actually inspected by successful reviewer read actions.
    pub inspected_paths: BTreeSet<String>,
    /// Reviewer evidence IDs proving the inspection ran.
    pub evidence_ids: Vec<Uuid>,
}

impl ReviewReceipt {
    /// Validates independence, binding, evidence, finding scope, and disposition.
    pub fn validate(
        &self,
        handoff: &HandoffReceipt,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<(), AgentError> {
        handoff.validate(plan, parent)?;
        if self.schema_version != SCHEMA_VERSION {
            return Err(AgentError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AGENT_PROTOCOL_VERSION {
            return Err(AgentError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        if self.handoff_hash != handoff.digest(plan, parent)? {
            return Err(AgentError::ReviewBinding);
        }
        self.authority.validate()?;
        if !matches!(
            self.authority.role,
            AgentRole::Reviewer | AgentRole::Adversary
        ) || self.authority.agent_id == handoff.authority.agent_id
            || self.authority.authority_hash == handoff.authority.authority_hash
            || self.reviewer_session_id == handoff.child_session_id
            || self.reviewer_session_id == plan.parent_session_id
        {
            return Err(AgentError::ReviewerNotIndependent);
        }
        if self.evidence_ids.is_empty() || self.inspected_paths.is_empty() {
            return Err(AgentError::MissingEvidence);
        }
        for path in &self.inspected_paths {
            validate_scope_path(path)?;
            if !plan.lease.permits_read(path) {
                return Err(AgentError::InvalidFinding);
            }
        }
        if handoff
            .changes
            .iter()
            .any(|change| !self.inspected_paths.contains(&change.path))
        {
            return Err(AgentError::MissingEvidence);
        }
        match self.decision {
            ReviewDecision::Approved if !self.findings.is_empty() => {
                return Err(AgentError::ReviewDisposition);
            }
            ReviewDecision::Rejected if self.findings.is_empty() => {
                return Err(AgentError::ReviewDisposition);
            }
            _ => {}
        }
        for finding in &self.findings {
            if finding.code.trim().is_empty() || finding.message.trim().is_empty() {
                return Err(AgentError::InvalidFinding);
            }
            if let Some(criterion_id) = &finding.criterion_id
                && !plan.delegated_criterion_ids.contains(criterion_id)
            {
                return Err(AgentError::InvalidFinding);
            }
            if let Some(path) = &finding.path {
                validate_scope_path(path)?;
                if !plan.lease.permits_read(path) {
                    return Err(AgentError::InvalidFinding);
                }
            }
        }
        Ok(())
    }

    /// Computes the canonical receipt digest after validation.
    pub fn digest(
        &self,
        handoff: &HandoffReceipt,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<String, AgentError> {
        self.validate(handoff, plan, parent)?;
        let value = serde_json::to_value(self).map_err(|_| AgentError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Runtime-owned receipt for an atomically accepted handoff.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MergeReceipt {
    /// Public schema identifier.
    pub schema_version: String,
    /// Delegation protocol version.
    pub protocol_version: String,
    /// Bound handoff digest.
    pub handoff_hash: String,
    /// Bound approving review digest.
    pub review_hash: String,
    /// Parent workspace generation immediately before merge.
    pub parent_generation_before: String,
    /// Parent workspace generation immediately after merge.
    pub parent_generation_after: String,
    /// Exact path-ordered changes applied transactionally.
    pub changes: Vec<HandoffChange>,
}

impl MergeReceipt {
    /// Validates approval and immutable workspace-generation bindings.
    pub fn validate(
        &self,
        handoff: &HandoffReceipt,
        review: &ReviewReceipt,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<(), AgentError> {
        review.validate(handoff, plan, parent)?;
        if self.schema_version != SCHEMA_VERSION {
            return Err(AgentError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AGENT_PROTOCOL_VERSION {
            return Err(AgentError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        if review.authority.role != AgentRole::Reviewer
            || review.decision != ReviewDecision::Approved
            || self.handoff_hash != handoff.digest(plan, parent)?
            || self.review_hash != review.digest(handoff, plan, parent)?
            || self.parent_generation_before != plan.lease.input_workspace_generation
            || !valid_digest(&self.parent_generation_after)
            || self.changes != handoff.changes
        {
            return Err(AgentError::MergeBinding);
        }
        Ok(())
    }

    /// Computes the canonical merge-receipt digest after validation.
    pub fn digest(
        &self,
        handoff: &HandoffReceipt,
        review: &ReviewReceipt,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<String, AgentError> {
        self.validate(handoff, review, plan, parent)?;
        let value = serde_json::to_value(self).map_err(|_| AgentError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Runtime-owned reason that an unmerged delegation became unusable.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DelegationInvalidationReason {
    /// The parent no longer matches the generation leased to the worker.
    ParentWorkspaceGenerationChanged,
    /// The child no longer matches the generation committed by its handoff.
    ChildWorkspaceGenerationChanged,
    /// Recomputed child changes differ from the reviewed handoff.
    HandoffChangeSetDiverged,
    /// Transactional application of the reviewed changes failed.
    MergeApplyFailed,
    /// A required P3B reviewer/adversary gate produced blocking counterevidence.
    AgentGraphReviewRejected,
    /// The graph-level wall-clock budget expired before merge.
    AgentGraphBudgetExceeded,
}

/// Versioned receipt proving why an active delegation was invalidated.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DelegationInvalidation {
    /// Public schema identifier.
    pub schema_version: String,
    /// Delegation protocol version.
    pub protocol_version: String,
    /// Digest of the exact delegation plan.
    pub delegation_hash: String,
    /// Stable runtime-owned invalidation reason.
    pub reason: DelegationInvalidationReason,
    /// Workspace generation observed when the conflict was detected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observed_workspace_generation: Option<String>,
    /// Canonical digest of recomputed changes when change-set divergence was detected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observed_changes_hash: Option<String>,
}

impl DelegationInvalidation {
    /// Constructs and validates one plan-bound invalidation receipt.
    pub fn new(
        plan: &DelegationPlan,
        parent: &TaskContract,
        reason: DelegationInvalidationReason,
        observed_workspace_generation: Option<String>,
        observed_changes_hash: Option<String>,
    ) -> Result<Self, AgentError> {
        let invalidation = Self {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(parent)?,
            reason,
            observed_workspace_generation,
            observed_changes_hash,
        };
        invalidation.validate(plan, parent)?;
        Ok(invalidation)
    }

    /// Validates schema, plan binding, and reason-specific observations.
    pub fn validate(&self, plan: &DelegationPlan, parent: &TaskContract) -> Result<(), AgentError> {
        plan.validate(parent)?;
        if self.schema_version != SCHEMA_VERSION {
            return Err(AgentError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AGENT_PROTOCOL_VERSION {
            return Err(AgentError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        if self.delegation_hash != plan.digest(parent)? {
            return Err(AgentError::InvalidationBinding);
        }
        if self
            .observed_workspace_generation
            .as_deref()
            .is_some_and(|value| !valid_digest(value))
            || self
                .observed_changes_hash
                .as_deref()
                .is_some_and(|value| !valid_digest(value))
        {
            return Err(AgentError::InvalidInvalidationObservation);
        }
        let observations_are_valid = match self.reason {
            DelegationInvalidationReason::ParentWorkspaceGenerationChanged
            | DelegationInvalidationReason::ChildWorkspaceGenerationChanged
            | DelegationInvalidationReason::AgentGraphReviewRejected
            | DelegationInvalidationReason::AgentGraphBudgetExceeded => {
                self.observed_workspace_generation.is_some() && self.observed_changes_hash.is_none()
            }
            DelegationInvalidationReason::HandoffChangeSetDiverged => {
                self.observed_workspace_generation.is_some() && self.observed_changes_hash.is_some()
            }
            DelegationInvalidationReason::MergeApplyFailed => {
                self.observed_workspace_generation.is_some()
            }
        };
        if !observations_are_valid {
            return Err(AgentError::InvalidInvalidationObservation);
        }
        Ok(())
    }

    /// Computes the canonical invalidation-receipt digest after validation.
    pub fn digest(
        &self,
        plan: &DelegationPlan,
        parent: &TaskContract,
    ) -> Result<String, AgentError> {
        self.validate(plan, parent)?;
        let value = serde_json::to_value(self).map_err(|_| AgentError::Serialization)?;
        Ok(hash_json(&value))
    }
}

pub(crate) fn validate_scope_path(path: &str) -> Result<(), AgentError> {
    if path.is_empty() || path == "." {
        return if path == "." {
            Ok(())
        } else {
            Err(AgentError::InvalidLeasePath(path.to_owned()))
        };
    }
    let value = std::path::Path::new(path);
    if value.is_absolute()
        || value.has_root()
        || path.contains('\\')
        || path.ends_with('/')
        || value.components().any(|component| {
            !matches!(component, Component::Normal(_))
                || component.as_os_str().to_string_lossy().contains(':')
        })
    {
        return Err(AgentError::InvalidLeasePath(path.to_owned()));
    }
    Ok(())
}

pub(crate) fn scope_contains(scope: &str, path: &str) -> bool {
    scope == "."
        || scope == path
        || path
            .strip_prefix(scope)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

pub(crate) fn valid_digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// Fail-closed delegation or handoff validation error.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum AgentError {
    /// Public schema is not supported by this runtime.
    #[error("unsupported agent schema: {0}")]
    UnsupportedSchema(String),
    /// Delegation protocol is not supported by this runtime.
    #[error("unsupported agent protocol: {0}")]
    UnsupportedProtocol(String),
    /// Authority contains an empty public identity field.
    #[error("agent authority fields must be non-empty")]
    EmptyAuthority,
    /// Authority hash does not match its canonical material.
    #[error("agent authority digest is invalid")]
    AuthorityDigest,
    /// A workspace generation or lease hash is malformed.
    #[error("workspace lease digest is invalid")]
    WorkspaceDigest,
    /// A lease omits its read scope.
    #[error("workspace lease read paths must not be empty")]
    EmptyLease,
    /// A lease path is absolute, ambiguous, or traverses a parent.
    #[error("invalid workspace lease path: {0}")]
    InvalidLeasePath(String),
    /// A write scope is not contained by a read scope.
    #[error("write path is outside every read scope: {0}")]
    WriteOutsideReadScope(String),
    /// At least one hard budget limit is zero.
    #[error("agent budget limits must be non-zero")]
    InvalidBudget,
    /// Delegation selected no acceptance criterion.
    #[error("delegated criterion subset must not be empty")]
    EmptyCriterionSubset,
    /// Delegation references a criterion absent from the parent.
    #[error("delegation references an unknown parent criterion")]
    UnknownDelegatedCriterion,
    /// An additive child constraint is empty.
    #[error("delegated constraints must not be empty")]
    EmptyConstraint,
    /// Parent contract fails its own validation.
    #[error("parent task contract is invalid")]
    InvalidParentContract,
    /// Derived child contract fails its own validation.
    #[error("child task contract is invalid")]
    InvalidChildContract,
    /// Plan does not bind the confirmed parent contract.
    #[error("delegation is not bound to the confirmed parent contract")]
    ParentBinding,
    /// Delegated execution authority is not a worker.
    #[error("delegation authority must have the worker role")]
    InvalidWorkerRole,
    /// Parent proof-state binding is absent.
    #[error("parent state binding must not be empty")]
    EmptyStateBinding,
    /// Child contract widened or altered a parent obligation.
    #[error("child contract widens or alters delegated parent obligations")]
    ChildContractWidened,
    /// Child authority contains a forbidden or empty action set.
    #[error("delegated action authority is empty or contains forbidden classes")]
    InvalidActionAuthority,
    /// Handoff change has inconsistent digest fields.
    #[error("handoff change is invalid: {0}")]
    InvalidChange(String),
    /// Handoff names one path more than once.
    #[error("handoff contains a duplicate path: {0}")]
    DuplicateChange(String),
    /// Handoff changes are not canonically path-sorted.
    #[error("handoff changes must be strictly path-sorted")]
    UnsortedChanges,
    /// Handoff includes a path outside delegated write authority.
    #[error("handoff changed a path outside the write lease: {0}")]
    ChangeOutsideLease(String),
    /// Handoff metadata does not match its plan.
    #[error("handoff does not match its delegation plan")]
    HandoffBinding,
    /// Worker did not satisfy the child proof gate.
    #[error("handoff child outcome is not verified")]
    UnverifiedHandoff,
    /// Worker or reviewer receipt omits runtime evidence.
    #[error("handoff or review lacks runtime evidence")]
    MissingEvidence,
    /// Review digest does not bind the handoff.
    #[error("review does not match the handoff")]
    ReviewBinding,
    /// Reviewer shares worker identity or authority.
    #[error("reviewer is not independent from the worker")]
    ReviewerNotIndependent,
    /// Review decision and finding set are inconsistent.
    #[error("review disposition and findings disagree")]
    ReviewDisposition,
    /// Review finding is empty or outside delegated scope.
    #[error("review finding is empty or outside delegated scope")]
    InvalidFinding,
    /// Merge receipt does not bind an approved current handoff.
    #[error("merge receipt does not match the approved handoff and lease")]
    MergeBinding,
    /// Canonical serialization failed.
    #[error("agent contract serialization failed")]
    Serialization,
    /// Invalidation receipt does not bind the immutable delegation.
    #[error("delegation invalidation does not match its plan")]
    InvalidationBinding,
    /// Invalidation reason lacks its required canonical observation.
    #[error("delegation invalidation observation is invalid")]
    InvalidInvalidationObservation,
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use crate::{AssuranceLevel, Criterion, EvidenceFreshness, EvidenceKind, EvidenceRequirement};

    use super::*;

    fn parent_contract() -> TaskContract {
        let mut criterion = Criterion::required("tests", "tests pass");
        criterion.evidence_requirement = EvidenceRequirement {
            allowed_kinds: [EvidenceKind::Tool].into_iter().collect(),
            allowed_producers: ["workspace.edit".to_owned()].into_iter().collect(),
            minimum_assurance: AssuranceLevel::Observed,
            freshness: EvidenceFreshness::FinalWorkspaceState,
            minimum_observations: 1,
            minimum_independent_producers: 1,
            require_artifacts: false,
        };
        let mut parent = TaskContract::new("change the file", vec![criterion]);
        parent.confirmed = true;
        parent.constraints.push("do not weaken tests".to_owned());
        parent
    }

    fn authority(role: AgentRole, profile: &str) -> AgentAuthority {
        AgentAuthority::new(role, profile, "mock", "m1", None).unwrap()
    }

    fn lease() -> WorkspaceLease {
        WorkspaceLease {
            input_workspace_generation: "a".repeat(64),
            leased_input_hash: "b".repeat(64),
            read_paths: ["src".to_owned()].into_iter().collect(),
            write_paths: ["src/lib.rs".to_owned()].into_iter().collect(),
        }
    }

    fn plan(parent: &TaskContract) -> DelegationPlan {
        DelegationPlan::derive(
            Uuid::now_v7(),
            parent,
            ["tests".to_owned()].into_iter().collect(),
            vec!["only change leased paths".to_owned()],
            authority(AgentRole::Worker, "worker"),
            lease(),
            AgentBudget {
                max_provider_turns: 4,
                max_tool_calls: 8,
                max_duration_ms: 30_000,
            },
            [ActionClass::Read, ActionClass::WorkspaceWrite]
                .into_iter()
                .collect(),
            "state",
        )
        .unwrap()
    }

    #[test]
    fn derived_contract_is_a_strict_reset_subset() {
        let parent = parent_contract();
        let plan = plan(&parent);
        plan.validate(&parent).unwrap();
        assert_eq!(plan.child_contract.criteria.len(), 1);
        assert_eq!(
            plan.child_contract.criteria[0].state,
            CriterionState::Pending
        );
        assert!(
            plan.child_contract
                .constraints
                .contains(&"do not weaken tests".to_owned())
        );
    }

    #[test]
    fn altered_child_obligation_fails_closed() {
        let parent = parent_contract();
        let mut plan = plan(&parent);
        plan.child_contract.criteria[0].required = false;
        assert_eq!(
            plan.validate(&parent),
            Err(AgentError::InvalidChildContract)
        );
    }

    #[test]
    fn write_scope_must_be_visible_and_normalized() {
        let mut lease = lease();
        lease.write_paths = ["tests".to_owned()].into_iter().collect();
        assert_eq!(
            lease.validate(),
            Err(AgentError::WriteOutsideReadScope("tests".to_owned()))
        );
        lease.write_paths = ["../src".to_owned()].into_iter().collect();
        assert_eq!(
            lease.validate(),
            Err(AgentError::InvalidLeasePath("../src".to_owned()))
        );
    }

    #[test]
    fn read_only_workspace_lease_is_valid() {
        let mut lease = lease();
        lease.write_paths.clear();
        lease.validate().unwrap();
        lease.read_paths.clear();
        assert_eq!(lease.validate(), Err(AgentError::EmptyLease));
    }

    #[test]
    fn invalidation_receipt_is_plan_bound_and_reason_complete() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let mut invalidation = DelegationInvalidation::new(
            &plan,
            &parent,
            DelegationInvalidationReason::HandoffChangeSetDiverged,
            Some("c".repeat(64)),
            Some("d".repeat(64)),
        )
        .unwrap();
        assert_eq!(invalidation.digest(&plan, &parent).unwrap().len(), 64);
        invalidation.observed_changes_hash = None;
        assert_eq!(
            invalidation.validate(&plan, &parent),
            Err(AgentError::InvalidInvalidationObservation)
        );
    }

    #[test]
    fn reviewer_must_have_distinct_authority() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let handoff = HandoffReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(&parent).unwrap(),
            child_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            output_workspace_generation: "c".repeat(64),
            changes: vec![HandoffChange {
                path: "src/lib.rs".to_owned(),
                kind: HandoffChangeKind::Modified,
                before_digest: Some("d".repeat(64)),
                after_digest: Some("e".repeat(64)),
            }],
            evidence_ids: vec![Uuid::now_v7()],
            outcome: RunOutcome::Verified,
            output_digest: "f".repeat(64),
        };
        handoff.validate(&plan, &parent).unwrap();
        let review = ReviewReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            handoff_hash: handoff.digest(&plan, &parent).unwrap(),
            reviewer_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            decision: ReviewDecision::Approved,
            findings: Vec::new(),
            inspected_paths: ["src/lib.rs".to_owned()].into_iter().collect(),
            evidence_ids: vec![Uuid::now_v7()],
        };
        assert_eq!(
            review.validate(&handoff, &plan, &parent),
            Err(AgentError::ReviewerNotIndependent)
        );
        let mut parent_session_review = review;
        parent_session_review.authority = authority(AgentRole::Reviewer, "reviewer");
        parent_session_review.reviewer_session_id = plan.parent_session_id;
        assert_eq!(
            parent_session_review.validate(&handoff, &plan, &parent),
            Err(AgentError::ReviewerNotIndependent)
        );
    }

    #[test]
    fn rejected_review_requires_findings() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let handoff = HandoffReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(&parent).unwrap(),
            child_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            output_workspace_generation: "c".repeat(64),
            changes: Vec::new(),
            evidence_ids: vec![Uuid::now_v7()],
            outcome: RunOutcome::Verified,
            output_digest: "f".repeat(64),
        };
        let review = ReviewReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            handoff_hash: handoff.digest(&plan, &parent).unwrap(),
            reviewer_session_id: Uuid::now_v7(),
            authority: authority(AgentRole::Reviewer, "reviewer"),
            decision: ReviewDecision::Rejected,
            findings: Vec::new(),
            inspected_paths: ["src/lib.rs".to_owned()].into_iter().collect(),
            evidence_ids: vec![Uuid::now_v7()],
        };
        assert_eq!(
            review.validate(&handoff, &plan, &parent),
            Err(AgentError::ReviewDisposition)
        );
    }

    #[test]
    fn empty_review_inspection_fails_closed() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let handoff = HandoffReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(&parent).unwrap(),
            child_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            output_workspace_generation: "c".repeat(64),
            changes: Vec::new(),
            evidence_ids: vec![Uuid::now_v7()],
            outcome: RunOutcome::Verified,
            output_digest: "f".repeat(64),
        };
        let review = ReviewReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            handoff_hash: handoff.digest(&plan, &parent).unwrap(),
            reviewer_session_id: Uuid::now_v7(),
            authority: authority(AgentRole::Reviewer, "reviewer"),
            decision: ReviewDecision::Approved,
            findings: Vec::new(),
            inspected_paths: BTreeSet::new(),
            evidence_ids: vec![Uuid::now_v7()],
        };
        assert_eq!(
            review.validate(&handoff, &plan, &parent),
            Err(AgentError::MissingEvidence)
        );
    }

    #[test]
    fn review_inspection_outside_read_lease_fails_closed() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let handoff = HandoffReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(&parent).unwrap(),
            child_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            output_workspace_generation: "c".repeat(64),
            changes: Vec::new(),
            evidence_ids: vec![Uuid::now_v7()],
            outcome: RunOutcome::Verified,
            output_digest: "f".repeat(64),
        };
        let review = ReviewReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            handoff_hash: handoff.digest(&plan, &parent).unwrap(),
            reviewer_session_id: Uuid::now_v7(),
            authority: authority(AgentRole::Reviewer, "reviewer"),
            decision: ReviewDecision::Approved,
            findings: Vec::new(),
            inspected_paths: ["unleased.txt".to_owned()].into_iter().collect(),
            evidence_ids: vec![Uuid::now_v7()],
        };
        assert_eq!(
            review.validate(&handoff, &plan, &parent),
            Err(AgentError::InvalidFinding)
        );
    }

    #[test]
    fn uninspected_handoff_change_fails_closed() {
        let parent = parent_contract();
        let plan = plan(&parent);
        let handoff = HandoffReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            delegation_hash: plan.digest(&parent).unwrap(),
            child_session_id: Uuid::now_v7(),
            authority: plan.authority.clone(),
            output_workspace_generation: "c".repeat(64),
            changes: vec![HandoffChange {
                path: "src/lib.rs".to_owned(),
                kind: HandoffChangeKind::Modified,
                before_digest: Some("d".repeat(64)),
                after_digest: Some("e".repeat(64)),
            }],
            evidence_ids: vec![Uuid::now_v7()],
            outcome: RunOutcome::Verified,
            output_digest: "f".repeat(64),
        };
        let review = ReviewReceipt {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AGENT_PROTOCOL_VERSION.to_owned(),
            handoff_hash: handoff.digest(&plan, &parent).unwrap(),
            reviewer_session_id: Uuid::now_v7(),
            authority: authority(AgentRole::Reviewer, "reviewer"),
            decision: ReviewDecision::Approved,
            findings: Vec::new(),
            inspected_paths: ["src".to_owned()].into_iter().collect(),
            evidence_ids: vec![Uuid::now_v7()],
        };
        assert_eq!(
            review.validate(&handoff, &plan, &parent),
            Err(AgentError::MissingEvidence)
        );
    }

    #[test]
    fn root_read_scope_can_contain_narrow_write_scope() {
        let lease = WorkspaceLease {
            read_paths: [".".to_owned()].into_iter().collect(),
            ..lease()
        };
        lease.validate().unwrap();
        assert!(lease.permits_read("Cargo.toml"));
        assert!(!lease.permits_write("Cargo.toml"));
    }
}