tatara-process 0.2.488

Process CRD — K8s clusters, workloads, migrations, tests as Unix processes in the tatara convergence lattice
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
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
//! `EphemeralAllocation` CRD — a typed request for a pool member.
//!
//! Pairs with `EphemeralPool`: an Allocation is the request side;
//! the pool reconciler answers it by matching one of its free
//! Process members and stamping the requestor's identity on the
//! Allocation's status.
//!
//! Topology:
//! - The requestor (GitHub PR webhook, CI runner, operator running
//!   `feira allocation request …`) creates an `EphemeralAllocation`.
//! - The pool reconciler watches Allocations; matches `spec.poolRef`
//!   (or routes via PoolSelector if `poolRef` is omitted) to a pool;
//!   picks one Free member; transitions the member to Allocated and
//!   the Allocation to Bound.
//! - When the requestor is done, it deletes the Allocation. The pool
//!   reconciler honors the pool's `returnPolicy` (Reset / Replace /
//!   Keep).

use chrono::{DateTime, Utc};
use kube::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::pool::AllocationRef;

/// `EphemeralAllocation` CRD spec — a typed request for a pool member.
///
/// ```yaml
/// apiVersion: tatara.pleme.io/v1alpha1
/// kind: EphemeralAllocation
/// metadata:
///   name: pr-123-demo-app
///   namespace: ephemeral-pools
/// spec:
///   poolRef:
///     name: attest-pool
///     namespace: ephemeral-pools
///   requestor:
///     kind: github-pr
///     repo: "pleme-io/demo-app"
///     branch: "fix-something"
///     prNumber: 123
///     prLabels: ["needs-ephemeral"]
///   ttl: "1h"
/// ```
#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[kube(
    group = "tatara.pleme.io",
    version = "v1alpha1",
    kind = "EphemeralAllocation",
    plural = "ephemeralallocations",
    shortname = "ealloc",
    namespaced,
    status = "AllocationStatus",
    printcolumn = r#"{"name":"Pool","type":"string","jsonPath":".spec.poolRef.name"}"#,
    printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
    printcolumn = r#"{"name":"Process","type":"string","jsonPath":".status.assignedProcess.name"}"#,
    printcolumn = r#"{"name":"Requestor","type":"string","jsonPath":".spec.requestor.kind"}"#,
    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
)]
#[serde(rename_all = "camelCase")]
pub struct AllocationSpec {
    /// Direct pool reference. When set, skip selector-based routing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pool_ref: Option<AllocationRef>,

    /// Who is asking for the env.
    pub requestor: Requestor,

    /// How long the requestor needs the env (`humantime`). The pool
    /// reconciler clamps this to `pool.spec.maxAllocationTtl`.
    /// When unset, falls back to the pool's `template.ttl`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,

    /// Operator-supplied notes — surfaced in `feira allocation list`
    /// for audit / debugging context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// Identity + routing context for a request.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Requestor {
    /// Discriminator: `"github-pr"`, `"manual"`, `"ci-run"`,
    /// `"scheduled"`, … The wire shape is open by design — operators
    /// may register their own kinds and the [`crate::pool::PoolSelector`]
    /// matches on raw string equality. The substrate's own emitters
    /// stamp one of the four canonical kebab-case kinds enumerated by
    /// [`RequestorKind::ALL`]; [`Requestor::known_kind`] projects the
    /// open wire field through that closed-set view at ONE site so
    /// future kind-keyed consumers (pool dashboards, completion lists,
    /// audit-trail classifiers) sweep the typed variants without
    /// re-implementing `match self.kind.as_str()` arm-by-arm. Sibling
    /// shape to [`crate::receipt::ReceiptEnvelope::known_kind`].
    pub kind: String,

    /// Optional repo identifier (e.g., `"pleme-io/demo-app"`).
    /// Matched against `PoolSelector.repos`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo: Option<String>,

    /// Optional branch name. Matched against `PoolSelector.branches`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,

    /// Optional PR number (for `kind: github-pr`). Surfaces in
    /// printcolumns + audit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pr_number: Option<u64>,

    /// Optional commit SHA (for `kind: github-pr` or `ci-run`).
    /// Stamped onto the allocated Process for traceability.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha: Option<String>,

    /// PR / commit labels — matched as a subset against
    /// `PoolSelector.prLabels`.
    #[serde(default)]
    pub pr_labels: Vec<String>,

    /// Free-form actor — username, CI runner ID, etc.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
}

impl Requestor {
    /// Decode [`Self::kind`] into the typed [`RequestorKind`] variant
    /// when the wire string matches one of the four substrate-emitted
    /// canonical kebab-case kinds; `None` when the kind is an
    /// operator-registered open string (the schema is open by design —
    /// every allocation remains a valid allocation, but only typed
    /// kinds participate in closed-set dispatch). The (open `String`,
    /// closed-typed view) split lets future kind-keyed consumers
    /// (pool-selector classifiers, dashboard completion, audit-trail
    /// classifiers) sweep the typed variants without touching the
    /// open-by-design wire shape. Lifted as the canonical decode site
    /// so no consumer re-implements the `match self.kind.as_str()` arm-
    /// by-arm — the closed-set sweep happens through
    /// [`RequestorKind::from_str`] at ONE site. Sibling shape to
    /// [`crate::receipt::ReceiptEnvelope::known_kind`].
    #[must_use]
    pub fn known_kind(&self) -> Option<RequestorKind> {
        self.kind.parse().ok()
    }
}

/// Closed-set view over the substrate-emitted canonical
/// [`Requestor::kind`] wire strings — the four kebab-case
/// discriminators every pleme-io requestor stamps onto an
/// [`EphemeralAllocation`]: `github-pr` (the [`tatara_github_watcher`-
/// authored](../../tatara-github-watcher/src/allocation_factory.rs)
/// PR-driven path), `manual` (operator-authored via `feira allocation
/// request …`), `ci-run` (non-PR CI driver), and `scheduled` (a
/// cron-style emitter). The wire field stays `pub kind: String` on
/// [`Requestor`] so operators can register their own kinds without a
/// schema bump; this enum is the typed view future kind-keyed
/// consumers (pool dashboards, LSP completion, audit-trail
/// classifiers) sweep against.
///
/// Pre-lift the four canonical kinds existed only as `&'static str`
/// literals at four scattered sites — the documentation header on
/// [`Requestor::kind`], the [`crate::pool::PoolSelector::kinds`]
/// docstring, the `tatara-github-watcher` allocation factory, and the
/// per-test `kind: "github-pr".into()` fixtures. A rename of one
/// canonical kind (e.g. `"github-pr"` → `"github-pull-request"`) had
/// no compile-time link to the others, so the documentation drifted
/// independently of the emitter, and the [`PoolSelector::matches`]
/// kind-filter silently kept matching the old spelling forever. Post-
/// lift the (canonical-name, typed-variant) pairing binds at ONE site
/// ([`Self::as_str`]); the `From<RequestorKind> for String` bridge
/// lets emitters compose `Requestor { kind: RequestorKind::GithubPr.into(), … }`
/// so the four canonical strings stop appearing as bare `&'static str`
/// literals at author sites.
///
/// Adding a fifth kind (e.g. `Slack` → `"slack"`, `Webhook` →
/// `"webhook"`) lands at one [`Self::ALL`] entry + one [`Self::as_str`]
/// arm — exhaustively checked by the compiler (the `[Self; 4]` array
/// literal forces the arity) AND by the per-variant truth-table tests
/// below.
///
/// Sibling closed-set `ALL`-keyed lifts across the crate:
/// [`crate::receipt::ReceiptKind::ALL`] (the four substrate-emitted
/// receipt kinds — direct shape peer, same open-wire + closed-view
/// split), [`AllocationPhase::ALL`], [`crate::phase::ProcessPhase::ALL`],
/// [`crate::signal::ProcessSignal::ALL`],
/// [`crate::boundary::ConditionKind::ALL`],
/// [`crate::lifetime::TeardownPolicy::ALL`],
/// [`crate::lifetime::LifetimeKind::ALL`],
/// [`crate::intent::IntentKind::ALL`],
/// [`crate::lifetime_clock::TerminateReasonKind::ALL`].
///
/// Theory anchor: THEORY.md §III — the typescape; the substrate's own
/// requestor kinds become a TYPE rather than four `&'static str`
/// literals at every author + docstring + fixture site. THEORY.md
/// §V.1 — knowable platform; the closed-set view turns "which kinds
/// does the substrate actually emit" from a grep job into a method
/// the compiler enforces exhaustively at every dispatch site.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
#[closed_set(via = "as_str", generate_unknown, display)]
pub enum RequestorKind {
    /// GitHub pull-request webhook — `tatara-github-watcher` stamps
    /// this on every allocation built from a `PullRequestEvent`.
    GithubPr,
    /// Operator-authored allocation — `feira allocation request …`
    /// and any hand-crafted CR.
    Manual,
    /// Non-PR CI driver — a pipeline run that wants an ephemeral env
    /// without an associated pull request.
    CiRun,
    /// Cron-style scheduled emitter — periodic allocation creation
    /// (e.g. nightly drift detection).
    Scheduled,
}

impl RequestorKind {
    /// The closed set of substrate-emitted requestor kinds — single
    /// source of truth that drives the [`Self::from_str`] decode sweep
    /// AND any future enumeration consumer (pool-selector classifiers,
    /// dashboard completion, `tatara-check` kind enumeration). Adding
    /// a fifth variant (e.g. `Slack` → `"slack"`) lands at one `ALL`
    /// entry + one `as_str` arm — exhaustively checked by the compiler
    /// (the `[Self; 4]` array literal forces the arity) AND by the
    /// per-variant truth-table tests below.
    pub const ALL: [Self; 4] = [Self::GithubPr, Self::Manual, Self::CiRun, Self::Scheduled];

    /// Canonical kebab-case wire-format kind — the literal that lands
    /// in [`Requestor::kind`] when this variant authors the request.
    /// Pinned to four byte-exact strings the substrate has already
    /// published (the `tatara-github-watcher` factory, the operator
    /// fixtures in this file, the `PoolSelector.kinds` filter, the
    /// CRD printcolumns) — renaming any one is a wire-format change,
    /// not a typed-internal refactor, and the
    /// `requestor_kind_canonical_names_pinned` truth-table test fails
    /// first to keep the substrate honest. Used by [`std::fmt::Display`]
    /// (single source of truth) and as the `String` projection that
    /// `From<RequestorKind> for String` ([`Self::into`]) composes so
    /// emitters can spell `Requestor { kind: RequestorKind::GithubPr.into(), … }`
    /// without re-typing the canonical literal at every author site.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GithubPr => "github-pr",
            Self::Manual => "manual",
            Self::CiRun => "ci-run",
            Self::Scheduled => "scheduled",
        }
    }
}

// `impl FromStr for RequestorKind` + `impl tatara_lisp::ClosedSet for
// RequestorKind` + `impl std::fmt::Display for RequestorKind` are
// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
// declaration above. `label` delegates to the inherent
// `RequestorKind::as_str` via `#[closed_set(via = "as_str")]` so the
// kebab-case wire-format projection stays load-bearing (matches the
// `tatara-github-watcher` factory + the CRD printcolumns + the
// `PoolSelector.kinds` filter verbatim) while generic `T: ClosedSet`
// consumers reach the STABLE workspace-wide name (`label`). The
// `display` flag emits the `f.write_str(self.as_str())` delegation
// block — the substrate-wide closed-set-enum idiom's third piece —
// at the same proc-macro site rather than a hand-rolled
// `fmt::Display` block per implementor.

