rusty-agent-runtime 0.12.0

The durable agent runtime built in Rust — core graph engine: typed channels with reducers, Pregel/BSP super-step execution, checkpoints, interrupts, and streaming.
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
1813
1814
1815
1816
1817
1818
1819
//! The deployment control plane's core contracts (R0.12 Operations
//! Plane, wave 3): revisions, environments, and the per-environment
//! deployment pointer, plus the journaled payloads of every control-plane
//! act and the environment-scoped secret records.
//!
//! The governing decision, from the design: the heavy machinery is
//! reused, so the new entities stay small. A [`DeploymentRevision`] is
//! the [`crate::learn::Candidate`] discipline turned toward deployments —
//! immutable, content-addressed ([`derive_revision_id`], the
//! [`crate::learn::derive_candidate_id`] rule), authored (`human:{id}`
//! attribution) — carrying the graph/assistant identity, the
//! `graph_hash` the checkpoint header already computes, and a **frozen
//! pin set**: the registry surfaces the revision binds, resolved to
//! candidate ids at revision *creation* from a declared source
//! environment. The freeze is deliberate and priced in the design's
//! honest edges: a revision evaluated against a recorded dataset must be
//! the same thing the gate evaluated when it canaries, and pins resolved
//! at admission would make that evidence a moving target. The weight —
//! every registry promotion that should reach prod requires a new
//! revision — is the price of evaluable deployments, paid knowingly.
//!
//! An [`Environment`] is R0.11's tag promoted to a first-class record:
//! a name (the `dev` / `staging` / `prod` convention, deployment-declared
//! rather than enumerated), the gate and approval declarations that will
//! govern promotions into it (wired in wave 4; declared here so the rule
//! in force is data, not code), and creation metadata. What an
//! environment is *not* — the R0.11 tag discipline applied one level up:
//! not a separate process, not an isolated store, not a trust boundary.
//! Environments are logical surfaces over one deployment's stores and one
//! binary's admission path.
//!
//! The [`DeploymentPointer`] is the R0.8
//! [`crate::learn::VersionPointer`] shape applied to revisions: one
//! pointer per environment under the surface key `deployment:{env}`, an
//! `active` full-traffic revision, and a `canary` binding one revision to
//! a declared fraction of new runs. Promotion moves `active` and clears
//! any canary — a full promotion supersedes the experiment it graduated
//! from. Rollback re-points `active` to the previously serving revision:
//! byte-exact, because the restored revision is the immutable record that
//! served before, not a reconstruction. Canary admission is the seeded
//! draw ([`deployment_admission`]) over the pointer surface — the draw
//! machinery reused verbatim; only the surface it draws over is new.
//!
//! Environment-scoped secrets are custody, not brokerage (R0.11's line,
//! re-argued by the environment dimension): named, tenant-scoped,
//! environment-tagged values stored as ciphertext envelopes on both
//! backends (the broker's construction — the store side only ever holds
//! [`StoredEnvSecret`]), journaled as metadata — never bytes — on the
//! deployment evidence chain. A request outside the holder's environment
//! is a typed, journaled [`EnvSecretDenial`]: scoping is enforcement, not
//! convention.
//!
//! Wave 4 turns the declared rules into enforced ones. The gate an
//! [`Environment`] declares is evaluated through the
//! [`RevisionGateEvaluator`] seam — core owns the contract, never the
//! evaluator, so the runtime keeps its distance from `rusty-eval` (the
//! workspace's dependency direction) — and the decision journals as a
//! [`GateDecisionRecord`] *before* the pointer move it governs, allowed
//! or refused: a gate whose refusals leave no evidence is a gate an
//! audit cannot tell apart from never having run. Approval-required
//! environments gate promotion behind a token scoped to the revision's
//! own promotion effect id ([`revision_promotion_effect_id`]) — a token
//! minted for one revision admits no other, so an approval is a fact
//! about a specific deploy, not a standing permission. Canary declare
//! and clear are journaled acts ([`CanaryDeclaration`],
//! [`CanaryClearance`]) on the same chain, so the experiment's whole
//! lifecycle — declared, drawn against, graduated or cleared — reads
//! from one evidence trail. And a shadow run replays a recorded run's
//! twin against a candidate revision behind the shadow admission
//! boundary, journaling its start ([`ShadowRunStarted`]), every refusal
//! the boundary served or not, and its [`ShadowVerdict`]: divergence as
//! evidence, with no path to the world.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::broker::SealedCredential;
use crate::effects::{derive_effect_id, EffectId, ShadowRefusal};
use crate::error::Result;
use crate::learn::{canary_admits, CanaryBinding, CandidateId, EnvironmentTag, SurfaceKey};
use crate::memory::ProvenanceAuthor;
use crate::record::{sha256_hex, DecisionRole};
use crate::registry::PointerBinding;

// --------------------------------------------------------------------- //
// The deployment revision
// --------------------------------------------------------------------- //

/// A content-addressed revision identity: lowercase hex SHA-256 over the
/// revision's canonical content ([`derive_revision_id`]). Transparent
/// newtype so the type system — not convention — keeps revision ids
/// distinct from candidate ids, memory addresses, and other digest
/// strings (the [`CandidateId`] precedent).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RevisionId(String);

impl RevisionId {
    /// The hex digest.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl From<String> for RevisionId {
    /// Wrap a digest the caller already trusts — rehydration from storage,
    /// a rollback's `to`. Minting ids from content is
    /// [`derive_revision_id`]'s job alone; nothing here re-verifies.
    fn from(digest: String) -> Self {
        Self(digest)
    }
}

/// One frozen pin: a registry surface bound to the candidate id that
/// served it in the revision's source environment at creation. The pin
/// names a *candidate* — content-addressed, immutable — so the pin set
/// can never drift beneath a recorded revision: what the gate evaluated
/// is what canaries, byte for byte.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegistryPin {
    /// The untagged registry surface (`prompt:system`,
    /// `model_settings:primary`, …). The environment the pin was resolved
    /// from travels once on the revision (`source_environment`), not on
    /// every pin.
    pub surface: SurfaceKey,

    /// The candidate the source environment's pointer served at creation.
    pub candidate_id: CandidateId,
}

/// What a revision binds: the content the address covers.
///
/// Struct serialization is field-ordered, so the canonical form is stable
/// across map backends — the same discipline
/// [`crate::learn::derive_candidate_id`] relies on. Attribution is not
/// identity (the [`crate::learn::Candidate`] rule): the author and the
/// creation instant travel on the record, outside the address, so two
/// registrations of the same declaration converge on one id.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionContent {
    /// The registered graph this revision serves (the `GraphRegistry`
    /// name — the run's admission target).
    pub graph: String,

    /// The graph's topology hash — exactly what
    /// [`crate::graph::Graph::topology_hash`] computes and the checkpoint
    /// header stamps. Code identity is the R0.7/R0.11 story, unchanged;
    /// the revision records it so admission can refuse a build the
    /// revision no longer describes.
    pub graph_hash: String,

    /// The assistant identity the revision binds, when the deployment
    /// serves through one. Absent when the revision binds the graph
    /// directly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assistant: Option<String>,

    /// The environment the pin set was resolved from at creation. A
    /// revision-refresh is a new revision resolved again from its source
    /// — the staleness of the freeze becomes a journaled act, never
    /// silent drift.
    pub source_environment: EnvironmentTag,

    /// The frozen pin set, sorted by surface (the canonical order — a
    /// set, so order is derivation, not declaration). May be empty: a
    /// graph that binds no registry artifacts pins nothing.
    pub pins: Vec<RegistryPin>,
}

