codewhale-protocol 0.9.4

App-server protocol frames for Codewhale runtime integrations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
//! Agent Fleet control-plane protocol types.
//!
//! These types define the durable, serializable contract between the fleet
//! manager, workers, CLI/TUI surfaces, and the Runtime API. They are
//! intentionally additive: existing runtime-event consumers ignore unknown
//! fields and are unaffected by fleet extensions.
//!
//! See:
//! - <https://github.com/Hmbown/CodeWhale/issues/3154> (Agent Fleet control plane)
//! - <https://github.com/Hmbown/CodeWhale/issues/3096> (Runtime API sub-agent direction)

use std::collections::BTreeMap;
use std::path::PathBuf;

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use serde_json::Value;

use super::Status;

pub const FLEET_PROTOCOL_VERSION: &str = "0.1.0";

/// Globally unique identifier for a fleet run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct FleetRunId(pub String);

impl From<String> for FleetRunId {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for FleetRunId {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

/// Top-level fleet run handle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetRun {
    pub id: FleetRunId,
    pub name: String,
    pub status: FleetRunStatus,
    /// Explicit execution target selected by the managed client.
    ///
    /// Older CLI-created runs predate target selection and therefore omit
    /// this field. Runtime API creation always persists it and currently
    /// accepts only [`FleetRuntimeTarget::ThisComputer`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<FleetRuntimeTarget>,
    /// Named Workflow descriptor that owns this Fleet run.
    ///
    /// The durable task specs below remain the executable source of truth;
    /// this descriptor keeps the product identity and scheduling policy
    /// inspectable without smuggling them through labels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workflow: Option<FleetWorkflowDescriptor>,
    /// Canonical named roles declared for the run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<String>,
    /// Maximum number of workers the manager may drive concurrently.
    ///
    /// Older ledgers omit this field; callers fall back to the persisted
    /// worker roster when resuming those runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_workers: Option<usize>,
    #[serde(default)]
    pub task_specs: Vec<FleetTaskSpec>,
    #[serde(default)]
    pub worker_specs: Vec<FleetWorkerSpec>,
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security_policy: Option<FleetSecurityPolicy>,
    pub created_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,
}

/// Product-level Runtime target for a managed Fleet run.
///
/// The enum intentionally names unsupported targets as contract values so a
/// client receives a precise capability refusal instead of silently falling
/// back to local execution.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetRuntimeTarget {
    ThisComputer,
    AnotherComputer,
    Cloud,
}

/// Scheduling shape currently executable by the durable Fleet manager.
///
/// Fleet tasks are independent queue entries today, so only parallel
/// workflows are advertised. Sequence/pipeline support must not be accepted
/// until dependencies are durable in the Fleet ledger.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetWorkflowKind {
    Parallel,
}

/// Durable identity for the Workflow that coordinates a Fleet run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetWorkflowDescriptor {
    pub id: String,
    pub kind: FleetWorkflowKind,
}

/// One privacy-bounded durable event exposed to managed Fleet clients.
///
/// `cursor` is an opaque stable digest of the underlying ledger transition.
/// Clients persist it and send it back on reconnect; they must not parse it.
/// Worker-local sequence numbers remain available separately because they are
/// monotonic only within one `(worker, task)` lifecycle, not across a run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FleetRuntimeEvent {
    pub cursor: String,
    pub event: String,
    pub run_id: FleetRunId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_seq: Option<u64>,
    #[serde(default)]
    pub payload: Value,
}

/// Bounded durable replay page.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FleetEventReplay {
    pub run_id: FleetRunId,
    pub events: Vec<FleetRuntimeEvent>,
    #[serde(default)]
    pub has_more: bool,
    /// True when a no-cursor request returned only the newest bounded tail.
    #[serde(default)]
    pub history_truncated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Lifecycle status for an entire fleet run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetRunStatus {
    Pending,
    Queued,
    Running,
    Paused,
    Completed,
    Failed,
    Cancelled,
}

impl Status for FleetRunStatus {
    fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }
    fn is_active(&self) -> bool {
        matches!(self, Self::Pending | Self::Queued | Self::Running)
    }
    fn is_paused(&self) -> bool {
        matches!(self, Self::Paused)
    }
}

/// Specification of a single unit of work within a run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetTaskSpec {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub objective: Option<String>,
    pub instructions: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worker: Option<FleetTaskWorkerProfile>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<FleetWorkspaceRequirements>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub input_files: Vec<PathBuf>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub context: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget: Option<FleetTaskBudget>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(default)]
    pub expected_artifacts: Vec<FleetArtifactKind>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scorer: Option<FleetScorerSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_policy: Option<FleetRetryPolicy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_policy: Option<FleetAlertPolicy>,
    #[serde(default)]
    pub timeout_seconds: Option<u64>,
    #[serde(default)]
    pub metadata: BTreeMap<String, Value>,
}

/// Worker role and tool expectations for a task.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct FleetTaskWorkerProfile {
    /// Named agent profile/persona posture to layer onto this worker.
    ///
    /// `profile` is accepted as a shorter authoring alias. This is an intent
    /// reference only; profile loading and permission narrowing happen in the
    /// Fleet runtime layer.
    #[serde(default, alias = "profile", skip_serializing_if = "Option::is_none")]
    pub agent_profile: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Fleet loadout intent such as `auto`, `fast`, or `review`.
    ///
    /// This is not a concrete provider/model selection; route resolution owns
    /// the executable provider/model/wire-model decision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loadout: Option<String>,
    /// Fleet model class hint such as `strong`, `balanced`, or `fast`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_class: Option<String>,
    /// Optional explicit model id for this worker.
    ///
    /// Task-level model overrides are visible authoring data and take
    /// precedence over the referenced agent profile's model hint. Provider and
    /// wire-model validation still belong to route resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_profile: Option<String>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<String>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<String>,
}

/// Workspace and environment constraints needed before a task starts.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct FleetWorkspaceRequirements {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub root: Option<PathBuf>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub required_files: Vec<PathBuf>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub writable_paths: Vec<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<FleetEnvironmentRequirements>,
}

/// Environment variables a task requires or may pass through to workers.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct FleetEnvironmentRequirements {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub required: Vec<String>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowlist: Vec<String>,
}

/// Budget limits for a task.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct FleetTaskBudget {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tool_calls: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_seconds: Option<u64>,
}

/// Reference to an artifact produced or consumed by a task.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetArtifactRef {
    pub kind: FleetArtifactKind,
    pub path: PathBuf,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    #[serde(default)]
    pub size_bytes: Option<u64>,
}

/// Kind of artifact a task may produce or consume.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FleetArtifactKind {
    Log,
    Patch,
    TestResult,
    Report,
    Checkpoint,
    Receipt,
    Other(String),
}

impl FleetArtifactKind {
    fn as_wire_str(&self) -> &str {
        match self {
            Self::Log => "log",
            Self::Patch => "patch",
            Self::TestResult => "test_result",
            Self::Report => "report",
            Self::Checkpoint => "checkpoint",
            Self::Receipt => "receipt",
            Self::Other(kind) => kind.as_str(),
        }
    }

