shepherd-core 6.6.1

The harness-agnostic shepherd engine: domain types, configuration schema, and run state. Knows nothing about any CLI, harness, or process.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
//! The six role result contracts, as types instead of prose.
//!
//! Every dispatched role returns exactly one document, and until this module
//! existed the SHAPE of all six lived only in doctrine prose under
//! `content/skills/*/references/*-contract.md`. `record.rs` bound the six
//! identifiers so a name could not be invented, but a name is only half a
//! contract: a producer and a verifier that agree on `shepherd.coder-result/1`
//! and disagree on what is inside it still drift, and neither side fails at the
//! moment of the disagreement. That is precisely how the release publisher
//! emitted `shepherd.publish/4` against an authority verifying schema 3 and
//! stranded a release AFTER both immutable registries had been written.
//!
//! So the shape is derived here rather than restated anywhere. `schemars` was
//! already a workspace dependency behind the `schema` feature and already
//! generates the configuration schema from `ShepherdConfig`; the same
//! `#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]` idiom makes
//! these six documents machine-checkable without a hand-written JSON Schema
//! that could itself drift.
//!
//! ## What is deliberately NOT here
//!
//! These types are shape and identity. They are not a second validator: where
//! a document already has one (`ReviewResult::validate` in `review.rs`,
//! `ReviewCustody` in `review_custody.rs`), this module reuses the existing
//! types instead of restating their rules, and says so at the field.
//!
//! ## Reading ambiguous prose
//!
//! The contracts are prose, and prose is sometimes silent on optionality. The
//! rule applied throughout: a field the contract lists under a "Required"
//! heading is a plain field, so serde rejects a document that omits it; a field
//! the contract introduces with "when relevant", "if applicable", "optional",
//! or that only exists for one event kind, is an `Option`. Every place that
//! judgement was close carries a comment naming the reading and why the
//! alternative was rejected.

#[cfg(feature = "alloc")]
use alloc::{format, string::String, vec::Vec};

use super::{
    AgentId, DispatchError, DispatchId, DispatchResult, LaneId, ReviewFinding, ReviewMode,
    ReviewVerdict, Role, RunId, WorkKind,
};
use super::{
    CODER_RESULT_SCHEMA, DEBUGGING_EVIDENCE_SCHEMA, DISCOVERY_REPORT_SCHEMA, LANE_LEDGER_SCHEMA,
    REVIEW_FINDING_SCHEMA, WORKER_RESULT_SCHEMA,
};

/// Bind a result type to exactly one identifier from `record.rs`, and to the
/// role and startup skill the contract pins where it pins them.
///
/// The binding is an associated `const` rather than a free function so the
/// pairing cannot be passed the wrong constant at a call site: `T::SCHEMA` has
/// one definition and `validate_header` is the only thing that reads it.
macro_rules! role_result {
    ($name:ident, $schema:ident, role: $role:expr, skill: $skill:literal) => {
        role_result!($name, $schema);

        impl $name {
            /// The single role the contract names in its required shape.
            pub const ROLE: Role = $role;
            /// The startup skill the contract names in its required shape.
            pub const STARTUP_SKILL: &'static str = $skill;

            /// Reject a document whose identity fields do not match the one
            /// contract this type stands for.
            ///
            /// A relabelled document is the drift this module exists to stop:
            /// the shapes of several of these contracts overlap enough that a
            /// Worker result with `role: coder` would otherwise deserialize
            /// into a Coder result without complaint.
            pub fn validate_header(&self) -> DispatchResult<()> {
                self.validate_schema()?;
                if self.role != Self::ROLE {
                    return Err(DispatchError::InvalidRecord(format!(
                        "`{}` carries role `{}`, expected `{}`",
                        Self::SCHEMA,
                        self.role,
                        Self::ROLE
                    )));
                }
                if self.startup_skill != Self::STARTUP_SKILL {
                    return Err(DispatchError::InvalidRecord(format!(
                        "`{}` carries startup skill `{}`, expected `{}`",
                        Self::SCHEMA,
                        self.startup_skill,
                        Self::STARTUP_SKILL
                    )));
                }
                Ok(())
            }
        }
    };
    ($name:ident, $schema:ident, skill: $skill:literal) => {
        role_result!($name, $schema);

        impl $name {
            /// The startup skill the contract names in its required header.
            pub const STARTUP_SKILL: &'static str = $skill;

            /// Reject a document whose identity fields do not match the one
            /// contract this type stands for.
            pub fn validate_header(&self) -> DispatchResult<()> {
                self.validate_schema()?;
                if self.startup_skill != Self::STARTUP_SKILL {
                    return Err(DispatchError::InvalidRecord(format!(
                        "`{}` carries startup skill `{}`, expected `{}`",
                        Self::SCHEMA,
                        self.startup_skill,
                        Self::STARTUP_SKILL
                    )));
                }
                Ok(())
            }
        }
    };
    ($name:ident, $schema:ident) => {
        impl $name {
            /// The exact doctrine identifier this document carries, taken from
            /// the single definition in `record.rs`. Never a second literal:
            /// a second literal is the drift.
            pub const SCHEMA: &'static str = $schema;

            /// Reject a document whose `schema` field is not this identifier.
            pub fn validate_schema(&self) -> DispatchResult<()> {
                if self.schema == Self::SCHEMA {
                    Ok(())
                } else {
                    Err(DispatchError::InvalidRecord(format!(
                        "unsupported schema `{}`, expected `{}`",
                        self.schema,
                        Self::SCHEMA
                    )))
                }
            }
        }
    };
}