/// The content address of a revision: `sha256` over the canonical
/// serialization of its content — the [`crate::learn::derive_candidate_id`]
/// discipline, so two registrations of the same declaration converge on
/// one id and a tampered revision fails its own address.
pub fn derive_revision_id(content: &RevisionContent) -> Result<RevisionId> {
    Ok(RevisionId(sha256_hex(&serde_json::to_vec(content)?)))
}

/// The digest a journaled [`DeploymentResolved`] names for the bound
/// revision's pin set: `sha256` over the canonical pin list. The
/// revision's own address already covers the pins — one derivation, two
/// homes — so the audit walk reads the pin-set commitment out of the
/// resolution event without fetching the revision.
pub fn pin_set_digest(pins: &[RegistryPin]) -> String {
    // Struct serialization is field-ordered (see `RevisionContent`), so
    // this digest is stable across map backends.
    let bytes = serde_json::to_vec(pins).expect("a pin list always serializes");
    sha256_hex(&bytes)
}

/// An immutable, content-addressed declaration of what may serve.
///
/// Immutable by construction: a changed declaration is a new id, and
/// there is no in-place update anywhere in the control plane. A registry
/// prompt promotion does not flow into an existing revision — the
/// revision-refresh path mints a new one addressing the delta, a
/// journaled act like any other.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentRevision {
    /// The content address ([`derive_revision_id`]).
    pub revision_id: RevisionId,

    /// What the revision binds.
    pub content: RevisionContent,

    /// Who registered the revision (`human:{id}`, the registry commit
    /// discipline). Mandatory — journaled with registration, because a
    /// deployment act that cannot name its author is indistinguishable
    /// from an untracked edit.
    pub author: ProvenanceAuthor,

    /// When the revision was registered.
    pub created_at: DateTime<Utc>,
}

impl DeploymentRevision {
    /// Mint a revision over `content`, attributed to `author`. The pin
    /// set is canonicalized here — sorted by surface, duplicate surfaces
    /// refused — so equal declarations converge on one address however
    /// the caller ordered them.
    pub fn new(
        mut content: RevisionContent,
        author: ProvenanceAuthor,
        created_at: DateTime<Utc>,
    ) -> std::result::Result<Self, DeployError> {
        if content.graph.is_empty() {
            return Err(DeployError::InvalidRevision {
                reason: "empty graph identity — a revision exists to name what serves",
            });
        }
        content.pins.sort_by(|a, b| a.surface.cmp(&b.surface));
        for pair in content.pins.windows(2) {
            if pair[0].surface == pair[1].surface {
                return Err(DeployError::DuplicatePin {
                    surface: pair[0].surface.clone(),
                });
            }
        }
        let revision_id = derive_revision_id(&content)
            .map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
        Ok(Self {
            revision_id,
            content,
            author,
            created_at,
        })
    }

    /// Re-derive the content address and compare. The integrity check the
    /// store read path and admission run before anything serves or pins —
    /// a revision failing its own address is tampered evidence, refused
    /// rather than journaled.
    pub fn verify_address(&self) -> std::result::Result<(), DeployError> {
        let derived = derive_revision_id(&self.content)
            .map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
        if derived != self.revision_id {
            return Err(DeployError::AddressMismatch {
                declared: self.revision_id.clone(),
                derived,
            });
        }
        Ok(())
    }
}

// --------------------------------------------------------------------- //
// The environment record
// --------------------------------------------------------------------- //

/// The gate declaration governing promotions into an environment: the
/// gate policy's name and the dataset version the gate replays. Names
/// only — the declaration, not the evaluator: the rule in force when a
/// promotion happens is data an audit reads, not code it infers. Wave 4
/// evaluates it through the [`RevisionGateEvaluator`] seam before any
/// pointer moves.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GateDeclaration {
    /// The gate policy's name (the `rusty-eval` `GatePolicy` the control
    /// plane will evaluate through the core seam, wave 4).
    pub policy: String,

    /// The recorded dataset version the gate replays the revision
    /// against. Versioned because datasets are immutable per version:
    /// re-running the gate must mean re-reading the same evidence.
    pub dataset_version: String,
}

/// An environment: R0.11's promotion tag as a first-class record.
///
/// Logical, not physical — one deployment serves every environment from
/// one store and one binary's admission path; the record exists so the
/// control plane can name the surface, declare its promotion rule, and
/// answer "which revision serves here" from journaled data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Environment {
    /// The environment's name — `dev` / `staging` / `prod` by
    /// deployment-declared convention, not an enum: the R0.11 tag set,
    /// promoted. Validated by [`EnvironmentTag`], so the pointer surface
    /// key (`deployment:{name}`) is always well-formed.
    pub name: EnvironmentTag,

    /// The gate declaration promotions into this environment must clear,
    /// when one is declared (enforced by the control plane since wave 4;
    /// recorded from the start). Absent: promotion is an operator act
    /// with no gate — the `dev` floor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gate: Option<GateDeclaration>,

    /// Whether promotions into this environment require a human approval
    /// token scoped to the revision's promotion effect id (enforced
    /// since wave 4; the `prod` stance). Recorded as data so the
    /// declaration is auditable before it is enforced.
    #[serde(default)]
    pub approval_required: bool,

    /// Who declared the environment (`human:{id}`).
    pub created_by: ProvenanceAuthor,

    /// When the environment was declared.
    pub created_at: DateTime<Utc>,
}

/// The pointer surface key for one environment: `deployment:{env}`. One
/// prefix for every deployment pointer, so pointer listings and the
/// canary draw's seed material read without string surgery.
pub fn deployment_surface(environment: &EnvironmentTag) -> SurfaceKey {
    SurfaceKey::new(format!("deployment:{environment}"))
}

// --------------------------------------------------------------------- //
// The deployment pointer
// --------------------------------------------------------------------- //

/// A canary binding on a deployment pointer: one revision bound to a
/// declared fraction of new runs while `active` serves the rest — the
/// [`crate::learn::CanaryBinding`] shape with a revision in the slot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryDeployment {
    /// The canaried revision.
    pub revision_id: RevisionId,

    /// The fraction of new runs the revision serves, in `(0, 1]`.
    pub fraction: f64,
}

impl CanaryDeployment {
    /// Declare a canary. Fractions outside `(0, 1]` are refused: zero
    /// binds nothing (a cleared slot says that), and above one is not a
    /// fraction.
    pub fn new(revision_id: RevisionId, fraction: f64) -> std::result::Result<Self, DeployError> {
        if !(fraction > 0.0 && fraction <= 1.0) {
            return Err(DeployError::InvalidFraction { fraction });
        }
        Ok(Self {
            revision_id,
            fraction,
        })
    }
}

/// The serving revision of one environment: an immutable-pointer move
/// away from any revision that ever served — the R0.8
/// [`crate::learn::VersionPointer`] shape applied to revisions.
///
/// New runs bind the pointer at admission (the canary by seeded draw —
/// [`deployment_admission`]); in-flight runs keep the revision their
/// journaled resolution names, the same conservatism as checkpoint
/// pinning. There is no hot reload: a hot-reloaded deployment is a
/// silent behavioral rewrite, forbidden since R0.8.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentPointer {
    /// The surface this pointer governs (`deployment:{env}`).
    pub surface: SurfaceKey,

    /// The full-traffic revision (`None`: the environment serves
    /// nothing — there is no implicit "latest", because latest is a
    /// guess with a deploy's blast radius).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<RevisionId>,

    /// The canary binding, when one is declared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canary: Option<CanaryDeployment>,
}