    fn from_wire_str(value: &str) -> Self {
        match value {
            "log" => Self::Log,
            "patch" => Self::Patch,
            "test_result" => Self::TestResult,
            "report" => Self::Report,
            "checkpoint" => Self::Checkpoint,
            "receipt" => Self::Receipt,
            other => Self::Other(other.to_string()),
        }
    }
}

impl Serialize for FleetArtifactKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_wire_str())
    }
}

impl<'de> Deserialize<'de> for FleetArtifactKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(Self::from_wire_str(&value))
    }
}

/// Scoring rule used to verify a task result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FleetScorerSpec {
    ExitCode,
    FileExists {
        path: PathBuf,
    },
    RegexMatch {
        path: PathBuf,
        pattern: String,
    },
    JsonPath {
        path: PathBuf,
        expression: String,
    },
    Command {
        command: String,
        #[serde(default)]
        args: Vec<String>,
    },
    CodeWhaleVerifierPrompt {
        prompt: String,
    },
    Manual,
}

/// Worker specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetWorkerSpec {
    pub id: String,
    pub name: String,
    pub host: FleetHostSpec,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_level: Option<FleetTrustLevel>,
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_concurrent_tasks: Option<usize>,
}

/// Host on which a worker runs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FleetHostSpec {
    Local,
    Ssh {
        host: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        port: Option<u16>,
        #[serde(skip_serializing_if = "Option::is_none")]
        user: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        identity: Option<PathBuf>,
        /// Known hosts file for host-key verification.
        #[serde(skip_serializing_if = "Option::is_none")]
        known_hosts: Option<PathBuf>,
        /// Expected host key fingerprint (SHA256:...) for key pinning.
        /// When set, the connection is only trusted if the server's
        /// host key matches this fingerprint exactly.
        #[serde(skip_serializing_if = "Option::is_none")]
        host_key_fingerprint: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        working_directory: Option<PathBuf>,
        #[serde(default)]
        #[serde(skip_serializing_if = "Vec::is_empty")]
        env_allowlist: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        codewhale_binary: Option<String>,
    },
    #[serde(alias = "container")]
    #[serde(alias = "Container")]
    Docker {
        image: String,
        #[serde(default)]
        args: Vec<String>,
    },
}

// ── Security and trust types ────────────────────────────────────────────────

/// Trust classification assigned to a worker host.
///
/// The trust level determines what a worker is allowed to do and what
/// secrets it may access. The default for new workers is [`FleetTrustLevel::Sandbox`];
/// operators must explicitly raise trust for SSH or container workers.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)]
#[serde(rename_all = "snake_case")]
pub enum FleetTrustLevel {
    /// Fully isolated: no network, no secrets, no writes outside `.codewhale/fleet/`.
    /// Suitable for untrusted code review, community PR checks, or third-party tool runs.
    #[default]
    Sandbox = 0,
    /// Local-only worker with access to the workspace and configured secrets.
    /// Default for local workers. May read repo files but writes are gated.
    Local = 1,
    /// Worker on a known remote host with verified identity and a bounded
    /// set of explicitly granted capabilities. Requires SSH host-key
    /// verification or equivalent attestation.
    #[serde(alias = "remote-verified", alias = "remoteVerified")]
    RemoteVerified = 2,
    /// Fully trusted worker (e.g. operator's own machine, CI runner).
    /// Has access to all configured secrets and may perform any action the
    /// operator can. Reserved for dogfood smoke and operator-owned machines.
    Operator = 3,
}

impl FleetTrustLevel {
    /// Whether this trust level is allowed to access provider secrets.
    #[must_use]
    pub fn may_access_secrets(&self) -> bool {
        matches!(self, Self::Operator | Self::RemoteVerified | Self::Local)
    }

    /// Whether this trust level is allowed to write outside `.codewhale/fleet/`.
    #[must_use]
    pub fn may_write_workspace(&self) -> bool {
        matches!(self, Self::Operator | Self::Local)
    }

    /// Whether this trust level is allowed network access.
    #[must_use]
    pub fn may_access_network(&self) -> bool {
        matches!(self, Self::Operator | Self::RemoteVerified | Self::Local)
    }
}

/// Security policy applied to a fleet run.
///
/// A policy defines the default trust level for workers, which secrets
/// may be resolved, and what capabilities are granted. When a run has no
/// explicit policy, workers inherit conservative defaults.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetSecurityPolicy {
    /// Default trust level for workers that don't declare one explicitly.
    #[serde(default)]
    pub default_trust_level: FleetTrustLevel,
    /// Secret refs that workers may resolve. An empty list means no secrets
    /// are available. Each entry is a key name, not a value.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_secrets: Vec<FleetSecretRef>,
    /// Capability grants for workers in this run.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capability_grants: Vec<FleetCapabilityGrant>,
    /// Maximum trust level any worker in this run may have, even if the
    /// worker spec requests higher. Defaults to Operator (no ceiling).
    #[serde(default = "default_max_trust_level")]
    pub max_trust_level: FleetTrustLevel,
    /// Require identity verification for remote workers. When true, SSH
    /// workers must pass host-key verification before being trusted at
    /// RemoteVerified level; unverified remotes stay at Sandbox.
    #[serde(default)]
    pub require_identity_verification: bool,
    /// Allow conservative parallel execution of read-only tools (#2983).
    /// When true, workers may batch independent read-only tool calls
    /// (reads, searches, greps) into concurrent turns. Disabled by default
    /// to avoid overwhelming providers or hitting rate limits.
    #[serde(default)]
    pub allow_parallel_reads: bool,
}

fn default_max_trust_level() -> FleetTrustLevel {
    FleetTrustLevel::Operator
}

impl Default for FleetSecurityPolicy {
    fn default() -> Self {
        Self {
            default_trust_level: FleetTrustLevel::Sandbox,
            allowed_secrets: Vec::new(),
            capability_grants: Vec::new(),
            max_trust_level: FleetTrustLevel::Operator,
            require_identity_verification: false,
            allow_parallel_reads: false,
        }
    }
}

/// A reference to a secret that should be resolved at runtime, never
/// serialized as a plaintext value.
///
/// Secret refs appear in task specs, alert configs, and worker definitions.
/// The actual secret value is resolved by the fleet manager from the
/// secrets backend (OS keyring, environment, or file store) just before
/// the worker starts.
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FleetSecretRef {
    /// The secret key name (e.g. `"CODEWHALE_API_KEY"`, `"GH_TOKEN"`).
    pub key: String,
    /// Optional source hint for resolution order.
    /// - `"env"` — resolve from environment variable
    /// - `"keyring"` — resolve from OS keyring
    /// - `"file"` — resolve from `~/.codewhale/secrets/`
    /// - absent / null — try all sources in default order
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

impl FleetSecretRef {
    /// Create a secret ref from a key name with default resolution.
    #[must_use]
    pub fn new(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            source: None,
        }
    }

    /// Create a secret ref with an explicit source.
    #[must_use]
    pub fn with_source(key: impl Into<String>, source: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            source: Some(source.into()),
        }
    }

    /// Redacted display form for logging. Shows the key name and source
    /// but never the resolved value.
    #[must_use]
    pub fn redacted(&self) -> String {
        match &self.source {
            Some(src) => format!("<secret:{}.{}>", src, self.key),
            None => format!("<secret:{}>", self.key),
        }
    }
}