// `pub struct UnknownRequestorKind(pub String)` is generated by
// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
// on the enum declaration above. The auto-derived label `"requestor kind"`
// matches the prior hand-rolled `#[error("unknown requestor kind: {0}")]`
// verbatim — pinned generically by clause (5) of
// `tatara_closed_set::assert_closed_set_well_formed::<RequestorKind>()` (called
// from `requestor_kind_is_well_formed_closed_set` in the test module).
// Symmetric to every sibling `Unknown*` error in this crate (e.g.
// [`UnknownAllocationPhase`], [`crate::receipt::UnknownReceiptKind`],
// [`crate::phase::UnknownPhase`], [`crate::lifetime::UnknownTeardownPolicy`]).

impl From<RequestorKind> for String {
    /// Composes [`RequestorKind::as_str`] into an owned `String` so
    /// every `impl Into<String>` API surface (the `kind:` field
    /// initializer on [`Requestor`] most notably) accepts the typed
    /// variant transparently — the call site stays
    /// `kind: RequestorKind::GithubPr.into()` and the typed → wire
    /// bridge runs through ONE place. Sibling shape to
    /// [`crate::receipt::ReceiptKind`]'s `From for String`.
    fn from(k: RequestorKind) -> Self {
        k.as_str().to_owned()
    }
}

impl From<RequestorKind> for &'static str {
    fn from(k: RequestorKind) -> Self {
        k.as_str()
    }
}

/// `EphemeralAllocation.status` — observed allocation state.
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AllocationStatus {
    /// Current lifecycle phase.
    #[serde(default)]
    pub phase: AllocationPhase,

    /// When the phase last changed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase_since: Option<DateTime<Utc>>,

    /// Pool that owns the matched member. Set as soon as routing
    /// resolves; not cleared on release (audit trail).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bound_pool: Option<AllocationRef>,

    /// The Process backing this allocation, if Bound.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assigned_process: Option<AllocationRef>,

    /// When the allocation was matched to a Process.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allocated_at: Option<DateTime<Utc>>,

    /// Wall-clock expiry derived from `spec.ttl` + `allocated_at`.
    /// The pool reconciler force-returns the member at this point.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,

    /// Operator-visible message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,

    /// Standard Conditions.
    ///
    /// The empty case is skipped at serialization so a merge-patch
    /// body built from a caller-supplied [`AllocationStatus`] whose
    /// `conditions` slot has not been touched does NOT emit
    /// `"conditions": []` on the wire — under RFC-7396 JSON Merge
    /// Patch (the shape `Patch::Merge` sends) an empty array
    /// REPLACES the persisted list rather than merges into it, so a
    /// controller round-trip that reused a scratch `AllocationStatus`
    /// as a patch body would silently clobber whatever conditions the
    /// prior status carried. Peer to `phase_since` /
    /// `bound_pool` / `assigned_process` / `allocated_at` /
    /// `expires_at` above, each already skip-serialized on its
    /// [`Default`]-equivalent variant.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub conditions: Vec<AllocationCondition>,
}

impl AllocationStatus {
    /// Substrate composer for a phase-transition [`AllocationStatus`]
    /// seed: stamps the THREE always-present slots (`phase` +
    /// `phase_since = Some(now)` + `message = Some(<supplied>)`) and
    /// defaults every other slot (`bound_pool` / `assigned_process` /
    /// `allocated_at` / `expires_at` = `None`, `conditions = vec![]`).
    /// Caller-branches attach the extra slots via struct-update
    /// syntax onto the seed.
    ///
    /// Pre-lift the 4-slot phase-transition seed
    /// ```rust,ignore
    /// json!({
    ///     "status": {
    ///         "phase": <AllocationPhase-variant>,
    ///         "phaseSince": Utc::now(),
    ///         "message": "<transition-reason>",
    ///         …optional caller-attached slots…
    ///     }
    /// })
    /// ```
    /// was hand-authored at FOUR sites past the ★★ PRIME-DIRECTIVE
    /// ≥ 2 duplication threshold in
    /// `tatara-pool-reconciler::controller_allocation::reconcile_inner`,
    /// each restating the SAME `phase + phase_since + message` invariant
    /// triplet on a different [`AllocationPhase`] variant:
    /// * `AllocationDecision::NoMatchingPool` — the "no Pool selector
    ///   matched this Requestor" fallthrough
    ///   ([`AllocationPhase::NoMatchingPool`]).
    /// * `AllocationDecision::Wait` — the "pool matched; no Free member
    ///   available" queued path
    ///   ([`AllocationPhase::Queued`]) with a `bound_pool` addition.
    /// * `AllocationDecision::Bind` — the "bound to pool member"
    ///   allocation path ([`AllocationPhase::Bound`]) with
    ///   `bound_pool` + `assigned_process` + `allocated_at` +
    ///   `expires_at` additions.
    /// * `AllocationDecision::Release` — the "released; pool reconciler
    ///   will return the member" release path
    ///   ([`AllocationPhase::Released`]) with `bound_pool` +
    ///   `assigned_process` additions.
    ///
    /// All four hand-authored the SAME `phaseSince: Utc::now()` stamp
    /// alongside the phase transition, and all four spelled the
    /// invariant triplet as bare JSON keys inside a `json!({...})`
    /// literal — a fragile shape where any drift in the underlying
    /// [`AllocationStatus`] field naming (a rename from `phaseSince`
    /// to `phase_since` at the serde surface, a promotion of `message`
    /// to a structured envelope) silently stops the JSON keys from
    /// mapping to the typed struct's fields and the K8s API server
    /// merges an ill-shaped patch. Post-lift the four callers build a
    /// typed [`AllocationStatus`] via `AllocationStatus::transition`,
    /// attach any branch-specific slots via struct-update syntax, and
    /// wrap the result in `json!({ "status": s })` — the serde
    /// `rename_all = "camelCase"` derive on [`AllocationStatus`] owns
    /// the wire-shape composition, so a field rename lands at ONE
    /// site (the derive) and every emit site inherits the upgrade
    /// mechanically.
    ///
    /// Cross-CRD peer to [`crate::pool::PoolStatus::observed`] on the
    /// same `<CRD>Status` substrate-composer axis — both primitives
    /// stamp `phase_since = Some(now)` from a caller-supplied `now`
    /// timestamp so the composer stays clock-injectable rather than
    /// implicitly reading wall time, and both close every optional slot
    /// with its [`Default`]-equivalent variant so a future slot
    /// addition on either status shape plugs into the composer at ONE
    /// site and every downstream emit site inherits the new slot
    /// mechanically.
    ///
    /// Cross-CRD peer to the `tatara-reconciler::patch::phase_status_msg`
    /// primitive on the (CRD × phase-transition-with-message) axis —
    /// both primitives own the three-slot `phase + phase_since +
    /// message` invariant on their respective CRDs' status subresource,
    /// and both accept `impl Into<String>` for the message so the
    /// callsite carries `&'static str` literal reasons and
    /// `format!(...)`-owned strings without widening the signature.
    ///
    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
    /// the 4-slot phase-transition status-seed incantation recurred at
    /// four hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
    /// duplication trigger, and is lifted to ONE owner here).
    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
    /// the pins bind the three always-present slots + the
    /// [`Default`]-defaulted rest + byte-identical parity with the
    /// pre-lift `json!({...})` triplet through serde round-trip, so a
    /// regression that drifted any surface at
    /// `tests::allocation_status_transition_*` rather than as silent
    /// operator-visible skew between the four allocation-decision
    /// patch sites).
    #[must_use]
    pub fn transition(
        phase: AllocationPhase,
        message: impl Into<String>,
        now: DateTime<Utc>,
    ) -> Self {
        Self {
            phase,
            phase_since: Some(now),
            message: Some(message.into()),
            ..Default::default()
        }
    }

    /// Substrate composer for a phase-transition [`AllocationStatus`]
    /// seed whose `bound_pool` + `assigned_process` axis-pair is
    /// stamped alongside the base [`Self::transition`] triplet
    /// (`phase` + `phase_since = Some(now)` + `message =
    /// Some(<supplied>)`). Every other slot lands at its
    /// [`Default`]-equivalent variant so a caller-branch that attaches
    /// an optional slot via struct-update syntax (a `Bind` arm's
    /// `allocated_at` / `expires_at` addenda, say) does not silently
    /// inherit a pre-populated non-`None` value.
    ///
    /// Pre-lift the `bound_pool: Some(pool)` + `assigned_process:
    /// Some(AllocationRef::new(name, ns))` pair rode struct-update
    /// syntax onto [`Self::transition`] at TWO sites past the ★★
    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
    /// `tatara-pool-reconciler::controller_allocation::reconcile_inner`
    /// — the `AllocationDecision::Bind` arm ([`AllocationPhase::Bound`]
    /// with two extra `allocated_at` / `expires_at` addenda) and the
    /// `AllocationDecision::Release` arm ([`AllocationPhase::Released`]
    /// with no addenda). Both restated the SAME pair-of-`Some`-slot
    /// invariant against the SAME struct-update seed and funneled the
    /// resulting body through the SAME `patch_status` call on
    /// `Api<EphemeralAllocation>`. Post-lift both callers reach the
    /// pair through ONE substrate composer; a future normalization on
    /// the bound-set axis (a symmetry gate that the assigned_process's
    /// namespace matches the bound_pool's namespace, a canonicalization
    /// that closes the pair against a stale audit record, a
    /// backwards-compatibility rename of either slot at the serde
    /// surface) lands at ONE substrate site rather than at each
    /// callsite in the two-arm allocation reconciler.
    ///
    /// Composes atop [`Self::transition`] so any future evolution to
    /// the base three-slot invariant triplet (a `phase_since` rename,
    /// a `message` promotion to a structured envelope, a fourth
    /// always-stamped diagnostic slot) reaches this composer through
    /// ONE substrate site and both consumers inherit the upgrade
    /// mechanically. Sibling composition discipline to
    /// [`crate::pool::PoolStatus::observed`]'s `state_count_fanout` +
    /// `Utc::now()` fold — the compound composer names its axis + calls
    /// the substrate primitive on the invariant it wraps rather than
    /// restating the wrapped shape inline.
    ///
    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
    /// the `bound_pool + assigned_process` pair recurred at two hand-
    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
    /// invariant 5 (composition preserves proofs — the pins bind the
    /// pair + the composed base triplet + byte-identical parity with
    /// the pre-lift struct-update shape through serde round-trip, so a
    /// regression that drifted any surface at
    /// `tests::allocation_status_bound_transition_*` rather than as
    /// silent operator-visible skew between the two Bind / Release
    /// patch sites).
    #[must_use]
    pub fn bound_transition(
        phase: AllocationPhase,
        message: impl Into<String>,
        now: DateTime<Utc>,
        bound_pool: AllocationRef,
        assigned_process: AllocationRef,
    ) -> Self {
        Self {
            bound_pool: Some(bound_pool),
            assigned_process: Some(assigned_process),
            ..Self::transition(phase, message, now)
        }
    }
}

/// Allocation lifecycle phase.
///
/// Sibling closed-set lifts on the same `EphemeralAllocation` /
/// `EphemeralPool` axis: [`crate::pool::ReplacementPolicy::ALL`],
/// [`crate::pool::ReturnPolicy::ALL`]. Sibling closed-sets on the
/// `tatara-process` algebra: [`crate::lifetime::TeardownPolicy::ALL`],
/// [`crate::lifetime::LifetimeKind::ALL`],
/// [`crate::boundary::ConditionKind::ALL`],
/// [`crate::intent::IntentKind::ALL`],
/// [`crate::phase::ProcessPhase::ALL`],
/// [`crate::signal::ProcessSignal::ALL`].
#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    JsonSchema,
    tatara_closed_set::DeriveClosedSet,
)]
#[serde(rename_all = "PascalCase")]
#[closed_set(via = "as_str", generate_unknown, display)]
pub enum AllocationPhase {
    /// Admitted; pool selector matching not yet attempted.
    Pending,
    /// Routed to a pool but no `Free` member is available — queued.
    Queued,
    /// A pool member has been assigned + transitioned to Allocated.
    Bound,
    /// `expires_at` reached or requestor deleted; member is returning.
    Releasing,
    /// Released; the allocation is a permanent audit record.
    Released,
    /// No pool selector matched. The reconciler will retry on each
    /// pool spec update; surfaced in status so operators see why.
    NoMatchingPool,
    /// Pool refused (e.g., `max_size` reached and no member can be
    /// freed) — operator intervention needed.
    Failed,
}