impl DeploymentPointer {
    /// A pointer with nothing serving.
    pub fn new(surface: SurfaceKey) -> Self {
        Self {
            surface,
            active: None,
            canary: None,
        }
    }

    /// The pointer after a promotion: `active` moves to the promoted
    /// revision and any canary clears — a full promotion supersedes the
    /// experiment it graduated from (the
    /// [`crate::learn::VersionPointer::promoted`] semantics).
    pub fn promoted(&self, promotion: &RevisionPromotion) -> DeploymentPointer {
        let mut next = self.clone();
        next.active = Some(promotion.revision_id.clone());
        next.canary = None;
        next
    }

    /// The pointer after a rollback: `active` re-points to the
    /// revision that served before — byte-exact, because revisions are
    /// content-addressed and immutable, so the restored revision is the
    /// one that served, not a reconstruction. A canary naming the rolled
    /// revision clears with it. The caller derives `to` from the
    /// journaled transition history before building the rollback — this
    /// is the move, not the check.
    pub fn rolled_back(&self, rollback: &RevisionRollback) -> DeploymentPointer {
        let mut next = self.clone();
        if self.active.as_ref() == Some(&rollback.from) {
            next.active = rollback.to.clone();
        }
        if self
            .canary
            .as_ref()
            .is_some_and(|canary| canary.revision_id == rollback.from)
        {
            next.canary = None;
        }
        next
    }
}

/// The revision an environment's pointer binds for `run_id`: the canary
/// when this run's seeded draw admits, else the full-traffic revision.
/// `None` when the pointer serves nothing — a pointer serving nothing
/// binds nothing, and admission refuses the run rather than guessing.
///
/// The draw reuses [`canary_admits`] verbatim: its seed material is the
/// bound id's string form, so wrapping the revision id as a one-off
/// [`CanaryBinding`] draws the identical seeded value the learn plane
/// would — a canary at staging and a canary at prod are independent
/// draws over the same run id (the surface is part of the seed), and a
/// recorded run re-derives its assignment from the journaled resolution
/// alone.
pub fn deployment_admission(
    pointer: &DeploymentPointer,
    run_id: &str,
) -> Option<(RevisionId, PointerBinding)> {
    if let Some(canary) = &pointer.canary {
        let binding = CanaryBinding {
            candidate_id: CandidateId::from(canary.revision_id.as_str().to_owned()),
            fraction: canary.fraction,
        };
        if canary_admits(&binding, &pointer.surface, run_id) {
            return Some((canary.revision_id.clone(), PointerBinding::Canary));
        }
    }
    pointer
        .active
        .clone()
        .map(|revision_id| (revision_id, PointerBinding::Active))
}

// --------------------------------------------------------------------- //
// The journaled control-plane acts
// --------------------------------------------------------------------- //

/// A revision was registered: the journaled payload of a
/// [`crate::record::RunEventKind::RevisionRegistered`] event on the
/// deployment evidence chain. The revision carries its own author and
/// content address; the tenant rides alongside because the chain is
/// deployment-wide (the [`crate::artifact::ArtifactRelease`] precedent —
/// audit metadata, not scoping).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionRegistration {
    /// The tenant the revision registered under.
    pub tenant: String,

    /// The registered revision.
    pub revision: DeploymentRevision,
}

/// An environment was declared: the journaled payload of a
/// [`crate::record::RunEventKind::EnvironmentDeclared`] event. The rule
/// in force journals with the declaration, so an audit reads the
/// declaration that governed a promotion, not a later edit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvironmentDeclaration {
    /// The tenant the environment was declared under.
    pub tenant: String,

    /// The declared environment.
    pub environment: Environment,
}

/// A revision was promoted into an environment: the journaled payload of
/// a [`crate::record::RunEventKind::RevisionPromoted`] event, and the
/// move [`DeploymentPointer::promoted`] applies. `previous` is recorded
/// because it is the rollback path's whole story: the transition history
/// on the chain is what a byte-exact rollback re-derives, never a
/// reconstruction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionPromotion {
    /// The tenant the promotion governs.
    pub tenant: String,

    /// The environment promoted into.
    pub environment: EnvironmentTag,

    /// The revision that now serves full traffic.
    pub revision_id: RevisionId,

    /// The revision the promotion displaced (`None` when the environment
    /// served nothing before).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<RevisionId>,

    /// Who promoted (`human:{id}` — a deployment act with a name on it).
    pub author: ProvenanceAuthor,

    /// When the promotion journaled.
    pub promoted_at: DateTime<Utc>,
}

/// A serving revision was rolled back: the journaled payload of a
/// [`crate::record::RunEventKind::RevisionRolledBack`] event, and the
/// move [`DeploymentPointer::rolled_back`] applies. Byte-exact by
/// construction: `to` is derived from the chain's transition history —
/// the immutable revision that served before — so the restored serving
/// state is a fact about what happened, not a guess at what should.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionRollback {
    /// The tenant the rollback governs.
    pub tenant: String,

    /// The environment rolling back.
    pub environment: EnvironmentTag,

    /// The revision that was serving.
    pub from: RevisionId,

    /// The previously serving revision, re-derived from the journaled
    /// transition history (`None`: the environment returns to serving
    /// nothing — the state before its first promotion).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub to: Option<RevisionId>,

    /// Why the rollback happened — the operator's note, the incident id.
    pub cause: String,

    /// Who rolled back (`human:{id}`).
    pub author: ProvenanceAuthor,

    /// When the rollback journaled.
    pub rolled_back_at: DateTime<Utc>,
}

/// The journaled admission resolution (R0.12 wave 3): the output of a
/// [`crate::record::RunEventKind::DeploymentResolved`] event, journaled
/// at admission into the run's own journal — the
/// [`crate::registry::ConfigResolution`] precedent lifted from
/// configuration to deployments.
///
/// The walk it closes: the run's signed receipt commits the journal head;
/// this event names the environment, the bound `revision_id`, and the
/// pointer slot; the revision addresses the frozen pin set; the pins name
/// candidates; the candidates carry their authors and promotions. Every
/// hop is signature-covered — this event sits inside the journal the
/// receipt's head signs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentResolved {
    /// The environment the run was admitted to.
    pub environment: EnvironmentTag,

    /// The revision the environment's pointer bound — reproducible at
    /// audit from this id alone (revisions are content-addressed: the id
    /// *is* the integrity check).
    pub revision_id: RevisionId,

    /// Which pointer slot admitted the revision (the full-traffic
    /// `active`, or the `canary` when this run's seeded draw admitted).
    pub pointer: PointerBinding,

    /// The digest of the bound revision's frozen pin set
    /// ([`pin_set_digest`]) — the pin-set commitment, readable without
    /// fetching the revision.
    pub pin_set_digest: String,
}

// --------------------------------------------------------------------- //
// Environment-scoped secrets
// --------------------------------------------------------------------- //

/// The longest an environment-secret name may be. Names ride in scoped
/// keys (`{name}@{environment}`), journal payloads, and store primary
/// keys, so a bound keeps a configuration typo from minting an unbounded
/// key.
pub const MAX_SECRET_NAME_LEN: usize = 128;

/// The scoped id of an environment secret: `{name}@{environment}` — the
/// scope is part of the secret's identity, so the staging database URL
/// and the prod database URL are two secrets that can never be
/// interchangeable. The sealed envelope authenticates this id as
/// associated data, so a ciphertext transplanted between scopes fails to
/// open.
pub fn scoped_secret_name(name: &str, environment: &EnvironmentTag) -> String {
    format!("{name}@{environment}")
}