/// The status vocabulary each contract closes, and the shared bounded budget.
///
/// `ascii_case_insensitive` is deliberately absent, matching [`Role`]. These
/// values are written into durable result artifacts and read back by a
/// verifier; leniency there buys nothing and costs byte-stability, exactly as
/// it did when a stored role deserialized as `"eNgInEeR"` and rewrote itself.
macro_rules! result_status {
    ($(#[$meta:meta])* $name:ident { $($variant:ident),+ $(,)? }) => {
        $(#[$meta])*
        #[derive(
            Clone,
            Copy,
            Debug,
            Eq,
            Hash,
            Ord,
            PartialEq,
            PartialOrd,
            serde::Deserialize,
            serde::Serialize,
            strum::AsRefStr,
            strum::Display,
            strum::EnumCount,
            strum::EnumIs,
            strum::EnumString,
            strum::IntoStaticStr,
            strum::VariantNames,
        )]
        #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
        #[serde(rename_all = "kebab-case")]
        #[strum(serialize_all = "kebab-case")]
        pub enum $name {
            $($variant),+
        }
    };
}

result_status! {
    /// `status: green|blocked|needs-amendment` from the Coder result contract.
    CoderStatus { Green, Blocked, NeedsAmendment }
}

result_status! {
    /// `status: complete|partial|blocked|needs-amendment` from the Worker
    /// result contract.
    WorkerStatus { Complete, Partial, Blocked, NeedsAmendment }
}

result_status! {
    /// `status: complete|partial|blocked` from the Discovery source contract.
    /// Discovery has no `needs-amendment`: a research question that cannot be
    /// answered is `partial` or `blocked`, never routed back as a diff.
    DiscoveryStatus { Complete, Partial, Blocked }
}

result_status! {
    /// `status: reproduced|root-cause-found|fixed|unresolved|blocked` from the
    /// debugging evidence contract.
    DebuggingStatus { Reproduced, RootCauseFound, Fixed, Unresolved, Blocked }
}

result_status! {
    /// `status: ready|running|reviewing|redo|blocked|accepted|handed-off` from
    /// the lane ledger contract.
    LaneLedgerStatus { Ready, Running, Reviewing, Redo, Blocked, Accepted, HandedOff }
}

result_status! {
    /// Whether a declared discovery source was actually retrieved.
    ///
    /// The contract does not enumerate these two words; it says "retrieval
    /// status" and then "unavailable sources are explicit". Two states is the
    /// smallest vocabulary that makes the second sentence representable, and a
    /// third state would be invented.
    SourceRetrieval { Retrieved, Unavailable }
}

/// `budget: {tool_calls: <n>, seconds: <n>}`, shared verbatim by the Worker
/// result and Discovery report contracts.
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ResultBudget {
    pub tool_calls: u32,
    pub seconds: u32,
}

// ********* [1/6] shepherd.coder-result/1 *********

/// One Coder result artifact. Reports the assigned worktree and scope; it
/// grants no integration custody, so there is no field here for a merge,
/// a push, or a tag.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CoderResult {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub lane: LaneId,
    /// Plan node id. `plan::PlanNode::id` is a plain `String`, so this stays a
    /// `String` rather than inventing a `NodeId` the plan side would not use.
    pub node: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub role: Role,
    /// "one measurable behavior" -- the outcome the change moves.
    pub outcome: String,
    pub task_digest: String,
    pub startup_skill: String,
    pub skill_bundle_digest: String,
    pub worktree: String,
    pub baseline_commit: String,
    pub owned_paths: Vec<String>,
    pub changed_paths: Vec<String>,
    pub status: CoderStatus,
}

role_result!(
    CoderResult,
    CODER_RESULT_SCHEMA,
    role: Role::Coder,
    skill: "implementing"
);

// ********* [2/6] shepherd.worker-result/1 *********

/// One Worker result artifact: a bounded deliverable report, never a review
/// grade and never a production change.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct WorkerResult {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub lane: LaneId,
    pub node: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub role: Role,
    /// The contract pins `work_kind: artifact`. Reusing [`WorkKind`] rather
    /// than a `String` keeps the one enum the pending-edge authorization
    /// already keys on from acquiring a second spelling here.
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub work_kind: WorkKind,
    /// "one sentence".
    pub deliverable: String,
    pub source_paths: Vec<String>,
    pub owned_scope: Vec<String>,
    pub budget: ResultBudget,
    /// "schema or section list" -- the contract accepts either, so this is the
    /// free text it actually specifies and not a nested union.
    pub output_shape: String,
    pub status: WorkerStatus,
    pub task_digest: String,
    pub startup_skill: String,
    pub skill_bundle_digest: String,
}

role_result!(
    WorkerResult,
    WORKER_RESULT_SCHEMA,
    role: Role::Worker,
    skill: "artifact-work"
);

// ********* [3/6] shepherd.discovery-report/1 *********

/// One declared source and whether it was actually reached.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoverySource {
    /// "canonical identifier".
    pub identifier: String,
    /// "version/date" -- one field, because the contract offers them as
    /// alternatives for the same fact rather than as two facts.
    pub version: String,
    pub retrieval_status: SourceRetrieval,
    /// AMBIGUOUS in the prose: every source must state a retrieval status and
    /// an evidence location, but an unavailable source has no evidence to
    /// point at. `Option` is the only reading under which "unavailable sources
    /// are explicit" can be satisfied at all; a required field would force the
    /// author to fabricate a pointer.
    pub evidence_location: Option<String>,
}

/// One claim, with the citation that makes it a claim rather than a question.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoveryClaim {
    pub claim: String,
    /// "A claim without a citation is an unresolved question", so this is not
    /// optional: an entry that cannot cite belongs in `limits`, not here.
    pub citation: String,
    /// The contract requires "a separation between observed text and
    /// interpretation", which is only enforceable as two fields.
    pub observed: String,
    pub interpretation: String,
}

/// A contradiction between sources, and what the report did about it.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoveryConflict {
    /// The source identifiers that disagree.
    pub sources: Vec<String>,
    pub contradiction: String,
    /// "freshness gaps" -- present only when the conflict is one of staleness
    /// rather than of substance.
    pub freshness_gap: Option<String>,
    /// "the selected disposition".
    pub disposition: String,
}