impl Default for AllocationPhase {
    fn default() -> Self {
        Self::Pending
    }
}

impl AllocationPhase {
    /// The closed set of allocation phases — single source of truth
    /// that drives the `as_str` / Display / `FromStr` triad AND the
    /// `is_terminal` / `needs_pool_routing` predicate pair the
    /// allocation reconciler's observe/decide split dispatches on.
    /// Adding an eighth variant lands at one `ALL` entry + one
    /// `as_str` arm + one arm per predicate — exhaustively checked by
    /// the compiler (the `[Self; 7]` array literal forces the arity)
    /// and by the implication test
    /// (`allocation_phase_terminal_excludes_routing`) so a new
    /// variant can't claim to be both terminal AND routing-eligible.
    pub const ALL: [Self; 7] = [
        Self::Pending,
        Self::Queued,
        Self::Bound,
        Self::Releasing,
        Self::Released,
        Self::NoMatchingPool,
        Self::Failed,
    ];

    /// Canonical PascalCase wire-format projection — matches the
    /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
    /// `enum:` enumeration the allocation reconciler stamps on the
    /// `ephemeralallocations.tatara.pleme.io` schema. Pinned by
    /// `allocation_phase_as_str_matches_serde` so a variant rename
    /// can't drift between the typed surface, the CRD enum, the YAML
    /// wire format AND any operator-facing diagnostic composed via
    /// Display rather than a hard-coded literal that would silently
    /// rot.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "Pending",
            Self::Queued => "Queued",
            Self::Bound => "Bound",
            Self::Releasing => "Releasing",
            Self::Released => "Released",
            Self::NoMatchingPool => "NoMatchingPool",
            Self::Failed => "Failed",
        }
    }

    /// True iff the allocation has reached an absorbing state —
    /// `Released` (clean audit record) or `Failed` (pool refused;
    /// operator intervention needed). The allocation reconciler
    /// short-circuits both phases to `NoOp` rather than re-running
    /// the routing / heartbeat ladder against a settled record.
    ///
    /// Closed-set match (not `matches!`) so a future variant
    /// triggers the compiler's exhaustiveness check at this site
    /// rather than silently defaulting to `false` and letting a new
    /// terminal phase fall through into pool rebinding. Paired with
    /// `needs_pool_routing` they form the two-axis projection
    /// `allocation_decide::AllocationConvergence::decide` matches
    /// against — the impossible bucket `(true, true)` is pinned
    /// empty by `allocation_phase_terminal_excludes_routing`.
    pub const fn is_terminal(self) -> bool {
        match self {
            Self::Released | Self::Failed => true,
            Self::Pending | Self::Queued | Self::Bound | Self::Releasing | Self::NoMatchingPool => {
                false
            }
        }
    }

    /// True iff the allocation is on the routing path — the
    /// reconciler still needs to resolve a target pool + look up a
    /// free member. `Pending` (just admitted), `Queued` (matched
    /// pool was full last tick), and `NoMatchingPool` (no selector
    /// matched yet; retry on pool spec updates) all live here. The
    /// settled non-terminal phases `Bound` (already matched) and
    /// `Releasing` (being torn down) don't — they short-circuit to
    /// the heartbeat / release ladder without re-resolving the pool.
    ///
    /// Closed-set match (not `matches!`) — same exhaustiveness
    /// discipline as [`Self::is_terminal`]. Lifts the open-coded
    /// `phase != Released && phase != Bound` gate that
    /// `allocation_decide::AllocationConvergenceCtx::observe` used
    /// to predicate pool resolution on, AND closes the latent gap
    /// where `Failed` / `Releasing` (neither `Released` nor `Bound`)
    /// would slip through to the routing branch — a `Failed`
    /// allocation without a deletion timestamp could be silently
    /// rebound to a fresh pool member, which is the opposite of
    /// "operator intervention needed."
    pub const fn needs_pool_routing(self) -> bool {
        match self {
            Self::Pending | Self::Queued | Self::NoMatchingPool => true,
            Self::Bound | Self::Releasing | Self::Released | Self::Failed => false,
        }
    }
}

// `impl FromStr for AllocationPhase` + `impl tatara_lisp::ClosedSet for
// AllocationPhase` + `impl std::fmt::Display for AllocationPhase` are
// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
// declaration above. `label` delegates to the inherent
// `AllocationPhase::as_str` via `#[closed_set(via = "as_str")]` so the
// PascalCase wire-format projection stays load-bearing (matches the serde
// rename + the CRD `enum:` enumeration the allocation reconciler stamps
// on the `ephemeralallocations.tatara.pleme.io` schema verbatim) while
// generic `T: ClosedSet` consumers reach the STABLE workspace-wide name
// (`label`). The `display` flag emits the `f.write_str(self.as_str())`
// delegation block at the same proc-macro site rather than a
// hand-rolled `fmt::Display` block per implementor.

// `pub struct UnknownAllocationPhase(pub String)` is generated by
// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
// on the enum declaration above. The auto-derived label `"allocation phase"`
// matches the prior hand-rolled `#[error("unknown allocation phase: {0}")]`
// verbatim — pinned generically by clause (5) of
// `tatara_closed_set::assert_closed_set_well_formed::<AllocationPhase>()` (called
// from `allocation_phase_is_well_formed_closed_set` in the test module).
// Symmetric to [`crate::pool::UnknownReplacementPolicy`],
// [`crate::pool::UnknownReturnPolicy`],
// [`crate::lifetime::UnknownTeardownPolicy`],
// [`crate::boundary::UnknownConditionKind`], and
// [`crate::phase::UnknownPhase`].

/// Allocation Condition (same shape as PoolCondition for downstream
/// uniformity).
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AllocationCondition {
    pub type_: String,
    pub status: String,
    pub reason: String,
    pub message: String,
    pub last_transition_time: DateTime<Utc>,
}

impl EphemeralAllocation {
    /// The copy-form status-projection primitive on the phase axis:
    /// returns the [`AllocationPhase`] the pool reconciler currently
    /// persists at `status.phase`, wrapped in an `Option` so the
    /// missing-`status` corner collapses to `None` — the ONE-liner
    /// collapse of the paired `self.status.as_ref().map(|s| s.phase)`
    /// incantation the pool reconciler's `AllocationConvergenceCtx::
    /// observe` restated by hand pre-lift.
    ///
    /// Cross-CRD peer to [`crate::prelude::Process::observed_phase`]
    /// on the (CRD × phase-slot × observed-status) axis pair — both
    /// primitives walk the identical `.status.as_ref().map(|s| s.
    /// phase)` shape, differing only in the `Phase` type projected
    /// ([`AllocationPhase`] vs [`crate::phase::ProcessPhase`]). The
    /// substrate now owns the borrow-form `.status.as_ref().map(|s|
    /// s.phase)` chain axis-uniformly across the two `Phase`-having
    /// CRDs so a future normalization (a generation-filter that
    /// returns `None` for a phase stamped with a stale
    /// `metadata.generation`, a staleness gate that drops a phase
    /// whose observing `phase_since` predates a reconcile deadline,
    /// a canonicalization pass that maps a phase outside the CRD's
    /// closed set to `None`) lands at ONE substrate method per CRD
    /// rather than being restated at every observer.
    #[must_use]
    pub fn observed_phase(&self) -> Option<AllocationPhase> {
        self.status.as_ref().map(|s| s.phase)
    }

    /// The copy-form status-projection primitive on the phase axis
    /// with the [`AllocationPhase::Pending`] sink applied — the
    /// ONE-liner collapse of the paired `self.observed_phase().
    /// unwrap_or(AllocationPhase::Pending)` incantation the pool
    /// reconciler's `AllocationConvergenceCtx::observe` restated by
    /// hand pre-lift as a 5-line `.status.as_ref().map(|s| s.phase).
    /// unwrap_or(AllocationPhase::Pending)` chain.
    ///
    /// Pre-lift the chain sat at [`tatara-pool-reconciler::
    /// allocation_decide::AllocationConvergenceCtx::observe`]'s
    /// `phase` seed. Cross-CRD peer to [`crate::prelude::Process::
    /// observed_phase_or_pending`] on the (CRD × phase-slot × sink)
    /// axis pair — both primitives close the missing-`status`
    /// corner with each CRD's respective [`Default`]-equivalent
    /// `Pending` variant, and both compose on top of their peer
    /// [`Self::observed_phase`] / [`crate::prelude::Process::
    /// observed_phase`] borrow-form projections so a future
    /// normalization at the underlying `observed_phase` primitive
    /// reaches both the raw-`Option` accessor and the `Pending`-
    /// sinked composer through the SAME upstream body.
    ///
    /// The [`AllocationPhase::Pending`] sink is load-bearing as the
    /// "not yet observed" default — the pool reconciler's typed
    /// `AllocationPhase::needs_pool_routing` predicate returns
    /// `true` for `Pending`, so a freshly-admitted Allocation whose
    /// pool reconciler has not yet stamped a `.status` slot reads
    /// as `Pending` and immediately enters the routing ladder,
    /// matching the pre-lift `AllocationPhase::Pending` fallback
    /// semantics verbatim.
    ///
    /// Theory anchor: THEORY.md §VI.1 (generation over composition
    /// — the two-link `.status.as_ref().map(|s| s.phase).unwrap_or
    /// (AllocationPhase::Pending)` chain recurred at both the
    /// [`crate::prelude::Process`] site (already lifted onto
    /// [`crate::prelude::Process::observed_phase_or_pending`]) AND
    /// the [`EphemeralAllocation`] site by hand, i.e. the SHAPE
    /// itself recurs past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
    /// trigger, and is lifted to ONE owner per CRD here). THEORY.md
    /// §II.1 invariant 5 (composition preserves proofs — the pins
    /// bind the missing-`status` sink to `Pending` + populated-
    /// status pass-through + every [`AllocationPhase`] variant
    /// round-trip + byte-identical parity with the pre-lift
    /// two-link chain + cross-CRD peer coherence with
    /// [`crate::prelude::Process::observed_phase_or_pending`], so
    /// a regression that drifted any surface at
    /// `tests::observed_phase_*` rather than as silent operator-
    /// facing skew between the allocation observer's routing seed
    /// and the Process observer's dispatch seed).
    #[must_use]
    pub fn observed_phase_or_pending(&self) -> AllocationPhase {
        self.observed_phase().unwrap_or(AllocationPhase::Pending)
    }