/// The secret naming rules, enforced at set time: non-empty, bounded
/// ([`MAX_SECRET_NAME_LEN`]), no leading or trailing whitespace, no
/// control characters, no `@` (the scope separator — a name carrying it
/// would make scoped ids ambiguous), and no `/` (the tenant id-prefix
/// separator). The registry artifact naming rule, applied to secrets.
pub fn validate_secret_name(name: &str) -> std::result::Result<(), DeployError> {
    let refuse = |reason: &'static str| DeployError::InvalidSecretName {
        name: name.to_owned(),
        reason,
    };
    if name.is_empty() {
        return Err(refuse("empty — a secret exists to be named"));
    }
    if name.len() > MAX_SECRET_NAME_LEN {
        return Err(refuse("over 128 bytes"));
    }
    if name != name.trim() {
        return Err(refuse(
            "leading or trailing whitespace — visually identical names would be distinct \
             secrets, which is a misreview waiting to happen",
        ));
    }
    if name.chars().any(|c| c.is_control() || c == '@' || c == '/') {
        return Err(refuse(
            "carries a control character, `@`, or `/` — the scope separator and the tenant \
             separator are structural, and control characters have no business in a key",
        ));
    }
    Ok(())
}

/// The public record of one environment secret: metadata by
/// construction, safe to serve and journal. Rotation is replacement
/// beneath the stable scoped name — what a run's evidence pins is the
/// scoped name, not the value of the moment (the broker's "rotate a
/// credential without redeploying" argument applied to static material).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretRecord {
    /// The secret's name within its scope.
    pub name: String,

    /// The environment the secret is scoped to. Enforcement, not
    /// convention: resolution serves `name@{environment}` and nothing
    /// else.
    pub environment: EnvironmentTag,

    /// Who set (or last rotated) the secret (`human:{id}`).
    pub set_by: ProvenanceAuthor,

    /// When the secret was first set.
    pub created_at: DateTime<Utc>,

    /// When the secret was last rotated beneath the stable scoped name.
    /// Absent when never rotated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rotated_at: Option<DateTime<Utc>>,
}

/// What both store backends hold for one environment secret: the
/// metadata record plus the sealed value. Plaintext on neither backend,
/// ever — a Postgres dump of this row contains no secret (the broker's
/// custody shape, verbatim).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredEnvSecret {
    /// The metadata record (safe to serve and journal).
    pub record: EnvSecretRecord,

    /// The sealed value — the broker's envelope construction with the
    /// scoped secret id as associated data.
    pub envelope: SealedCredential,
}

/// A secret was set or rotated: the journaled payload of an
/// [`crate::record::RunEventKind::EnvSecretSet`] event on the deployment
/// evidence chain. Metadata only — the bytes live only in the sealed
/// envelope and can never appear here.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretAct {
    /// The tenant the secret serves.
    pub tenant: String,

    /// The secret's metadata after the act (`rotated_at` marks a
    /// rotation beneath the stable scoped name).
    pub record: EnvSecretRecord,
}

/// A secret was revoked by deletion: the journaled payload of an
/// [`crate::record::RunEventKind::EnvSecretRevoked`] event. Deletion is
/// the only revocation path — there is no disable flag to forget, and
/// the tombstone is the evidence the scope once held a value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretRevocation {
    /// The tenant the secret served.
    pub tenant: String,

    /// The revoked secret's name.
    pub name: String,

    /// The environment the secret was scoped to.
    pub environment: EnvironmentTag,

    /// Who revoked it (`human:{id}`).
    pub revoked_by: ProvenanceAuthor,

    /// When the revocation journaled.
    pub revoked_at: DateTime<Utc>,
}

/// A secret resolution was refused on scope: the journaled payload of an
/// [`crate::record::RunEventKind::EnvSecretDenied`] event — the
/// [`crate::capsule::CapsuleDenial`] discipline (attributable to a
/// declaration, not a stack trace) applied to environment scope. Names
/// the scope requested and the scope the holder holds, because the
/// difference between the two is exactly what a scope audit reads.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretDenial {
    /// The tenant the request ran under.
    pub tenant: String,

    /// The secret's name.
    pub name: String,

    /// The environment scope the request asked for.
    pub requested_environment: EnvironmentTag,

    /// The environment scope the requester holds — the admission
    /// environment the resolution runs under.
    pub held_environment: EnvironmentTag,

    /// When the refusal journaled.
    pub denied_at: DateTime<Utc>,
}

// --------------------------------------------------------------------- //
// Errors
// --------------------------------------------------------------------- //

/// The deployment plane's typed refusals. A refused declaration, move,
/// or resolution changes nothing — the [`crate::learn::LearnError`]
/// discipline: refused operations are contract outcomes surfaced to the
/// caller, never silent no-ops.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum DeployError {
    /// A revision declaration outside the construction rules.
    #[error("invalid revision: {reason}")]
    InvalidRevision {
        /// The rule it broke.
        reason: &'static str,
    },

    /// A pin set naming one surface twice — a set, not a bag.
    #[error(
        "pin set names surface `{surface}` twice — a revision pins one candidate per surface; \
         a second naming is a configuration error, not a second pin"
    )]
    DuplicatePin {
        /// The doubly pinned surface.
        surface: SurfaceKey,
    },

    /// A revision's content could not be serialized for addressing —
    /// unreachable for well-formed content, surfaced rather than
    /// panicked (the `UndiffableContent` precedent).
    #[error("revision content could not be addressed: {0}")]
    UnaddressableContent(String),

    /// A stored revision fails its own content address.
    #[error(
        "revision declares id `{declared}` but its content addresses to `{derived}` — \
         tampered evidence; refused, never served"
    )]
    AddressMismatch {
        /// The id the record carried.
        declared: RevisionId,
        /// The id its content derives.
        derived: RevisionId,
    },

    /// A canary fraction outside `(0, 1]`.
    #[error(
        "canary fraction {fraction} is outside (0, 1] — zero binds nothing (a cleared slot \
         says that), and above one is not a fraction"
    )]
    InvalidFraction {
        /// The refused fraction.
        fraction: f64,
    },

    /// A secret name outside the naming rules (see
    /// [`validate_secret_name`]).
    #[error("invalid secret name {name:?}: {reason}")]
    InvalidSecretName {
        /// The refused name.
        name: String,
        /// The rule it broke.
        reason: &'static str,
    },
}

// --------------------------------------------------------------------- //
// Wave 4: the release gate
// --------------------------------------------------------------------- //

/// One gate check, journaled: the core mirror of `rusty-eval`'s
/// `GateCheck`, serde-mapped at the seam so the runtime never links the
/// eval crate (the workspace's dependency direction is `rusty-eval` →
/// runtime, never the reverse — the
/// [`crate::learn::EvaluationThresholds`] precedent). `metric` is the
/// eval metric's own serde form (`snake_case`-tagged), carried as a
/// string so a new eval metric needs no core release to journal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateCheckRecord {
    /// The check's metric, in `rusty-eval`'s serde form.
    pub metric: String,

    /// Whether the check passed.
    pub passed: bool,

    /// What the candidate measured.
    pub observed: Value,

    /// What the policy required.
    pub required: Value,

    /// The check's explanation — the journaled why, so an audit reads
    /// the refusal without re-running the gate.
    pub detail: String,
}

/// A gate's verdict. Two states and no third: a gate that cannot say
/// `allow` says `block` — unevaluable comparisons fail closed (the
/// `ComparisonAvailable` precedent in `rusty-eval`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GateVerdict {
    /// Every check passed; the promotion may proceed.
    Allow,

    /// At least one check failed — or the gate could not be evaluated;
    /// the promotion is refused.
    Block,
}