/// What the report does not cover.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoveryLimits {
    pub scope: String,
    pub budget: String,
    pub compatibility: String,
    pub unresolved_questions: Vec<String>,
}

/// "report hash and all retained source pointers".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoveryEvidence {
    pub report_sha256: String,
    pub source_pointers: Vec<String>,
}

/// One Discovery report. "The report contains one answer and no hidden second
/// deliverable", which is why `output_path` is a single path and not a list.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DiscoveryReport {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub lane: LaneId,
    /// "one bounded external question".
    pub question: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub role: Role,
    /// "ordered primary source identifiers" -- order is load-bearing, so this
    /// is a `Vec` and never a set.
    pub source_list: Vec<String>,
    pub output_path: String,
    pub budget: ResultBudget,
    pub startup_skill: String,
    pub skill_bundle_digest: String,
    pub task_digest: String,
    pub status: DiscoveryStatus,
    // The contract splits into a "Required header" and "Required sections".
    // Both are required, so both are plain fields; the split is presentational.
    pub sources: Vec<DiscoverySource>,
    pub claims: Vec<DiscoveryClaim>,
    pub conflicts: Vec<DiscoveryConflict>,
    pub limits: DiscoveryLimits,
    pub evidence: DiscoveryEvidence,
}

role_result!(
    DiscoveryReport,
    DISCOVERY_REPORT_SCHEMA,
    role: Role::Discovery,
    skill: "researching"
);

// ********* [4/6] shepherd.debugging-evidence/1 *********

/// The fresh reproduction, recorded so a reviewer can re-run it rather than
/// trust the narrative.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingReproduction {
    pub command: String,
    pub input: String,
    /// "environment/binary identity" is two identities in the prose, kept as
    /// two fields: a report that names the environment but not the binary is
    /// exactly the stale-output case the contract rejects.
    pub environment_identity: String,
    pub binary_identity: String,
    pub exit_status: i32,
    pub stdout_path: String,
    pub stderr_path: String,
    /// "the fresh observed failure" -- a process exit alone is not one.
    pub observed_failure: String,
}

/// One observed fact, separated from what the author makes of it.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingObservation {
    pub fact: String,
    pub interpretation: String,
    /// "file/symbol/line or artifact pointers" -- one pointer per observation,
    /// in whichever of those forms applies.
    pub pointer: String,
}

/// "one falsifiable claim per suspected boundary and the probe that tests it".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingHypothesis {
    pub boundary: String,
    pub claim: String,
    pub probe: String,
}

/// The result of running one hypothesis's probe.
///
/// The contract says "for each hypothesis" but names no join key, so the
/// pairing is positional. A validator therefore has to compare the two lists'
/// lengths; inventing a `hypothesis_id` here would add a field the contract
/// does not have and that no existing producer emits.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingFalsification {
    pub command: String,
    pub exit_status: i32,
    pub observation: String,
    pub conclusion: String,
}

/// "the shared fault boundary and why caller-only alternatives do not explain
/// it".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingRootCause {
    pub fault_boundary: String,
    pub caller_only_rejection: String,
}

/// "changed paths, scope, and why the change is the smallest root-cause
/// correction".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingFix {
    pub changed_paths: Vec<String>,
    pub scope: String,
    pub minimality: String,
}

/// The RED-before/GREEN-after pair that is the proof the bug is fixed.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingRegression {
    pub test: String,
    /// The observed failing result before the fix, and the passing result
    /// after. Recorded as the observations themselves rather than as two
    /// booleans: a pair of `bool`s that are always `true` and `false` proves
    /// nothing, which is the failure this contract calls out by name.
    pub red_before: String,
    pub green_after: String,
    /// AMBIGUOUS in the prose: "with input and output hashes" is singular for
    /// the regression as a whole, not one pair per run. Read as one pair,
    /// because that is what the sentence says; a producer that needs per-run
    /// hashes has `evidence` for them.
    pub input_sha256: String,
    pub output_sha256: String,
}

/// "fresh deterministic command, status, semantic result, and candidate
/// identity".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingGate {
    pub command: String,
    /// "status" here is the process exit status, read the same way the lane
    /// ledger's `exit_status` and the review finding's
    /// `falsification_exit_status` are. `semantic_result` carries the meaning,
    /// which is exactly why the contract lists both.
    pub exit_status: i32,
    pub semantic_result: String,
    pub candidate_identity: String,
}

/// One retained artifact, with the eval it was scored against when there is
/// one.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingArtifact {
    pub path: String,
    pub sha256: String,
    /// "paired eval and threshold when relevant" -- optional, and optional
    /// together: an eval without its threshold is an unscored claim.
    pub eval: Option<String>,
    pub threshold: Option<String>,
}

/// "unresolved environment, timing, or compatibility limits and the next
/// route".
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingResidualRisk {
    pub limits: Vec<String>,
    pub next_route: String,
}

/// One debugging evidence report. One report covers one observed failure.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DebuggingEvidence {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub lane: LaneId,
    pub node: String,
    /// The contract pins `role: coder` and `startup_skill: implementing`:
    /// debugging is a Coder activity carrying its own evidence digest, not a
    /// tenth role.
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub role: Role,
    pub status: DebuggingStatus,
    pub candidate_commit: String,
    pub worktree: String,
    pub startup_skill: String,
    pub debugging_skill_digest: String,
    pub input_digest: String,
    pub reproduction: DebuggingReproduction,
    pub observed: Vec<DebuggingObservation>,
    pub hypothesis: Vec<DebuggingHypothesis>,
    pub falsification: Vec<DebuggingFalsification>,
    pub root_cause: DebuggingRootCause,
    pub fix: DebuggingFix,
    pub regression: DebuggingRegression,
    pub gate: DebuggingGate,
    pub evidence: Vec<DebuggingArtifact>,
    pub residual_risk: DebuggingResidualRisk,
}