    /// The borrow-form status-projection primitive on the bound-pool
    /// axis: returns the [`AllocationRef`] the pool reconciler
    /// currently persists at `status.bound_pool` (name + namespace of
    /// the pool that owns the matched member), with the
    /// missing-`status` corner AND the empty-slot corner BOTH
    /// collapsed to `None` — the ONE-liner collapse of the paired
    /// `self.status.as_ref().and_then(|s| s.bound_pool.<clone|as_ref>())`
    /// incantation the pool reconciler's `AllocationConvergenceCtx::
    /// observe` restated by hand pre-lift.
    ///
    /// Cross-CRD peer to [`crate::prelude::Process::observed_identity`]
    /// on the (CRD × structured-record-slot × borrow-form) axis pair
    /// — both primitives walk the identical `.status.as_ref()
    /// .and_then(|s| s.<slot>.as_ref())` shape, differing only in the
    /// record projected ([`AllocationRef`] here, [`crate::identity::
    /// Identity`] on `Process`). The substrate now owns the
    /// borrow-form `.status.as_ref().and_then(|s| s.<slot>.as_ref())`
    /// chain on the second `structured-record` slot across the two
    /// `status`-having CRDs, so a future normalization step (a
    /// generation-filter that returns `None` for a bound-pool
    /// reference stamped with a stale `metadata.generation`, a
    /// canonicalization pass that rejects a malformed
    /// `(name, namespace)` pair, a cross-cluster reference-rewrite
    /// gate) lands at ONE substrate method per CRD rather than being
    /// restated at every observer.
    ///
    /// Return-form axis: `Option<&AllocationRef>` mirrors the
    /// borrow-first discipline of [`crate::prelude::Process::
    /// observed_identity`]. The lone pre-lift consumer
    /// ([`tatara-pool-reconciler::allocation_decide::
    /// AllocationConvergenceCtx::observe`]'s `bound_pool` seed) spelled
    /// the projection as `.and_then(|s| s.bound_pool.clone())` — an
    /// eager clone allocated inside every reconcile pass even when the
    /// downstream branch (the Release-composition arm) needed only the
    /// borrow for the `.as_ref()` re-projection two lines later.
    /// Post-lift the consumer reaches the primitive borrow-first
    /// (`alloc.observed_bound_pool().cloned()`) and the empty-borrow
    /// corner clones nothing (`Option::cloned` on `None` is `None`);
    /// the composition point where the owned `AllocationRef` fallback
    /// is required (the `AllocationConvergenceCtx` snapshot slot,
    /// still `Option<AllocationRef>`-typed for serde stability) is the
    /// ONLY site that materializes an owned copy.
    ///
    /// The missing-`status` corner AND the populated-status-with-
    /// `bound_pool=None` corner BOTH collapse to `None` so
    /// `.is_some()` / `if let Some(_)` / `.cloned()` behave
    /// identically on an `EphemeralAllocation` whose status field is
    /// `None` and on one whose status carries an unpopulated
    /// `bound_pool` slot — matching what the pre-lift `.and_then(...)`
    /// chain produced. Consumers that need to tell those corners
    /// apart reach for [`Self::status`] directly, exactly as the
    /// existing peer accessors [`Self::observed_phase`] +
    /// [`Self::observed_phase_or_pending`] admit.
    ///
    /// Theory anchor: THEORY.md §VI.1 (generation over composition
    /// — the `.status.as_ref().and_then(|s| s.<structured-record>
    /// .<clone|as_ref>())` shape recurred as ONE hand-authored
    /// `.and_then(|s| s.bound_pool.clone())` chain in
    /// [`tatara-pool-reconciler::allocation_decide::
    /// AllocationConvergenceCtx::observe`] AND as the peer
    /// [`crate::prelude::Process::observed_identity`] primitive
    /// already owned on the `Process` CRD's `status.identity` slot,
    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger at
    /// substrate-shape level. THEORY.md §II.1 invariant 5
    /// (composition preserves proofs — the pins bind the missing-
    /// `status` corner + the empty-`bound_pool`-slot corner + the
    /// borrow-form `&AllocationRef` lifetime + the zero-copy
    /// projection contract + byte-identical parity with the pre-lift
    /// `.and_then(|s| s.bound_pool.clone())` chain across the full
    /// corner set + cross-CRD peer coherence with
    /// [`crate::prelude::Process::observed_identity`], so a
    /// regression that drifted any surface at
    /// `tests::observed_bound_pool_*` rather than as silent operator-
    /// facing skew between the allocation observer's Release-
    /// composition seed and the Process observer's FORK-time
    /// identity seed on the SAME reconcile tick).
    #[must_use]
    pub fn observed_bound_pool(&self) -> Option<&AllocationRef> {
        self.status.as_ref().and_then(|s| s.bound_pool.as_ref())
    }

    /// The copy-form status-projection primitive on the TTL-expiry axis:
    /// returns the wall-clock deadline the pool reconciler currently
    /// persists at `status.expires_at` (derived from `spec.ttl` +
    /// `allocated_at` at Bind time), wrapped in an `Option` so both the
    /// missing-`status` corner AND the populated-status-with-`expires_at
    /// =None` corner collapse to `None` — the ONE-liner collapse of the
    /// paired `self.status.as_ref().and_then(|s| s.expires_at)`
    /// incantation the pool reconciler's `AllocationConvergenceCtx::
    /// observe` restated by hand pre-lift.
    ///
    /// Same-CRD peer to [`Self::observed_phase`] on the (CRD × copy-form
    /// × status-slot) axis pair — both primitives walk the identical
    /// `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` shape,
    /// differing only in the record projected ([`DateTime<Utc>`] here,
    /// [`AllocationPhase`] on the phase axis) and in the outer combinator
    /// (`and_then` here because the persisted field is itself an
    /// `Option<DateTime<Utc>>`, `map` there because the persisted phase
    /// is bare). The substrate now owns the copy-form
    /// `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` chain
    /// axis-uniformly across every `Copy`-valued slot on
    /// `AllocationStatus`, so a future normalization (a clock-skew
    /// guard that drops an `expires_at` stamped before its owning
    /// allocation's observed `allocated_at`, a canonicalization pass
    /// that clamps a deadline to a monotonic upper bound, a stale-
    /// timestamp gate that returns `None` on an `expires_at` older than
    /// a controller-configured horizon) lands at ONE substrate method
    /// rather than being restated at every observer.
    ///
    /// Return-form axis: `Option<DateTime<Utc>>` mirrors the copy-first
    /// discipline of [`Self::observed_phase`]. The lone pre-lift consumer
    /// ([`tatara-pool-reconciler::allocation_decide::
    /// AllocationConvergenceCtx::observe`]'s `expires_at` seed) spelled
    /// the projection as `.status.as_ref().and_then(|s| s.expires_at)` —
    /// a 3-link hand-authored chain the observer walked on every
    /// reconcile pass. Post-lift the consumer reaches the primitive
    /// once and the whole missing-status + empty-slot corner cross
    /// collapses at the substrate rather than at the callsite.
    ///
    /// The missing-`status` corner AND the populated-status-with-
    /// `expires_at=None` corner BOTH collapse to `None` so
    /// `.is_some()` / `if let Some(_)` / any `>=` deadline comparison
    /// behave identically on an `EphemeralAllocation` whose status
    /// field is `None` and on one whose status carries an unpopulated
    /// `expires_at` slot — matching what the pre-lift `.and_then(...)`
    /// chain produced. Consumers that need to tell those corners apart
    /// reach for [`Self::status`] directly, exactly as the existing peer
    /// accessors [`Self::observed_phase`] +
    /// [`Self::observed_phase_or_pending`] admit.
    ///
    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
    /// the `.status.as_ref().and_then(|s| s.<Copy-field>)` shape
    /// recurred as ONE hand-authored chain in
    /// [`tatara-pool-reconciler::allocation_decide::
    /// AllocationConvergenceCtx::observe`] AND as the copy-form peer
    /// [`Self::observed_phase`] primitive already owned on the same
    /// CRD's `status.phase` slot, past the substrate-shape recurrence
    /// trigger; the substrate now owns the third status-projection
    /// primitive on `EphemeralAllocation`, closing the copy-form family
    /// alongside the borrow-form [`Self::observed_bound_pool`]).
    /// THEORY.md §II.1 invariant 5 (composition preserves proofs — the
    /// pins bind the missing-`status` corner + the empty-`expires_at`-
    /// slot corner + the copy-form `DateTime<Utc>` return + byte-
    /// identical parity with the pre-lift `.and_then(|s| s.expires_at)`
    /// chain across the full corner set, so a regression that drifted
    /// any surface surfaces at `tests::observed_expires_at_*` rather
    /// than as silent operator-facing skew between the allocation
    /// observer's Release-composition TTL gate and any future consumer
    /// that reaches for the same slot).
    #[must_use]
    pub fn observed_expires_at(&self) -> Option<DateTime<Utc>> {
        self.status.as_ref().and_then(|s| s.expires_at)
    }
}

#[cfg(test)]
mod tests {
    // `FromStr` lives in scope at the test surface only — the derive
    // emits `impl ::core::str::FromStr` via the full path so the lib
    // body no longer reaches `FromStr` directly, but the cross-axis
    // sweeps + the verbatim-echo contract tests call
    // `AllocationPhase::from_str(bad)` / `bad.parse::<RequestorKind>()`.
    use std::str::FromStr;

    use super::*;