/// The gate evaluation the [`RevisionGateEvaluator`] seam returns: the
/// verdict and every check behind it, naming the policy and dataset
/// version it ran under. The seam's contract requires the evaluator to
/// name back the declaration it was handed — an evaluation that cannot
/// say what it evaluated is not evidence about this promotion.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateEvaluation {
    /// The policy the evaluation ran (must equal the declaration's).
    pub policy: String,

    /// The dataset version the evaluation replayed (must equal the
    /// declaration's).
    pub dataset_version: String,

    /// The verdict.
    pub outcome: GateVerdict,

    /// Every check the verdict stands on.
    pub checks: Vec<GateCheckRecord>,
}

impl GateEvaluation {
    /// Whether the promotion may proceed: the verdict allows **and**
    /// every check passed. The conjunction is deliberate — a verdict
    /// and its checks disagreeing is a broken evaluator, and a broken
    /// evaluator fails closed.
    pub fn allowed(&self) -> bool {
        self.outcome == GateVerdict::Allow && self.checks.iter().all(|check| check.passed)
    }
}

/// A gate decision, journaled: the payload of a
/// [`crate::record::RunEventKind::GateDecisionRecorded`] event on the
/// deployment evidence chain. The decision journals before the pointer
/// move it governs — and journals when it *refuses*, so the chain holds
/// the gate's refusals, not only its permissions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateDecisionRecord {
    /// The tenant the decision governs.
    pub tenant: String,

    /// The gated environment.
    pub environment: EnvironmentTag,

    /// The revision the gate evaluated.
    pub revision_id: RevisionId,

    /// The revision the gate compared against — the environment's
    /// serving revision at decision time (`None`: nothing served, so
    /// comparative checks ran baseline-less and failed closed where the
    /// policy needed a comparison).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub baseline_revision_id: Option<RevisionId>,

    /// The policy the gate ran — the declaration's, echoed.
    pub policy: String,

    /// The dataset version the gate replayed — the declaration's,
    /// echoed.
    pub dataset_version: String,

    /// The verdict.
    pub outcome: GateVerdict,

    /// Every check the verdict stands on.
    pub checks: Vec<GateCheckRecord>,

    /// When the gate decided.
    pub decided_at: DateTime<Utc>,
}

/// The release-gate seam: core owns the contract, the server composes
/// the evaluator over `rusty-eval` (the [`crate::learn::CandidateEvaluator`]
/// precedent — the runtime declares what a gate must answer; the
/// composition that answers it lives one crate out, where the eval
/// dependency is allowed).
///
/// The contract: `baseline` is the environment's serving revision at
/// decision time (`None` when nothing serves); the returned evaluation
/// **must** name `gate.policy` and `gate.dataset_version` back — the
/// control plane refuses an evaluation that cannot say what it
/// evaluated. Errors are refusals of the evaluation itself (the dataset
/// is unreadable, the policy unknown); the control plane fails closed
/// on one — a gate that could not run is a gate that did not pass.
#[async_trait]
pub trait RevisionGateEvaluator: Send + Sync + std::fmt::Debug {
    /// Evaluate `revision` against `gate`, comparing against `baseline`
    /// when one serves.
    async fn evaluate(
        &self,
        revision: &DeploymentRevision,
        baseline: Option<&DeploymentRevision>,
        gate: &GateDeclaration,
    ) -> Result<GateEvaluation>;
}

/// The effect kind a revision promotion is admitted under: distinct
/// from the learn plane's `candidate_promotion`, because the acts are
/// distinct — promoting a candidate changes what the registry *points
/// at*; promoting a revision changes what an environment *serves*.
pub const REVISION_PROMOTION_EFFECT_KIND: &str = "revision_promotion";

/// The promotion effect id for a revision into an environment: the
/// approval-token scope for approval-required environments, derived by
/// the [`crate::learn::promotion_effect_id`] rule over the deployment
/// surface. Scoped to the revision's own content address, so a token
/// minted for one revision admits no other — an approval is a fact
/// about a specific deploy, not a standing permission.
pub fn revision_promotion_effect_id(
    environment: &EnvironmentTag,
    revision: &DeploymentRevision,
) -> EffectId {
    derive_effect_id(
        deployment_surface(environment).as_str(),
        REVISION_PROMOTION_EFFECT_KIND,
        revision.revision_id.as_str(),
        Some(&format!("promotion:{}", revision.revision_id.as_str())),
    )
}

// --------------------------------------------------------------------- //
// Wave 4: canary acts
// --------------------------------------------------------------------- //

/// A canary was declared on an environment's pointer: the journaled
/// payload of a [`crate::record::RunEventKind::CanaryDeclared`] event,
/// and the move [`DeploymentPointer::canaried`] applies. The binding
/// journals whole — revision and fraction — because the seeded draw an
/// audit replays is a function of exactly these fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryDeclaration {
    /// The tenant the canary governs.
    pub tenant: String,

    /// The environment canarying.
    pub environment: EnvironmentTag,

    /// The canaried revision.
    pub revision_id: RevisionId,

    /// The fraction of new runs the revision serves.
    pub fraction: f64,

    /// Who declared the canary (`human:{id}`).
    pub author: ProvenanceAuthor,

    /// When the canary journaled.
    pub declared_at: DateTime<Utc>,
}

/// A canary was cleared without graduating: the journaled payload of a
/// [`crate::record::RunEventKind::CanaryCleared`] event, and the move
/// [`DeploymentPointer::cleared_canary`] applies. Naming the cleared
/// revision is the point — a bare "slot emptied" would leave the
/// experiment's end unattributable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryClearance {
    /// The tenant the clearance governs.
    pub tenant: String,

    /// The environment clearing its canary.
    pub environment: EnvironmentTag,

    /// The revision the canary slot held.
    pub cleared_revision_id: RevisionId,

    /// Who cleared the canary (`human:{id}`).
    pub author: ProvenanceAuthor,

    /// When the clearance journaled.
    pub cleared_at: DateTime<Utc>,
}

impl DeploymentPointer {
    /// The pointer after a canary declaration: the canary slot binds the
    /// revision and `active` keeps serving the rest — a canary is an
    /// experiment alongside the serving revision, not a move of it.
    pub fn canaried(&self, declaration: &CanaryDeclaration) -> DeploymentPointer {
        let mut next = self.clone();
        next.canary = Some(CanaryDeployment {
            revision_id: declaration.revision_id.clone(),
            fraction: declaration.fraction,
        });
        next
    }

    /// The pointer after a canary clearance: the slot empties and
    /// `active` serves everything again.
    pub fn cleared_canary(&self) -> DeploymentPointer {
        let mut next = self.clone();
        next.canary = None;
        next
    }
}

// --------------------------------------------------------------------- //
// Wave 4: shadow runs
// --------------------------------------------------------------------- //

/// A shadow run started: the journaled payload of a
/// [`crate::record::RunEventKind::ShadowRunStarted`] event in the shadow
/// run's own journal. Naming the source run and pinning
/// `role: shadow` makes the twin-pair discipline data the journal
/// carries: the shadow's evidence names what it shadows, and its role
/// can never be confused with the acting twin's.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShadowRunStarted {
    /// The tenant the shadow runs under.
    pub tenant: String,

    /// The shadow run's id.
    pub shadow_run_id: String,

    /// The recorded run this shadow replays.
    pub source_run_id: String,

    /// The candidate revision under test.
    pub revision_id: RevisionId,

    /// The decision role — always [`DecisionRole::Shadow`]; pinned in
    /// the payload so the discipline survives any caller.
    pub role: DecisionRole,

    /// Who launched the shadow (`human:{id}`).
    pub author: ProvenanceAuthor,

    /// When the shadow started.
    pub started_at: DateTime<Utc>,
}