role_result!(
    DebuggingEvidence,
    DEBUGGING_EVIDENCE_SCHEMA,
    role: Role::Coder,
    skill: "implementing"
);

// ********* [5/6] shepherd.review-finding/1 *********

/// One review finding record.
///
/// IDENTIFIER DRIFT, NAMED DELIBERATELY. Doctrine's finding contract heads this
/// document `shepherd.review-finding/1`; [`super::ReviewResult`] in `review.rs`
/// carries the same field list under `shepherd.review-result/1`. Two names for
/// one document is the same class of defect as one name for two documents, and
/// it cannot be resolved from inside this module: `review.rs` and `content/`
/// are both owned elsewhere. What is fixed here is that the second name can no
/// longer be shapeless -- `findings` reuses the real [`ReviewFinding`], and
/// `review_finding_report_matches_the_review_result_document` fails the moment
/// the two shapes stop agreeing.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ReviewFindingReport {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    /// `lane: null` is reserved for run-scoped planning Critic review. The
    /// native adapter still has to bind that scope to the current planning
    /// Engineer; the shape only makes the null representable.
    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
    pub lane: Option<LaneId>,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub mode: ReviewMode,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub reviewer_role: Role,
    pub candidate_commit: String,
    pub input_digest: String,
    pub startup_skill: String,
    pub skill_bundle_digest: String,
    pub result_channel: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub verdict: ReviewVerdict,
    /// The real finding type from `review.rs`, so the finding rules
    /// (`ReviewResult::validate`) apply unchanged to a document parsed here.
    #[cfg_attr(feature = "schema", schemars(with = "Vec<ReviewFindingShape>"))]
    pub findings: Vec<ReviewFinding>,
    /// "`report_path` is optional in the record and is valid only when the
    /// native reviewer capability explicitly includes `report-write`". The
    /// capability check is `ReviewResult::validate_with_report_capability`;
    /// this type only carries the optional field.
    pub report_path: Option<String>,
}

role_result!(ReviewFindingReport, REVIEW_FINDING_SCHEMA, skill: "reviewing");

/// The schema witness for [`ReviewFinding`], which lives in `review.rs` and
/// cannot derive `JsonSchema` from here.
///
/// This exists ONLY so `findings` gets a real derived shape instead of an
/// "array of anything", and it is pinned to the real type by
/// `review_finding_shape_matches_the_review_finding_type`: any field added,
/// removed, or renamed on [`ReviewFinding`] fails that test, because both sides
/// deny unknown fields.
#[cfg(any(test, feature = "schema"))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub(crate) struct ReviewFindingShape {
    pub finding_id: String,
    pub location: String,
    pub hypothesis: String,
    pub falsification_command: String,
    pub falsification_exit_status: i32,
    pub observed_result: String,
    pub confidence: String,
    pub severity: String,
    pub impact: String,
    pub acceptance_predicate: String,
    pub owner_role: String,
    pub route: String,
    pub evidence_paths: Vec<String>,
}

// ********* [6/6] shepherd.lane-ledger/1 *********

/// One appended lifecycle event.
///
/// The ledger "indexes evidence; Native dispatch and Git custody remain
/// authoritative", so nothing here is a second source of truth for a dispatch
/// or a commit.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LaneLedgerEvent {
    pub event_id: String,
    pub node_id: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub role: Role,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub work_kind: WorkKind,
    pub read_scope: Vec<String>,
    pub write_scope: Vec<String>,
    pub task_digest: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub dispatch_id: DispatchId,
    /// AMBIGUOUS in the prose: the contract lists `result_artifact` and
    /// `review_artifact` under "Every event", but a `gate-request` event is
    /// recorded before either exists. Read as optional, because the alternative
    /// makes the earliest events in every lane unrepresentable. A writer that
    /// wants the key always present emits an explicit `null`.
    pub result_artifact: Option<String>,
    pub review_artifact: Option<String>,
    pub command: String,
    pub exit_status: i32,
    pub semantic_result: String,
    pub evidence_digest: String,
    pub recorded_at: i64,
    pub next_action: String,
    /// "Mutation adds worktree/output commit".
    pub worktree: Option<String>,
    pub output_commit: Option<String>,
    /// "retry adds `retry_of`, finding, bounded predicate and re-review".
    pub retry_of: Option<String>,
    pub finding: Option<String>,
    pub bounded_predicate: Option<String>,
    pub re_review: Option<String>,
    /// "escalation adds route, reason, preserved evidence and parent
    /// response".
    pub route: Option<String>,
    pub reason: Option<String>,
    pub preserved_evidence: Option<Vec<String>>,
    pub parent_response: Option<String>,
}

/// A RED or GREEN gate outcome inside the acceptance record.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LaneGateOutcome {
    pub exit_status: i32,
    pub semantic_result: String,
}

/// The acceptance record the ledger requires before `accepted`.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LaneAcceptance {
    /// "final reviewed commit/path manifest".
    pub reviewed_commit: String,
    pub path_manifest: Vec<String>,
    /// "independent Auditor evidence with no unresolved Critical/Important
    /// finding". The severity rule itself is enforced by
    /// `ReviewResult::validate`, not restated here.
    pub auditor_evidence: Vec<String>,
    /// "real RED/GREEN status and semantic results".
    pub red: LaneGateOutcome,
    pub green: LaneGateOutcome,
    pub startup_skill: String,
    pub skill_bundle_digest: String,
    /// "risks/rollback/restart and independently verifiable handoff".
    pub risks: Vec<String>,
    pub rollback: String,
    pub restart: String,
    pub handoff: String,
}