    #[test]
    fn requestor_minimum_shape_round_trips() {
        let r = Requestor {
            kind: "github-pr".into(),
            repo: Some("pleme-io/demo-app".into()),
            branch: Some("fix-something".into()),
            pr_number: Some(123),
            sha: Some("abc123def".into()),
            pr_labels: vec!["needs-ephemeral".into()],
            actor: Some("drzln".into()),
        };
        let yaml = serde_yaml::to_string(&r).unwrap();
        assert!(yaml.contains("kind: github-pr"));
        assert!(yaml.contains("prNumber: 123"));
        let back: Requestor = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back.kind, "github-pr");
        assert_eq!(back.pr_number, Some(123));
    }

    #[test]
    fn allocation_status_defaults_pending() {
        let s = AllocationStatus::default();
        assert_eq!(s.phase, AllocationPhase::Pending);
        assert!(s.bound_pool.is_none());
        assert!(s.assigned_process.is_none());
    }

    #[test]
    fn allocation_phase_round_trips_via_serde() {
        for p in [
            AllocationPhase::Pending,
            AllocationPhase::Queued,
            AllocationPhase::Bound,
            AllocationPhase::Releasing,
            AllocationPhase::Released,
            AllocationPhase::NoMatchingPool,
            AllocationPhase::Failed,
        ] {
            let s = serde_yaml::to_string(&p).unwrap();
            let back: AllocationPhase = serde_yaml::from_str(&s).unwrap();
            assert_eq!(back, p);
        }
    }

    // ── closed-set algebra contracts for AllocationPhase
    //    (ALL × as_str × FromStr × predicate-pair) ────────────────────

    /// `ALL` is the source of truth — pin its closure so a variant
    /// added without an `ALL` entry fails here via the uniqueness
    /// check before drifting `FromStr` or the sweep tests below. The
    /// arity is asserted by the `[Self; 7]` array type itself.
    ///
    /// Structural well-formedness of [`AllocationPhase`] as a
    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
    /// testkit lift that pins all three structural invariants
    /// (`ALL` is non-empty, every variant round-trips through
    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
    /// outside the closed set) at ONE call site. Replaces the hand-
    /// derived `allocation_phase_all_is_unique_and_complete` +
    /// `allocation_phase_roundtrip_via_as_str` + the empty-input arm
    /// of `unknown_allocation_phase_errors`. `FromStr` delegates to
    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
    /// helper exercises the same code path the allocation reconciler
    /// hits when parsing a CRD `enum:`-validated value back to the
    /// typed phase.
    #[test]
    fn allocation_phase_is_well_formed_closed_set() {
        tatara_closed_set::assert_closed_set_well_formed::<AllocationPhase>();
    }

    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
    /// output verbatim for every variant. A future variant rename
    /// (or an `as_str` arm typo) lands here at one site, instead of
    /// drifting between the typed surface, the CRD enum, the YAML
    /// wire format, and the operator-facing reason strings the
    /// reconciler stamps via Display.
    #[test]
    fn allocation_phase_as_str_matches_serde() {
        crate::tagged_union::assert_label_matches_serde_serialization::<AllocationPhase>();
    }

    /// The Display impl IS `as_str` — pinning this lets future
    /// callers reach for either projection without drift.
    #[test]
    fn allocation_phase_display_matches_as_str() {
        crate::tagged_union::assert_display_matches_label::<AllocationPhase>();
    }

    /// `FromStr` rejects strings that aren't in the canonical
    /// projection — lowercased / typo / unrelated — and the error
    /// echoes the input verbatim so the operator-facing diagnostic
    /// carries the offending value, not a normalized form. The
    /// empty-input arm is pinned by
    /// [`allocation_phase_is_well_formed_closed_set`] via the
    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
    /// verbatim-echo contract on the [`UnknownAllocationPhase`]
    /// newtype, which the trait's `make_unknown` can't see.
    #[test]
    fn unknown_allocation_phase_errors() {
        for bad in [
            "pending",
            "BOUND",
            "no-matching-pool",
            "release",
            "failed_state",
            "Reaped",
        ] {
            let err = AllocationPhase::from_str(bad).unwrap_err();
            assert_eq!(err.0, bad, "error payload should echo input verbatim");
        }
    }

    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
    /// documented per-variant disposition. `Released` + `Failed` are
    /// terminal (absorbing); `Pending` / `Queued` / `NoMatchingPool`
    /// need pool routing; `Bound` / `Releasing` are settled-but-not-
    /// terminal (heartbeat / release ladder).
    #[test]
    fn allocation_phase_predicate_truth_tables() {
        assert!(!AllocationPhase::Pending.is_terminal());
        assert!(AllocationPhase::Pending.needs_pool_routing());

        assert!(!AllocationPhase::Queued.is_terminal());
        assert!(AllocationPhase::Queued.needs_pool_routing());

        assert!(!AllocationPhase::Bound.is_terminal());
        assert!(!AllocationPhase::Bound.needs_pool_routing());

        assert!(!AllocationPhase::Releasing.is_terminal());
        assert!(!AllocationPhase::Releasing.needs_pool_routing());

        assert!(AllocationPhase::Released.is_terminal());
        assert!(!AllocationPhase::Released.needs_pool_routing());

        assert!(!AllocationPhase::NoMatchingPool.is_terminal());
        assert!(AllocationPhase::NoMatchingPool.needs_pool_routing());

        assert!(AllocationPhase::Failed.is_terminal());
        assert!(!AllocationPhase::Failed.needs_pool_routing());
    }

    /// IMPLICATION CONTRACT: `is_terminal → !needs_pool_routing`. A
    /// terminal allocation cannot also be routing-eligible — that's
    /// the bug the typed projection closes (a `Failed` allocation
    /// that's neither `Released` nor `Bound` would otherwise slip
    /// through the open-coded gate in `observe` and try to rebind to
    /// a pool member). A future variant that flipped both predicates
    /// true would fail here, forcing the author to flip one or
    /// extend the consumer dispatch site in
    /// `tatara-pool-reconciler::allocation_decide` deliberately
    /// rather than letting an impossible state slip in.
    #[test]
    fn allocation_phase_terminal_excludes_routing() {
        for phase in AllocationPhase::ALL {
            assert!(
                !(phase.is_terminal() && phase.needs_pool_routing()),
                "{phase:?} is both terminal and routing-eligible",
            );
        }
    }

    /// DEFAULT-AGREEMENT CONTRACT: `AllocationPhase::default()` is
    /// `Pending` — the entry state, neither terminal nor settled —
    /// and it lives on the routing path. A future default-variant
    /// rename without flipping the predicates fails here.
    #[test]
    fn allocation_phase_default_is_pending_and_routes() {
        let d = AllocationPhase::default();
        assert_eq!(d, AllocationPhase::Pending);
        assert!(!d.is_terminal());
        assert!(d.needs_pool_routing());
    }

    // ── RequestorKind closed-set truth-table ─────────────────────────

    /// Structural well-formedness of [`RequestorKind`] as a
    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
    /// testkit lift that pins all three structural invariants
    /// (`ALL` is non-empty, every variant round-trips through
    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
    /// outside the closed set) at ONE call site. Replaces the hand-
    /// derived `requestor_kind_all_enumerates_each_variant_exactly_once`
    /// + `requestor_kind_from_str_round_trips_canonical_names` + the
    /// empty-input arm of `requestor_kind_from_str_rejects_open_kinds`.
    /// `FromStr` delegates to
    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
    /// exercises the same code path
    /// [`Requestor::known_kind`]'s `Option<RequestorKind>` collapse
    /// rides on when classifying inbound `Requestor.kind` strings. The
    /// arity is asserted by the `[Self; 4]` array type itself.
    #[test]
    fn requestor_kind_is_well_formed_closed_set() {
        tatara_closed_set::assert_closed_set_well_formed::<RequestorKind>();
    }

    /// Byte-exact wire-format pin — renaming any of these is a wire-
    /// format change (the `tatara-github-watcher` emitter, the CRD
    /// printcolumns, the `PoolSelector.kinds` filter strings, the
    /// per-test `kind: "…".into()` fixtures all depend on these
    /// literals), not a typed-internal refactor.
    #[test]
    fn requestor_kind_canonical_names_pinned() {
        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
        assert_eq!(RequestorKind::Manual.as_str(), "manual");
        assert_eq!(RequestorKind::CiRun.as_str(), "ci-run");
        assert_eq!(RequestorKind::Scheduled.as_str(), "scheduled");
    }

    /// `FromStr` rejects strings that aren't in the canonical
    /// projection — lowercased-mismatch / typo / unrelated — and the
    /// error echoes the input verbatim so the operator-facing
    /// diagnostic carries the offending value, not a normalized form.
    /// The schema is open at the wire layer (operators MAY register
    /// new kinds and `Requestor::known_kind` collapses them to
    /// `None`), but the closed-set view is byte-exact. The empty-input
    /// arm is pinned by [`requestor_kind_is_well_formed_closed_set`]
    /// via the `tatara_lisp::ClosedSet` testkit; the cases here pin
    /// the verbatim-echo contract on the [`UnknownRequestorKind`]
    /// newtype, which the trait's `make_unknown` can't see.
    #[test]
    fn requestor_kind_from_str_rejects_open_kinds() {
        for bad in [
            "github_pr",
            "GithubPr",
            "operator-custom-kind",
            "ci_run",
            "Scheduled",
        ] {
            let err = bad.parse::<RequestorKind>().unwrap_err();
            assert_eq!(err, UnknownRequestorKind(bad.to_string()));
        }
    }

    /// The Display impl IS `as_str` — pinning this lets future
    /// callers reach for either projection without drift (Display is
    /// what operator-facing diagnostics compose against).
    #[test]
    fn requestor_kind_display_delegates_to_as_str() {
        for k in RequestorKind::ALL {
            assert_eq!(format!("{k}"), k.as_str());
        }
    }

    /// The `String` projection that `From<RequestorKind> for String`
    /// ([`RequestorKind::into`]) composes is byte-equal to `as_str`.
    /// This is the typed → wire bridge — emitters spell
    /// `kind: RequestorKind::GithubPr.into()` and the canonical
    /// literal is materialized at ONE place.
    #[test]
    fn requestor_kind_into_string_matches_as_str() {
        for k in RequestorKind::ALL {
            let s: String = k.into();
            assert_eq!(s, k.as_str());
        }
    }

    /// The typed → wire → typed round-trip: composing a `Requestor`
    /// with `kind: RequestorKind::X.into()` produces an object whose
    /// `known_kind()` decodes back to `X`. Pins the bridge invariant
    /// at the `Requestor` boundary, not just at `RequestorKind`.
    #[test]
    fn known_kind_decodes_built_requestors() {
        for k in RequestorKind::ALL {
            let r = Requestor {
                kind: k.into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            };
            assert_eq!(r.known_kind(), Some(k), "round-trip failed for {k:?}");
        }
    }

    /// Open-by-design: a custom operator-registered kind still
    /// stamps a valid `Requestor` (no schema rejection), it just
    /// doesn't project through the closed-set typed view. Mirrors
    /// `ReceiptEnvelope::known_kind`'s open-kind posture.
    #[test]
    fn known_kind_returns_none_for_open_kinds() {
        let r = Requestor {
            kind: "operator-custom-kind".into(),
            repo: None,
            branch: None,
            pr_number: None,
            sha: None,
            pr_labels: vec![],
            actor: None,
        };
        assert_eq!(r.known_kind(), None);
    }

    /// The four canonical literals match every previously-published
    /// fixture / doc anchor in this crate — pinning the bridge to
    /// existing call sites so any drift fails here before the next
    /// release ships.
    #[test]
    fn requestor_kind_matches_existing_fixture_literals() {
        // The `requestor_minimum_shape_round_trips` fixture above
        // composes `kind: "github-pr".into()` verbatim.
        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
        // The `allocation_spec_omits_optional_fields` fixture below
        // composes `kind: "manual".into()` verbatim.
        assert_eq!(RequestorKind::Manual.as_str(), "manual");
    }

    // Per-implementor `unknown_X_message_matches_substrate_convention`
    // tests removed — clause (5) of
    // `tatara_closed_set::assert_closed_set_well_formed::<T>()` now verifies
    // the substrate-wide `"unknown {SET_LABEL}: {input}"` carrier shape
    // generically (called above on `RequestorKind` /
    // `AllocationPhase` through their `*_is_well_formed_closed_set`
    // sites). The `SET_LABEL` projection is pinned independently by
    // `tatara_lisp_derive::pascal_to_spaced_lowercase_tests` —
    // together the two contracts guarantee the operator-facing
    // diagnostic without needing per-enum literal pins.

    // ─── EphemeralAllocation::observed_phase* substrate pins ────────
    //
    // Fail-before-pass-after granularity: neither `observed_phase` nor
    // `observed_phase_or_pending` existed before this commit, so each
    // pin fails to compile until the corresponding inherent method
    // lands. Post-lift the pins bind the missing-`status` corner + the
    // populated-status pass-through + byte-identical parity with the
    // pre-lift 5-line `.status.as_ref().map(|s| s.phase).unwrap_or
    // (AllocationPhase::Pending)` chain the pool reconciler's
    // `AllocationConvergenceCtx::observe` walked. Cross-CRD peer
    // coherence with `Process::observed_phase_or_pending` is pinned
    // by the `_matches_process_peer_shape` sweep at the tail.

    fn alloc_with_phase(phase: AllocationPhase) -> EphemeralAllocation {
        let spec = AllocationSpec {
            pool_ref: None,
            requestor: Requestor {
                kind: "manual".into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            },
            ttl: None,
            note: None,
        };
        let mut a = EphemeralAllocation::new("obs-alloc", spec);
        a.status = Some(AllocationStatus {
            phase,
            ..AllocationStatus::default()
        });
        a
    }

    fn alloc_without_status() -> EphemeralAllocation {
        let spec = AllocationSpec {
            pool_ref: None,
            requestor: Requestor {
                kind: "manual".into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            },
            ttl: None,
            note: None,
        };
        let mut a = EphemeralAllocation::new("no-status-alloc", spec);
        a.status = None;
        a
    }

    #[test]
    fn observed_phase_returns_none_when_status_is_none() {
        let a = alloc_without_status();
        assert!(a.observed_phase().is_none());
    }

    #[test]
    fn observed_phase_returns_populated_variant_verbatim() {
        for p in AllocationPhase::ALL {
            let a = alloc_with_phase(p);
            assert_eq!(
                a.observed_phase(),
                Some(p),
                "observed_phase must project the persisted variant verbatim for {p:?}"
            );
        }
    }

    #[test]
    fn observed_phase_matches_pre_lift_chain_bytewise() {
        // Sweep every corner: (status: None) plus every populated
        // (status: Some(phase)) variant. The pre-lift chain was
        // `alloc.status.as_ref().map(|s| s.phase)` — a 3-link chain
        // hand-authored inline at the observer. The primitive must
        // return the same `Option<AllocationPhase>` on every corner.
        let none_alloc = alloc_without_status();
        assert_eq!(
            none_alloc.observed_phase(),
            none_alloc.status.as_ref().map(|s| s.phase),
        );
        for p in AllocationPhase::ALL {
            let a = alloc_with_phase(p);
            assert_eq!(
                a.observed_phase(),
                a.status.as_ref().map(|s| s.phase),
                "primitive must be byte-identical to the pre-lift chain for {p:?}",
            );
        }
    }

    #[test]
    fn observed_phase_or_pending_defaults_to_pending_when_status_absent() {
        let a = alloc_without_status();
        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::Pending);
    }

    #[test]
    fn observed_phase_or_pending_returns_populated_phase_verbatim() {
        for p in AllocationPhase::ALL {
            let a = alloc_with_phase(p);
            assert_eq!(
                a.observed_phase_or_pending(),
                p,
                "populated status must pass through verbatim for {p:?}"
            );
        }
    }

    #[test]
    fn observed_phase_or_pending_defaults_agree_with_allocation_phase_default() {
        // The `Pending` sink is load-bearing as the "not yet observed"
        // default. `AllocationPhase::default()` returns `Pending`; the
        // primitive must return the same variant on the missing-status
        // corner. A future default-variant rename that flipped
        // `AllocationPhase::default` without flipping the primitive
        // (or vice versa) surfaces here as a divergent seed for the
        // routing ladder.
        let a = alloc_without_status();
        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::default());
    }

    #[test]
    fn observed_phase_or_pending_matches_pre_lift_chain_bytewise() {
        // The exact pre-lift 5-line chain in
        // `tatara-pool-reconciler::allocation_decide::
        // AllocationConvergenceCtx::observe` was:
        //     let phase = alloc
        //         .status
        //         .as_ref()
        //         .map(|s| s.phase)
        //         .unwrap_or(AllocationPhase::Pending);
        // Sweep every corner: (status: None) plus every populated
        // status variant. The primitive must be byte-identical for
        // every corner so the observer's routing decision matches
        // bytewise post-lift.
        let none_alloc = alloc_without_status();
        assert_eq!(
            none_alloc.observed_phase_or_pending(),
            none_alloc
                .status
                .as_ref()
                .map(|s| s.phase)
                .unwrap_or(AllocationPhase::Pending),
        );
        for p in AllocationPhase::ALL {
            let a = alloc_with_phase(p);
            assert_eq!(
                a.observed_phase_or_pending(),
                a.status
                    .as_ref()
                    .map(|s| s.phase)
                    .unwrap_or(AllocationPhase::Pending),
                "primitive must be byte-identical to the pre-lift 5-line chain for {p:?}",
            );
        }
    }

    #[test]
    fn observed_phase_or_pending_composes_from_observed_phase() {
        // The composer sits on top of the borrow-form projection —
        // `observed_phase_or_pending() == observed_phase().unwrap_or
        // (Pending)`. Pinning the composition means a future
        // normalization step layered onto `observed_phase` (a
        // generation-filter, a staleness gate, a canonicalization
        // pass) reaches BOTH the raw-`Option` accessor and the
        // `Pending`-sinked composer through the SAME upstream body,
        // without needing a per-corner rewrite of the composer.
        let none_alloc = alloc_without_status();
        assert_eq!(
            none_alloc.observed_phase_or_pending(),
            none_alloc
                .observed_phase()
                .unwrap_or(AllocationPhase::Pending),
        );
        for p in AllocationPhase::ALL {
            let a = alloc_with_phase(p);
            assert_eq!(
                a.observed_phase_or_pending(),
                a.observed_phase().unwrap_or(AllocationPhase::Pending),
                "composer must ride on top of the borrow-form projection for {p:?}",
            );
        }
    }

    #[test]
    fn observed_phase_is_a_pure_projection() {
        // Reading the phase twice must not mutate the allocation or
        // its status slot — pure projection semantics. Also witnesses
        // that the accessor doesn't clone / drop the inner `phase`
        // (the `Copy` scalar comes out identical on both reads).
        let a = alloc_with_phase(AllocationPhase::Bound);
        let one = a.observed_phase();
        let two = a.observed_phase();
        assert_eq!(one, two);
        assert!(a.status.is_some(), "projection must not consume the status");
    }

    #[test]
    fn observed_phase_pending_missing_status_and_populated_pending_collapse_to_same_composer_output(
    ) {
        // A subtle correctness pin: the missing-`status` corner and
        // a populated-with-Pending status BOTH read as `Pending`
        // through the composer — the observer cannot distinguish the
        // two through this accessor. This matches the pre-lift 5-line
        // chain's semantics exactly (an operator patching
        // `status.phase: Pending` is indistinguishable from a
        // freshly-admitted allocation with no status stamped yet).
        // The borrow-form `observed_phase` accessor DOES distinguish
        // the two, so a caller that needs to tell them apart reaches
        // for the raw `Option`.
        let none_alloc = alloc_without_status();
        let pending_alloc = alloc_with_phase(AllocationPhase::Pending);

        assert_eq!(
            none_alloc.observed_phase_or_pending(),
            pending_alloc.observed_phase_or_pending(),
        );
        assert_ne!(
            none_alloc.observed_phase(),
            pending_alloc.observed_phase(),
            "borrow-form accessor MUST distinguish missing-status from populated-Pending",
        );
    }

    #[test]
    fn observed_phase_or_pending_missing_status_sink_agrees_with_process_peer_shape() {
        // Cross-CRD peer-axis coherence with
        // `Process::observed_phase_or_pending`. Both primitives walk
        // the identical `.status.as_ref().map(|s| s.phase).unwrap_or
        // (<Phase>::Pending)` chain differing ONLY in the `Phase`
        // type projected. On a missing-status observation, each
        // primitive must return its CRD's `Default`-equivalent
        // `Pending` variant — for `EphemeralAllocation` that's
        // `AllocationPhase::Pending`; for `Process` that's
        // `crate::phase::ProcessPhase::Pending`. This pin binds the
        // sink-parity structurally so a future rename of either
        // default variant surfaces here as a divergent seed for the
        // observer's routing / dispatch decision rather than as
        // silent drift between the two reconcilers.
        let no_status_alloc = alloc_without_status();
        assert_eq!(
            no_status_alloc.observed_phase_or_pending(),
            AllocationPhase::default(),
        );
        // Peer-axis invariant on the `Process` side — the primitive
        // that owns the same shape reads `ProcessPhase::Pending` on
        // the missing-status corner via its own inherent method. The
        // parity is coordinated at the `Default` seat: both CRDs'
        // phase types default to `Pending`, so a rename that broke
        // one without the other would fail one of these two
        // conjoined assertions.
        assert_eq!(AllocationPhase::default(), AllocationPhase::Pending,);
        assert_eq!(
            crate::phase::ProcessPhase::default(),
            crate::phase::ProcessPhase::Pending,
        );
    }

    // ─── EphemeralAllocation::observed_bound_pool substrate pins ────
    //
    // The borrow-form status-projection primitive on the bound-pool
    // axis. Collapses the pre-lift hand-authored `.status.as_ref()
    // .and_then(|s| s.bound_pool.clone())` chain in
    // `tatara-pool-reconciler::allocation_decide::
    // AllocationConvergenceCtx::observe`'s `bound_pool` seed onto the
    // ONE substrate primitive. Cross-CRD peer to
    // `Process::observed_identity` on the (CRD × structured-record-
    // slot × borrow-form) axis pair — both primitives walk the
    // identical `.status.as_ref().and_then(|s| s.<slot>.as_ref())`
    // shape. Each pin is fail-before-pass-after: `observed_bound_pool`
    // did not exist pre-lift, so any test invoking it fails to compile
    // pre-lift and passes post-lift.

    fn sample_pool_ref(name: &str, ns: &str) -> AllocationRef {
        AllocationRef {
            name: name.to_string(),
            namespace: ns.to_string(),
        }
    }

    fn alloc_with_bound_pool(bound: Option<AllocationRef>) -> EphemeralAllocation {
        let spec = AllocationSpec {
            pool_ref: None,
            requestor: Requestor {
                kind: "manual".into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            },
            ttl: None,
            note: None,
        };
        let mut a = EphemeralAllocation::new("bp-alloc", spec);
        a.status = Some(AllocationStatus {
            phase: AllocationPhase::Bound,
            bound_pool: bound,
            ..AllocationStatus::default()
        });
        a
    }

    #[test]
    fn observed_bound_pool_returns_none_when_status_is_none() {
        // Missing-`status` corner pin: the primitive collapses the
        // no-status case to `None` so downstream `.is_some()` /
        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
        // identically on an `EphemeralAllocation` whose status field
        // is `None` and on one whose status carries an unpopulated
        // `bound_pool` slot. Matches the pre-lift `.and_then(...)`
        // chain's `None` byte-identically at the pool reconciler's
        // Release-composition seed.
        let a = alloc_without_status();
        assert!(a.observed_bound_pool().is_none());
    }

    #[test]
    fn observed_bound_pool_returns_none_when_slot_is_none() {
        // Empty-slot-under-populated-status corner pin: the primitive
        // returns `None`, matching the missing-`status` corner byte-
        // identically. A regression that treated the two corners
        // differently would silently promote an internal representation
        // detail (whether the pool reconciler has ever written a
        // status subresource) into observable behavior at the
        // Release-composition branch of the allocation reconciler's
        // `decide` transition rule.
        let a = alloc_with_bound_pool(None);
        assert!(a.observed_bound_pool().is_none());
    }

    #[test]
    fn observed_bound_pool_returns_borrow_when_slot_is_populated() {
        // Happy-path pin: with a populated `status.bound_pool` slot,
        // the primitive returns a borrowed `&AllocationRef` whose
        // (name, namespace) fields match the persisted record. A
        // regression that filtered / reshaped / canonicalized the
        // record would surface here rather than as silent skew at the
        // Release-composition seed's `.cloned()` materialization.
        let expected = sample_pool_ref("demo-pool", "pools");
        let a = alloc_with_bound_pool(Some(expected.clone()));
        let observed = a.observed_bound_pool().expect("populated slot");
        assert_eq!(observed, &expected);
        assert_eq!(observed.name, "demo-pool");
        assert_eq!(observed.namespace, "pools");
    }

    #[test]
    fn observed_bound_pool_is_a_zero_copy_borrow_projection() {
        // Borrow-discipline pin: the returned reference points at the
        // persisted `AllocationRef` in place — NOT a fresh allocation
        // or a clone. A regression that switched the projection to an
        // owned `AllocationRef` (via `.clone()`) would defeat the
        // zero-copy contract the lift's primary strict-widening
        // delivers (the observer's Release-composition arm clones
        // once at the composition point where the
        // `AllocationConvergenceCtx` snapshot slot requires the owned
        // value). Peer to the sibling
        // `Process::observed_identity_is_a_zero_copy_borrow_projection`
        // pin on the `Process` CRD's `status.identity` slot.
        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
        let observed = a.observed_bound_pool().expect("populated slot") as *const _;
        let persisted = a.status.as_ref().unwrap().bound_pool.as_ref().unwrap() as *const _;
        assert!(std::ptr::eq(observed, persisted));
    }

    #[test]
    fn observed_bound_pool_is_a_pure_projection() {
        // Purity pin: calling the projection twice on the same
        // `EphemeralAllocation` returns byte-identical borrows (same
        // pointer). A regression that introduced state — a lazy-
        // cached reference, a normalization step that ran once and
        // cached — would surface here rather than as silent drift
        // between two dispatches within one reconcile pass.
        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
        let one = a.observed_bound_pool().expect("populated slot") as *const _;
        let two = a.observed_bound_pool().expect("populated slot") as *const _;
        assert!(std::ptr::eq(one, two));
    }

    #[test]
    fn observed_bound_pool_matches_pre_lift_chain_bytewise() {
        // Byte-identical parity pin between the borrow-form primitive
        // here and the pre-lift `tatara-pool-reconciler`
        // `.status.as_ref().and_then(|s| s.bound_pool.clone())` chain.
        // Sweeps every corner every callsite plausibly encounters
        // (missing status, empty `bound_pool` slot, populated
        // `bound_pool` slot). A regression that inserted a
        // normalization step at the primitive the pre-lift chain does
        // NOT apply — or vice versa — surfaces here rather than as
        // silent drift between the pre-lift consumer site and the ONE
        // substrate owner it now routes through.
        fn pre_lift(a: &EphemeralAllocation) -> Option<AllocationRef> {
            a.status.as_ref().and_then(|s| s.bound_pool.clone())
        }
        // Missing status.
        let a = alloc_without_status();
        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
        // Populated status, empty `bound_pool` slot.
        let a = alloc_with_bound_pool(None);
        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
        // Populated status, populated `bound_pool` slot.
        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
    }

    #[test]
    fn observed_bound_pool_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
        // Cross-corner coherence pin: the missing-`status` corner and
        // the populated-empty-slot corner return `Option`s whose
        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
        // regression that promoted the missing-`status` corner to a
        // typed error (via a signature change to `Result<_, _>`) — or
        // that widened the empty-slot corner to a synthetic
        // `Some(AllocationRef::default())` — would surface here rather
        // than as silent operator-facing divergence between a never-
        // status-written allocation and a bound-pool-cleared
        // allocation on the Release-composition branch.
        let a_no_status = alloc_without_status();
        let a_empty_slot = alloc_with_bound_pool(None);
        assert_eq!(
            a_no_status.observed_bound_pool().is_none(),
            a_empty_slot.observed_bound_pool().is_none(),
        );
        assert_eq!(
            a_no_status.observed_bound_pool().is_some(),
            a_empty_slot.observed_bound_pool().is_some(),
        );
    }

    #[test]
    fn observed_bound_pool_shape_agrees_with_process_observed_identity_peer_axis() {
        // Cross-CRD peer-axis coherence pin binding the SAME
        // `.status.as_ref().and_then(|s| s.<slot>.as_ref())` shape
        // that both `EphemeralAllocation::observed_bound_pool` (this
        // primitive) and `Process::observed_identity` walk, differing
        // ONLY in the record projected. Structural test — both
        // signatures must resolve as `&Self -> Option<&Record>` fn
        // pointers, so a future rename or a signature drift that
        // (say) widened one side to `Option<Record>` or narrowed one
        // side to `Option<&str>` fails to compile here rather than
        // silently drifting the two reconcilers apart at their
        // respective observer seeds. The runtime side of the pin
        // sweeps the missing-status + empty-slot corners on the
        // `EphemeralAllocation` half; the `Process` half is exercised
        // by its own `crd.rs::tests::observed_identity_*` pin
        // family — this test binds only the peer-axis shape.
        let a_no_status = alloc_without_status();
        let a_empty_slot = alloc_with_bound_pool(None);
        assert!(a_no_status.observed_bound_pool().is_none());
        assert!(a_empty_slot.observed_bound_pool().is_none());
        // Structural peer-axis coherence: bind both signatures as fn
        // pointers at their peer resolution type so the compiler
        // refuses to build if either side's shape drifts. The `_`
        // let-bindings assert the target type inference.
        let _bound_pool_shape: fn(&EphemeralAllocation) -> Option<&AllocationRef> =
            EphemeralAllocation::observed_bound_pool;
        let _identity_shape: fn(&crate::prelude::Process) -> Option<&crate::identity::Identity> =
            crate::prelude::Process::observed_identity;
    }

    // ─── EphemeralAllocation::observed_expires_at substrate pins ────
    //
    // The copy-form status-projection primitive on the TTL-expiry axis.
    // Collapses the pre-lift hand-authored `.status.as_ref().and_then(
    // |s| s.expires_at)` chain in `tatara-pool-reconciler::
    // allocation_decide::AllocationConvergenceCtx::observe`'s
    // `expires_at` seed onto the ONE substrate primitive. Same-CRD peer
    // to `observed_phase` on the (copy-form × status-slot) axis — both
    // primitives walk the identical `.status.as_ref().<map|and_then>(
    // |s| s.<Copy-field>)` shape. Each pin is fail-before-pass-after:
    // `observed_expires_at` did not exist pre-lift, so any test invoking
    // it fails to compile pre-lift and passes post-lift.

    fn alloc_with_expires_at(expires_at: Option<DateTime<Utc>>) -> EphemeralAllocation {
        let spec = AllocationSpec {
            pool_ref: None,
            requestor: Requestor {
                kind: "manual".into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            },
            ttl: None,
            note: None,
        };
        let mut a = EphemeralAllocation::new("exp-alloc", spec);
        a.status = Some(AllocationStatus {
            phase: AllocationPhase::Bound,
            expires_at,
            ..AllocationStatus::default()
        });
        a
    }

    #[test]
    fn observed_expires_at_returns_none_when_status_is_none() {
        // Missing-`status` corner pin: the primitive collapses the
        // no-status case to `None` so downstream `.is_some()` / any
        // deadline comparison behaves identically on an
        // `EphemeralAllocation` whose status field is `None` and on
        // one whose status carries an unpopulated `expires_at` slot.
        // Matches the pre-lift `.and_then(...)` chain's `None` byte-
        // identically at the pool reconciler's Release-composition
        // TTL gate.
        let a = alloc_without_status();
        assert!(a.observed_expires_at().is_none());
    }

    #[test]
    fn observed_expires_at_returns_none_when_slot_is_none() {
        // Empty-slot-under-populated-status corner pin: the primitive
        // returns `None`, matching the missing-`status` corner byte-
        // identically. A regression that treated the two corners
        // differently would silently promote an internal representation
        // detail (whether the pool reconciler has ever written a
        // `status.expires_at` field for a not-yet-Bound allocation)
        // into observable behavior at the Release-composition branch
        // of the allocation reconciler's `decide` transition rule.
        let a = alloc_with_expires_at(None);
        assert!(a.observed_expires_at().is_none());
    }

    #[test]
    fn observed_expires_at_returns_populated_timestamp_verbatim() {
        // Happy-path pin: with a populated `status.expires_at` slot,
        // the primitive returns the persisted `DateTime<Utc>` verbatim.
        // A regression that filtered / clamped / canonicalized the
        // timestamp would surface here rather than as silent skew at
        // the Release-composition TTL gate's `>=` deadline comparison.
        let expected = Utc::now();
        let a = alloc_with_expires_at(Some(expected));
        assert_eq!(a.observed_expires_at(), Some(expected));
    }

    #[test]
    fn observed_expires_at_is_a_pure_projection() {
        // Purity pin: calling the projection twice on the same
        // `EphemeralAllocation` returns byte-identical `Option`s. A
        // regression that introduced state — a lazy-cached value, a
        // normalization step that ran once and cached — would surface
        // here rather than as silent drift between two dispatches
        // within one reconcile pass.
        let expected = Utc::now();
        let a = alloc_with_expires_at(Some(expected));
        assert_eq!(a.observed_expires_at(), a.observed_expires_at());
    }

    #[test]
    fn observed_expires_at_matches_pre_lift_chain_bytewise() {
        // Byte-identical parity pin between the copy-form primitive
        // here and the pre-lift `tatara-pool-reconciler`
        // `.status.as_ref().and_then(|s| s.expires_at)` chain. Sweeps
        // every corner every callsite plausibly encounters (missing
        // status, empty `expires_at` slot, populated `expires_at`
        // slot). A regression that inserted a normalization step at
        // the primitive the pre-lift chain does NOT apply — or vice
        // versa — surfaces here rather than as silent drift between
        // the pre-lift consumer site and the ONE substrate owner it
        // now routes through.
        fn pre_lift(a: &EphemeralAllocation) -> Option<DateTime<Utc>> {
            a.status.as_ref().and_then(|s| s.expires_at)
        }
        // Missing status.
        let a = alloc_without_status();
        assert_eq!(a.observed_expires_at(), pre_lift(&a));
        // Populated status, empty `expires_at` slot.
        let a = alloc_with_expires_at(None);
        assert_eq!(a.observed_expires_at(), pre_lift(&a));
        // Populated status, populated `expires_at` slot.
        let a = alloc_with_expires_at(Some(Utc::now()));
        assert_eq!(a.observed_expires_at(), pre_lift(&a));
    }

    #[test]
    fn observed_expires_at_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
        // Cross-corner coherence pin: the missing-`status` corner and
        // the populated-empty-slot corner return `Option`s whose
        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
        // regression that promoted the missing-`status` corner to a
        // typed error (via a signature change to `Result<_, _>`) — or
        // that widened the empty-slot corner to a synthetic
        // `Some(Utc::now())` — would surface here rather than as
        // silent operator-facing divergence between a never-status-
        // written allocation and a Bind-time-without-TTL allocation on
        // the Release-composition branch.
        let a_no_status = alloc_without_status();
        let a_empty_slot = alloc_with_expires_at(None);
        assert_eq!(
            a_no_status.observed_expires_at().is_none(),
            a_empty_slot.observed_expires_at().is_none(),
        );
        assert_eq!(
            a_no_status.observed_expires_at().is_some(),
            a_empty_slot.observed_expires_at().is_some(),
        );
    }

    #[test]
    fn observed_expires_at_shape_agrees_with_observed_phase_peer_axis() {
        // Same-CRD peer-axis coherence pin binding the SAME
        // `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` shape
        // that both `EphemeralAllocation::observed_expires_at` (this
        // primitive) and `EphemeralAllocation::observed_phase` walk,
        // differing only in the outer combinator (`and_then` here
        // because the persisted field is itself `Option<T>`, `map`
        // there because the persisted phase is bare) and in the
        // projected `Copy` type. Structural test — both signatures
        // must resolve as `&Self -> Option<T>` fn pointers with `T`
        // `Copy`, so a future rename or a signature drift that (say)
        // widened one side to `Option<&T>` or narrowed one side to
        // `T` fails to compile here rather than silently drifting
        // the family apart. The runtime side of the pin sweeps the
        // missing-status + empty-slot corners on the `expires_at`
        // half; the `phase` half is exercised by its own
        // `tests::observed_phase_*` pin family — this test binds
        // only the peer-axis shape.
        let a_no_status = alloc_without_status();
        let a_empty_slot = alloc_with_expires_at(None);
        assert!(a_no_status.observed_expires_at().is_none());
        assert!(a_empty_slot.observed_expires_at().is_none());
        // Structural peer-axis coherence: bind both signatures as fn
        // pointers at their peer resolution type so the compiler
        // refuses to build if either side's shape drifts.
        let _expires_at_shape: fn(&EphemeralAllocation) -> Option<DateTime<Utc>> =
            EphemeralAllocation::observed_expires_at;
        let _phase_shape: fn(&EphemeralAllocation) -> Option<AllocationPhase> =
            EphemeralAllocation::observed_phase;
    }

    #[test]
    fn allocation_spec_omits_optional_fields() {
        let s = AllocationSpec {
            pool_ref: None,
            requestor: Requestor {
                kind: "manual".into(),
                repo: None,
                branch: None,
                pr_number: None,
                sha: None,
                pr_labels: vec![],
                actor: None,
            },
            ttl: None,
            note: None,
        };
        let yaml = serde_yaml::to_string(&s).unwrap();
        assert!(!yaml.contains("poolRef"));
        assert!(!yaml.contains("ttl"));
        assert!(!yaml.contains("note"));
    }

    // ─── AllocationStatus::transition substrate pins ────────────────────
    //
    // Pin the substrate composer at fail-before-pass-after granularity:
    // the composer did not exist pre-lift, so any regression against
    // the four hand-authored sites in
    // `tatara-pool-reconciler::controller_allocation::reconcile_inner`
    // surfaces at these pins rather than as silent operator-visible
    // status-patch skew.

    fn anchor_time() -> DateTime<Utc> {
        // A deterministic non-`Utc::now()` anchor so pins that read
        // back `phase_since` do not race the wall clock.
        DateTime::parse_from_rfc3339("2026-05-01T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc)
    }

    #[test]
    fn allocation_status_transition_stamps_supplied_phase_verbatim() {
        for phase in AllocationPhase::ALL {
            let s = AllocationStatus::transition(phase, "irrelevant", anchor_time());
            assert_eq!(s.phase, phase, "phase drifted for {phase:?}");
        }
    }

    #[test]
    fn allocation_status_transition_stamps_supplied_message_verbatim() {
        let s = AllocationStatus::transition(
            AllocationPhase::Queued,
            "pool matched; no Free member available",
            anchor_time(),
        );
        assert_eq!(
            s.message.as_deref(),
            Some("pool matched; no Free member available"),
        );
    }

    #[test]
    fn allocation_status_transition_sets_phase_since_to_supplied_now() {
        let anchor = anchor_time();
        let s = AllocationStatus::transition(AllocationPhase::Bound, "bound", anchor);
        assert_eq!(
            s.phase_since,
            Some(anchor),
            "phase_since must be the supplied `now`, not a fresh Utc::now()",
        );
    }

    #[test]
    fn allocation_status_transition_defaults_every_optional_slot() {
        // The composer stamps only the three always-present slots
        // (`phase + phase_since + message`); every other slot on
        // `AllocationStatus` must land at its `Default`-equivalent
        // variant so a caller-branch that attaches an optional slot
        // via struct-update syntax does not silently inherit a
        // pre-populated non-`None`/non-empty value.
        let s = AllocationStatus::transition(AllocationPhase::Released, "released", anchor_time());
        assert!(s.bound_pool.is_none(), "bound_pool must default to None");
        assert!(
            s.assigned_process.is_none(),
            "assigned_process must default to None"
        );
        assert!(
            s.allocated_at.is_none(),
            "allocated_at must default to None"
        );
        assert!(s.expires_at.is_none(), "expires_at must default to None");
        assert!(
            s.conditions.is_empty(),
            "conditions must default to an empty Vec"
        );
    }

    #[test]
    fn allocation_status_transition_accepts_owned_string_and_static_str() {
        // `impl Into<String>` matches every current callsite:
        // three of the four hand-authored sites pass `&'static str`
        // literal reasons; the fourth ("bound to pool member") also
        // passes a `&'static str`. Sibling to
        // `tatara-reconciler::patch::phase_status_msg`'s identical
        // `impl Into<String>` signature.
        let via_static = AllocationStatus::transition(
            AllocationPhase::NoMatchingPool,
            "no Pool selector matched this Requestor",
            anchor_time(),
        );
        let via_owned = AllocationStatus::transition(
            AllocationPhase::NoMatchingPool,
            String::from("no Pool selector matched this Requestor"),
            anchor_time(),
        );
        assert_eq!(via_static.message, via_owned.message);
    }

    #[test]
    fn allocation_status_transition_serializes_to_pre_lift_json_shape() {
        // Byte-shape pin against the exact `json!({ "status": {
        // "phase": <variant>, "phaseSince": <now>, "message": "<msg>"
        // } })` incantation every pre-lift callsite restated. A
        // regression that reordered a slot, dropped the `phaseSince`
        // stamp, or drifted the camelCase key naming here surfaces at
        // THIS pin rather than as a subtle patch_status body the K8s
        // API server accepts but the pool reconciler's next observe
        // pass fails to read back.
        let anchor = anchor_time();
        let via_composer =
            AllocationStatus::transition(AllocationPhase::NoMatchingPool, "no match", anchor);
        let composed = serde_json::json!({ "status": via_composer });
        let hand_authored = serde_json::json!({
            "status": {
                "phase": AllocationPhase::NoMatchingPool,
                "phaseSince": anchor,
                "message": "no match",
            }
        });
        assert_eq!(composed, hand_authored);
    }

    #[test]
    fn allocation_status_transition_composes_with_struct_update_for_bind_seed() {
        // Pin the compound shape the `AllocationDecision::Bind`
        // callsite composes: the substrate seed carries `phase +
        // phase_since + message`, and the branch attaches
        // `bound_pool` + `assigned_process` + `allocated_at` +
        // `expires_at` via struct-update syntax. Post-lift the four
        // extra slots survive the compose intact and the base three
        // slots inherit the composer's stamps verbatim.
        let anchor = anchor_time();
        let ttl = anchor + chrono::Duration::hours(1);
        let pool = AllocationRef::new("demo-pool", "pools");
        let assigned = AllocationRef::new("demo-abcd", "pools");
        let bind_status = AllocationStatus {
            bound_pool: Some(pool.clone()),
            assigned_process: Some(assigned.clone()),
            allocated_at: Some(anchor),
            expires_at: Some(ttl),
            ..AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor)
        };
        // Base-three slots stamped by the composer.
        assert_eq!(bind_status.phase, AllocationPhase::Bound);
        assert_eq!(bind_status.phase_since, Some(anchor));
        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
        // Struct-update-attached branch slots.
        assert_eq!(
            bind_status.bound_pool.as_ref().map(|r| &r.name),
            Some(&pool.name)
        );
        assert_eq!(
            bind_status.assigned_process.as_ref().map(|r| &r.name),
            Some(&assigned.name)
        );
        assert_eq!(bind_status.allocated_at, Some(anchor));
        assert_eq!(bind_status.expires_at, Some(ttl));
    }

    // ─── AllocationStatus::bound_transition substrate pins ─────────────
    //
    // Pin the compound composer at fail-before-pass-after granularity:
    // the composer wraps [`AllocationStatus::transition`] with the
    // `bound_pool + assigned_process` pair the Bind / Release arms
    // both stamped inline pre-lift.

    #[test]
    fn allocation_status_bound_transition_stamps_supplied_pool_and_process_verbatim() {
        let anchor = anchor_time();
        let pool = AllocationRef::new("demo-pool", "pools");
        let assigned = AllocationRef::new("demo-abcd", "pools");
        let s = AllocationStatus::bound_transition(
            AllocationPhase::Released,
            "released; pool reconciler will return the member",
            anchor,
            pool.clone(),
            assigned.clone(),
        );
        assert_eq!(s.bound_pool.as_ref(), Some(&pool));
        assert_eq!(s.assigned_process.as_ref(), Some(&assigned));
    }

    #[test]
    fn allocation_status_bound_transition_inherits_transition_triplet_verbatim() {
        // The compound composer must not stamp its own `phase +
        // phase_since + message` triplet — it MUST compose the pair
        // atop the substrate `Self::transition` seed so any future
        // evolution to the base triplet lands at ONE site and this
        // composer inherits the upgrade mechanically. Pin the triplet
        // through the same axis-uniform reads the transition tests use.
        let anchor = anchor_time();
        let via_compound = AllocationStatus::bound_transition(
            AllocationPhase::Bound,
            "bound to pool member",
            anchor,
            AllocationRef::new("p", "ns"),
            AllocationRef::new("q", "ns"),
        );
        let via_base =
            AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor);
        assert_eq!(via_compound.phase, via_base.phase);
        assert_eq!(via_compound.phase_since, via_base.phase_since);
        assert_eq!(via_compound.message, via_base.message);
    }

    #[test]
    fn allocation_status_bound_transition_defaults_every_optional_slot_beyond_the_pair() {
        // The compound composer stamps only the base triplet + the
        // `bound_pool + assigned_process` pair; every other optional
        // slot (`allocated_at` / `expires_at` / `conditions`) must
        // land at its `Default`-equivalent variant so a caller-branch
        // that attaches an addendum via struct-update syntax (a Bind
        // arm's `allocated_at` + `expires_at` stamp) does not
        // silently inherit a pre-populated non-`None`/non-empty value.
        let s = AllocationStatus::bound_transition(
            AllocationPhase::Released,
            "released",
            anchor_time(),
            AllocationRef::new("p", "ns"),
            AllocationRef::new("q", "ns"),
        );
        assert!(
            s.allocated_at.is_none(),
            "allocated_at must default to None"
        );
        assert!(s.expires_at.is_none(), "expires_at must default to None");
        assert!(
            s.conditions.is_empty(),
            "conditions must default to an empty Vec"
        );
    }

    #[test]
    fn allocation_status_bound_transition_composes_with_struct_update_for_bind_seed() {
        // Pin the compound shape the `AllocationDecision::Bind`
        // callsite post-lift composes: the compound composer seeds
        // `phase + phase_since + message + bound_pool +
        // assigned_process`, and the Bind branch attaches
        // `allocated_at` + `expires_at` via struct-update syntax.
        // Post-lift the two extra slots survive the compose intact
        // and the base five slots inherit the composer's stamps
        // verbatim.
        let anchor = anchor_time();
        let ttl = anchor + chrono::Duration::hours(1);
        let pool = AllocationRef::new("demo-pool", "pools");
        let assigned = AllocationRef::new("demo-abcd", "pools");
        let bind_status = AllocationStatus {
            allocated_at: Some(anchor),
            expires_at: Some(ttl),
            ..AllocationStatus::bound_transition(
                AllocationPhase::Bound,
                "bound to pool member",
                anchor,
                pool.clone(),
                assigned.clone(),
            )
        };
        assert_eq!(bind_status.phase, AllocationPhase::Bound);
        assert_eq!(bind_status.phase_since, Some(anchor));
        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
        assert_eq!(bind_status.bound_pool.as_ref(), Some(&pool));
        assert_eq!(bind_status.assigned_process.as_ref(), Some(&assigned));
        assert_eq!(bind_status.allocated_at, Some(anchor));
        assert_eq!(bind_status.expires_at, Some(ttl));
    }

    #[test]
    fn allocation_status_bound_transition_matches_pre_lift_release_arm_verbatim() {
        // Byte-shape pin against the exact pre-lift `AllocationStatus
        // { bound_pool: Some(pool), assigned_process:
        // Some(AllocationRef::new(..)), ..AllocationStatus::transition
        // (Released, "…", now) }` composition the
        // `AllocationDecision::Release` arm restated inline pre-lift.
        // A regression that reordered the pair, dropped a `Some`, or
        // drifted the composed base triplet here surfaces at THIS pin
        // rather than as a subtle patch_status body the K8s API
        // server accepts but the audit record disagrees on.
        let anchor = anchor_time();
        let pool = AllocationRef::new("demo-pool", "pools");
        let assigned = AllocationRef::new("demo-abcd", "pools");
        let via_composer = AllocationStatus::bound_transition(
            AllocationPhase::Released,
            "released; pool reconciler will return the member",
            anchor,
            pool.clone(),
            assigned.clone(),
        );
        let via_hand_authored = AllocationStatus {
            bound_pool: Some(pool),
            assigned_process: Some(assigned),
            ..AllocationStatus::transition(
                AllocationPhase::Released,
                "released; pool reconciler will return the member",
                anchor,
            )
        };
        assert_eq!(
            serde_json::to_value(&via_composer).unwrap(),
            serde_json::to_value(&via_hand_authored).unwrap(),
        );
    }

    #[test]
    fn allocation_status_transition_shape_agrees_with_pool_status_observed_peer() {
        // Cross-CRD peer-axis coherence: both substrate composers
        // (`PoolStatus::observed`, `AllocationStatus::transition`)
        // accept a caller-supplied `now: DateTime<Utc>` at the SAME
        // signature slot, stamp it into `phase_since` uniformly, and
        // leave every other slot at its `Default`-equivalent variant.
        // Structural pin: if either side's `now` signature drifts to
        // `impl Into<DateTime<Utc>>` or a reference form, this bind
        // fails to compile here rather than silently drifting the
        // family apart.
        let _allocation_shape: fn(
            AllocationPhase,
            &'static str,
            DateTime<Utc>,
        ) -> AllocationStatus = AllocationStatus::transition;
        // (`PoolStatus::observed`'s pinned coherence lives at its own
        // peer pin family in `crate::pool`; this pin binds the
        // `AllocationStatus::transition` side of the peer pair.)
    }
}