/// How a shadow run ended.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ShadowRunOutcome {
    /// The graph ran to completion behind the shadow boundary.
    Completed,

    /// The run failed — a graph error, not an admission refusal
    /// (refusals are the shadow's normal path, journaled as they
    /// happen). The verdict still journals: a failed shadow is evidence
    /// about the candidate, not a run to sweep away.
    Failed {
        /// The executor's error, surfaced verbatim.
        error: String,
    },
}

/// A shadow run's verdict: the journaled payload of a
/// [`crate::record::RunEventKind::ShadowVerdict`] event, and the answer
/// the shadow exists to give — what the candidate tried to do to the
/// world, what the recorded world served back, and where the candidate
/// diverged from the run it shadows.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShadowVerdict {
    /// The tenant the shadow ran under.
    pub tenant: String,

    /// The shadow run's id.
    pub shadow_run_id: String,

    /// The recorded run this shadow replayed.
    pub source_run_id: String,

    /// The candidate revision under test.
    pub revision_id: RevisionId,

    /// Every effect the boundary refused, journaled served-or-not as it
    /// happened — the shadow's reason to exist, verbatim.
    pub refusals: Vec<ShadowRefusal>,

    /// How many refused calls were served from the recorded world.
    pub matched: usize,

    /// How many refused calls the recorded world could not serve — the
    /// candidate asked for something its source never did.
    pub unserved: usize,

    /// Recorded effect kinds with calls the candidate never requested —
    /// divergence in the other direction, evidence the candidate does
    /// *less* than the run it shadows.
    pub unrequested: Vec<String>,

    /// How the run ended.
    pub outcome: ShadowRunOutcome,

    /// When the verdict journaled.
    pub completed_at: DateTime<Utc>,
}

