meerkat-workgraph 0.8.18

Realm-scoped durable work graph subsystem for Meerkat
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
use std::collections::BTreeSet;
use std::fmt;
use std::str::FromStr;

use chrono::{DateTime, Utc};
use meerkat_core::SessionId;
use meerkat_core::auth::PrincipalId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

use crate::WorkGraphError;
pub use crate::machines::work_attention_lifecycle::WorkAttentionLifecycleMachineState as WorkAttentionMachineState;
pub use crate::machines::work_execution_lifecycle::WorkExecutionEvidenceKind;
pub use crate::machines::work_execution_lifecycle::WorkExecutionLifecycleMachineState as WorkExecutionMachineState;
use crate::machines::workgraph_lifecycle as wg_dsl;
pub use crate::machines::workgraph_lifecycle::WorkGraphLifecycleMachineState as WorkGraphMachineState;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct WorkItemId(String);

impl WorkItemId {
    pub fn new(value: impl Into<String>) -> Result<Self, WorkGraphError> {
        validate_token("work item id", value.into()).map(Self)
    }

    pub fn generated() -> Self {
        Self(format!("work_{}", Uuid::now_v7()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct WorkAttentionBindingId(String);

impl WorkAttentionBindingId {
    pub fn new(value: impl Into<String>) -> Result<Self, WorkGraphError> {
        validate_token("work attention binding id", value.into()).map(Self)
    }

    pub fn generated() -> Self {
        Self(format!("attention_{}", Uuid::now_v7()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl FromStr for WorkAttentionBindingId {
    type Err = WorkGraphError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// Stable identity for one WorkGraph-to-execution association.
///
/// Binding identity and target specification are immutable once inserted. The
/// generated execution-handoff machine state advances by CAS while the target
/// runtime remains the sole owner of run state and outputs.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct WorkExecutionBindingId(String);

impl WorkExecutionBindingId {
    pub fn new(value: impl Into<String>) -> Result<Self, WorkGraphError> {
        validate_token("work execution binding id", value.into()).map(Self)
    }

    pub fn generated() -> Self {
        Self(format!("execution_{}", Uuid::now_v7()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl FromStr for WorkExecutionBindingId {
    type Err = WorkGraphError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

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

impl FromStr for WorkItemId {
    type Err = WorkGraphError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct WorkNamespace(String);

impl WorkNamespace {
    pub fn new(value: impl Into<String>) -> Result<Self, WorkGraphError> {
        validate_token("work namespace", value.into()).map(Self)
    }

    pub fn default_namespace() -> Self {
        Self("default".to_string())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for WorkNamespace {
    fn default() -> Self {
        Self::default_namespace()
    }
}

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

impl FromStr for WorkNamespace {
    type Err = WorkGraphError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

fn validate_token(name: &str, value: String) -> Result<String, WorkGraphError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(WorkGraphError::InvalidInput(format!(
            "{name} must not be empty"
        )));
    }
    if trimmed.chars().any(char::is_control) {
        return Err(WorkGraphError::InvalidInput(format!(
            "{name} must not contain control characters"
        )));
    }
    Ok(trimmed.to_string())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkStatus {
    #[default]
    Open,
    InProgress,
    Blocked,
    Completed,
    Cancelled,
    Failed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkPriority {
    Low,
    #[default]
    Medium,
    High,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkEdgeKind {
    Blocks,
    Parent,
    Related,
    Supersedes,
    DerivedFrom,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkOwnerKind {
    Principal,
    Agent,
    Session,
    Mob,
    Label,
}

impl WorkOwnerKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Principal => "principal",
            Self::Agent => "agent",
            Self::Session => "session",
            Self::Mob => "mob",
            Self::Label => "label",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkOwnerKey {
    pub kind: WorkOwnerKind,
    pub id: String,
}

impl WorkOwnerKey {
    pub fn new(kind: WorkOwnerKind, id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Ok(Self {
            kind,
            id: validate_token("work owner id", id.into())?,
        })
    }

    pub fn principal(id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Self::new(WorkOwnerKind::Principal, id)
    }

    pub fn agent(id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Self::new(WorkOwnerKind::Agent, id)
    }

    pub fn session(id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Self::new(WorkOwnerKind::Session, id)
    }

    pub fn mob(id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Self::new(WorkOwnerKind::Mob, id)
    }

    pub fn label(id: impl Into<String>) -> Result<Self, WorkGraphError> {
        Self::new(WorkOwnerKind::Label, id)
    }

    pub fn canonical(&self) -> String {
        format!("{}:{}", self.kind.as_str(), self.id)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkOwner {
    pub key: WorkOwnerKey,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WorkCompletionPolicy {
    #[default]
    SelfAttest,
    HostConfirmed,
    PrincipalConfirmed,
    Supervisor {
        owner_key: WorkOwnerKey,
    },
    ReviewerQuorum {
        #[cfg_attr(feature = "schema", schemars(range(min = 1, max = 64)))]
        threshold: u16,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PublicGoalCompletionPolicy {
    #[default]
    SelfAttest,
}

impl From<PublicGoalCompletionPolicy> for WorkCompletionPolicy {
    fn from(policy: PublicGoalCompletionPolicy) -> Self {
        match policy {
            PublicGoalCompletionPolicy::SelfAttest => Self::SelfAttest,
        }
    }
}

impl WorkCompletionPolicy {
    pub fn requires_trusted_principal(&self) -> bool {
        matches!(
            self,
            Self::PrincipalConfirmed | Self::Supervisor { .. } | Self::ReviewerQuorum { .. }
        )
    }

    pub(crate) fn to_machine(&self) -> wg_dsl::WorkCompletionPolicy {
        match self {
            Self::SelfAttest => wg_dsl::WorkCompletionPolicy::SelfAttest,
            Self::HostConfirmed => wg_dsl::WorkCompletionPolicy::HostConfirmed,
            Self::PrincipalConfirmed => wg_dsl::WorkCompletionPolicy::PrincipalConfirmed,
            Self::Supervisor { .. } => wg_dsl::WorkCompletionPolicy::Supervisor,
            Self::ReviewerQuorum { .. } => wg_dsl::WorkCompletionPolicy::ReviewerQuorum,
        }
    }

    pub(crate) fn supervisor_owner_key(&self) -> Option<wg_dsl::WorkOwnerKey> {
        match self {
            Self::Supervisor { owner_key } => Some(work_owner_key_to_machine(owner_key)),
            _ => None,
        }
    }

    pub(crate) fn reviewer_quorum_threshold(&self) -> Option<u64> {
        match self {
            Self::ReviewerQuorum { threshold } => Some(u64::from(*threshold)),
            _ => None,
        }
    }

    pub(crate) fn from_machine(
        policy: wg_dsl::WorkCompletionPolicy,
        supervisor_owner_key: Option<wg_dsl::WorkOwnerKey>,
        reviewer_quorum_threshold: Option<u64>,
    ) -> Self {
        match policy {
            wg_dsl::WorkCompletionPolicy::SelfAttest => Self::SelfAttest,
            wg_dsl::WorkCompletionPolicy::HostConfirmed => Self::HostConfirmed,
            wg_dsl::WorkCompletionPolicy::PrincipalConfirmed => Self::PrincipalConfirmed,
            wg_dsl::WorkCompletionPolicy::Supervisor => Self::Supervisor {
                owner_key: supervisor_owner_key
                    .map(work_owner_key_from_machine)
                    .unwrap_or_else(|| WorkOwnerKey {
                        kind: WorkOwnerKind::Principal,
                        id: "supervisor".to_string(),
                    }),
            },
            wg_dsl::WorkCompletionPolicy::ReviewerQuorum => Self::ReviewerQuorum {
                threshold: reviewer_quorum_threshold
                    .and_then(|threshold| u16::try_from(threshold).ok())
                    .unwrap_or(1),
            },
        }
    }
}

impl WorkOwner {
    pub fn new(key: WorkOwnerKey) -> Self {
        Self {
            key,
            display_name: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkClaim {
    pub owner: WorkOwner,
    pub claimed_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lease_expires_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ExternalWorkRef {
    pub kind: String,
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// Typed classification of confirmation evidence.
///
/// This is the canonical signal the `WorkGraphLifecycleMachine` consumes to
/// decide completion-policy satisfaction. The producer
/// (`confirmation_evidence_for_policy`) sets this field; the raw
/// [`WorkEvidenceRef::kind`] string remains only as opaque provenance/display
/// and is never re-read to classify evidence for the satisfaction decision.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkEvidenceKind {
    /// Generic / self-attested evidence that does not satisfy any
    /// confirmation policy on its own.
    #[default]
    SelfAttest,
    HostConfirmation,
    PrincipalConfirmation,
    SupervisorConfirmation,
    ReviewerConfirmation,
}

impl WorkEvidenceKind {
    pub(crate) fn to_machine(self) -> wg_dsl::WorkEvidenceKind {
        match self {
            Self::SelfAttest => wg_dsl::WorkEvidenceKind::SelfAttest,
            Self::HostConfirmation => wg_dsl::WorkEvidenceKind::HostConfirmation,
            Self::PrincipalConfirmation => wg_dsl::WorkEvidenceKind::PrincipalConfirmation,
            Self::SupervisorConfirmation => wg_dsl::WorkEvidenceKind::SupervisorConfirmation,
            Self::ReviewerConfirmation => wg_dsl::WorkEvidenceKind::ReviewerConfirmation,
        }
    }

    /// Parse a reserved confirmation classification out of the opaque
    /// provenance/display [`WorkEvidenceRef::kind`] string at the ingress
    /// boundary. The recognized reserved literals map 1:1 onto a confirmation
    /// variant; the generic `"self_attest"` literal and every other string
    /// (including the empty string) carry no reserved confirmation and yield
    /// `None`. This is the single place the opaque string is classified — every
    /// downstream decision reads the typed classification, not the string.
    pub(crate) fn from_kind_str(kind: &str) -> Option<Self> {
        match kind {
            "host_confirmation" => Some(Self::HostConfirmation),
            "principal_confirmation" => Some(Self::PrincipalConfirmation),
            "supervisor_confirmation" => Some(Self::SupervisorConfirmation),
            "reviewer_confirmation" => Some(Self::ReviewerConfirmation),
            _ => None,
        }
    }

    /// Whether this classification is a reserved confirmation that may only be
    /// stamped by the trusted goal-confirm producer. Generic
    /// [`WorkEvidenceKind::SelfAttest`] evidence is never reserved.
    pub(crate) fn is_reserved_confirmation(self) -> bool {
        !matches!(self, Self::SelfAttest)
    }

    /// Project the typed classification into the machine-owned confirmation
    /// observation the `WorkGraphLifecycleMachine` consumes. Generic
    /// self-attested evidence projects to the `Other` observation; the
    /// empty-display case is handled separately by the caller.
    pub(crate) fn to_confirmation_observation(self) -> wg_dsl::WorkConfirmationEvidenceObservation {
        match self {
            Self::SelfAttest => wg_dsl::WorkConfirmationEvidenceObservation::Other,
            Self::HostConfirmation => wg_dsl::WorkConfirmationEvidenceObservation::HostConfirmation,
            Self::PrincipalConfirmation => {
                wg_dsl::WorkConfirmationEvidenceObservation::PrincipalConfirmation
            }
            Self::SupervisorConfirmation => {
                wg_dsl::WorkConfirmationEvidenceObservation::SupervisorConfirmation
            }
            Self::ReviewerConfirmation => {
                wg_dsl::WorkConfirmationEvidenceObservation::ReviewerConfirmation
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkEvidenceRef {
    /// Opaque provenance/display label for the evidence. It is parsed into the
    /// typed confirmation classification at the ingress boundary only (see
    /// [`WorkEvidenceRef::confirmation_classification`]); no completion-policy
    /// satisfaction decision re-reads this string. The typed
    /// [`WorkEvidenceRef::confirmation_kind`] is the authoritative carrier.
    pub kind: String,
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Typed confirmation classification set by the trusted producer. Drives the
    /// machine-owned completion-policy satisfaction decision. Generic evidence
    /// leaves this unset (treated as `SelfAttest`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmation_kind: Option<WorkEvidenceKind>,
    /// Typed identity of the confirming owner for supervisor/reviewer
    /// confirmations. Set by the trusted producer; the machine records distinct
    /// owners per confirmation kind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirming_owner_key: Option<WorkOwnerKey>,
    /// Typed execution provenance stamped only by the execution bridge. The
    /// opaque `id` remains a display/dedup projection and is never interpreted
    /// as mutation authority.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
    pub execution_binding_id: Option<WorkExecutionBindingId>,
}

impl WorkEvidenceRef {
    /// The effective typed confirmation classification carried by this evidence,
    /// considering BOTH carriers: the typed [`WorkEvidenceRef::confirmation_kind`]
    /// field (authoritative when set) and the reserved confirmation literals that
    /// may be encoded only in the opaque [`WorkEvidenceRef::kind`] string at
    /// ingress. Returns `None` for generic self-attested evidence.
    ///
    /// This is the single typed read every confirmation decision uses, so a
    /// reserved classification surfaces regardless of which carrier the caller
    /// supplied — closing the gap where the machine honored a forged
    /// `confirmation_kind` while the guards inspected only the `kind` string.
    pub(crate) fn confirmation_classification(&self) -> Option<WorkEvidenceKind> {
        self.confirmation_kind
            .filter(|kind| kind.is_reserved_confirmation())
            .or_else(|| WorkEvidenceKind::from_kind_str(&self.kind))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkItemRef {
    pub realm_id: String,
    pub namespace: WorkNamespace,
    pub item_id: WorkItemId,
}

/// Durable target-runtime principal under which one execution attempt was
/// admitted. Recovery must re-present this exact authority rather than inherit
/// the ambient principal of whichever host happens to reconcile the binding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum WorkExecutionAuthority {
    TargetOwner,
    Principal { principal_id: PrincipalId },
}

impl WorkExecutionAuthority {
    pub fn principal(principal_id: PrincipalId) -> Self {
        Self::Principal { principal_id }
    }

    fn validate(&self) -> Result<(), WorkGraphError> {
        match self {
            Self::TargetOwner => Ok(()),
            Self::Principal { .. } => Ok(()),
        }
    }
}

/// Exact execution identity bound to a durable WorkGraph commitment.
///
/// This enum intentionally carries stable domain identifiers and canonical
/// input bytes, never process-local handles. The target runtime remains the
/// sole owner of execution status and outputs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum WorkExecutionTarget {
    MobFlow {
        mob_id: String,
        flow_id: String,
        flow_config_digest: String,
        run_id: String,
        execution_authority: WorkExecutionAuthority,
        activation_params: Value,
    },
}

impl WorkExecutionTarget {
    const MAX_ACTIVATION_PARAMS_BYTES: usize = 64 * 1024;

    pub fn mob_flow(
        mob_id: impl Into<String>,
        flow_id: impl Into<String>,
        flow_config_digest: impl Into<String>,
        run_id: impl Into<String>,
        execution_authority: WorkExecutionAuthority,
        activation_params: Value,
    ) -> Result<Self, WorkGraphError> {
        let mob_id = validate_token("mob id", mob_id.into())?;
        let flow_id = validate_token("flow id", flow_id.into())?;
        let flow_config_digest =
            validate_sha256_digest("Flow run config digest", flow_config_digest.into())?;
        let run_id = validate_token("flow run id", run_id.into())?;
        execution_authority.validate()?;
        Self::validate_activation_params(&activation_params)?;
        Ok(Self::MobFlow {
            mob_id,
            flow_id,
            flow_config_digest,
            run_id,
            execution_authority,
            activation_params,
        })
    }

    pub fn run_id(&self) -> &str {
        match self {
            Self::MobFlow { run_id, .. } => run_id,
        }
    }

    fn validate_activation_params(value: &Value) -> Result<(), WorkGraphError> {
        let bytes = serde_json::to_vec(value).map_err(|error| {
            WorkGraphError::InvalidInput(format!(
                "Flow activation parameters are not serializable: {error}"
            ))
        })?;
        if bytes.len() > Self::MAX_ACTIVATION_PARAMS_BYTES {
            return Err(WorkGraphError::InvalidInput(format!(
                "Flow activation parameters exceed the {} byte durable binding limit",
                Self::MAX_ACTIVATION_PARAMS_BYTES
            )));
        }
        Ok(())
    }
}

/// Durable association between one WorkGraph item and one execution attempt.
///
/// Retries form a single append-only chain through `supersedes`. The binding
/// specification is immutable. Only `machine_state` advances, by
/// CAS through `WorkExecutionLifecycleMachine`. There is no copied execution
/// status here: reconciliation always reads the target runtime's canonical run
/// state. Evidence projection is deduplicated by [`Self::evidence_id`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct WorkExecutionBinding {
    pub binding_id: WorkExecutionBindingId,
    pub work_ref: WorkItemRef,
    pub target: WorkExecutionTarget,
    pub idempotency_key: String,
    pub correlation_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supersedes: Option<WorkExecutionBindingId>,
    #[cfg_attr(feature = "schema", schemars(with = "WorkExecutionMachineStateSchema"))]
    pub machine_state: WorkExecutionMachineState,
    pub created_at: DateTime<Utc>,
}

#[cfg(feature = "schema")]
#[derive(schemars::JsonSchema)]
#[allow(dead_code)]
struct WorkExecutionMachineStateSchema {
    lifecycle_phase: String,
    binding_id: String,
    run_id: String,
    revision: u64,
    last_failure_detail: Option<String>,
    evidence_kind: Option<String>,
}

impl WorkExecutionBinding {
    const MAX_IDEMPOTENCY_KEY_BYTES: usize = 256;

    pub fn evidence_id(&self) -> String {
        format!("work_execution:{}", self.binding_id)
    }

    pub(crate) fn validate(&self) -> Result<(), WorkGraphError> {
        validate_token(
            "work execution idempotency key",
            self.idempotency_key.clone(),
        )?;
        if self.idempotency_key.len() > Self::MAX_IDEMPOTENCY_KEY_BYTES {
            return Err(WorkGraphError::InvalidInput(format!(
                "work execution idempotency key exceeds {} bytes",
                Self::MAX_IDEMPOTENCY_KEY_BYTES
            )));
        }
        let correlation = Uuid::parse_str(&self.correlation_id).map_err(|_| {
            WorkGraphError::InvalidInput(
                "work execution correlation id must be a canonical UUID".to_string(),
            )
        })?;
        if correlation.is_nil() || correlation.to_string() != self.correlation_id {
            return Err(WorkGraphError::InvalidInput(
                "work execution correlation id must be a canonical non-nil UUID".to_string(),
            ));
        }
        match &self.target {
            WorkExecutionTarget::MobFlow {
                mob_id,
                flow_id,
                flow_config_digest,
                run_id,
                execution_authority,
                activation_params,
            } => {
                validate_token("mob id", mob_id.clone())?;
                validate_token("flow id", flow_id.clone())?;
                validate_sha256_digest("Flow run config digest", flow_config_digest.clone())?;
                validate_token("flow run id", run_id.clone())?;
                execution_authority.validate()?;
                WorkExecutionTarget::validate_activation_params(activation_params)?;
            }
        }
        Ok(())
    }

    /// Whether two projections describe the same immutable execution attempt.
    ///
    /// Stores call this independently of the service so a direct trait caller
    /// cannot rewrite authority-bearing identity while advancing machine state.
    pub(crate) fn has_same_immutable_spec(&self, other: &Self) -> bool {
        self.binding_id == other.binding_id
            && self.work_ref == other.work_ref
            && self.target == other.target
            && self.idempotency_key == other.idempotency_key
            && self.correlation_id == other.correlation_id
            && self.supersedes == other.supersedes
            && self.created_at == other.created_at
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkExecutionEvidenceProjection {
    pub kind: WorkExecutionEvidenceKind,
    pub label: Option<String>,
    pub summary: Option<String>,
}

fn validate_sha256_digest(name: &str, value: String) -> Result<String, WorkGraphError> {
    let valid = value.len() == "sha256:".len() + 64
        && value.strip_prefix("sha256:").is_some_and(|hex| {
            hex.bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        });
    if !valid {
        return Err(WorkGraphError::InvalidInput(format!(
            "{name} must be a canonical lowercase SHA-256 digest"
        )));
    }
    Ok(value)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WorkAttentionTarget {
    Session { session_id: SessionId },
    LoweredOwner { owner_key: WorkOwnerKey },
}

impl WorkAttentionTarget {
    pub fn owner_key(&self) -> Result<WorkOwnerKey, WorkGraphError> {
        match self {
            Self::Session { session_id } => WorkOwnerKey::session(session_id.to_string()),
            Self::LoweredOwner { owner_key } => Ok(owner_key.clone()),
        }
    }

    /// Canonical query/uniqueness key for an attention target. This string is
    /// persisted as an indexed store column and backs the
    /// active-binding-per-target invariant, so it must be stable and
    /// injective over the target vocabulary.
    pub fn target_key(&self) -> String {
        match self {
            Self::Session { session_id } => format!("session:{session_id}"),
            Self::LoweredOwner { owner_key } => {
                format!("owner:{}:{}", owner_key.kind.as_str(), owner_key.id)
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum GoalAttentionTarget {
    Session { session_id: SessionId },
    Owner { owner_key: WorkOwnerKey },
}

impl GoalAttentionTarget {
    pub fn to_attention_target(&self) -> WorkAttentionTarget {
        match self {
            Self::Session { session_id } => WorkAttentionTarget::Session {
                session_id: session_id.clone(),
            },
            Self::Owner { owner_key } => WorkAttentionTarget::LoweredOwner {
                owner_key: owner_key.clone(),
            },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkAttentionMode {
    #[default]
    Pursue,
    Coordinate,
    Review,
    Falsify,
    Judge,
    Observe,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "state", rename_all = "snake_case")]
// `status_key()` below mirrors this serde tag vocabulary; keep them in sync.
pub enum WorkAttentionStatus {
    #[default]
    Active,
    Paused {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        until: Option<DateTime<Utc>>,
    },
    Superseded,
    Stopped,
}

impl WorkAttentionStatus {
    /// Canonical status key persisted as an indexed store column (SQL query
    /// pushdown + the active-binding-per-target occupancy guard). Mirrors the
    /// serde `state` tag vocabulary.
    pub fn status_key(&self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::Paused { .. } => "paused",
            Self::Superseded => "superseded",
            Self::Stopped => "stopped",
        }
    }

    /// Terminal statuses are eligible for store pruning: no lifecycle
    /// transition leads out of them.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Superseded | Self::Stopped)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum AttentionDelegatedAuthority {
    #[default]
    AddEvidence,
    CloseOwnReviewItem,
    RequestClosure,
    CloseIfPolicyAllows,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionProjectionPolicy {
    #[serde(default = "default_projection_max_text_chars")]
    pub max_text_chars: u32,
    #[serde(default = "default_include_parent_context")]
    pub include_parent_context: bool,
}

fn default_include_parent_context() -> bool {
    true
}

impl Default for AttentionProjectionPolicy {
    fn default() -> Self {
        Self {
            max_text_chars: default_projection_max_text_chars(),
            include_parent_context: true,
        }
    }
}

fn default_projection_max_text_chars() -> u32 {
    4096
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkAttentionBinding {
    pub binding_id: WorkAttentionBindingId,
    pub work_ref: WorkItemRef,
    pub target: WorkAttentionTarget,
    pub mode: WorkAttentionMode,
    pub status: WorkAttentionStatus,
    #[serde(default = "default_work_attention_machine_state")]
    #[cfg_attr(feature = "schema", schemars(with = "WorkAttentionMachineStateSchema"))]
    pub machine_state: WorkAttentionMachineState,
    pub delegated_authority: AttentionDelegatedAuthority,
    #[serde(default)]
    pub projection_policy: AttentionProjectionPolicy,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[cfg(feature = "schema")]
#[derive(schemars::JsonSchema)]
#[allow(dead_code)]
struct WorkAttentionMachineStateSchema {
    lifecycle_phase: String,
    revision: u64,
    paused_until_utc_ms: Option<u64>,
    superseded_by_binding_key: Option<String>,
    terminal_at_utc_ms: Option<u64>,
}

fn default_work_attention_machine_state() -> WorkAttentionMachineState {
    WorkAttentionMachineState::default()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WorkItem {
    pub id: WorkItemId,
    pub realm_id: String,
    pub namespace: WorkNamespace,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub status: WorkStatus,
    #[serde(default)]
    pub completion_policy: WorkCompletionPolicy,
    pub priority: WorkPriority,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub labels: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<WorkOwner>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claim: Option<WorkClaim>,
    pub machine_state: WorkGraphMachineState,
    pub revision: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub due_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_before: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snoozed_until: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub terminal_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub external_refs: Vec<ExternalWorkRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence_refs: Vec<WorkEvidenceRef>,
}

#[derive(Deserialize)]
struct WorkItemWire {
    id: WorkItemId,
    realm_id: String,
    namespace: WorkNamespace,
    title: String,
    #[serde(default)]
    description: Option<String>,
    status: WorkStatus,
    #[serde(default)]
    completion_policy: WorkCompletionPolicy,
    priority: WorkPriority,
    #[serde(default)]
    labels: BTreeSet<String>,
    #[serde(default)]
    owner: Option<WorkOwner>,
    #[serde(default)]
    claim: Option<WorkClaim>,
    #[serde(default)]
    machine_state: Option<WorkGraphMachineState>,
    revision: u64,
    #[serde(default)]
    due_at: Option<DateTime<Utc>>,
    #[serde(default)]
    not_before: Option<DateTime<Utc>>,
    #[serde(default)]
    snoozed_until: Option<DateTime<Utc>>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    #[serde(default)]
    terminal_at: Option<DateTime<Utc>>,
    #[serde(default)]
    external_refs: Vec<ExternalWorkRef>,
    #[serde(default)]
    evidence_refs: Vec<WorkEvidenceRef>,
}

impl<'de> Deserialize<'de> for WorkItem {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut wire = WorkItemWire::deserialize(deserializer)?;
        let machine_state = wire.machine_state.take().ok_or_else(|| {
            serde::de::Error::custom(
                "WorkItem is missing `machine_state`: lifecycle/revision authority is machine-owned \
                 and cannot be reconstructed from projected fields",
            )
        })?;
        Ok(Self {
            id: wire.id,
            realm_id: wire.realm_id,
            namespace: wire.namespace,
            title: wire.title,
            description: wire.description,
            status: wire.status,
            completion_policy: wire.completion_policy,
            priority: wire.priority,
            labels: wire.labels,
            owner: wire.owner,
            claim: wire.claim,
            machine_state,
            revision: wire.revision,
            due_at: wire.due_at,
            not_before: wire.not_before,
            snoozed_until: wire.snoozed_until,
            created_at: wire.created_at,
            updated_at: wire.updated_at,
            terminal_at: wire.terminal_at,
            external_refs: wire.external_refs,
            evidence_refs: wire.evidence_refs,
        })
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for WorkItem {
    // NOTE (K21): this manual schema inlines the composite field shapes
    // (`owner`, `claim`, `completion_policy`, `external_refs`,
    // `evidence_refs`). The SDK generator's inline-object promotion pass
    // (tools/sdk-codegen/generate.py) dedupes them by structural content
    // against the derived sibling schemas (`WorkOwnerKey`,
    // `WorkCompletionPolicy`, `WorkEvidenceRef`); keep these inline copies
    // structurally identical to the derived shapes or the generator will
    // mint `WorkItem*`-named twins (visible in the regen diff and the
    // promotion report).
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "WorkItem".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "object",
            "required": [
                "id",
                "realm_id",
                "namespace",
                "title",
                "status",
                "completion_policy",
                "priority",
                "machine_state",
                "revision",
                "created_at",
                "updated_at"
            ],
            "properties": {
                "id": { "type": "string" },
                "realm_id": { "type": "string" },
                "namespace": { "type": "string" },
                "title": { "type": "string" },
                "description": { "type": ["string", "null"] },
                "status": {
                    "type": "string",
                    "enum": ["open", "in_progress", "blocked", "completed", "cancelled", "failed"]
                },
                "completion_policy": {
                    "oneOf": [
                        {
                            "type": "object",
                            "required": ["kind"],
                            "properties": { "kind": { "type": "string", "const": "self_attest" } }
                        },
                        {
                            "type": "object",
                            "required": ["kind"],
                            "properties": { "kind": { "type": "string", "const": "host_confirmed" } }
                        },
                        {
                            "type": "object",
                            "required": ["kind"],
                            "properties": { "kind": { "type": "string", "const": "principal_confirmed" } }
                        },
                        {
                            "type": "object",
                            "required": ["kind", "owner_key"],
                            "properties": {
                                "kind": { "type": "string", "const": "supervisor" },
                                "owner_key": {
                                    "type": "object",
                                    "required": ["kind", "id"],
                                    "properties": {
                                        "kind": {
                                            "type": "string",
                                            "enum": ["principal", "agent", "session", "mob", "label"]
                                        },
                                        "id": { "type": "string" }
                                    }
                                }
                            }
                        },
                        {
                            "type": "object",
                            "required": ["kind", "threshold"],
                            "properties": {
                                "kind": { "type": "string", "const": "reviewer_quorum" },
                                "threshold": { "type": "integer", "format": "uint16", "minimum": 1, "maximum": 64 }
                            }
                        }
                    ]
                },
                "priority": {
                    "type": "string",
                    "enum": ["low", "medium", "high"]
                },
                "labels": {
                    "type": "array",
                    "uniqueItems": true,
                    "items": { "type": "string" }
                },
                "owner": {
                    "anyOf": [
                        {
                            "type": "object",
                            "required": ["key"],
                            "properties": {
                                "key": {
                                    "type": "object",
                                    "required": ["kind", "id"],
                                    "properties": {
                                        "kind": {
                                            "type": "string",
                                            "enum": ["principal", "agent", "session", "mob", "label"]
                                        },
                                        "id": { "type": "string" }
                                    }
                                },
                                "display_name": { "type": ["string", "null"] }
                            }
                        },
                        { "type": "null" }
                    ]
                },
                "claim": {
                    "anyOf": [
                        {
                            "type": "object",
                            "required": ["owner", "claimed_at"],
                            "properties": {
                                "owner": {
                                    "type": "object",
                                    "required": ["key"],
                                    "properties": {
                                        "key": {
                                            "type": "object",
                                            "required": ["kind", "id"],
                                            "properties": {
                                                "kind": {
                                                    "type": "string",
                                                    "enum": ["principal", "agent", "session", "mob", "label"]
                                                },
                                                "id": { "type": "string" }
                                            }
                                        },
                                        "display_name": { "type": ["string", "null"] }
                                    }
                                },
                                "claimed_at": { "type": "string", "format": "date-time" },
                                "lease_expires_at": { "type": ["string", "null"], "format": "date-time" }
                            }
                        },
                        { "type": "null" }
                    ]
                },
                "machine_state": {
                    "type": "object",
                    "description": "Catalog-generated WorkGraphLifecycleMachine state projection."
                },
                "revision": { "type": "integer", "format": "uint64", "minimum": 0 },
                "due_at": { "type": ["string", "null"], "format": "date-time" },
                "not_before": { "type": ["string", "null"], "format": "date-time" },
                "snoozed_until": { "type": ["string", "null"], "format": "date-time" },
                "created_at": { "type": "string", "format": "date-time" },
                "updated_at": { "type": "string", "format": "date-time" },
                "terminal_at": { "type": ["string", "null"], "format": "date-time" },
                "external_refs": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "required": ["kind", "id"],
                        "properties": {
                            "kind": { "type": "string" },
                            "id": { "type": "string" },
                            "url": { "type": ["string", "null"] }
                        }
                    }
                },
                "evidence_refs": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "required": ["kind", "id"],
                        "properties": {
                            "kind": { "type": "string" },
                            "id": { "type": "string" },
                            "label": { "type": ["string", "null"] },
                            "summary": { "type": ["string", "null"] },
                            "confirmation_kind": {
                                "anyOf": [
                                    {
                                        "oneOf": [
                                            {
                                                "type": "string",
                                                "enum": [
                                                    "host_confirmation",
                                                    "principal_confirmation",
                                                    "supervisor_confirmation",
                                                    "reviewer_confirmation"
                                                ]
                                            },
                                            { "type": "string", "const": "self_attest" }
                                        ]
                                    },
                                    { "type": "null" }
                                ]
                            },
                            "confirming_owner_key": {
                                "anyOf": [
                                    {
                                        "type": "object",
                                        "required": ["kind", "id"],
                                        "properties": {
                                            "kind": {
                                                "type": "string",
                                                "enum": ["principal", "agent", "session", "mob", "label"]
                                            },
                                            "id": { "type": "string" }
                                        }
                                    },
                                    { "type": "null" }
                                ]
                            },
                            "execution_binding_id": {
                                "type": ["string", "null"]
                            }
                        }
                    }
                }
            }
        })
    }
}

pub(crate) fn work_lifecycle_state_from_status(status: WorkStatus) -> wg_dsl::WorkLifecycleState {
    match status {
        WorkStatus::Open => wg_dsl::WorkLifecycleState::Open,
        WorkStatus::InProgress => wg_dsl::WorkLifecycleState::InProgress,
        WorkStatus::Blocked => wg_dsl::WorkLifecycleState::Blocked,
        WorkStatus::Completed => wg_dsl::WorkLifecycleState::Completed,
        WorkStatus::Cancelled => wg_dsl::WorkLifecycleState::Cancelled,
        WorkStatus::Failed => wg_dsl::WorkLifecycleState::Failed,
    }
}

pub(crate) fn work_owner_kind_to_machine(kind: WorkOwnerKind) -> wg_dsl::WorkOwnerKind {
    match kind {
        WorkOwnerKind::Principal => wg_dsl::WorkOwnerKind::Principal,
        WorkOwnerKind::Agent => wg_dsl::WorkOwnerKind::Agent,
        WorkOwnerKind::Session => wg_dsl::WorkOwnerKind::Session,
        WorkOwnerKind::Mob => wg_dsl::WorkOwnerKind::Mob,
        WorkOwnerKind::Label => wg_dsl::WorkOwnerKind::Label,
    }
}

pub(crate) fn work_owner_key_to_machine(owner: &WorkOwnerKey) -> wg_dsl::WorkOwnerKey {
    wg_dsl::WorkOwnerKey {
        kind: work_owner_kind_to_machine(owner.kind),
        id: owner.id.clone(),
    }
}

fn work_owner_key_from_machine(owner: wg_dsl::WorkOwnerKey) -> WorkOwnerKey {
    let kind = match owner.kind {
        wg_dsl::WorkOwnerKind::Principal => WorkOwnerKind::Principal,
        wg_dsl::WorkOwnerKind::Agent => WorkOwnerKind::Agent,
        wg_dsl::WorkOwnerKind::Session => WorkOwnerKind::Session,
        wg_dsl::WorkOwnerKind::Mob => WorkOwnerKind::Mob,
        wg_dsl::WorkOwnerKind::Label => WorkOwnerKind::Label,
    };
    WorkOwnerKey { kind, id: owner.id }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkEdge {
    pub realm_id: String,
    pub namespace: WorkNamespace,
    pub kind: WorkEdgeKind,
    pub from_id: WorkItemId,
    pub to_id: WorkItemId,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkGraphEventKind {
    Created,
    Updated,
    Claimed,
    Released,
    Blocked,
    Closed,
    Linked,
    EvidenceAdded,
    AttentionCreated,
    AttentionUpdated,
    ExecutionBound,
    ExecutionTransitioned,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphEvent {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    pub realm_id: String,
    pub namespace: WorkNamespace,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub item_id: Option<WorkItemId>,
    pub kind: WorkGraphEventKind,
    pub at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub payload: Value,
}

impl WorkGraphEvent {
    pub fn item(
        realm_id: String,
        namespace: WorkNamespace,
        item_id: WorkItemId,
        kind: WorkGraphEventKind,
        at: DateTime<Utc>,
        payload: Value,
    ) -> Self {
        Self {
            seq: None,
            realm_id,
            namespace,
            item_id: Some(item_id),
            kind,
            at,
            payload,
        }
    }

    pub fn graph(
        realm_id: String,
        namespace: WorkNamespace,
        kind: WorkGraphEventKind,
        at: DateTime<Utc>,
        payload: Value,
    ) -> Self {
        Self {
            seq: None,
            realm_id,
            namespace,
            item_id: None,
            kind,
            at,
            payload,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CreateWorkItemRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub priority: WorkPriority,
    #[serde(default)]
    pub completion_policy: WorkCompletionPolicy,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub labels: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub due_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_before: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snoozed_until: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub external_refs: Vec<ExternalWorkRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence_refs: Vec<WorkEvidenceRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<WorkStatus>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpdateWorkItemRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub priority: Option<WorkPriority>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completion_policy: Option<WorkCompletionPolicy>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<BTreeSet<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub due_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_before: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snoozed_until: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub external_refs: Vec<ExternalWorkRef>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PolicyEscalateRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub authority_projection: AttentionContextProjection,
    pub completion_policy: WorkCompletionPolicy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ClaimWorkItemRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub owner: WorkOwner,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lease_seconds: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lease_expires_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReleaseWorkItemRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CloseWorkItemRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    #[serde(default = "default_terminal_status")]
    pub status: WorkStatus,
}

fn default_terminal_status() -> WorkStatus {
    WorkStatus::Completed
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct LinkWorkItemsRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub kind: WorkEdgeKind,
    pub from_id: WorkItemId,
    pub to_id: WorkItemId,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AddEvidenceRequest {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub evidence: WorkEvidenceRef,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalCreateRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub target: GoalAttentionTarget,
    #[serde(default)]
    pub mode: WorkAttentionMode,
    #[serde(default)]
    pub completion_policy: WorkCompletionPolicy,
    #[serde(default)]
    pub delegated_authority: AttentionDelegatedAuthority,
    #[serde(default)]
    pub projection_policy: AttentionProjectionPolicy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PublicGoalCreateRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub target: GoalAttentionTarget,
    #[serde(default)]
    pub mode: WorkAttentionMode,
    #[serde(default)]
    pub completion_policy: PublicGoalCompletionPolicy,
    #[serde(default)]
    pub delegated_authority: AttentionDelegatedAuthority,
    #[serde(default)]
    pub projection_policy: AttentionProjectionPolicy,
}

impl From<PublicGoalCreateRequest> for GoalCreateRequest {
    fn from(request: PublicGoalCreateRequest) -> Self {
        Self {
            realm_id: request.realm_id,
            namespace: request.namespace,
            title: request.title,
            description: request.description,
            target: request.target,
            mode: request.mode,
            completion_policy: request.completion_policy.into(),
            delegated_authority: request.delegated_authority,
            projection_policy: request.projection_policy,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalCreateResult {
    pub item: WorkItem,
    pub attention: WorkAttentionBinding,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalStatusRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalStatusResult {
    pub item: WorkItem,
    pub attention: WorkAttentionBinding,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalConfirmRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub evidence: WorkEvidenceRef,
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schemars(skip))]
    pub principal: Option<WorkOwnerKey>,
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schemars(skip))]
    pub trusted_principal: Option<WorkOwnerKey>,
}

impl GoalConfirmRequest {
    /// Promote an already-authenticated host principal into the service authority field.
    pub fn with_trusted_principal(mut self, principal: Option<WorkOwnerKey>) -> Self {
        if self.trusted_principal.is_none() {
            self.trusted_principal = principal;
        }
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalConfirmResult {
    pub item: WorkItem,
    pub attention: WorkAttentionBinding,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalRequestCloseRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    #[serde(default)]
    pub status: GoalTerminalStatus,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum GoalTerminalStatus {
    #[default]
    Completed,
    Cancelled,
    Failed,
}

impl From<GoalTerminalStatus> for WorkStatus {
    fn from(status: GoalTerminalStatus) -> Self {
        match status {
            GoalTerminalStatus::Completed => Self::Completed,
            GoalTerminalStatus::Cancelled => Self::Cancelled,
            GoalTerminalStatus::Failed => Self::Failed,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PublicGoalRequestCloseRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    #[serde(default)]
    pub status: GoalTerminalStatus,
}

impl From<PublicGoalRequestCloseRequest> for GoalRequestCloseRequest {
    fn from(request: PublicGoalRequestCloseRequest) -> Self {
        Self {
            binding_id: request.binding_id,
            realm_id: request.realm_id,
            namespace: request.namespace,
            expected_revision: request.expected_revision,
            status: request.status,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GoalRequestCloseResult {
    pub item: WorkItem,
    pub attention: WorkAttentionBinding,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionListRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<WorkAttentionTarget>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<WorkAttentionStatus>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionListResult {
    pub attention: Vec<WorkAttentionBinding>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionBindingRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionPauseRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub until: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionResumeRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionReassignRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub authority_projection: AttentionContextProjection,
    pub target: GoalAttentionTarget,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionBindingResult {
    pub attention: WorkAttentionBinding,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionReassignResult {
    pub previous: WorkAttentionBinding,
    pub attention: WorkAttentionBinding,
}

/// Break-glass host-plane reassignment (host API only — never exposed on the
/// agent tool surface or any wire catalog). WorkGraphs are agent-operated;
/// the agent-native transfer is a coordinate-mode agent executing the move.
/// This request exists for the one case the graph cannot heal agent-natively:
/// a binding stuck on a wedged/retired agent with no coordinator holding
/// authority over it. It carries mandatory attribution and is audit-logged in
/// the workgraph event stream.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreakGlassAttentionReassignRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub expected_revision: u64,
    pub target: GoalAttentionTarget,
    /// Authenticated principal performing the break-glass move. Recorded in
    /// the audit event; must identify a human/host operator, not an agent.
    pub principal: String,
    /// Operator-supplied justification. Recorded in the audit event.
    pub reason: String,
}

/// Prune request for TERMINAL (superseded/stopped) attention bindings. The
/// event stream keeps the full audit history; pruning removes only the
/// binding rows, which otherwise grow monotonically with reassignment churn.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AttentionPruneRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    /// Only prune bindings last updated strictly before this instant; `None`
    /// prunes every terminal binding in scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_before: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttentionPruneResult {
    pub pruned: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum AttentionContinueOutcome {
    Accepted,
    Deduplicated,
    Rejected,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionContinueResult {
    pub outcome: AttentionContinueOutcome,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub existing_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionProjectionRequest {
    pub binding_id: WorkAttentionBindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionProjectionResult {
    pub projection: AttentionContextProjection,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionContextProjection {
    pub binding_id: WorkAttentionBindingId,
    pub work_ref: WorkItemRef,
    pub mode: WorkAttentionMode,
    pub binding_revision: u64,
    pub item_revision: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parent_refs: Vec<WorkItemRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parent_context: Vec<AttentionProjectionParentContext>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence_refs: Vec<WorkEvidenceRef>,
    pub authority: ProjectedAttentionAuthority,
    pub text: AttentionProjectionText,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionProjectionParentContext {
    pub work_ref: WorkItemRef,
    pub status: WorkStatus,
    pub revision: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ProjectedAttentionAuthority {
    pub can_get: bool,
    pub can_add_evidence: bool,
    pub can_release: bool,
    pub can_update: bool,
    pub can_block: bool,
    pub can_create: bool,
    pub can_link: bool,
    pub can_link_parent: bool,
    pub can_link_related: bool,
    pub can_link_derived_from: bool,
    #[serde(default)]
    pub can_close_own_review_item: bool,
    pub can_close_if_policy_allows: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttentionProjectionText {
    pub title: String,
    pub rendered: String,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkItemFilter {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    #[serde(default)]
    pub all_namespaces: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub statuses: Vec<WorkStatus>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    #[serde(default)]
    pub include_terminal: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkExecutionBindingFilter {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub item_id: Option<WorkItemId>,
    #[serde(default)]
    pub current_only: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReadyWorkFilter {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphSnapshotFilter {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    #[serde(default)]
    pub all_namespaces: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub statuses: Vec<WorkStatus>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    #[serde(default)]
    pub include_terminal: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

/// Parameters identifying a single WorkGraph item by id within an optional
/// realm/namespace scope (`workgraph/get`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphIdParams {
    pub id: WorkItemId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realm_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphSnapshot {
    pub realm_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<WorkNamespace>,
    pub all_namespaces: bool,
    pub captured_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event_high_water_mark: Option<i64>,
    pub items: Vec<WorkItem>,
    pub edges: Vec<WorkEdge>,
    #[serde(default)]
    pub attention: Vec<WorkAttentionBinding>,
    pub ready_item_ids: Vec<WorkItemId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphItemsResponse {
    pub items: Vec<WorkItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkGraphEventsResponse {
    pub events: Vec<WorkGraphEvent>,
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::machine::WorkGraphMachine;

    fn machine_item() -> WorkItem {
        WorkGraphMachine::create_item(
            CreateWorkItemRequest {
                title: "deserialize-authority".to_string(),
                ..Default::default()
            },
            "realm".to_string(),
            WorkNamespace::default(),
            Utc::now(),
        )
        .expect("machine create_item")
        .0
    }

    #[test]
    fn work_item_round_trip_preserves_machine_state() {
        let item = machine_item();
        let json = serde_json::to_string(&item).expect("serialize work item");
        let decoded: WorkItem = serde_json::from_str(&json).expect("deserialize work item");
        assert_eq!(
            decoded, item,
            "round-trip must preserve the whole work item"
        );
        assert_eq!(
            decoded.machine_state, item.machine_state,
            "round-trip must preserve machine-owned lifecycle authority verbatim"
        );
    }

    #[test]
    fn work_item_without_machine_state_fails_closed() {
        let item = machine_item();
        let mut value = serde_json::to_value(&item).expect("serialize work item to value");
        value
            .as_object_mut()
            .expect("work item json object")
            .remove("machine_state");

        let result: Result<WorkItem, _> = serde_json::from_value(value);
        let err = result.expect_err(
            "deserializing a WorkItem without machine_state must fail closed, \
             never fabricate lifecycle/revision authority from projected fields",
        );
        assert!(
            err.to_string().contains("machine_state"),
            "fail-closed error must cite the missing machine_state authority, got: {err}"
        );
    }
}