impl std::fmt::Display for FleetSecretRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.redacted())
    }
}

impl From<&str> for FleetSecretRef {
    fn from(key: &str) -> Self {
        Self::new(key)
    }
}

impl From<String> for FleetSecretRef {
    fn from(key: String) -> Self {
        Self::new(key)
    }
}

impl<'de> Deserialize<'de> for FleetSecretRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum SecretRefWire {
            Key(String),
            Structured {
                key: String,
                #[serde(default)]
                source: Option<String>,
            },
        }

        match SecretRefWire::deserialize(deserializer)? {
            SecretRefWire::Key(key) if !key.trim().is_empty() => Ok(FleetSecretRef::new(key)),
            SecretRefWire::Key(_) => Err(de::Error::custom("secret ref key cannot be empty")),
            SecretRefWire::Structured { key, source } if !key.trim().is_empty() => {
                Ok(FleetSecretRef { key, source })
            }
            SecretRefWire::Structured { .. } => {
                Err(de::Error::custom("secret ref key cannot be empty"))
            }
        }
    }
}

/// How a worker authenticates to the fleet manager.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "method", rename_all = "snake_case")]
pub enum FleetWorkerAuth {
    /// No authentication (local workers share the same uid).
    None,
    /// SSH key-based authentication with host-key verification.
    SshKey {
        /// Path to the SSH identity file (may be a FleetSecretRef in JSON
        /// as `{"key": "...", "source": "file"}`).
        identity: PathBuf,
        /// Known hosts file for host-key verification.
        #[serde(skip_serializing_if = "Option::is_none")]
        known_hosts: Option<PathBuf>,
        /// Expected host key fingerprint for pinning.
        #[serde(skip_serializing_if = "Option::is_none")]
        host_key_fingerprint: Option<String>,
        /// SSH user for the connection.
        #[serde(skip_serializing_if = "Option::is_none")]
        user: Option<String>,
    },
    /// Token-based authentication for remote workers behind a fleet proxy.
    Token {
        /// Reference to the token secret.
        token_ref: FleetSecretRef,
    },
    /// mTLS certificate-based authentication.
    Mtls {
        /// Path to the client certificate.
        cert_path: PathBuf,
        /// Reference to the private key secret.
        key_ref: FleetSecretRef,
    },
}

/// A capability grant that explicitly authorizes a worker to perform
/// a specific class of action.
///
/// By default, new workers get no grants (least privilege). Grants are
/// additive: a worker's effective capabilities are the union of its
/// trust-level defaults plus any explicit grants.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetCapabilityGrant {
    /// The capability being granted (e.g. `"network"`, `"git-push"`,
    /// `"provider-secrets"`, `"release"`).
    pub capability: String,
    /// Optional scope limiting the grant (e.g. `"github.com"` for network,
    /// `"crates/tui/**"` for file writes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Optional justification for the grant (audit trail).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Runtime status of a worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetWorkerStatus {
    Unknown,
    Online,
    Busy,
    Offline,
    Unhealthy,
    Draining,
    Retired,
}

impl Status for FleetWorkerStatus {
    fn is_terminal(&self) -> bool {
        matches!(self, Self::Retired)
    }
    fn is_active(&self) -> bool {
        matches!(self, Self::Online | Self::Busy)
    }
    fn is_paused(&self) -> bool {
        false
    }
}

/// Durable inbox entry: a task waiting to be leased to a worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetInboxEntry {
    pub run_id: FleetRunId,
    pub task_id: String,
    pub priority: i32,
    pub enqueued_at: String,
    #[serde(default)]
    pub lease_deadline: Option<String>,
    #[serde(default)]
    pub attempts: u32,
}

/// Worker event envelope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetWorkerEvent {
    pub seq: u64,
    pub run_id: FleetRunId,
    pub worker_id: String,
    pub task_id: String,
    pub timestamp: String,
    #[serde(flatten)]
    pub payload: FleetWorkerEventPayload,
    #[serde(default)]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

/// Union of all worker event payloads.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum FleetWorkerEventPayload {
    Queued,
    Leased {
        #[serde(skip_serializing_if = "Option::is_none")]
        lease_expires_at: Option<String>,
    },
    Starting,
    Running,
    ModelWait {
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
    },
    RunningTool {
        tool: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        call_id: Option<String>,
    },
    /// Typed receipt emitted by a Workflow running inside this worker.
    WorkflowEvent {
        /// Inner Workflow run id. Named distinctly from the outer Fleet run id
        /// because payloads are flattened into `FleetWorkerEvent`.
        workflow_run_id: String,
        event: Value,
    },
    Heartbeat {
        #[serde(default)]
        #[serde(skip_serializing_if = "Option::is_none")]
        cpu_percent: Option<f32>,
        #[serde(default)]
        #[serde(skip_serializing_if = "Option::is_none")]
        memory_mb: Option<u64>,
    },
    Artifact(FleetArtifactRef),
    Completed {
        #[serde(default)]
        #[serde(skip_serializing_if = "Option::is_none")]
        exit_code: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        summary: Option<String>,
    },
    Failed {
        reason: String,
        #[serde(default)]
        recoverable: bool,
    },
    Cancelled {
        #[serde(skip_serializing_if = "Option::is_none")]
        cancelled_by: Option<String>,
    },
    Interrupted {
        #[serde(skip_serializing_if = "Option::is_none")]
        signal: Option<String>,
    },
    Stale {
        #[serde(skip_serializing_if = "Option::is_none")]
        last_heartbeat_at: Option<String>,
    },
    Restarted {
        #[serde(default)]
        restart_count: u32,
    },
    Escalated {
        channel: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        alert_id: Option<String>,
    },
}

/// Retry policy for a task or worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetRetryPolicy {
    #[serde(default = "default_retry_max_attempts")]
    pub max_attempts: u32,
    #[serde(default = "default_retry_initial_backoff_seconds")]
    pub initial_backoff_seconds: u64,
    #[serde(default = "default_retry_max_backoff_seconds")]
    pub max_backoff_seconds: u64,
    #[serde(default = "default_retry_backoff_multiplier")]
    pub backoff_multiplier: u32,
}

impl Default for FleetRetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            initial_backoff_seconds: 5,
            max_backoff_seconds: 300,
            backoff_multiplier: 2,
        }
    }
}

fn default_retry_max_attempts() -> u32 {
    FleetRetryPolicy::default().max_attempts
}