// --------------------------------------------------------------------- //
// Tests
// --------------------------------------------------------------------- //

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Serialize;
    use std::path::PathBuf;

    // ---------- golden-file machinery (the artifact.rs discipline) ----------
    //
    // Asserted here (unit tests beside the contracts) so the golden
    // fixtures under `tests/golden/` pin the new wire shapes without the
    // wave touching another test file. `UPDATE_GOLDEN=1` blesses an
    // intentional change — the diff is then the contract change under
    // review.

    fn golden_path(name: &str) -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("golden")
            .join(name)
    }

    fn assert_golden(name: &str, value: &impl Serialize) {
        let rendered = format!("{}\n", serde_json::to_string_pretty(value).unwrap());
        let path = golden_path(name);
        if std::env::var_os("UPDATE_GOLDEN").is_some() {
            std::fs::write(&path, &rendered).unwrap();
            return;
        }
        let expected = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("missing golden file `{}`: {e}", path.display()));
        assert_eq!(
            rendered,
            expected,
            "contract drift in `{}` — if intentional, re-run with UPDATE_GOLDEN=1 \
             and review the diff",
            path.display()
        );
    }

    fn ts(millis: i64) -> DateTime<Utc> {
        DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
    }

    fn author() -> ProvenanceAuthor {
        ProvenanceAuthor::Human {
            human_id: "amjad".into(),
        }
    }

    fn tag(name: &str) -> EnvironmentTag {
        EnvironmentTag::new(name).unwrap()
    }

    fn candidate_id(seed: char) -> CandidateId {
        CandidateId::from(seed.to_string().repeat(64))
    }

    fn revision(seed: char) -> DeploymentRevision {
        DeploymentRevision::new(
            RevisionContent {
                graph: "pipeline".into(),
                graph_hash: "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
                    .into(),
                assistant: Some("support-agent".into()),
                source_environment: tag("staging"),
                pins: vec![
                    RegistryPin {
                        surface: SurfaceKey::new("model_settings:primary"),
                        candidate_id: candidate_id(seed),
                    },
                    RegistryPin {
                        surface: SurfaceKey::new("prompt:system"),
                        candidate_id: candidate_id('p'),
                    },
                ],
            },
            author(),
            ts(1_760_000_000_000),
        )
        .unwrap()
    }

    // ---------- construction and identity ----------

    #[test]
    fn content_addressing_converges_and_ignores_attribution() {
        // Identity is integrity: equal declarations converge on one id,
        // however they are ordered and whoever registers them — the pin
        // set sorts at construction, and the author lives outside the
        // address.
        let first = revision('a');
        let mut shuffled = first.content.clone();
        shuffled.pins.reverse();
        let second = DeploymentRevision::new(
            shuffled,
            ProvenanceAuthor::Human {
                human_id: "someone-else".into(),
            },
            ts(1_760_000_999_000),
        )
        .unwrap();
        assert_eq!(first.revision_id, second.revision_id);
        assert_ne!(first.author, second.author, "attribution is not identity");
        first.verify_address().unwrap();
    }

    #[test]
    fn a_changed_declaration_is_a_new_id() {
        let changed = DeploymentRevision::new(
            RevisionContent {
                graph_hash: "0".repeat(64),
                ..revision('a').content
            },
            author(),
            ts(1_760_000_000_000),
        )
        .unwrap();
        assert_ne!(changed.revision_id, revision('a').revision_id);
    }

    #[test]
    fn duplicate_pins_and_empty_graphs_are_refused() {
        let dup = DeploymentRevision::new(
            RevisionContent {
                pins: vec![
                    RegistryPin {
                        surface: SurfaceKey::new("prompt:system"),
                        candidate_id: candidate_id('a'),
                    },
                    RegistryPin {
                        surface: SurfaceKey::new("prompt:system"),
                        candidate_id: candidate_id('b'),
                    },
                ],
                ..revision('a').content
            },
            author(),
            ts(1_760_000_000_000),
        );
        assert!(
            matches!(dup, Err(DeployError::DuplicatePin { .. })),
            "one surface pins one candidate"
        );
        let empty = DeploymentRevision::new(
            RevisionContent {
                graph: String::new(),
                ..revision('a').content
            },
            author(),
            ts(1_760_000_000_000),
        );
        assert!(matches!(empty, Err(DeployError::InvalidRevision { .. })));
    }

    #[test]
    fn verify_address_refuses_tampering() {
        let mut tampered = revision('a');
        tampered.content.graph_hash = "f".repeat(64);
        assert!(matches!(
            tampered.verify_address(),
            Err(DeployError::AddressMismatch { .. })
        ));
    }

    // ---------- the pointer moves ----------

    #[test]
    fn promotion_moves_active_and_clears_the_canary() {
        let surface = deployment_surface(&tag("prod"));
        let mut pointer = DeploymentPointer::new(surface.clone());
        pointer.active = Some(RevisionId::from("a".repeat(64)));
        pointer.canary =
            Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
        let promotion = RevisionPromotion {
            tenant: "default".into(),
            environment: tag("prod"),
            revision_id: RevisionId::from("b".repeat(64)),
            previous: pointer.active.clone(),
            author: author(),
            promoted_at: ts(1_760_000_100_000),
        };
        let moved = pointer.promoted(&promotion);
        assert_eq!(moved.active, Some(RevisionId::from("b".repeat(64))));
        assert_eq!(
            moved.canary, None,
            "a full promotion supersedes its experiment"
        );
    }

    #[test]
    fn rollback_repoints_byte_exact() {
        let surface = deployment_surface(&tag("prod"));
        let mut pointer = DeploymentPointer::new(surface);
        pointer.active = Some(RevisionId::from("b".repeat(64)));
        let rollback = RevisionRollback {
            tenant: "default".into(),
            environment: tag("prod"),
            from: RevisionId::from("b".repeat(64)),
            to: Some(RevisionId::from("a".repeat(64))),
            cause: "error rate".into(),
            author: author(),
            rolled_back_at: ts(1_760_000_200_000),
        };
        let moved = pointer.rolled_back(&rollback);
        assert_eq!(
            moved.active,
            Some(RevisionId::from("a".repeat(64))),
            "the restored revision is the one that served, not a reconstruction"
        );
        // Rolling back a revision the pointer does not serve moves nothing.
        let stray = pointer.rolled_back(&RevisionRollback {
            from: RevisionId::from("c".repeat(64)),
            ..rollback
        });
        assert_eq!(stray, pointer);
    }

    #[test]
    fn canary_fraction_bounds_are_enforced() {
        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 0.0).is_err());
        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.0).is_ok());
        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.1).is_err());
    }

    #[test]
    fn the_canary_draw_is_seeded_and_reproducible() {
        // A recorded run re-derives its assignment from the pointer alone:
        // one draw over the same (surface, revision, run) triple, every
        // time; a different surface (staging vs prod) is an independent
        // draw.
        let revision = RevisionId::from("a".repeat(64));
        let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
        pointer.active = Some(RevisionId::from("f".repeat(64)));
        pointer.canary = Some(CanaryDeployment::new(revision.clone(), 0.5).unwrap());
        let first = deployment_admission(&pointer, "run-1");
        let second = deployment_admission(&pointer, "run-1");
        assert_eq!(
            first, second,
            "the draw is a pure function of journaled facts"
        );
        let prod_pointer =
            DeploymentPointer::new(deployment_surface(&tag("prod"))).promoted(&RevisionPromotion {
                tenant: "default".into(),
                environment: tag("prod"),
                revision_id: RevisionId::from("f".repeat(64)),
                previous: None,
                author: author(),
                promoted_at: ts(1_760_000_000_000),
            });
        let mut prod_with_canary = prod_pointer;
        prod_with_canary.canary = Some(CanaryDeployment::new(revision, 0.5).unwrap());
        // Not asserting inequality (the draws could coincide); asserting
        // the mechanism: both answers come from their own surface's seed.
        assert!(deployment_admission(&prod_with_canary, "run-1").is_some());
        // A pointer serving nothing binds nothing.
        let empty = DeploymentPointer::new(deployment_surface(&tag("dev")));
        assert_eq!(deployment_admission(&empty, "run-1"), None);
    }

    #[test]
    fn secret_names_follow_the_registry_naming_rule() {
        assert!(validate_secret_name("database-url").is_ok());
        assert!(validate_secret_name("").is_err());
        assert!(
            validate_secret_name("db@prod").is_err(),
            "the scope separator is structural"
        );
        assert!(
            validate_secret_name("a/b").is_err(),
            "the tenant separator is structural"
        );
        assert_eq!(
            scoped_secret_name("database-url", &tag("staging")),
            "database-url@staging"
        );
    }

    // ---------- goldens ----------

    #[test]
    fn golden_deployment_event_kinds_shape() {
        // The plane's additive RunEventKind wire names (the
        // `artifact_event_kinds.json` discipline): pinned so no wire
        // shape lands unpinned — declared in wire order, appended after
        // wave 2's retention acts.
        use crate::record::RunEventKind;
        assert_golden(
            "deployment_event_kinds.json",
            &vec![
                RunEventKind::DeploymentResolved,
                RunEventKind::RevisionRegistered,
                RunEventKind::RevisionPromoted,
                RunEventKind::RevisionRolledBack,
                RunEventKind::EnvironmentDeclared,
                RunEventKind::EnvSecretSet,
                RunEventKind::EnvSecretRevoked,
                RunEventKind::EnvSecretDenied,
            ],
        );
    }

    #[test]
    fn golden_deployment_revision_shape() {
        assert_golden("deployment_revision.json", &revision('a'));
    }

    #[test]
    fn golden_environment_shape() {
        let environment = Environment {
            name: tag("prod"),
            gate: Some(GateDeclaration {
                policy: "r0.12-default".into(),
                dataset_version: "support-v3".into(),
            }),
            approval_required: true,
            created_by: author(),
            created_at: ts(1_760_000_000_000),
        };
        assert_golden("environment.json", &environment);
    }

    #[test]
    fn golden_deployment_pointer_shape() {
        // The full shape: both slots bound — active plus a 10% canary.
        let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
        pointer.active = Some(RevisionId::from("a".repeat(64)));
        pointer.canary =
            Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
        assert_golden("deployment_pointer.json", &pointer);
    }

    #[test]
    fn golden_deployment_resolved_shape() {
        // The journaled resolution: a run admitted to staging under the
        // canary slot, naming the bound revision and the pin-set digest.
        let resolved = DeploymentResolved {
            environment: tag("staging"),
            revision_id: revision('a').revision_id,
            pointer: PointerBinding::Canary,
            pin_set_digest: pin_set_digest(&revision('a').content.pins),
        };
        assert_golden("deployment_resolved.json", &resolved);
    }

    #[test]
    fn golden_revision_registration_shape() {
        assert_golden(
            "revision_registration.json",
            &RevisionRegistration {
                tenant: "default".into(),
                revision: revision('a'),
            },
        );
    }

    #[test]
    fn golden_environment_declaration_shape() {
        assert_golden(
            "environment_declaration.json",
            &EnvironmentDeclaration {
                tenant: "default".into(),
                environment: Environment {
                    name: tag("dev"),
                    gate: None,
                    approval_required: false,
                    created_by: author(),
                    created_at: ts(1_760_000_000_000),
                },
            },
        );
    }

    #[test]
    fn golden_revision_promotion_shape() {
        assert_golden(
            "revision_promotion.json",
            &RevisionPromotion {
                tenant: "default".into(),
                environment: tag("prod"),
                revision_id: revision('a').revision_id,
                previous: Some(RevisionId::from("f".repeat(64))),
                author: author(),
                promoted_at: ts(1_760_000_100_000),
            },
        );
    }

    #[test]
    fn golden_revision_rollback_shape() {
        assert_golden(
            "revision_rollback.json",
            &RevisionRollback {
                tenant: "default".into(),
                environment: tag("prod"),
                from: revision('a').revision_id,
                to: Some(RevisionId::from("f".repeat(64))),
                cause: "canary regression".into(),
                author: author(),
                rolled_back_at: ts(1_760_000_200_000),
            },
        );
    }

    #[test]
    fn golden_env_secret_record_shape() {
        assert_golden(
            "env_secret_record.json",
            &EnvSecretRecord {
                name: "database-url".into(),
                environment: tag("staging"),
                set_by: author(),
                created_at: ts(1_760_000_000_000),
                rotated_at: Some(ts(1_760_000_500_000)),
            },
        );
    }

    #[test]
    fn golden_stored_env_secret_shape() {
        // The custody shape: metadata plus the sealed envelope — hex
        // ciphertext fields, never bytes (fixed vectors pin the wire).
        assert_golden(
            "stored_env_secret.json",
            &StoredEnvSecret {
                record: EnvSecretRecord {
                    name: "database-url".into(),
                    environment: tag("prod"),
                    set_by: author(),
                    created_at: ts(1_760_000_000_000),
                    rotated_at: None,
                },
                envelope: SealedCredential {
                    format_version: 1,
                    key_id: "esk-0123456789abcdef".into(),
                    wrapped_data_key: "aa".repeat(48),
                    wrap_nonce: "bb".repeat(24),
                    nonce: "cc".repeat(24),
                    ciphertext: "dd".repeat(80),
                    sealed_at: ts(1_760_000_000_000),
                },
            },
        );
    }

    #[test]
    fn golden_env_secret_denial_shape() {
        assert_golden(
            "env_secret_denial.json",
            &EnvSecretDenial {
                tenant: "default".into(),
                name: "database-url".into(),
                requested_environment: tag("prod"),
                held_environment: tag("staging"),
                denied_at: ts(1_760_000_300_000),
            },
        );
    }

    // ---------- wave 4: gates, canary acts, shadows ----------

    fn gate_evaluation(outcome: GateVerdict, checks: Vec<GateCheckRecord>) -> GateEvaluation {
        GateEvaluation {
            policy: "r0.12-default".into(),
            dataset_version: "support-v3".into(),
            outcome,
            checks,
        }
    }

    fn passing_check() -> GateCheckRecord {
        GateCheckRecord {
            metric: "\"pass_rate\"".into(),
            passed: true,
            observed: serde_json::json!(0.91),
            required: serde_json::json!(0.85),
            detail: "pass rate clears the floor".into(),
        }
    }

    #[test]
    fn the_gate_allows_only_when_verdict_and_every_check_agree() {
        // Fail-closed twice over: a blocked verdict refuses however the
        // checks read, and an allow verdict with one failing check
        // refuses too — a verdict and its checks disagreeing is a broken
        // evaluator, and a broken evaluator does not ship revisions.
        assert!(gate_evaluation(GateVerdict::Allow, vec![passing_check()]).allowed());
        assert!(!gate_evaluation(GateVerdict::Block, vec![passing_check()]).allowed());
        let mut failing = passing_check();
        failing.passed = false;
        assert!(!gate_evaluation(GateVerdict::Allow, vec![passing_check(), failing]).allowed());
    }

    #[test]
    fn canary_moves_keep_the_active_revision_serving() {
        // Declare: the canary slot binds, active keeps serving the rest.
        // Clear: the slot empties, active is untouched. Promotion still
        // supersedes the experiment it graduated from (wave 3 semantics,
        // unchanged).
        let pointer = DeploymentPointer {
            canary: None,
            ..DeploymentPointer::new(deployment_surface(&tag("staging")))
        };
        let declaration = CanaryDeclaration {
            tenant: "default".into(),
            environment: tag("staging"),
            revision_id: revision('b').revision_id.clone(),
            fraction: 0.1,
            author: author(),
            declared_at: ts(1_760_000_100_000),
        };
        let canaried = pointer.canaried(&declaration);
        assert_eq!(
            canaried.canary,
            Some(CanaryDeployment {
                revision_id: revision('b').revision_id.clone(),
                fraction: 0.1,
            })
        );
        assert_eq!(
            canaried.active, pointer.active,
            "a canary moves nothing serving"
        );
        let cleared = canaried.cleared_canary();
        assert_eq!(cleared, pointer, "clearing restores the pre-canary pointer");
    }

    #[test]
    fn the_revision_promotion_effect_id_is_scoped_to_the_revision() {
        // Deterministic for one revision into one environment; different
        // for any other revision or any other environment — a token
        // minted for this deploy admits no other.
        let rev = revision('a');
        let staging = tag("staging");
        let id = revision_promotion_effect_id(&staging, &rev);
        assert_eq!(id, revision_promotion_effect_id(&staging, &rev));
        assert_ne!(
            id,
            revision_promotion_effect_id(&staging, &revision('b')),
            "another revision is another approval"
        );
        assert_ne!(
            id,
            revision_promotion_effect_id(&tag("prod"), &rev),
            "another environment is another approval"
        );
    }

    fn gate_decision_record() -> GateDecisionRecord {
        GateDecisionRecord {
            tenant: "default".into(),
            environment: tag("staging"),
            revision_id: revision('b').revision_id.clone(),
            baseline_revision_id: Some(revision('a').revision_id.clone()),
            policy: "r0.12-default".into(),
            dataset_version: "support-v3".into(),
            outcome: GateVerdict::Allow,
            checks: vec![passing_check()],
            decided_at: ts(1_760_000_200_000),
        }
    }

    fn shadow_refusal() -> ShadowRefusal {
        ShadowRefusal {
            kind: "charge".into(),
            effect: crate::record::Effect::NonIdempotent,
            effect_id: derive_effect_id(
                "shadow-run-1",
                "charge",
                &sha256_hex(b"{\"tool\":\"charge\"}"),
                Some("shadow-run-1:7"),
            ),
            input_hash: sha256_hex(b"{\"tool\":\"charge\"}"),
            served: true,
        }
    }

    #[test]
    fn golden_gate_event_kinds_shape() {
        // Wave 4's additive RunEventKind wire names, pinned beside wave
        // 3's (`deployment_event_kinds.json`) — appended after
        // `EnvSecretDenied`, in wire order.
        use crate::record::RunEventKind;
        assert_golden(
            "deployment_gate_event_kinds.json",
            &vec![
                RunEventKind::GateDecisionRecorded,
                RunEventKind::CanaryDeclared,
                RunEventKind::CanaryCleared,
                RunEventKind::ShadowRunStarted,
                RunEventKind::ShadowEffectRefused,
                RunEventKind::ShadowVerdict,
            ],
        );
    }

    #[test]
    fn golden_gate_decision_record_shape() {
        assert_golden("gate_decision_record.json", &gate_decision_record());
    }

    #[test]
    fn golden_canary_declaration_shape() {
        assert_golden(
            "canary_declaration.json",
            &CanaryDeclaration {
                tenant: "default".into(),
                environment: tag("staging"),
                revision_id: revision('b').revision_id.clone(),
                fraction: 0.1,
                author: author(),
                declared_at: ts(1_760_000_100_000),
            },
        );
    }

    #[test]
    fn golden_canary_clearance_shape() {
        assert_golden(
            "canary_clearance.json",
            &CanaryClearance {
                tenant: "default".into(),
                environment: tag("staging"),
                cleared_revision_id: revision('b').revision_id.clone(),
                author: author(),
                cleared_at: ts(1_760_000_400_000),
            },
        );
    }

    #[test]
    fn golden_shadow_run_started_shape() {
        assert_golden(
            "shadow_run_started.json",
            &ShadowRunStarted {
                tenant: "default".into(),
                shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
                source_run_id: "run-1".into(),
                revision_id: revision('b').revision_id.clone(),
                role: DecisionRole::Shadow,
                author: author(),
                started_at: ts(1_760_000_500_000),
            },
        );
    }

    #[test]
    fn golden_shadow_effect_refusal_shape() {
        assert_golden("shadow_effect_refusal.json", &shadow_refusal());
    }

    #[test]
    fn golden_shadow_verdict_shape() {
        assert_golden(
            "shadow_verdict.json",
            &ShadowVerdict {
                tenant: "default".into(),
                shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
                source_run_id: "run-1".into(),
                revision_id: revision('b').revision_id.clone(),
                refusals: vec![shadow_refusal()],
                matched: 1,
                unserved: 0,
                unrequested: vec!["lookup".into()],
                outcome: ShadowRunOutcome::Completed,
                completed_at: ts(1_760_000_600_000),
            },
        );
    }
}