/// One lane ledger.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LaneLedger {
    pub schema: String,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub run: RunId,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub lane: LaneId,
    /// "measurable outcome".
    pub outcome: String,
    /// "one Conductor identity" -- one, so this is not a list.
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub owner: AgentId,
    pub baseline_commit: String,
    pub plan_digest: String,
    pub skill_bundle_digest: String,
    pub status: LaneLedgerStatus,
    /// "Append one structured event per lifecycle step in the assigned lane."
    pub events: Vec<LaneLedgerEvent>,
    /// Required before `accepted`/`handed-off` and absent before then, which
    /// is a cross-field rule and not a shape rule. The ledger's rejection
    /// custody section is NOT restated here: `ReviewCustody`
    /// (`shepherd.review-custody/1`) already owns the count, the terminal
    /// fourth rejection and the no-resume state, and a second copy of that
    /// counter is how two counters disagree.
    pub acceptance: Option<LaneAcceptance>,
}

role_result!(LaneLedger, LANE_LEDGER_SCHEMA);

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};

    /// Prove a fixture document really is this contract's document.
    ///
    /// The point of the two lists is that neither can be padded: `required`
    /// entries must each break deserialization when removed, `optional`
    /// entries must each survive removal, and together they must be exactly the
    /// fixture's keys. A type with no fields cannot pass this.
    fn assert_document<T>(document: &Value, schema: &str, required: &[&str], optional: &[&str])
    where
        T: serde::Serialize + serde::de::DeserializeOwned + core::fmt::Debug,
    {
        let parsed: T =
            serde_json::from_value(document.clone()).expect("contract fixture must deserialize");
        assert_eq!(
            &serde_json::to_value(&parsed).expect("contract fixture must reserialize"),
            document,
            "the document does not round-trip through its type"
        );
        assert_eq!(
            document.get("schema").and_then(Value::as_str),
            Some(schema),
            "the document does not carry its own identifier"
        );

        let mut keys: Vec<&str> = document
            .as_object()
            .expect("fixture is an object")
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        let mut declared: Vec<&str> = required.iter().chain(optional.iter()).copied().collect();
        declared.sort_unstable();
        assert_eq!(
            keys, declared,
            "the fixture and the declared field lists disagree"
        );

        for key in required {
            let mut broken = document.clone();
            broken
                .as_object_mut()
                .expect("fixture is an object")
                .remove(*key)
                .unwrap_or_else(|| panic!("fixture has no `{key}` to remove"));
            assert!(
                serde_json::from_value::<T>(broken).is_err(),
                "`{key}` deserialized while absent, so it is not actually required"
            );
        }

        for key in optional {
            let mut trimmed = document.clone();
            trimmed
                .as_object_mut()
                .expect("fixture is an object")
                .remove(*key)
                .unwrap_or_else(|| panic!("fixture has no `{key}` to remove"));
            serde_json::from_value::<T>(trimmed)
                .unwrap_or_else(|error| panic!("`{key}` is required, not optional: {error}"));
        }
    }

    /// A derived schema must name the same required set the type enforces.
    /// Equality, not containment: containment passes for a schema that
    /// requires everything, which is the vacuous case.
    #[cfg(feature = "schema")]
    fn assert_schema_required(schema: schemars::Schema, required: &[&str]) {
        let value = serde_json::to_value(schema).expect("schema serializes");
        let mut actual: Vec<&str> = value
            .get("required")
            .and_then(Value::as_array)
            .expect("a derived object schema names its required fields")
            .iter()
            .map(|entry| entry.as_str().expect("required entries are strings"))
            .collect();
        actual.sort_unstable();
        let mut expected = required.to_vec();
        expected.sort_unstable();
        assert_eq!(actual, expected);
        assert_eq!(
            value.get("additionalProperties"),
            Some(&Value::Bool(false)),
            "a result contract that accepts unknown fields is not closed"
        );
    }

    const CODER_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "lane",
        "node",
        "role",
        "outcome",
        "task_digest",
        "startup_skill",
        "skill_bundle_digest",
        "worktree",
        "baseline_commit",
        "owned_paths",
        "changed_paths",
        "status",
    ];

    const WORKER_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "lane",
        "node",
        "role",
        "work_kind",
        "deliverable",
        "source_paths",
        "owned_scope",
        "budget",
        "output_shape",
        "status",
        "task_digest",
        "startup_skill",
        "skill_bundle_digest",
    ];

    const DISCOVERY_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "lane",
        "question",
        "role",
        "source_list",
        "output_path",
        "budget",
        "startup_skill",
        "skill_bundle_digest",
        "task_digest",
        "status",
        "sources",
        "claims",
        "conflicts",
        "limits",
        "evidence",
    ];

    const DEBUGGING_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "lane",
        "node",
        "role",
        "status",
        "candidate_commit",
        "worktree",
        "startup_skill",
        "debugging_skill_digest",
        "input_digest",
        "reproduction",
        "observed",
        "hypothesis",
        "falsification",
        "root_cause",
        "fix",
        "regression",
        "gate",
        "evidence",
        "residual_risk",
    ];

    const REVIEW_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "mode",
        "reviewer_role",
        "candidate_commit",
        "input_digest",
        "startup_skill",
        "skill_bundle_digest",
        "result_channel",
        "verdict",
        "findings",
    ];
    const REVIEW_OPTIONAL: &[&str] = &["lane", "report_path"];

    const LEDGER_REQUIRED: &[&str] = &[
        "schema",
        "run",
        "lane",
        "outcome",
        "owner",
        "baseline_commit",
        "plan_digest",
        "skill_bundle_digest",
        "status",
        "events",
    ];
    const LEDGER_OPTIONAL: &[&str] = &["acceptance"];

    const DIGEST: &str = "a3f1e2d4c5b6a7089192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8";
    const COMMIT: &str = "1f0a2b3c4d5e6f708192a3b4c5d6e7f809a1b2c3";

    fn coder_document() -> Value {
        json!({
            "schema": CODER_RESULT_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "node": "n-04",
            "role": "coder",
            "outcome": "the six role result contracts deserialize or fail",
            "task_digest": DIGEST,
            "startup_skill": "implementing",
            "skill_bundle_digest": DIGEST,
            "worktree": "target/lanes/wf-schemars",
            "baseline_commit": COMMIT,
            "owned_paths": ["crates/core/src/dispatch/result.rs"],
            "changed_paths": ["crates/core/src/dispatch/result.rs"],
            "status": "green"
        })
    }

    fn worker_document() -> Value {
        json!({
            "schema": WORKER_RESULT_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "node": "n-05",
            "role": "worker",
            "work_kind": "artifact",
            "deliverable": "one bounded contract reference page",
            "source_paths": ["content/skills/artifact-work/references/result-contract.md"],
            "owned_scope": ["docs/contracts.md"],
            "budget": {"tool_calls": 40, "seconds": 900},
            "output_shape": "sections: shape, evidence, status",
            "status": "complete",
            "task_digest": DIGEST,
            "startup_skill": "artifact-work",
            "skill_bundle_digest": DIGEST
        })
    }

    fn discovery_document() -> Value {
        json!({
            "schema": DISCOVERY_REPORT_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "question": "does schemars 1 keep Option fields out of `required`",
            "role": "discovery",
            "source_list": ["schemars-1.2.2"],
            "output_path": "runs/v661/discovery/schemars.md",
            "budget": {"tool_calls": 12, "seconds": 300},
            "startup_skill": "researching",
            "skill_bundle_digest": DIGEST,
            "task_digest": DIGEST,
            "status": "complete",
            "sources": [{
                "identifier": "schemars-1.2.2",
                "version": "1.2.2",
                "retrieval_status": "retrieved",
                "evidence_location": "vendor/schemars/src/generate.rs"
            }],
            "claims": [{
                "claim": "the default generator uses the deserialize contract",
                "citation": "generate.rs:88",
                "observed": "contract: Contract::Deserialize",
                "interpretation": "Option fields are omitted from `required`"
            }],
            "conflicts": [{
                "sources": ["schemars-0.9.0", "schemars-1.2.2"],
                "contradiction": "0.9 spells the wrapper differently",
                "freshness_gap": null,
                "disposition": "the locked 1.2.2 wins"
            }],
            "limits": {
                "scope": "schema generation only",
                "budget": "12 of 12 tool calls",
                "compatibility": "schemars 1.x only",
                "unresolved_questions": []
            },
            "evidence": {
                "report_sha256": DIGEST,
                "source_pointers": ["vendor/schemars/src/generate.rs"]
            }
        })
    }

    fn debugging_document() -> Value {
        json!({
            "schema": DEBUGGING_EVIDENCE_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "node": "n-06",
            "role": "coder",
            "status": "fixed",
            "candidate_commit": COMMIT,
            "worktree": "target/lanes/wf-schemars",
            "startup_skill": "implementing",
            "debugging_skill_digest": DIGEST,
            "input_digest": DIGEST,
            "reproduction": {
                "command": "cargo nextest run -p shepherd-core --all-features",
                "input": "crates/core/src/dispatch/result.rs",
                "environment_identity": "darwin-25.5.0",
                "binary_identity": "cargo-nextest 0.9",
                "exit_status": 101,
                "stdout_path": "runs/v661/out.log",
                "stderr_path": "runs/v661/err.log",
                "observed_failure": "missing field `status`"
            },
            "observed": [{
                "fact": "the fixture omitted `status`",
                "interpretation": "the fixture, not the type, was wrong",
                "pointer": "crates/core/src/dispatch/result.rs:1"
            }],
            "hypothesis": [{
                "boundary": "serde derive",
                "claim": "a plain field is required",
                "probe": "remove the key and deserialize"
            }],
            "falsification": [{
                "command": "cargo nextest run -p shepherd-core --all-features",
                "exit_status": 0,
                "observation": "deserialization returned Err",
                "conclusion": "the field is required"
            }],
            "root_cause": {
                "fault_boundary": "the fixture builder",
                "caller_only_rejection": "every caller failed, so it is not one caller"
            },
            "fix": {
                "changed_paths": ["crates/core/src/dispatch/result.rs"],
                "scope": "test fixture only",
                "minimality": "one key restored, no type change"
            },
            "regression": {
                "test": "coder_result_document_matches_its_contract",
                "red_before": "missing field `status`",
                "green_after": "1 passed",
                "input_sha256": DIGEST,
                "output_sha256": DIGEST
            },
            "gate": {
                "command": "cargo nextest run -p shepherd-core --all-features",
                "exit_status": 0,
                "semantic_result": "every result contract test passed",
                "candidate_identity": COMMIT
            },
            "evidence": [{
                "path": "runs/v661/out.log",
                "sha256": DIGEST,
                "eval": null,
                "threshold": null
            }],
            "residual_risk": {
                "limits": ["schemars 1.x only"],
                "next_route": "none"
            }
        })
    }

    fn review_finding_entry() -> Value {
        json!({
            "finding_id": "f-01",
            "location": "crates/core/src/dispatch/result.rs:1",
            "hypothesis": "the document shape is unenforced",
            "falsification_command": "cargo nextest run -p shepherd-core --all-features",
            "falsification_exit_status": 0,
            "observed_result": "deserialization accepted a document with no fields",
            "confidence": "structurally-verifiable",
            "severity": "important",
            "impact": "a producer and a verifier drift without failing",
            "acceptance_predicate": "removing any required key fails deserialization",
            "owner_role": "coder",
            "route": "wf-schemars",
            "evidence_paths": ["runs/v661/out.log"]
        })
    }

    fn review_document() -> Value {
        json!({
            "schema": REVIEW_FINDING_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "mode": "auditor-posthoc",
            "reviewer_role": "auditor",
            "candidate_commit": COMMIT,
            "input_digest": DIGEST,
            "startup_skill": "reviewing",
            "skill_bundle_digest": DIGEST,
            "result_channel": "native-result",
            "verdict": "redo",
            "findings": [review_finding_entry()],
            "report_path": "runs/v661/review/wf-schemars.md"
        })
    }

    fn ledger_document() -> Value {
        json!({
            "schema": LANE_LEDGER_SCHEMA,
            "run": "v661",
            "lane": "wf-schemars",
            "outcome": "the six role result contracts have a derived shape",
            "owner": "conductor-wf-schemars",
            "baseline_commit": COMMIT,
            "plan_digest": DIGEST,
            "skill_bundle_digest": DIGEST,
            "status": "accepted",
            "events": [{
                "event_id": "e-01",
                "node_id": "n-04",
                "role": "coder",
                "work_kind": "production-code",
                "read_scope": ["content/skills"],
                "write_scope": ["crates/core/src/dispatch/result.rs"],
                "task_digest": DIGEST,
                "dispatch_id": "d-01",
                "result_artifact": "runs/v661/result/n-04.json",
                "review_artifact": null,
                "command": "cargo nextest run -p shepherd-core --all-features",
                "exit_status": 0,
                "semantic_result": "every result contract test passed",
                "evidence_digest": DIGEST,
                "recorded_at": 1_756_000_000,
                "next_action": "hand off to root",
                "worktree": "target/lanes/wf-schemars",
                "output_commit": COMMIT,
                "retry_of": null,
                "finding": null,
                "bounded_predicate": null,
                "re_review": null,
                "route": null,
                "reason": null,
                "preserved_evidence": null,
                "parent_response": null
            }],
            "acceptance": {
                "reviewed_commit": COMMIT,
                "path_manifest": ["crates/core/src/dispatch/result.rs"],
                "auditor_evidence": ["runs/v661/review/wf-schemars.md"],
                "red": {"exit_status": 101, "semantic_result": "missing field `status`"},
                "green": {"exit_status": 0, "semantic_result": "every test passed"},
                "startup_skill": "lane-execution",
                "skill_bundle_digest": DIGEST,
                "risks": ["schemars 1.x only"],
                "rollback": "revert the module and its declaration",
                "restart": "none",
                "handoff": "root commits"
            }
        })
    }

    #[test]
    fn each_type_is_bound_to_exactly_one_record_constant() {
        assert_eq!(CoderResult::SCHEMA, CODER_RESULT_SCHEMA);
        assert_eq!(WorkerResult::SCHEMA, WORKER_RESULT_SCHEMA);
        assert_eq!(DiscoveryReport::SCHEMA, DISCOVERY_REPORT_SCHEMA);
        assert_eq!(DebuggingEvidence::SCHEMA, DEBUGGING_EVIDENCE_SCHEMA);
        assert_eq!(ReviewFindingReport::SCHEMA, REVIEW_FINDING_SCHEMA);
        assert_eq!(LaneLedger::SCHEMA, LANE_LEDGER_SCHEMA);

        // Six contracts, six identifiers. A duplicate here would let one
        // verifier accept another role's document.
        let bound = [
            CoderResult::SCHEMA,
            WorkerResult::SCHEMA,
            DiscoveryReport::SCHEMA,
            DebuggingEvidence::SCHEMA,
            ReviewFindingReport::SCHEMA,
            LaneLedger::SCHEMA,
        ];
        let mut sorted = bound.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), bound.len(), "two types share an identifier");
    }

    #[test]
    fn coder_result_matches_its_contract() {
        let document = coder_document();
        assert_document::<CoderResult>(&document, CODER_RESULT_SCHEMA, CODER_REQUIRED, &[]);
        let parsed: CoderResult = serde_json::from_value(document).expect("fixture");
        parsed.validate_header().expect("header matches");
    }

    #[test]
    fn worker_result_matches_its_contract() {
        let document = worker_document();
        assert_document::<WorkerResult>(&document, WORKER_RESULT_SCHEMA, WORKER_REQUIRED, &[]);
        let parsed: WorkerResult = serde_json::from_value(document).expect("fixture");
        parsed.validate_header().expect("header matches");
    }

    #[test]
    fn discovery_report_matches_its_contract() {
        let document = discovery_document();
        assert_document::<DiscoveryReport>(
            &document,
            DISCOVERY_REPORT_SCHEMA,
            DISCOVERY_REQUIRED,
            &[],
        );
        let parsed: DiscoveryReport = serde_json::from_value(document).expect("fixture");
        parsed.validate_header().expect("header matches");
    }

    #[test]
    fn debugging_evidence_matches_its_contract() {
        let document = debugging_document();
        assert_document::<DebuggingEvidence>(
            &document,
            DEBUGGING_EVIDENCE_SCHEMA,
            DEBUGGING_REQUIRED,
            &[],
        );
        let parsed: DebuggingEvidence = serde_json::from_value(document).expect("fixture");
        parsed.validate_header().expect("header matches");
    }

    #[test]
    fn review_finding_report_matches_its_contract() {
        let document = review_document();
        assert_document::<ReviewFindingReport>(
            &document,
            REVIEW_FINDING_SCHEMA,
            REVIEW_REQUIRED,
            REVIEW_OPTIONAL,
        );
        let parsed: ReviewFindingReport = serde_json::from_value(document).expect("fixture");
        parsed.validate_header().expect("header matches");
    }

    #[test]
    fn lane_ledger_matches_its_contract() {
        let document = ledger_document();
        assert_document::<LaneLedger>(
            &document,
            LANE_LEDGER_SCHEMA,
            LEDGER_REQUIRED,
            LEDGER_OPTIONAL,
        );
        let parsed: LaneLedger = serde_json::from_value(document).expect("fixture");
        parsed.validate_schema().expect("schema matches");
    }

    #[test]
    fn a_document_carrying_another_contracts_identifier_is_rejected() {
        // The exact drift the module exists to stop: same shape, wrong name.
        let mut document = coder_document();
        document["schema"] = json!(WORKER_RESULT_SCHEMA);
        let parsed: CoderResult = serde_json::from_value(document).expect("shape still parses");
        assert!(parsed.validate_schema().is_err());
    }

    #[test]
    fn a_document_carrying_another_roles_identity_is_rejected() {
        let mut document = coder_document();
        document["role"] = json!("worker");
        let parsed: CoderResult = serde_json::from_value(document).expect("shape still parses");
        assert!(parsed.validate_header().is_err());

        let mut document = coder_document();
        document["startup_skill"] = json!("artifact-work");
        let parsed: CoderResult = serde_json::from_value(document).expect("shape still parses");
        assert!(parsed.validate_header().is_err());
    }

    #[test]
    fn an_unknown_field_is_rejected_by_every_contract() {
        // `deny_unknown_fields` is what stops a producer adding a field a
        // verifier silently ignores, which is the other half of schema drift.
        for mut document in [
            coder_document(),
            worker_document(),
            discovery_document(),
            debugging_document(),
            review_document(),
            ledger_document(),
        ] {
            document["not_in_the_contract"] = json!(true);
            assert!(
                serde_json::from_value::<serde_json::Map<String, Value>>(document.clone()).is_ok()
            );
            let rejected = serde_json::from_value::<CoderResult>(document.clone()).is_err()
                && serde_json::from_value::<WorkerResult>(document.clone()).is_err()
                && serde_json::from_value::<DiscoveryReport>(document.clone()).is_err()
                && serde_json::from_value::<DebuggingEvidence>(document.clone()).is_err()
                && serde_json::from_value::<ReviewFindingReport>(document.clone()).is_err()
                && serde_json::from_value::<LaneLedger>(document).is_err();
            assert!(rejected, "an unknown field was accepted somewhere");
        }
    }

    #[test]
    fn review_finding_shape_matches_the_review_finding_type() {
        // The witness `ReviewFindingShape` only earns its keep if it cannot
        // drift from the real `ReviewFinding`. Both deny unknown fields and
        // both require every listed key, so a field added, removed or renamed
        // on either side fails one of these two conversions.
        let entry = review_finding_entry();
        let real: ReviewFinding =
            serde_json::from_value(entry.clone()).expect("the real finding type accepts it");
        let witness: ReviewFindingShape =
            serde_json::from_value(entry.clone()).expect("the schema witness accepts it");
        assert_eq!(serde_json::to_value(&real).expect("real"), entry);
        assert_eq!(serde_json::to_value(&witness).expect("witness"), entry);
    }

    #[test]
    fn review_finding_report_matches_the_review_result_document() {
        // Doctrine calls this document `shepherd.review-finding/1`; `review.rs`
        // calls the same field list `shepherd.review-result/1`. Until one of
        // them moves, this test is what keeps the two from becoming genuinely
        // different documents behind two names.
        let mut document = review_document();
        document["schema"] = json!(super::super::REVIEW_RESULT_SCHEMA);
        let review_result: super::super::ReviewResult =
            serde_json::from_value(document.clone()).expect("ReviewResult accepts it");
        assert_eq!(
            serde_json::to_value(&review_result).expect("value"),
            document
        );

        document["schema"] = json!(REVIEW_FINDING_SCHEMA);
        let report: ReviewFindingReport =
            serde_json::from_value(document.clone()).expect("ReviewFindingReport accepts it");
        assert_eq!(serde_json::to_value(&report).expect("value"), document);
    }

    #[cfg(feature = "schema")]
    #[test]
    fn every_derived_schema_names_the_required_fields() {
        assert_schema_required(schemars::schema_for!(CoderResult), CODER_REQUIRED);
        assert_schema_required(schemars::schema_for!(WorkerResult), WORKER_REQUIRED);
        assert_schema_required(schemars::schema_for!(DiscoveryReport), DISCOVERY_REQUIRED);
        assert_schema_required(schemars::schema_for!(DebuggingEvidence), DEBUGGING_REQUIRED);
        assert_schema_required(schemars::schema_for!(ReviewFindingReport), REVIEW_REQUIRED);
        assert_schema_required(schemars::schema_for!(LaneLedger), LEDGER_REQUIRED);
    }

    #[cfg(feature = "schema")]
    #[test]
    fn the_review_finding_schema_carries_the_finding_shape() {
        // A `findings: [anything]` schema would satisfy the required-field
        // check above while proving nothing about a finding, so the nested
        // shape is asserted directly.
        let value =
            serde_json::to_value(schemars::schema_for!(ReviewFindingReport)).expect("schema");
        let reference = value
            .pointer("/properties/findings/items/$ref")
            .and_then(Value::as_str)
            .expect("findings items reference a named definition");
        let name = reference
            .rsplit('/')
            .next()
            .expect("a $ref names a definition");
        let mut required: Vec<&str> = value
            .pointer(&format!("/$defs/{name}/required"))
            .and_then(Value::as_array)
            .expect("the finding definition names its required fields")
            .iter()
            .map(|entry| entry.as_str().expect("string"))
            .collect();
        required.sort_unstable();
        assert_eq!(
            required,
            [
                "acceptance_predicate",
                "confidence",
                "evidence_paths",
                "falsification_command",
                "falsification_exit_status",
                "finding_id",
                "hypothesis",
                "impact",
                "location",
                "observed_result",
                "owner_role",
                "route",
                "severity",
            ]
        );
    }
}