fn default_retry_initial_backoff_seconds() -> u64 {
    FleetRetryPolicy::default().initial_backoff_seconds
}

fn default_retry_max_backoff_seconds() -> u64 {
    FleetRetryPolicy::default().max_backoff_seconds
}

fn default_retry_backoff_multiplier() -> u32 {
    FleetRetryPolicy::default().backoff_multiplier
}

/// Alert/escalation policy attached to a task or run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetAlertPolicy {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<FleetAlertEventClass>,
    #[serde(default)]
    pub channels: Vec<FleetAlertChannel>,
    #[serde(default)]
    pub after_attempts: Option<u32>,
    #[serde(default)]
    pub after_minutes_stale: Option<u64>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum FleetAlertEventClass {
    Stale,
    RestartExhausted,
    NeedsHuman,
    BudgetExceeded,
    VerifierFailed,
    RunCompleted,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FleetAlertChannel {
    Slack {
        /// Webhook URL, resolved from a secret ref or inline.
        #[serde(flatten)]
        webhook: FleetAlertEndpoint,
    },
    Webhook {
        #[serde(flatten)]
        endpoint: FleetAlertEndpoint,
    },
    #[serde(alias = "pager_duty")]
    #[serde(alias = "pagerduty")]
    PagerDuty {
        routing_key: String,
        severity: String,
    },
}

/// An alert channel endpoint, supporting both inline URLs and secret refs.
///
/// For Slack and generic webhook channels, the URL may be provided directly
/// or as a secret reference resolved at send time. When both `url` and
/// `url_ref` are present, `url_ref` takes precedence after resolution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetAlertEndpoint {
    /// Inline URL (plaintext; only for non-sensitive endpoints).
    #[serde(
        alias = "webhook_url",
        alias = "endpoint_url",
        skip_serializing_if = "Option::is_none"
    )]
    pub url: Option<String>,
    /// Reference to a secret containing the webhook URL.
    #[serde(
        alias = "webhook_url_ref",
        alias = "webhook_ref",
        alias = "url_secret_ref",
        skip_serializing_if = "Option::is_none"
    )]
    pub url_ref: Option<FleetSecretRef>,
    /// Optional HMAC secret for webhook payload signing, as a secret ref.
    #[serde(
        alias = "secret",
        alias = "webhook_secret",
        alias = "signing_secret",
        skip_serializing_if = "Option::is_none"
    )]
    pub secret_ref: Option<FleetSecretRef>,
}

impl FleetAlertEndpoint {
    /// Create an inline URL endpoint (for non-sensitive use).
    #[must_use]
    pub fn inline(url: impl Into<String>) -> Self {
        Self {
            url: Some(url.into()),
            url_ref: None,
            secret_ref: None,
        }
    }

    /// Create a secret-backed URL endpoint.
    #[must_use]
    pub fn from_secret(url_ref: FleetSecretRef) -> Self {
        Self {
            url: None,
            url_ref: Some(url_ref),
            secret_ref: None,
        }
    }

    /// Redacted display form for logging.
    #[must_use]
    pub fn redacted(&self) -> String {
        self.url_ref
            .as_ref()
            .map_or_else(|| "<inline-url>".to_string(), |r| r.redacted())
    }
}

/// Resolved-route detail persisted on a [`FleetReceipt`] (#3154).
///
/// This is an additive, *plain-strings* snapshot of the route a fleet worker
/// resolved to. It deliberately does NOT depend on any `codewhale-config` route
/// type so the protocol crate stays free of the route model.
///
/// CRITICAL no-secrets invariant: this struct carries ONLY non-sensitive route
/// shape — provider id/kind, model ids, wire protocol, role/loadout/model-class
/// intent, reasoning tier when known, and deterministic intent sources. It
/// must NEVER hold a credential, API key, bearer token, or a base URL that
/// embeds credentials. There is intentionally no field that could carry a
/// secret.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetResolvedRoute {
    /// Resolved provider canonical id (e.g. `"deepseek"`).
    pub provider_id: String,
    /// Exact configured provider-table id when the worker used one.
    ///
    /// This is intentionally additive to `provider_id`: literal
    /// `[providers.custom]` resolves to `Some("custom")`, while the legacy
    /// idless root custom route resolves to `None`. Keeping the distinction
    /// prevents a receipt from silently collapsing two different credential
    /// and endpoint authorities into the same generic `custom` label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_exact_id: Option<String>,
    /// Resolved provider kind (e.g. `"deepseek"`).
    pub provider_kind: String,
    /// Canonical, provider-agnostic model identity, when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_model: Option<String>,
    /// Provider-owned wire model id placed on the request.
    pub wire_model_id: String,
    /// Selected wire protocol (e.g. `"chat_completions"`).
    pub protocol: String,
    /// Effective Fleet role intent, when one applied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Effective Fleet loadout intent, when one applied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loadout: Option<String>,
    /// Original task-level model-class intent, when authored separately from
    /// `loadout`. Profile `model_class_hint` is normalized into `loadout`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_class: Option<String>,
    /// Runtime model-route seam used by sub-agent routing (`inherit`, `faster`,
    /// `auto`, or `fixed`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_route: Option<String>,
    /// Concrete reasoning tier, when it is known by the route resolver path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    /// Deterministic source for the effective role intent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_source: Option<String>,
    /// Deterministic source for the effective loadout intent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loadout_source: Option<String>,
    /// Deterministic source for the model-class hint, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_class_source: Option<String>,
    /// Deterministic source for the model selector used by the resolver.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_source: Option<String>,
    /// How the route was produced (e.g. `"resolver"`).
    pub source: String,
}

/// Effective worker authority persisted on a [`FleetReceipt`] (#3211).
///
/// This is a non-secret snapshot of the already-computed runtime profile. It
/// records what the worker was allowed to do; it does not grant permissions and
/// does not carry credentials, sandbox paths, or provider endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FleetEffectivePermissions {
    /// Whether the worker profile may modify workspace files.
    pub write: bool,
    /// Whether the worker profile may use network-capable tools.
    pub network: bool,
    /// Shell posture (`none`, `read_only`, or `full`).
    pub shell: String,
    /// Tool-surface posture (`inherit` or `explicit`).
    pub tool_scope: String,
    /// Explicit tool names when `tool_scope` is `explicit`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<String>,
    /// Whether the worker is intended to run detached/background.
    pub background: bool,
    /// Remaining nested-delegation budget after parent intersection/hardening.
    pub max_spawn_depth: u32,
    /// Roster profile id that contributed to this worker, when any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Roster layer for `profile_id` (`built_in`, `config`, or `workspace`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_origin: Option<String>,
    /// How this snapshot was produced (e.g. `"worker_runtime_profile"`).
    pub source: String,
}

/// Receipt produced when a task completes verification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetReceipt {
    pub run_id: FleetRunId,
    pub task_id: String,
    pub worker_id: String,
    /// Durable lease generation that produced this receipt.
    ///
    /// Optional for backward compatibility with receipts written before Fleet
    /// attempts were fenced explicitly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attempt: Option<u32>,
    /// Sequence of the terminal worker event finalized with this receipt.
    ///
    /// Optional so older ledger records remain replayable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub terminal_seq: Option<u64>,
    pub completed_at: String,
    pub result: FleetTaskResult,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_kind: Option<FleetTaskFailureKind>,
    #[serde(default)]
    pub artifacts: Vec<FleetArtifactRef>,
    #[serde(default)]
    pub score: Option<FleetScore>,
    /// Resolved-route snapshot for this task (#3154).
    ///
    /// `#[serde(default)]` keeps older ledgers (written before this field
    /// existed) deserializable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_route: Option<FleetResolvedRoute>,
    /// Effective worker authority for this task (#3211).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_permissions: Option<FleetEffectivePermissions>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetTaskResult {
    Pass,
    Partial,
    Fail,
    Skip,
    Timeout,
}

/// Source category for a failed task receipt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FleetTaskFailureKind {
    Transport,
    Task,
    Verifier,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FleetScore {
    pub value: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

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

    #[test]
    fn fleet_run_round_trip() {
        let run = FleetRun {
            id: FleetRunId::from("run-001"),
            name: "dogfood smoke".to_string(),
            status: FleetRunStatus::Running,
            target: Some(FleetRuntimeTarget::ThisComputer),
            workflow: Some(FleetWorkflowDescriptor {
                id: "release-checks".to_string(),
                kind: FleetWorkflowKind::Parallel,
            }),
            roles: vec!["release-checker".to_string()],
            max_workers: Some(1),
            task_specs: vec![FleetTaskSpec {
                id: "task-1".to_string(),
                name: "lint".to_string(),
                description: None,
                objective: Some("Keep the workspace lint-clean".to_string()),
                instructions: "run cargo clippy".to_string(),
                worker: Some(FleetTaskWorkerProfile {
                    agent_profile: None,
                    role: Some("release-checker".to_string()),
                    loadout: None,
                    model_class: None,
                    model: None,
                    tool_profile: Some("read-only".to_string()),
                    tools: vec!["cargo".to_string()],
                    capabilities: vec!["rust".to_string()],
                }),
                workspace: Some(FleetWorkspaceRequirements {
                    root: Some(PathBuf::from(".")),
                    required_files: vec![PathBuf::from("Cargo.toml")],
                    writable_paths: vec![],
                    environment: Some(FleetEnvironmentRequirements {
                        required: vec!["PATH".to_string()],
                        allowlist: vec!["RUST_LOG".to_string()],
                    }),
                }),
                input_files: vec![PathBuf::from("crates/tui/src/main.rs")],
                context: vec!["release gate".to_string()],
                budget: Some(FleetTaskBudget {
                    max_tokens: Some(8000),
                    max_tool_calls: Some(20),
                    max_seconds: Some(300),
                }),
                tags: vec!["release".to_string()],
                expected_artifacts: vec![FleetArtifactKind::Log],
                scorer: Some(FleetScorerSpec::ExitCode),
                retry_policy: Some(FleetRetryPolicy::default()),
                alert_policy: None,
                timeout_seconds: Some(300),
                metadata: BTreeMap::new(),
            }],
            worker_specs: vec![],
            labels: BTreeMap::new(),
            security_policy: None,
            created_at: "2026-06-12T17:00:00Z".to_string(),
            updated_at: None,
            completed_at: None,
        };
        let json = serde_json::to_string(&run).unwrap();
        let back: FleetRun = serde_json::from_str(&json).unwrap();
        assert_eq!(back.id, run.id);
        assert_eq!(back.status, FleetRunStatus::Running);
        assert_eq!(back.target, Some(FleetRuntimeTarget::ThisComputer));
        assert_eq!(back.roles, vec!["release-checker"]);
        assert_eq!(
            back.workflow.as_ref().map(|workflow| workflow.id.as_str()),
            Some("release-checks")
        );
        assert_eq!(back.task_specs.len(), 1);
        assert_eq!(
            back.task_specs[0].worker.as_ref().unwrap().role.as_deref(),
            Some("release-checker")
        );
        assert_eq!(
            back.task_specs[0]
                .workspace
                .as_ref()
                .unwrap()
                .required_files,
            vec![PathBuf::from("Cargo.toml")]
        );
    }

    #[test]
    fn worker_profile_carries_agent_profile_and_loadout_intent() {
        let json = r#"{
            "profile": "adversarial_reviewer",
            "role": "reviewer",
            "loadout": "auto",
            "model_class": "balanced",
            "model": "deepseek-v4-pro",
            "tool_profile": "read-only",
            "tools": ["read_file"],
            "capabilities": ["rust"]
        }"#;

        let profile: FleetTaskWorkerProfile = serde_json::from_str(json).unwrap();

        assert_eq!(
            profile.agent_profile.as_deref(),
            Some("adversarial_reviewer")
        );
        assert_eq!(profile.role.as_deref(), Some("reviewer"));
        assert_eq!(profile.loadout.as_deref(), Some("auto"));
        assert_eq!(profile.model_class.as_deref(), Some("balanced"));
        assert_eq!(profile.model.as_deref(), Some("deepseek-v4-pro"));
        assert_eq!(profile.tool_profile.as_deref(), Some("read-only"));

        let serialized = serde_json::to_value(&profile).unwrap();
        assert_eq!(serialized["agent_profile"], "adversarial_reviewer");
        assert_eq!(serialized["model"], "deepseek-v4-pro");
        assert!(serialized.get("profile").is_none());
    }

    #[test]
    fn worker_event_lifecycle_round_trip() {
        let events = vec![
            FleetWorkerEvent {
                seq: 1,
                run_id: FleetRunId::from("run-002"),
                worker_id: "worker-a".to_string(),
                task_id: "task-1".to_string(),
                timestamp: "2026-06-12T17:01:00Z".to_string(),
                payload: FleetWorkerEventPayload::Queued,
                extra: BTreeMap::new(),
            },
            FleetWorkerEvent {
                seq: 2,
                run_id: FleetRunId::from("run-002"),
                worker_id: "worker-a".to_string(),
                task_id: "task-1".to_string(),
                timestamp: "2026-06-12T17:01:05Z".to_string(),
                payload: FleetWorkerEventPayload::RunningTool {
                    tool: "bash".to_string(),
                    call_id: Some("call-1".to_string()),
                },
                extra: BTreeMap::new(),
            },
            FleetWorkerEvent {
                seq: 3,
                run_id: FleetRunId::from("run-002"),
                worker_id: "worker-a".to_string(),
                task_id: "task-1".to_string(),
                timestamp: "2026-06-12T17:02:00Z".to_string(),
                payload: FleetWorkerEventPayload::Completed {
                    exit_code: Some(0),
                    summary: Some("ok".to_string()),
                },
                extra: BTreeMap::new(),
            },
        ];
        let json = serde_json::to_string(&events).unwrap();
        let back: Vec<FleetWorkerEvent> = serde_json::from_str(&json).unwrap();
        assert_eq!(back.len(), 3);
        assert!(matches!(back[0].payload, FleetWorkerEventPayload::Queued));
        assert!(matches!(
            back[2].payload,
            FleetWorkerEventPayload::Completed { .. }
        ));
    }

    #[test]
    fn workflow_receipt_round_trip_keeps_outer_and_inner_run_ids_distinct() {
        let event = FleetWorkerEvent {
            seq: 3,
            run_id: FleetRunId::from("fleet-run-1"),
            worker_id: "worker-a".to_string(),
            task_id: "task-1".to_string(),
            timestamp: "2026-07-10T00:00:00Z".to_string(),
            payload: FleetWorkerEventPayload::WorkflowEvent {
                workflow_run_id: "workflow_1".to_string(),
                event: serde_json::json!({"type": "task_completed"}),
            },
            extra: BTreeMap::new(),
        };
        let value = serde_json::to_value(&event).unwrap();
        assert_eq!(value["run_id"], "fleet-run-1");
        assert_eq!(value["workflow_run_id"], "workflow_1");
        let back: FleetWorkerEvent = serde_json::from_value(value).unwrap();
        assert!(matches!(
            back.payload,
            FleetWorkerEventPayload::WorkflowEvent {
                workflow_run_id,
                ref event,
            } if workflow_run_id == "workflow_1" && event["type"] == "task_completed"
        ));
    }

    #[test]
    fn alert_policy_round_trip() {
        let policy = FleetAlertPolicy {
            events: vec![FleetAlertEventClass::Stale],
            channels: vec![FleetAlertChannel::Slack {
                webhook: FleetAlertEndpoint::inline("https://hooks.slack.com/test"),
            }],
            after_attempts: Some(2),
            after_minutes_stale: Some(10),
        };
        let json = serde_json::to_string(&policy).unwrap();
        assert!(json.contains("\"events\":[\"stale\"]"));
        assert!(json.contains("\"kind\":\"slack\""));
        let back: FleetAlertPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(back.events, vec![FleetAlertEventClass::Stale]);
        assert_eq!(back.after_attempts, Some(2));
    }

    #[test]
    fn artifact_other_kind_round_trip() {
        let artifact = FleetArtifactRef {
            kind: FleetArtifactKind::Other("coverage.xml".to_string()),
            path: PathBuf::from("/tmp/coverage.xml"),
            checksum: Some("sha256:abc".to_string()),
            mime_type: Some("application/xml".to_string()),
            size_bytes: Some(1024),
        };
        let json = serde_json::to_string(&artifact).unwrap();
        let back: FleetArtifactRef = serde_json::from_str(&json).unwrap();
        assert_eq!(back.kind, artifact.kind);
        assert_eq!(back.size_bytes, Some(1024));
    }

    #[test]
    fn ssh_host_spec_accepts_minimal_legacy_json() {
        let json = r#"{"kind":"ssh","host":"builder.example.test"}"#;
        let host: FleetHostSpec = serde_json::from_str(json).unwrap();

        match host {
            FleetHostSpec::Ssh {
                host,
                port,
                user,
                identity,
                known_hosts,
                host_key_fingerprint,
                working_directory,
                env_allowlist,
                codewhale_binary,
            } => {
                assert_eq!(host, "builder.example.test");
                assert_eq!(port, None);
                assert_eq!(user, None);
                assert_eq!(identity, None);
                assert_eq!(known_hosts, None);
                assert_eq!(host_key_fingerprint, None);
                assert_eq!(working_directory, None);
                assert!(env_allowlist.is_empty());
                assert_eq!(codewhale_binary, None);
            }
            other => panic!("expected ssh host spec, got {other:?}"),
        }
    }

    #[test]
    fn artifact_kind_uses_flat_string_json() {
        let known = serde_json::to_string(&FleetArtifactKind::TestResult).unwrap();
        assert_eq!(known, "\"test_result\"");

        let custom =
            serde_json::to_string(&FleetArtifactKind::Other("coverage.xml".to_string())).unwrap();
        assert_eq!(custom, "\"coverage.xml\"");

        let parsed: FleetArtifactKind = serde_json::from_str("\"coverage.xml\"").unwrap();
        assert_eq!(parsed, FleetArtifactKind::Other("coverage.xml".to_string()));
    }

    #[test]
    fn retry_policy_missing_fields_use_nonzero_defaults() {
        let policy: FleetRetryPolicy = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(policy, FleetRetryPolicy::default());

        let policy: FleetRetryPolicy =
            serde_json::from_value(serde_json::json!({"max_attempts": 5})).unwrap();
        assert_eq!(policy.max_attempts, 5);
        assert_eq!(
            policy.initial_backoff_seconds,
            FleetRetryPolicy::default().initial_backoff_seconds
        );
        assert_eq!(
            policy.max_backoff_seconds,
            FleetRetryPolicy::default().max_backoff_seconds
        );
        assert_eq!(
            policy.backoff_multiplier,
            FleetRetryPolicy::default().backoff_multiplier
        );
    }

    #[test]
    fn sparse_worker_events_omit_absent_optional_fields() {
        let heartbeat = FleetWorkerEventPayload::Heartbeat {
            cpu_percent: None,
            memory_mb: None,
        };
        let heartbeat_json = serde_json::to_value(&heartbeat).unwrap();
        assert_eq!(heartbeat_json, serde_json::json!({"state": "heartbeat"}));

        let completed = FleetWorkerEventPayload::Completed {
            exit_code: None,
            summary: None,
        };
        let completed_json = serde_json::to_value(&completed).unwrap();
        assert_eq!(completed_json, serde_json::json!({"state": "completed"}));
    }

    #[test]
    fn receipt_round_trip() {
        let receipt = FleetReceipt {
            run_id: FleetRunId::from("run-003"),
            task_id: "task-1".to_string(),
            worker_id: "worker-b".to_string(),
            attempt: Some(2),
            terminal_seq: Some(7),
            completed_at: "2026-06-12T17:03:00Z".to_string(),
            result: FleetTaskResult::Pass,
            failure_kind: None,
            artifacts: vec![],
            score: Some(FleetScore {
                value: 0.95,
                max: Some(1.0),
                notes: None,
            }),
            resolved_route: None,
            effective_permissions: None,
        };
        let json = serde_json::to_string(&receipt).unwrap();
        let back: FleetReceipt = serde_json::from_str(&json).unwrap();
        assert_eq!(back.result, FleetTaskResult::Pass);
        assert_eq!(back.score.as_ref().unwrap().value, 0.95);
        assert_eq!(back.attempt, Some(2));
        assert_eq!(back.terminal_seq, Some(7));
    }

    #[test]
    fn partial_receipt_records_failure_source_when_needed() {
        let receipt = FleetReceipt {
            run_id: FleetRunId::from("run-004"),
            task_id: "task-2".to_string(),
            worker_id: "worker-c".to_string(),
            attempt: None,
            terminal_seq: None,
            completed_at: "2026-06-12T17:04:00Z".to_string(),
            result: FleetTaskResult::Partial,
            failure_kind: Some(FleetTaskFailureKind::Verifier),
            artifacts: vec![],
            score: Some(FleetScore {
                value: 0.5,
                max: Some(1.0),
                notes: Some("manual verification required".to_string()),
            }),
            resolved_route: None,
            effective_permissions: None,
        };

        let json = serde_json::to_string(&receipt).unwrap();
        assert!(json.contains("\"result\":\"partial\""));
        assert!(json.contains("\"failure_kind\":\"verifier\""));
        let back: FleetReceipt = serde_json::from_str(&json).unwrap();
        assert_eq!(back.result, FleetTaskResult::Partial);
        assert_eq!(back.failure_kind, Some(FleetTaskFailureKind::Verifier));
    }

    #[test]
    fn ssh_host_spec_with_key_pinning_round_trip() {
        let spec = FleetHostSpec::Ssh {
            host: "builder.trusted.example.com".to_string(),
            port: Some(22),
            user: Some("codewhale".to_string()),
            identity: Some(PathBuf::from("~/.ssh/codewhale_fleet")),
            known_hosts: Some(PathBuf::from("~/.ssh/known_hosts")),
            host_key_fingerprint: Some("SHA256:aLGqZo1M6c...".to_string()),
            working_directory: Some(PathBuf::from("/srv/codewhale/work")),
            env_allowlist: vec!["CODEWHALE_PROFILE".to_string()],
            codewhale_binary: Some("/usr/local/bin/codewhale".to_string()),
        };
        let json = serde_json::to_string_pretty(&spec).unwrap();
        assert!(json.contains("\"known_hosts\""));
        assert!(json.contains("\"host_key_fingerprint\""));
        assert!(json.contains("SHA256:aLGqZo1M6c..."));

        let back: FleetHostSpec = serde_json::from_str(&json).unwrap();
        match back {
            FleetHostSpec::Ssh {
                host,
                known_hosts,
                host_key_fingerprint,
                ..
            } => {
                assert_eq!(host, "builder.trusted.example.com");
                assert_eq!(known_hosts, Some(PathBuf::from("~/.ssh/known_hosts")));
                assert_eq!(
                    host_key_fingerprint,
                    Some("SHA256:aLGqZo1M6c...".to_string())
                );
            }
            other => panic!("expected ssh host spec, got {other:?}"),
        }
    }

    #[test]
    fn secret_ref_redacted_never_exposes_value() {
        let ref_ = FleetSecretRef::new("DEEPSEEK_API_KEY");
        let redacted = ref_.redacted();
        assert!(redacted.contains("DEEPSEEK_API_KEY"));
        assert!(!redacted.contains("sk-"));
        assert!(redacted.contains("<secret:"));

        let ref_ = FleetSecretRef::with_source("GH_TOKEN", "env");
        let redacted = ref_.redacted();
        assert!(redacted.contains("env.GH_TOKEN"));
        assert!(!redacted.contains("ghp_"));
    }

    #[test]
    fn alert_endpoint_from_secret_round_trip() {
        let endpoint = FleetAlertEndpoint::from_secret(FleetSecretRef::new("SLACK_WEBHOOK"));
        let json = serde_json::to_string(&endpoint).unwrap();
        assert!(json.contains("SLACK_WEBHOOK"));
        assert!(!json.contains("hooks.slack.com"));

        let back: FleetAlertEndpoint = serde_json::from_str(&json).unwrap();
        assert_eq!(back.url_ref.as_ref().unwrap().key, "SLACK_WEBHOOK");
        assert_eq!(back.url, None);
    }

    #[test]
    fn secret_ref_accepts_legacy_string_wire_shape() {
        let ref_: FleetSecretRef = serde_json::from_str(r#""CODEWHALE_FLEET_TOKEN""#).unwrap();
        assert_eq!(ref_, FleetSecretRef::new("CODEWHALE_FLEET_TOKEN"));

        let ref_: FleetSecretRef =
            serde_json::from_str(r#"{"key":"GH_TOKEN","source":"env"}"#).unwrap();
        assert_eq!(ref_, FleetSecretRef::with_source("GH_TOKEN", "env"));
    }

    #[test]
    fn trust_level_accepts_hyphenated_remote_verified() {
        let trust: FleetTrustLevel = serde_json::from_str(r#""remote-verified""#).unwrap();
        assert_eq!(trust, FleetTrustLevel::RemoteVerified);

        let canonical = serde_json::to_string(&trust).unwrap();
        assert_eq!(canonical, r#""remote_verified""#);
    }

    #[test]
    fn alert_channel_accepts_legacy_webhook_fields() {
        let channel: FleetAlertChannel = serde_json::from_str(
            r#"{
                "kind": "slack",
                "webhook_url": "https://hooks.slack.com/test",
                "secret": "SLACK_SIGNING_SECRET"
            }"#,
        )
        .unwrap();

        match channel {
            FleetAlertChannel::Slack { webhook } => {
                assert_eq!(webhook.url.as_deref(), Some("https://hooks.slack.com/test"));
                assert_eq!(
                    webhook.secret_ref,
                    Some(FleetSecretRef::new("SLACK_SIGNING_SECRET"))
                );
            }
            other => panic!("expected slack channel, got {other:?}"),
        }
    }

    #[test]
    fn security_policy_defaults_are_conservative() {
        let policy = FleetSecurityPolicy::default();
        assert_eq!(policy.default_trust_level, FleetTrustLevel::Sandbox);
        assert!(policy.allowed_secrets.is_empty());
        assert!(policy.capability_grants.is_empty());
        assert_eq!(policy.max_trust_level, FleetTrustLevel::Operator);
        assert!(!policy.require_identity_verification);
    }

    #[test]
    fn trust_level_ordinal_reflects_privilege() {
        assert!(FleetTrustLevel::Operator > FleetTrustLevel::RemoteVerified);
        assert!(FleetTrustLevel::RemoteVerified > FleetTrustLevel::Local);
        assert!(FleetTrustLevel::Local > FleetTrustLevel::Sandbox);

        assert!(FleetTrustLevel::Operator.may_access_secrets());
        assert!(!FleetTrustLevel::Sandbox.may_access_secrets());
        assert!(!FleetTrustLevel::Sandbox.may_write_workspace());
        assert!(FleetTrustLevel::Operator.may_write_workspace());
    }

    fn sample_receipt_with_route() -> FleetReceipt {
        FleetReceipt {
            run_id: FleetRunId::from("run-route"),
            task_id: "task-route".to_string(),
            worker_id: "worker-route".to_string(),
            attempt: Some(1),
            terminal_seq: Some(4),
            completed_at: "2026-06-23T00:00:00Z".to_string(),
            result: FleetTaskResult::Pass,
            failure_kind: None,
            artifacts: vec![],
            score: None,
            resolved_route: Some(FleetResolvedRoute {
                provider_id: "deepseek".to_string(),
                provider_exact_id: None,
                provider_kind: "deepseek".to_string(),
                canonical_model: Some("deepseek-v4-pro".to_string()),
                wire_model_id: "deepseek-v4-pro".to_string(),
                protocol: "chat_completions".to_string(),
                role: Some("builder".to_string()),
                loadout: Some("auto".to_string()),
                model_class: Some("balanced".to_string()),
                model_route: Some("auto".to_string()),
                reasoning_effort: Some("high".to_string()),
                role_source: Some("task.role".to_string()),
                loadout_source: Some("task.loadout".to_string()),
                model_class_source: Some("task.model_class".to_string()),
                model_source: Some("task.model".to_string()),
                source: "resolver".to_string(),
            }),
            effective_permissions: Some(FleetEffectivePermissions {
                write: true,
                network: true,
                shell: "full".to_string(),
                tool_scope: "explicit".to_string(),
                tools: vec!["read_file".to_string(), "apply_patch".to_string()],
                background: true,
                max_spawn_depth: 2,
                profile_id: Some("builder".to_string()),
                profile_origin: Some("built_in".to_string()),
                source: "worker_runtime_profile".to_string(),
            }),
        }
    }

    #[test]
    fn fleet_resolved_route_round_trips() {
        let receipt = sample_receipt_with_route();
        let json = serde_json::to_string(&receipt).unwrap();
        let back: FleetReceipt = serde_json::from_str(&json).unwrap();
        assert_eq!(back.resolved_route, receipt.resolved_route);
        assert_eq!(back.effective_permissions, receipt.effective_permissions);
        let route = back.resolved_route.unwrap();
        assert_eq!(route.provider_id, "deepseek");
        assert_eq!(route.wire_model_id, "deepseek-v4-pro");
        assert_eq!(route.protocol, "chat_completions");
        assert_eq!(route.role.as_deref(), Some("builder"));
        assert_eq!(route.loadout.as_deref(), Some("auto"));
        assert_eq!(route.model_class.as_deref(), Some("balanced"));
        assert_eq!(route.model_route.as_deref(), Some("auto"));
        assert_eq!(route.reasoning_effort.as_deref(), Some("high"));
        assert_eq!(route.role_source.as_deref(), Some("task.role"));
        assert_eq!(route.loadout_source.as_deref(), Some("task.loadout"));
        assert_eq!(
            route.model_class_source.as_deref(),
            Some("task.model_class")
        );
        assert_eq!(route.model_source.as_deref(), Some("task.model"));
        assert_eq!(route.source, "resolver");

        let permissions = back
            .effective_permissions
            .expect("effective permissions should round-trip");
        assert!(permissions.write);
        assert!(permissions.network);
        assert_eq!(permissions.shell, "full");
        assert_eq!(permissions.tool_scope, "explicit");
        assert_eq!(
            permissions.tools,
            vec!["read_file".to_string(), "apply_patch".to_string()]
        );
        assert!(permissions.background);
        assert_eq!(permissions.max_spawn_depth, 2);
        assert_eq!(permissions.profile_id.as_deref(), Some("builder"));
        assert_eq!(permissions.profile_origin.as_deref(), Some("built_in"));
        assert_eq!(permissions.source, "worker_runtime_profile");
    }

    #[test]
    fn fleet_receipt_without_resolved_route_still_deserializes() {
        // An old ledger receipt JSON written before #3154 has no
        // `resolved_route` key; `#[serde(default)]` must keep it readable.
        let legacy = r#"{
            "run_id": "run-legacy",
            "task_id": "task-legacy",
            "worker_id": "worker-legacy",
            "completed_at": "2026-06-01T00:00:00Z",
            "result": "pass",
            "artifacts": [],
            "score": null
        }"#;
        let receipt: FleetReceipt = serde_json::from_str(legacy).unwrap();
        assert_eq!(receipt.task_id, "task-legacy");
        assert!(receipt.resolved_route.is_none());
        assert!(receipt.attempt.is_none());
        assert!(receipt.terminal_seq.is_none());
    }

    #[test]
    fn fleet_resolved_route_legacy_shape_still_deserializes() {
        let legacy = r#"{
            "run_id": "run-route",
            "task_id": "task-route",
            "worker_id": "worker-route",
            "completed_at": "2026-06-23T00:00:00Z",
            "result": "pass",
            "artifacts": [],
            "score": null,
            "resolved_route": {
                "provider_id": "deepseek",
                "provider_kind": "deepseek",
                "canonical_model": "deepseek-v4-pro",
                "wire_model_id": "deepseek-v4-pro",
                "protocol": "chat_completions",
                "role": "builder",
                "loadout": "fast",
                "source": "resolver"
            }
        }"#;

        let receipt: FleetReceipt = serde_json::from_str(legacy).unwrap();
        let route = receipt.resolved_route.expect("legacy route should parse");
        assert_eq!(route.source, "resolver");
        assert_eq!(route.role.as_deref(), Some("builder"));
        assert_eq!(route.loadout.as_deref(), Some("fast"));
        assert_eq!(route.model_class, None);
        assert_eq!(route.model_route, None);
        assert_eq!(route.reasoning_effort, None);
        assert_eq!(route.role_source, None);
        assert_eq!(route.loadout_source, None);
        assert_eq!(route.model_class_source, None);
        assert_eq!(route.model_source, None);
    }

    #[test]
    fn fleet_resolved_route_serialization_carries_no_secrets() {
        let receipt = sample_receipt_with_route();
        // Scan the serialized resolved-route object: this is the field whose
        // no-secrets invariant we are asserting. Scoping to the route value
        // avoids false positives from unrelated envelope ids (e.g. a task id
        // such as "task-foo" innocently contains the substring "sk-").
        let route_json = serde_json::to_string(receipt.resolved_route.as_ref().unwrap()).unwrap();
        assert_no_secret_markers(&route_json);
        // The envelope as a whole must also stay credential-free.
        let receipt_json = serde_json::to_string(&receipt).unwrap();
        for needle in SECRET_KEY_MARKERS {
            assert!(
                !receipt_json.to_ascii_lowercase().contains(needle),
                "receipt JSON must not contain secret-key marker {needle:?}: {receipt_json}"
            );
        }
    }

    /// Substrings that indicate a leaked credential field/value. These are
    /// deliberately specific so legitimate ids/model names do not trip them.
    const SECRET_KEY_MARKERS: &[&str] = &[
        "api_key",
        "apikey",
        "api-key",
        "authorization",
        "bearer ",
        "auth_token",
        "auth-token",
        "password",
        "credential",
        "sk-ant-",
        "sk-proj-",
        "sk-or-",
        "secret",
    ];

    fn assert_no_secret_markers(json: &str) {
        let haystack = json.to_ascii_lowercase();
        for needle in SECRET_KEY_MARKERS {
            assert!(
                !haystack.contains(needle),
                "resolved-route JSON must not contain secret marker {needle:?}: {json}"
            );
        }
    }
}