uptrakit-wire 0.0.3

Uptrakit shared wire protocol: WS, NATS, and REST message types
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
use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};
use time::UtcDateTime;
use uuid::Uuid;

use super::capabilities::{Capability, EnrollmentStatus};
use super::shared_types::{DisconnectReason, UpdateFinalStatus};
use crate::serde_helpers::{duration_seconds, option_duration_seconds, utc_datetime_millis};
use uptrakit_shared_types::{
    DiscoveredSoftware, OutputStreamType, PluginTypeId, ReleaseInfo, SecretString, UpdateCategory,
};

/// Payload for ping messages.
///
/// Heartbeat sent by the service; the controller responds with [`PongPayload`],
/// echoing `service_ts` back so the service can calculate round-trip time.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PingPayload {
    /// Timestamp when the service sent the ping.
    pub service_ts: super::shared_types::Timestamp,
}

impl PingPayload {
    /// Creates a new `PingPayload` with the given service timestamp.
    pub fn new(service_ts: super::shared_types::Timestamp) -> Self {
        Self { service_ts }
    }
}

/// Payload for pong messages.
///
/// Heartbeat response sent by the controller. Echoes back the ping's
/// `service_ts` alongside `controller_ts`, letting the service compute
/// round-trip time as `now - service_ts` on receipt.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PongPayload {
    /// Original timestamp from the service's ping.
    pub service_ts: super::shared_types::Timestamp,
    /// Timestamp when the controller processed the ping.
    pub controller_ts: super::shared_types::Timestamp,
}

impl PongPayload {
    /// Creates a new `PongPayload` with the given service and controller timestamps.
    pub fn new(
        service_ts: super::shared_types::Timestamp,
        controller_ts: super::shared_types::Timestamp,
    ) -> Self {
        Self {
            service_ts,
            controller_ts,
        }
    }
}

/// Information about the host machine running the agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HostInfo {
    /// Persistent machine identifier (e.g. `/etc/machine-id` on Linux, `IOPlatformUUID` on macOS).
    ///
    /// Falls back to `"unknown"` if the identifier cannot be read.
    pub machine_id: String,
    /// Operating system type (e.g. "linux", "macos").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub os_type: Option<String>,
    /// Operating system version (e.g. "Ubuntu 24.04 LTS").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub os_version: Option<String>,
    /// CPU architecture (e.g. "x86_64", "aarch64").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub architecture: Option<String>,
    /// Hostname reported by the agent/host machine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hostname: Option<String>,
    /// Network address of the host (SSH target address for SSH agent hosts).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ip_address: Option<String>,
    /// Agent-local UUID assigned to this host at bootstrap time.
    ///
    /// When present, the controller uses this as `hosts.id` when creating a
    /// new row, ensuring agent and controller share the same UUID. This is
    /// required for plugin FK operations (e.g. Proxmox host mapping) that
    /// reference `hosts.id` before the controller has generated its own UUID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_host_id: Option<Uuid>,
    /// Agent-probed host features (e.g. `["posix_shell", "privilege_escalation", "systemd"]`).
    ///
    /// `None` for legacy agents that predate feature reporting. Uses `Vec<String>`
    /// (not `BTreeSet<HostFeature>`) on the wire for forward-compatibility: if a
    /// newer agent reports a feature the controller doesn't know, it is stored
    /// losslessly and ignored by `HostCapabilities` parsing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub features: Option<Vec<String>>,
}

/// Payload for service enrollment request.
///
/// Used by both agents and MQTT services. Host information is reported
/// separately via [`ReportHostsPayload`] after authentication.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct EnrollPayload {
    pub hostname: String,
    pub friendly_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
    pub enrollment_token: Option<SecretString>,
    /// Capabilities this service supports.
    ///
    /// The controller persists these in the `services.capabilities` column and
    /// derives behavioral defaults from the resulting [`ServiceProfile`](crate::ServiceProfile).
    pub capabilities: BTreeSet<Capability>,
    /// The binary/crate name of the enrolling service (e.g., `"uptrakit-agent-ssh"`).
    ///
    /// Derived from `env!("CARGO_PKG_NAME")` at compile time. Used for UI
    /// display, extension conflict detection, and distinguishing service binaries.
    pub service_app_name: String,
}

/// Payload for requesting a client certificate after approval.
///
/// Sent after receiving `approved`. The service generates a fresh ECDSA P-256
/// keypair, creates a CSR with CN=service_id, and submits it here; the controller
/// responds with [`CertificatePayload`] (cert PEM only — the private key stays on
/// the service).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RequestCertificatePayload {
    /// PEM-encoded Certificate Signing Request.
    pub csr_pem: String,
}

/// Payload for requesting certificate renewal (mTLS-authenticated services).
///
/// Generated with a fresh ECDSA P-256 keypair, sent either proactively before the
/// current certificate expires or in response to a [`RequestCertRenewalPayload`]
/// push (e.g. after CA rotation). The controller responds with [`CertificatePayload`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RenewCertificatePayload {
    /// PEM-encoded Certificate Signing Request with CN=service_id.
    pub csr_pem: String,
}

/// Payload for reporting host information (sent by authenticated agents on connect).
///
/// Supports multiple hosts per message, enabling a single service instance
/// (e.g. a future SSH-backed agent) to manage several remote hosts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReportHostsPayload {
    /// One or more host machines managed by this service.
    pub hosts: Vec<HostInfo>,
    /// Agent binary version (e.g., "0.0.1").
    pub agent_version: String,
    /// Capabilities advertised by this service.
    ///
    /// The controller computes the agreed set as the intersection of this set
    /// with its own capabilities, considering only typed (known) variants.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub capabilities: BTreeSet<Capability>,
}

/// Payload for enrollment confirmation.
///
/// Sent once by the controller in response to `enroll`. `enrollment_secret` must be
/// persisted by the service: it is presented as an `Authorization: Bearer` header to
/// reconnect and resume the enrollment session (e.g. after a restart) if the service
/// has not yet obtained a client certificate. `status` reflects whether the service
/// requires manual admin approval or was auto-approved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct EnrolledPayload {
    pub service_id: Uuid,
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    pub enrollment_secret: SecretString,
    pub status: EnrollmentStatus,
}

/// Payload for approval notification.
///
/// Pushed by the controller as soon as an admin approves the service — the service
/// does not poll for this; it simply waits on the still-open enrollment connection
/// (or a reconnect made with the `enrollment_secret` bearer token). On receipt, the
/// service proceeds to generate a keypair and send `request_certificate`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ApprovedPayload {
    pub service_id: Uuid,
}

/// Payload for rejection notification.
///
/// Pushed by the controller when an admin rejects a pending enrollment. The service
/// should disconnect and exit; it must not retry the enrollment flow automatically.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RejectedPayload {
    pub service_id: Uuid,
}

/// Payload for issued certificate.
///
/// Sent in response to [`RequestCertificatePayload`] or `RenewCertificatePayload`.
/// The private key is never included — the service already holds it locally. The
/// service should persist the certificate and reconnect using mTLS.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CertificatePayload {
    pub cert_pem: String,
    /// Certificate "not valid after" timestamp.
    #[serde(with = "utc_datetime_millis")]
    #[cfg_attr(feature = "schema", schemars(with = "i64"))]
    pub not_after: UtcDateTime,
}

/// Payload for service runtime settings pushed by the controller.
///
/// Used for both agents and MQTT services. `shutdown_timeout` is
/// present for agents and `None` for MQTT services.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceSettingsPayload {
    pub renewal_window_hours: u16,
    #[serde(default)]
    pub ca_bundle_hash: String,
    /// Capabilities advertised by the controller.
    ///
    /// The service computes the agreed set as the intersection of this set
    /// with its own capabilities, considering only typed (known) variants.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub capabilities: BTreeSet<Capability>,
    /// Per-page item-count limits for paginated service-to-controller reports.
    ///
    /// Services must honor these limits when splitting large `report_hosts`,
    /// `discovery_results`, `version_check_results`, and
    /// `batch_update_result` payloads across pages.
    #[serde(default, skip_serializing_if = "ReportPageLimits::is_default")]
    pub report_page_limits: ReportPageLimits,
    /// Maximum time to wait for in-flight operations during shutdown.
    /// Present for agents, absent for MQTT services.
    ///
    /// Wire field name: `shutdown_timeout_seconds` (kept for backward compatibility).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "option_duration_seconds",
        rename = "shutdown_timeout_seconds"
    )]
    #[cfg_attr(feature = "schema", schemars(with = "Option<u32>"))]
    pub shutdown_timeout: Option<std::time::Duration>,
    /// How often the service should send ping messages.
    /// Controller-managed; derived from per-service DB override or service-type default.
    #[serde(with = "duration_seconds")]
    #[cfg_attr(feature = "schema", schemars(with = "u32"))]
    pub ping_interval: std::time::Duration,
    /// Tenant UUID that this service belongs to.
    ///
    /// `None` for system services (MQTT, scheduler) which are not
    /// tenant-scoped. Present for tenant-scoped agents so they can
    /// include the tenant identity in external provisioning operations
    /// (e.g. PVE API credential naming).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<Uuid>,
    /// SPIFFE trust domain for Service identity URIs.
    ///
    /// Empty string when the Controller has no trust domain configured.
    /// Agent falls back to the dialed hostname for SPIFFE SAN generation.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub trust_domain: String,
}

impl ServiceSettingsPayload {
    /// Creates a new [`ServiceSettingsPayload`] with the required fields.
    ///
    /// Optional fields default to: `ca_bundle_hash` = empty, `capabilities` = empty,
    /// `report_page_limits` = default, `shutdown_timeout` = `None`,
    /// `tenant_id` = `None`, `trust_domain` = empty.
    pub fn new(renewal_window_hours: u16, ping_interval: std::time::Duration) -> Self {
        Self {
            renewal_window_hours,
            ca_bundle_hash: String::new(),
            capabilities: std::collections::BTreeSet::new(),
            report_page_limits: ReportPageLimits::default(),
            shutdown_timeout: None,
            ping_interval,
            tenant_id: None,
            trust_domain: String::new(),
        }
    }

    /// Sets the CA bundle hash.
    #[must_use]
    pub fn with_ca_bundle_hash(mut self, ca_bundle_hash: String) -> Self {
        self.ca_bundle_hash = ca_bundle_hash;
        self
    }

    /// Sets the controller capability set.
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: impl IntoIterator<Item = Capability>) -> Self {
        self.capabilities = capabilities.into_iter().collect();
        self
    }

    /// Sets the report page limits.
    #[must_use]
    pub fn with_report_page_limits(mut self, report_page_limits: ReportPageLimits) -> Self {
        self.report_page_limits = report_page_limits;
        self
    }

    /// Sets the graceful-shutdown timeout for agent services.
    #[must_use]
    pub fn with_shutdown_timeout(mut self, shutdown_timeout: std::time::Duration) -> Self {
        self.shutdown_timeout = Some(shutdown_timeout);
        self
    }

    /// Sets the tenant UUID for tenant-scoped services.
    #[must_use]
    pub fn with_tenant_id(mut self, tenant_id: Uuid) -> Self {
        self.tenant_id = Some(tenant_id);
        self
    }

    /// Sets the SPIFFE trust domain advertised to connecting services.
    #[must_use]
    pub fn with_trust_domain(mut self, trust_domain: String) -> Self {
        self.trust_domain = trust_domain;
        self
    }
}

/// Per-page item-count limits for paginated report payloads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReportPageLimits {
    /// Maximum `hosts` items per `report_hosts` page.
    pub report_hosts: u32,
    /// Maximum `results` items per `version_check_results` page.
    pub version_check_results: u32,
    /// Maximum `results` items per `discovery_results` page.
    pub discovery_results: u32,
    /// Maximum `results` items per `batch_update_result` page.
    pub batch_update_results: u32,
}

impl ReportPageLimits {
    /// Returns `true` when all fields match the default wire limits.
    pub fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

impl Default for ReportPageLimits {
    fn default() -> Self {
        Self {
            report_hosts: crate::limits::MAX_REPORT_HOSTS as u32,
            version_check_results: crate::limits::MAX_VERSION_CHECK_RESULTS as u32,
            discovery_results: crate::limits::MAX_DISCOVERY_PLUGIN_RESULTS as u32,
            batch_update_results: crate::limits::MAX_BATCH_UPDATE_RESULTS as u32,
        }
    }
}

/// Payload for CA bundle update notification.
///
/// Pushed by the controller when the CA certificate bundle changes (e.g. after CA
/// rotation). The service should update its trust store with the new bundle PEM
/// and prepare for certificate renewal (see [`RequestCertRenewalPayload`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CaBundleUpdatedPayload {
    pub ca_bundle_pem: String,
}

/// Payload for requesting immediate certificate renewal from services.
///
/// Sent by the controller after CA rotation or backend URL change to prompt
/// all connected services to renew their certificates with the new CA.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RequestCertRenewalPayload {
    /// Human-readable reason for the renewal request.
    pub reason: String,
}

/// Payload for server restarting notification.
///
/// Sent by the controller during graceful shutdown to notify connected services
/// that the server is restarting. Services should expect the connection to close
/// and reconnect automatically.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServerRestartingPayload {
    /// Human-readable reason for the restart.
    pub reason: String,
}

/// Payload for requesting version checks from the agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CheckVersionsPayload {
    /// The machine_id of the host to check versions on.
    ///
    /// For the regular agent (one service = one host), the agent validates that
    /// this matches its own machine_id as a defensive sanity check.
    /// For the SSH agent (one service = N remote hosts), the agent uses this
    /// field to look up the correct SSH credentials and route the operation to
    /// the right remote host.
    pub host_machine_id: String,
    /// List of software items to check.
    pub assignments: Vec<VersionCheckAssignment>,
}

/// A plugin assignment for a specific role in a version check or update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PluginAssignment {
    /// The plugin type (e.g. github_releases, apt, homebrew).
    pub plugin_type: PluginTypeId,
    /// Package identifier for this role's plugin.
    pub package_identifier: String,
    /// Merged plugin config (base + override).
    pub config: serde_json::Value,
}

/// A single software item to check for installed version and/or latest version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VersionCheckAssignment {
    /// Software item ID.
    pub software_item_id: Uuid,
    /// Human-readable name for logging.
    pub name: String,
    /// Plugin for the detect_version role.
    /// None if no detect_version plugin is configured for this host-software pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detect_version: Option<PluginAssignment>,
    /// Plugin for the fetch_releases role — only included for agent-side plugins
    /// (i.e., plugins without ControllerSideFetchReleases or with execution_site = agent).
    /// Controller-side fetch_releases is handled by the scheduler, not sent to the agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fetch_releases: Option<PluginAssignment>,
    /// Host software item ID for routing results to the host_software_items table.
    /// When set, this assignment is for a host-managed software item rather than
    /// a targeted software item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host_software_item_id: Option<Uuid>,
}

/// Payload for version check results from the agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VersionCheckResultsPayload {
    /// Results for each checked software item.
    pub results: Vec<VersionCheckResult>,
}

/// Result of a single version check.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VersionCheckResult {
    /// Software item ID.
    pub software_item_id: Uuid,
    /// Detected installed version, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub installed_version: Option<String>,
    /// Latest available version from the package index, if resolved locally
    /// by the agent (e.g., Homebrew). Absent for plugins whose latest
    /// version is resolved on the controller side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<String>,
    /// Error message if detection failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Classification of the available update (e.g. security, bugfix).
    /// Defaults to `Unknown` when the plugin cannot classify the update.
    #[serde(default)]
    pub update_category: UpdateCategory,
    /// Host software item ID for routing results to the host_software_items table.
    /// Mirrors the value from the corresponding [`VersionCheckAssignment`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host_software_item_id: Option<Uuid>,
    /// Human-readable installed version for display when `installed_version`
    /// is opaque (e.g. a Docker SHA256 digest → the image publish date).
    /// Set by the agent from `BatchDetectResult.display_version`.
    /// `None` when the plugin does not provide a display version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_display_version: Option<String>,
    /// When `true`, the agent is not yet ready to report a meaningful version
    /// for this item (e.g. a self-update is in progress and the binary has not
    /// restarted yet). The controller should treat this as "check again later"
    /// rather than clearing the installed version.
    ///
    /// `None` / absent means "ready" for wire backward compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_ready: Option<bool>,
}

// --- Update execution messages ---

/// Controller -> Agent: Trigger an update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ExecuteUpdatePayload {
    /// The machine_id of the host to run the update on.
    ///
    /// For the regular agent (one service = one host), the agent validates that
    /// this matches its own machine_id as a defensive sanity check.
    /// For the SSH agent (one service = N remote hosts), the agent uses this
    /// field to look up the correct SSH credentials and route the operation to
    /// the right remote host.
    pub host_machine_id: String,
    pub update_history_id: Uuid,
    pub software_item_id: Uuid,
    pub software_item_name: String,
    pub to_version: String,
    /// Plugin for the detect_version role (for before/after installed-version detection).
    /// Absent when no detect_version plugin is configured for this assignment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detect_version_plugin: Option<PluginAssignment>,
    /// Plugin for the execute_update role.
    pub execute_update_plugin: PluginAssignment,
    /// Pre-update hook plugins to execute before the update, ordered by priority.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pre_update_hook_plugins: Vec<PluginAssignment>,
    /// Post-update hook plugins to execute after the update, ordered by priority.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub post_update_hook_plugins: Vec<PluginAssignment>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub release_info: Option<ReleaseInfo>,
    /// Timeout for the update execution.
    ///
    /// Wire field name: `timeout_seconds` (kept for backward compatibility).
    #[serde(
        with = "duration_seconds",
        rename = "timeout_seconds",
        default = "super::shared_types::default_update_timeout"
    )]
    #[cfg_attr(feature = "schema", schemars(with = "u32"))]
    pub timeout: std::time::Duration,
    /// When `true`, the agent allocates a PTY and keeps stdin open for forwarding.
    ///
    /// Requires the agent to advertise the `InteractiveUpdates` capability.
    /// Defaults to `false` for backward compatibility with older agents.
    #[serde(default)]
    pub interactive: bool,
}

/// Agent -> Controller: Update is starting.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpdateStartedPayload {
    pub update_history_id: Uuid,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_version: Option<String>,
    /// Whether this update was dispatched in interactive mode and the agent's
    /// executor supports PTY allocation (dispatch intent). The PTY itself is
    /// allocated when the update command starts; on reconnect replay the agent
    /// reports live reality instead (channels resolved). Old agents that do
    /// not send this field will deserialize as `false`.
    #[serde(default)]
    pub interactive: bool,
}

/// Agent -> Controller: Streaming output line.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpdateOutputPayload {
    pub update_history_id: Uuid,
    pub output: String,
    #[serde(default)]
    pub stream: OutputStreamType,
}

/// Agent -> Controller: Final result of update execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpdateResultPayload {
    pub update_history_id: Uuid,
    pub status: UpdateFinalStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_version: Option<String>,
    pub output: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// When `true`, the agent signals that this update can be resumed after
    /// a restart (e.g. the update script supports idempotent re-entry or the
    /// agent is mid-self-update and will re-attach on reconnect).
    ///
    /// `None` / absent means "not resumable" for wire backward compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resumable: Option<bool>,
}

// --- Batch update messages ---

/// Controller → Agent: execute a batch update of software items.
///
/// Groups multiple items under a single plugin type so the agent can
/// run a single bulk command (e.g., `apt-get upgrade`, `brew upgrade`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ExecuteBatchUpdatePayload {
    /// The machine_id of the host to run the batch update on.
    ///
    /// For the regular agent (one service = one host) this is validated against
    /// its own machine_id. For the SSH agent this routes to the correct remote host.
    pub host_machine_id: String,
    /// Unique identifier for this batch operation.
    pub batch_id: Uuid,
    /// Plugin type for all items in this batch.
    pub plugin_type: PluginTypeId,
    /// Merged plugin configuration.
    pub plugin_config: serde_json::Value,
    /// Individual items to update.
    pub updates: Vec<BatchUpdateItem>,
    /// Pre-update hook plugins to execute before the batch, ordered by priority.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pre_update_hook_plugins: Vec<PluginAssignment>,
    /// Post-update hook plugins to execute after the batch, ordered by priority.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub post_update_hook_plugins: Vec<PluginAssignment>,
    /// Timeout for the entire batch operation.
    ///
    /// Wire field name: `timeout_seconds` (kept for backward compatibility).
    #[serde(
        with = "duration_seconds",
        rename = "timeout_seconds",
        default = "super::shared_types::default_update_timeout"
    )]
    #[cfg_attr(feature = "schema", schemars(with = "u32"))]
    pub timeout: std::time::Duration,
    /// When `true`, the agent allocates a PTY and keeps stdin open for forwarding.
    ///
    /// Requires the agent to advertise the `InteractiveUpdates` capability.
    /// Defaults to `false` for backward compatibility with older agents.
    #[serde(default)]
    pub interactive: bool,
}

/// A single software item within a batch update request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BatchUpdateItem {
    /// Host software item entity ID.
    pub host_software_item_id: Uuid,
    /// Update history record ID (pre-created by the controller).
    pub update_history_id: Uuid,
    /// Plugin-specific package identifier (e.g., APT package name).
    pub package_identifier: String,
    /// Target version to install.
    pub to_version: String,
    /// Optional release metadata from the upstream source.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_info: Option<ReleaseInfo>,
}

/// Agent → Controller: result of a batch update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BatchUpdateResultPayload {
    /// Batch ID matching the request.
    pub batch_id: Uuid,
    /// Per-item results.
    pub results: Vec<BatchUpdateItemResult>,
}

/// Result of updating a single item within a batch operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BatchUpdateItemResult {
    /// Host software item entity ID.
    pub host_software_item_id: Uuid,
    /// Update history record ID.
    pub update_history_id: Uuid,
    /// Final status of this item's update.
    pub status: UpdateFinalStatus,
    /// Accumulated output from the update.
    pub output: String,
    /// Detected installed version after the update (if detection succeeded).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_version: Option<String>,
    /// Error message if the update failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// --- Remote update freeze ---

/// Controller → Agent: enable or disable the update freeze.
///
/// When `enabled` is `true`, the agent creates its freeze file, which blocks
/// `ExecuteUpdate` and `ExecuteBatchUpdate` messages until the file
/// is removed (either via a subsequent `SetUpdateFreeze { enabled: false }`
/// message, or manually on the host via `rm <freeze-file>`).
///
/// This message is safe for NATS publication — it contains no credentials.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SetUpdateFreezePayload {
    /// Whether to enable (`true`) or disable (`false`) the freeze.
    pub enabled: bool,
    /// Optional human-readable reason for the freeze (audit trail).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// --- Graceful shutdown messages ---

/// Service -> Controller: Notification before disconnecting.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DisconnectingPayload {
    pub reason: DisconnectReason,
}

impl DisconnectingPayload {
    /// Create a `DisconnectingPayload` with the given reason.
    pub fn new(reason: DisconnectReason) -> Self {
        Self { reason }
    }
}

// =============================================================================
// Capability Management Payloads
// =============================================================================

/// Payload sent by every service on connect to declare its capabilities.
///
/// Sent from `on_connected` before any other messages. The controller uses
/// this as the authoritative source for capability detection on the current
/// session and persists the capability set to the DB.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RegisterPayload {
    /// Capabilities declared by this service instance.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub capabilities: BTreeSet<Capability>,
    /// Runtime instance identity for restart-vs-reconnect detection.
    ///
    /// Optional for mixed-version compatibility: legacy services omit this
    /// field and are treated as service-scoped (not instance-scoped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_instance_id: Option<Uuid>,
}

impl RegisterPayload {
    /// Create a new [`RegisterPayload`] with the given capability set.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BTreeSet;
    /// use uptrakit_wire::{Capability, RegisterPayload};
    ///
    /// let payload = RegisterPayload::new([Capability::SoftwareDiscovery, Capability::UpdateHooks]);
    /// assert!(payload.capabilities.contains(&Capability::SoftwareDiscovery));
    /// ```
    pub fn new(capabilities: impl IntoIterator<Item = Capability>) -> Self {
        Self {
            capabilities: capabilities.into_iter().collect(),
            runtime_instance_id: None,
        }
    }

    /// Set a runtime instance id on this register payload.
    #[must_use]
    pub fn with_runtime_instance_id(mut self, runtime_instance_id: Uuid) -> Self {
        self.runtime_instance_id = Some(runtime_instance_id);
        self
    }
}

// =============================================================================
// Service Config Store Payloads
// =============================================================================

/// A single stored service config entry, delivered to the service.
///
/// Sensitive values are already decrypted by the controller before delivery.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceConfigEntry {
    /// Tenant this entry belongs to, or `None` for global entries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<Uuid>,
    /// Entry key (e.g. `"clients.{uuid}"`).
    pub key: String,
    /// Entry value (plaintext JSON; controller decrypts before delivery).
    pub value: serde_json::Value,
}

impl ServiceConfigEntry {
    /// Create a new `ServiceConfigEntry`.
    pub fn new(tenant_id: Option<Uuid>, key: String, value: serde_json::Value) -> Self {
        Self {
            tenant_id,
            key,
            value,
        }
    }
}

/// Identifies a service config entry by scope and key (used in delete notifications).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceConfigKey {
    /// Tenant this entry belongs to, or `None` for global entries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<Uuid>,
    /// Entry key.
    pub key: String,
}

impl ServiceConfigKey {
    /// Create a new `ServiceConfigKey`.
    pub fn new(tenant_id: Option<Uuid>, key: String) -> Self {
        Self { tenant_id, key }
    }
}

/// Service → Controller: write or update a config entry.
///
/// The controller upserts the entry in `tenant_service_config` (when
/// `tenant_id` is set) or `global_service_config` (when `None`), encrypts
/// the value if `sensitive` is `true`, ACKs the operation, and broadcasts
/// `ServiceConfigUpdated` to all other connected instances of the same
/// `service_app_name`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct StoreServiceConfigPayload {
    /// Correlation ID for the `ServiceConfigAck` response.
    pub request_id: String,
    /// Tenant scope. `None` = global scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<Uuid>,
    /// Config key (e.g. `"clients.{uuid}"`).
    pub key: String,
    /// Config value (plaintext JSON; controller encrypts at rest if `sensitive`).
    pub value: serde_json::Value,
    /// When `true`, the controller stores the value using `EncryptedString`.
    #[serde(default)]
    pub sensitive: bool,
}

impl StoreServiceConfigPayload {
    /// Create a new `StoreServiceConfigPayload`.
    pub fn new(
        request_id: String,
        tenant_id: Option<Uuid>,
        key: String,
        value: serde_json::Value,
        sensitive: bool,
    ) -> Self {
        Self {
            request_id,
            tenant_id,
            key,
            value,
            sensitive,
        }
    }
}

/// Service → Controller: delete a config entry.
///
/// The controller deletes the entry, ACKs, and broadcasts `ServiceConfigUpdated`
/// to all other connected instances of the same `service_app_name`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DeleteServiceConfigPayload {
    /// Correlation ID for the `ServiceConfigAck` response.
    pub request_id: String,
    /// Tenant scope. `None` = global scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<Uuid>,
    /// Config key to delete.
    pub key: String,
}

impl DeleteServiceConfigPayload {
    /// Create a new `DeleteServiceConfigPayload`.
    pub fn new(request_id: String, tenant_id: Option<Uuid>, key: String) -> Self {
        Self {
            request_id,
            tenant_id,
            key,
        }
    }
}

/// Controller → Service: acknowledgment of a `StoreServiceConfig` or
/// `DeleteServiceConfig` operation.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceConfigAckPayload {
    /// Correlation ID matching the request.
    pub request_id: String,
    /// `true` if the operation succeeded.
    pub success: bool,
    /// Error message when `success` is `false`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl ServiceConfigAckPayload {
    /// Create a new success ACK.
    pub fn success(request_id: String) -> Self {
        Self {
            request_id,
            success: true,
            error: None,
        }
    }

    /// Create a new error ACK.
    pub fn error(request_id: String, error: String) -> Self {
        Self {
            request_id,
            success: false,
            error: Some(error),
        }
    }
}

/// Controller → Service: initial delivery of all stored config entries.
///
/// Sent once after the service authenticates (after credential delivery).
/// The service should use this as its authoritative in-memory state.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceConfigDeliveryPayload {
    /// All config entries stored for this `service_app_name`.
    pub entries: Vec<ServiceConfigEntry>,
}

impl ServiceConfigDeliveryPayload {
    /// Create a new `ServiceConfigDeliveryPayload`.
    pub fn new(entries: Vec<ServiceConfigEntry>) -> Self {
        Self { entries }
    }
}

/// Controller → Service: incremental config update notification.
///
/// Pushed to all connected instances of the same `service_app_name` when
/// any instance stores or deletes a config entry. Services should apply
/// these changes to their in-memory state atomically.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceConfigUpdatedPayload {
    /// Entries that were inserted or updated (with decrypted values).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub changed: Vec<ServiceConfigEntry>,
    /// Keys that were deleted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deleted: Vec<ServiceConfigKey>,
}

impl ServiceConfigUpdatedPayload {
    /// Create a new `ServiceConfigUpdatedPayload`.
    pub fn new(changed: Vec<ServiceConfigEntry>, deleted: Vec<ServiceConfigKey>) -> Self {
        Self { changed, deleted }
    }
}

// =============================================================================
// Infrastructure Credential Payloads
// =============================================================================

/// Infrastructure credentials for services that advertise credential capabilities.
///
/// Fields are populated based on the service's capability set:
///   - `database_access` → `db_url` is set
///   - `nats_access` → `nats_url` is set (if controller has NATS)
///   - `master_key_access` → `master_key_hex` is set (if encryption enabled)
///
/// **Security**: This payload contains highly sensitive credentials. It must
/// NEVER be published to NATS or any external transport. It is delivered
/// exclusively over the authenticated WebSocket connection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceCredentialsPayload {
    /// Database connection URL. Present when the service has `database_access`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
    pub db_url: Option<SecretString>,
    /// Master encryption key as 64-char hex. Present when the service has
    /// `master_key_access` and encryption is enabled on the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
    pub master_key_hex: Option<SecretString>,
    /// NATS server URL. Present when the service has `nats_access` and
    /// NATS is configured on the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nats_url: Option<String>,
}

/// Request from an external component (e.g. scheduler) for the controller to
/// perform CA certificate rotation.
///
/// Published via NATS to `uptrakit.events.controller` subject. Handled by
/// triggering `ca_rotation_trigger.notify_one()` on the receiving controller.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RequestCaRotationPayload {
    /// Human-readable reason for the rotation request.
    pub reason: String,
}

/// Request all controller instances to rebuild the CRL immediately.
///
/// Published via NATS to the `uptrakit.events.controller` subject by any
/// controller that revokes a certificate or by the `CrlRenewal` scheduled
/// task.  Receiving controllers fire `revocation_notify.notify_one()`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RequestCrlRenewalPayload {}

/// Signal that software states have changed for a tenant and need to be
/// re-loaded and pushed to update-tracking services.
///
/// Published to the `controller` NATS subject by the external scheduler after
/// a version-check run completes. The receiving controller loads the states
/// from the database and pushes them to all connected update-tracking services.
///
/// This is a lightweight signal — it carries only the tenant ID, not the state
/// data itself. This decouples the scheduler from the state-loading logic.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SoftwareStatesChangedPayload {
    pub tenant_id: uuid::Uuid,
}

impl SoftwareStatesChangedPayload {
    pub fn new(tenant_id: uuid::Uuid) -> Self {
        Self { tenant_id }
    }
}

/// Cross-controller token revocation event.
///
/// Published to the `controller` NATS subject by the controller that wrote
/// the revocation to the DB. Receiving controllers apply the revocation to
/// their in-memory denylist only — they do **not** write to DB (the
/// originating controller already did that).
///
/// A message may carry a JTI-level revocation, a user-level revocation, or
/// both. Fields not relevant to the revocation type are `None`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TokenRevokedPayload {
    /// JWT ID to deny (`exp` must also be set for JTI-level revocations).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<String>,
    /// Token expiry unix timestamp (seconds). Required when `jti` is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<i64>,
    /// User UUID for user-level revocations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_id: Option<Uuid>,
    /// Deny tokens with `iat < iat_cutoff`. Required when `user_id` is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat_cutoff: Option<i64>,
    /// Remove the user entry after this unix timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purge_after: Option<i64>,
}

/// Cross-controller access-cache invalidation event.
///
/// Published to the `controller` NATS subject by the controller that mutated
/// access grants or role assignments (mutation sites land in M1.6a).
/// Receivers flush their **entire** access-authority cache — the subject
/// lists are observability and forward-compat detail, not a promise of
/// granular invalidation. There is deliberately no `tenant_id` field: a
/// global (NULL-tenant) user grant surfaces in every tenant's cache entry
/// for that user, so receivers must always flush across tenants. Both lists
/// may be empty.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AccessInvalidatedPayload {
    /// Users whose grant rows or role assignments changed.
    pub user_ids: Vec<Uuid>,
    /// Roles whose grant rows changed.
    pub role_ids: Vec<Uuid>,
}

impl AccessInvalidatedPayload {
    pub fn new(user_ids: Vec<Uuid>, role_ids: Vec<Uuid>) -> Self {
        Self { user_ids, role_ids }
    }
}

/// Per-host metadata published to MQTT for MQTT-browser visibility and Home Assistant.
///
/// Included in [`SoftwareStatesPayload`]. All fields are sourced exclusively
/// from the shared DB — safe for multi-controller deployments.
///
/// Intentionally excludes `ip_address` (network topology risk) and `agent_online`
/// (must come from the event-driven [`HostConnectivityUpdatedPayload`]).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HostStateMetadata {
    /// Host UUID.
    pub host_id: Uuid,
    /// Hostname as reported by the agent.
    pub hostname: String,
    /// User-defined display name.
    pub friendly_name: String,
    /// Operating system type (e.g. `"linux"`, `"macos"`). `null` when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub os_type: Option<String>,
    /// Operating system version (e.g. `"Ubuntu 24.04 LTS"`). `null` when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub os_version: Option<String>,
    /// CPU architecture (e.g. `"x86_64"`, `"aarch64"`). `null` when unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub architecture: Option<String>,
    /// Organisational tag names assigned to this host (e.g. `["production", "web-server"]`).
    #[serde(default)]
    pub tags: Vec<String>,
    /// Agent binary version string (e.g. `"0.2.1"`). `null` when never connected.
    ///
    /// Sourced from `services.client_version` for the newest approved, non-deactivated
    /// agent linked to this host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_version: Option<String>,
    /// ISO 8601 timestamp of when the agent last sent a message.
    ///
    /// Sourced from `services.last_seen_at`. `null` when never seen.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_last_seen_at: Option<String>,
}

impl HostStateMetadata {
    /// Creates a new `HostStateMetadata` with required fields.
    pub fn new(host_id: Uuid, hostname: String, friendly_name: String) -> Self {
        Self {
            host_id,
            hostname,
            friendly_name,
            os_type: None,
            os_version: None,
            architecture: None,
            tags: Vec::new(),
            agent_version: None,
            agent_last_seen_at: None,
        }
    }
}

/// Connectivity status for a single host, used in [`HostConnectivityUpdatedPayload`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HostConnectivityUpdate {
    /// Host UUID.
    pub host_id: Uuid,
    /// Whether the agent is currently connected (`true` = online, `false` = offline).
    pub online: bool,
    /// Timestamp of last agent activity (ISO 8601). `null` when unavailable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_seen_at: Option<String>,
    /// Agent binary version. Present on connect; `null` on disconnect.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_version: Option<String>,
}

impl HostConnectivityUpdate {
    /// Creates an online update.
    pub fn online(
        host_id: Uuid,
        last_seen_at: Option<String>,
        agent_version: Option<String>,
    ) -> Self {
        Self {
            host_id,
            online: true,
            last_seen_at,
            agent_version,
        }
    }

    /// Creates an offline update.
    pub fn offline(host_id: Uuid, last_seen_at: Option<String>) -> Self {
        Self {
            host_id,
            online: false,
            last_seen_at,
            agent_version: None,
        }
    }
}

/// Controller → MQTT service: agent connectivity changed for one or more hosts.
///
/// Published to NATS with `target_capability = "update_tracking"` so that the MQTT
/// service on whichever controller the agent is connected to broadcasts the
/// connectivity state to **all** MQTT services across the cluster. This is the
/// canonical source of truth for `{prefix}/hosts/{h}/connectivity/state`.
///
/// Multi-controller safety: published by the controller that owns the agent
/// WebSocket connection (the only one with authoritative live state). All other
/// controllers receive this via NATS and update their caches.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HostConnectivityUpdatedPayload {
    /// Tenant this update belongs to.
    pub tenant_id: Uuid,
    /// One entry per host whose connectivity changed.
    pub updates: Vec<HostConnectivityUpdate>,
}

impl HostConnectivityUpdatedPayload {
    /// Creates a new payload.
    pub fn new(tenant_id: Uuid, updates: Vec<HostConnectivityUpdate>) -> Self {
        Self { tenant_id, updates }
    }
}

/// Pagination metadata for a [`SoftwareStatesPayload`] message.
///
/// All payloads carry a `page` field. For single-page delivery use
/// `{ page_index: 0, total_pages: 1 }`. Multi-page delivery uses
/// `page_index` 0…N-1; the last page satisfies `page_index + 1 == total_pages`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SoftwareStatesPage {
    /// Zero-based index of this page.
    pub page_index: u32,
    /// Total number of pages in this delivery batch.
    pub total_pages: u32,
}

impl SoftwareStatesPage {
    /// Creates a single-page marker (the only page in a single-page delivery).
    pub fn single() -> Self {
        Self {
            page_index: 0,
            total_pages: 1,
        }
    }
}

/// Controller -> MQTT service: current software version state for a tenant.
///
/// Sent after tenant assignment and after any version check or update result.
/// Safe to write to the outbox (contains no credentials).
///
/// Large tenants use multi-page delivery. The `page` field indicates which
/// page this payload represents. Receivers must accumulate all pages before
/// applying the full state update (see `page_index + 1 == total_pages` for
/// the last-page signal).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SoftwareStatesPayload {
    /// Tenant this state belongs to.
    pub tenant_id: Uuid,
    /// All active software items for the tenant with per-host version data.
    pub items: Vec<SoftwareStateItem>,
    /// Per-host aggregate summary of unpinned (unfeatured) software items.
    ///
    /// Each entry summarises all enabled, non-deactivated unfeatured items for
    /// one host. Only hosts with at least one such item are included.
    /// Defaults to an empty list on deserialization for backward compatibility
    /// with older MQTT services.
    #[serde(default)]
    pub host_summaries: Vec<HostPackageSummary>,
    /// Per-host metadata for all hosts referenced in `items` or `host_summaries`.
    ///
    /// Includes OS info, tags, and agent last-seen data. Sourced exclusively from DB.
    /// Defaults to an empty list for backward compatibility with older MQTT services.
    #[serde(default)]
    pub hosts: Vec<HostStateMetadata>,
    /// Pagination metadata indicating which page this payload represents.
    pub page: SoftwareStatesPage,
}

/// A single software item entry in [`SoftwareStatesPayload`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SoftwareStateItem {
    /// Software item UUID.
    pub software_item_id: Uuid,
    /// Human-readable software item name.
    pub name: String,
    /// Optional HTTPS URL to an icon/logo image.
    ///
    /// When present, the MQTT service includes this as `entity_picture` in the
    /// Home Assistant discovery config so HA displays it as the entity thumbnail.
    /// Limited to [`crate::limits::MAX_ICON_URL_LEN`] characters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
    /// Per-host version data for this software item.
    pub hosts: Vec<SoftwareStateHostEntry>,
}

/// Per-host version data for a software item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SoftwareStateHostEntry {
    /// Host UUID.
    pub host_id: Uuid,
    /// Human-readable hostname.
    pub hostname: String,
    /// User-defined display name for the host.
    pub friendly_name: String,
    /// Currently installed version, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_version: Option<String>,
    /// Latest available version, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<String>,
    /// Whether an update is available (`latest_version > installed_version`).
    pub update_available: bool,
    /// Whether an update is currently pending or in progress for this host-item pair.
    ///
    /// Set to `true` when an `update_history` record exists with status
    /// `Pending` or `InProgress`. Cleared to `false` once the update
    /// completes or fails. Defaults to `false` when absent (older controller).
    #[serde(default)]
    pub update_in_progress: bool,
    /// URL to the upstream release page (e.g. GitHub release), if available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_url: Option<String>,
    /// Release notes or changelog text, if available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_notes: Option<String>,
    /// Classification of the update (e.g. `"security"`, `"bugfix"`, `"feature"`, `"unknown"`).
    ///
    /// Sourced from `host_software_item.update_category`. Defaults to `"unknown"` when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub update_category: Option<String>,
    /// Date when the latest release was published (ISO 8601 date string, e.g. `"2025-01-15"`).
    ///
    /// Extracted from `latest_release_metadata.published_at`. `null` when metadata is absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_date: Option<String>,
    /// Timestamp when the installed version was last detected (ISO 8601).
    ///
    /// Sourced from `host_software_item.installed_version_detected_at`. `null` when never checked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_checked_at: Option<String>,
}

/// Service -> Controller: request to trigger a software update.
///
/// Sent when a Home Assistant user presses "Install" on an update entity.
/// The controller validates and dispatches the update to the appropriate agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceUpdateTriggerPayload {
    /// Tenant UUID (for validation).
    pub tenant_id: Uuid,
    /// Software item to update.
    pub software_item_id: Uuid,
    /// Host to update on.
    pub host_id: Uuid,
    /// Target version to install.
    pub to_version: String,
    /// Service instance UUID that initiated the trigger (used as actor_id).
    pub actor_service_id: Uuid,
}

/// Per-host aggregate summary of unpinned (unfeatured) software items.
///
/// Included in [`SoftwareStatesPayload`] to surface overall update
/// status per host to Home Assistant via a single `update` entity per host.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HostPackageSummary {
    /// Host UUID.
    pub host_id: Uuid,
    /// Human-readable hostname.
    pub hostname: String,
    /// User-defined display name for the host.
    #[serde(default)]
    pub friendly_name: String,
    /// Count of items where `installed_version != latest_version` (both known).
    pub pending_count: u32,
    /// Count of items where `update_category = "security"` AND versions differ.
    ///
    /// Used to drive the per-host security updates entity in Home Assistant.
    pub security_pending_count: u32,
    /// Total count of enabled, non-deactivated unfeatured items for this host.
    pub total_count: u32,
    /// Whether a batch update is currently pending or in progress for this host.
    pub update_in_progress: bool,
    /// Count of pending packages where `update_category = "bugfix"`.
    ///
    /// Defaults to `0` when absent (older controller that does not compute this field).
    #[serde(default)]
    pub bugfix_count: u32,
    /// Count of pending packages where `update_category = "feature"`.
    ///
    /// Defaults to `0` when absent (older controller that does not compute this field).
    #[serde(default)]
    pub feature_count: u32,
}

/// Service → Controller: trigger a batch update of all outdated software items on a host.
///
/// Sent when a Home Assistant user presses "Install" on a host update
/// entity. The controller resolves the latest versions for all outdated items
/// at trigger time and dispatches a `ExecuteBatchUpdate` to the agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ServiceHostBatchUpdateTriggerPayload {
    /// Tenant UUID (for validation).
    pub tenant_id: Uuid,
    /// Host whose items should be updated.
    pub host_id: Uuid,
    /// Service instance UUID that initiated the trigger (used as actor_id).
    pub actor_service_id: Uuid,
    /// When `true`, only items with `update_category = "security"` are updated.
    #[serde(default)]
    pub security_only: bool,
}

/// Service -> Controller: forwarded semantic audit event.
///
/// The wire payload intentionally keeps semantic fields as strings so the
/// controller can re-validate them against its canonical audit contract before
/// persisting or exporting the event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AuditEventPayload {
    /// Semantic action identifier, such as `service.certificate.issue`.
    pub action_type: String,
    /// Tenant UUID as a string when the event is tenant-scoped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<String>,
    /// Optional semantic target type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_type: Option<String>,
    /// Optional semantic target identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_id: Option<String>,
    /// Optional human-readable target display value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_display: Option<String>,
    /// Semantic outcome, such as `success` or `denied`.
    pub outcome: String,
    /// Optional JSON-encoded details payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details_json: Option<String>,
    /// Optional correlation identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Optional correlation identifier linking events in a workflow chain.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<uuid::Uuid>,
}

// =============================================================================
// Software Autodiscovery Payloads
// =============================================================================

/// Controller -> Agent: Run software discovery on the given host.
///
/// The `plugins` list contains one entry per plugin that should be used.
/// When `plugin_config_id` is `None`, the assignment uses a default (empty)
/// config — the controller will auto-create a `PluginConfig` record once
/// results arrive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiscoverSoftwarePayload {
    /// Machine ID of the host to discover software on.
    ///
    /// For the regular agent this is validated to match its own machine_id.
    /// For the SSH agent it identifies which remote host to connect to.
    pub host_machine_id: String,
    /// Per-plugin discovery assignments.
    pub plugins: Vec<DiscoveryPluginAssignment>,
}

/// A single plugin assignment inside a [`DiscoverSoftwarePayload`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiscoveryPluginAssignment {
    /// Pre-existing plugin config ID, or `None` for a default/auto run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config_id: Option<Uuid>,
    /// Plugin type to use for discovery.
    pub plugin_type: PluginTypeId,
    /// Plugin-specific configuration (`{}` for default assignments).
    pub config: serde_json::Value,
}

/// Agent -> Controller: Results of a software discovery run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiscoveryResultsPayload {
    /// Machine ID of the host that was scanned (echoed from the assignment).
    pub host_machine_id: String,
    /// Per-plugin results.
    pub results: Vec<DiscoveryPluginResult>,
}

/// Result for a single plugin inside a [`DiscoveryResultsPayload`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiscoveryPluginResult {
    /// Echoed from [`DiscoveryPluginAssignment`] so the controller can route
    /// results to the correct `PluginConfig` row.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config_id: Option<Uuid>,
    /// Plugin type that produced these results.
    pub plugin_type: PluginTypeId,
    /// Discovered software items (empty on error).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub discoveries: Vec<DiscoveredSoftware>,
    /// Plugin-level error message, if discovery failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// =============================================================================
// Plugin config reporting
// =============================================================================

/// Payload for `ServiceMessage::ReportPluginConfig`.
///
/// Sent by agents that detect infrastructure (e.g. PVE nodes) during bootstrap
/// and want the controller to create or retrieve a plugin configuration.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReportPluginConfigPayload {
    /// Unique request identifier for correlating the response.
    pub request_id: String,
    /// Plugin type string (e.g. `"infrastructure.proxmox"`).
    pub plugin_type: String,
    /// Human-readable name for the config (e.g. `"pve.local"`).
    pub name: String,
    /// Plugin-specific configuration JSON.
    pub config: serde_json::Value,
}

/// Payload for `ControllerMessage::ReportPluginConfigResponse`.
///
/// Returned to a service in response to `ReportPluginConfig`. Idempotent:
/// if a config with the same `(tenant_id, plugin_type, name)` already exists,
/// the existing ID is returned without creating a duplicate.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReportPluginConfigResponsePayload {
    /// The request ID from the original `ReportPluginConfig` message.
    pub request_id: String,
    /// Whether the operation succeeded.
    pub success: bool,
    /// The plugin config ID (set on success).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config_id: Option<Uuid>,
    /// Error message (set on failure).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// =============================================================================
// Interactive Update Payloads
// =============================================================================

/// Controller → Agent: forward stdin data or a signal to a running interactive update.
///
/// The `data` field contains raw bytes encoded as base64 to support binary
/// control sequences (e.g., `\x03` for Ctrl+C). When `signal` is set, the
/// agent delivers the signal to the process group instead of writing stdin.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpdateStdinDataPayload {
    /// The update history record this stdin data belongs to.
    pub update_history_id: Uuid,
    /// Raw bytes encoded as base64 (supports binary: Ctrl+C = \x03, etc.).
    pub data: String,
    /// When set, send this signal to the process group instead of writing stdin.
    /// Values: 2 = SIGINT, 15 = SIGTERM.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<i32>,
}

impl UpdateStdinDataPayload {
    /// Create a new stdin data payload.
    pub fn new(update_history_id: Uuid, data: String) -> Self {
        Self {
            update_history_id,
            data,
            signal: None,
        }
    }

    /// Create a new signal payload.
    pub fn with_signal(update_history_id: Uuid, signal: i32) -> Self {
        Self {
            update_history_id,
            data: String::new(),
            signal: Some(signal),
        }
    }
}

/// Agent → Controller: the update process appears to be waiting for stdin input.
///
/// Sent when the agent detects sustained silence from the process (no output for
/// ~10 seconds while still running). The controller broadcasts this to interactive
/// session subscribers and may trigger notifications.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct StdinAttentionPayload {
    /// The update history record that needs attention.
    pub update_history_id: Uuid,
    /// Optional hint about what the process might be waiting for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

impl StdinAttentionPayload {
    /// Create a new attention payload.
    pub fn new(update_history_id: Uuid) -> Self {
        Self {
            update_history_id,
            hint: None,
        }
    }

    /// Create a new attention payload with a hint.
    pub fn with_hint(update_history_id: Uuid, hint: String) -> Self {
        Self {
            update_history_id,
            hint: Some(hint),
        }
    }
}

// --- Cross-controller admin event broadcast ---

/// Cross-controller admin event broadcast payload.
///
/// Published via NATS to the `controller` subject by any controller instance
/// when it emits an [`AdminEvent`](crate::admin_events::AdminEvent)
/// to local SSE subscribers. Receiving controller instances decode the payload
/// and re-broadcast to their own local SSE subscribers without re-publishing
/// to NATS (to avoid infinite loops).
///
/// `tenant_id = None` means the event targets all tenants (system-wide).
///
/// **Safe to publish via NATS** — contains no credential material.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BroadcastAdminEventPayload {
    /// Target tenant, or `None` for system-wide events.
    pub tenant_id: Option<Uuid>,
    /// JSON-serialised `AdminEvent`.
    pub event_json: String,
}

// =============================================================================
// Workload Claim Protocol Payloads
// =============================================================================

/// Service → Controller: request exclusive ownership of config keys.
///
/// Each key in `claims` is a config key (e.g. `"clients.{uuid}"`) and the
/// value is the `tenant_id` that config belongs to. The controller grants
/// unclaimed keys and rejects keys already claimed by another service.
///
/// Uses **full replacement semantics**: each `WorkloadClaim` sends the
/// complete desired config key set. The controller diffs against current
/// grants to determine what to claim/release.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimPayload {
    /// Map of `config_key → tenant_id` representing the full desired set.
    pub claims: BTreeMap<String, Uuid>,
}

impl WorkloadClaimPayload {
    /// Create a new `WorkloadClaimPayload`.
    pub fn new(claims: BTreeMap<String, Uuid>) -> Self {
        Self { claims }
    }
}

/// Controller → Service: grant/reject response for a workload claim request.
///
/// Sent in response to `WorkloadClaim`, or unsolicited when the controller
/// proactively re-grants previously rejected keys that became available
/// (e.g. after another service disconnected), or when revoking keys due
/// to cross-controller conflict resolution.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimResultPayload {
    /// Config keys that were granted (exclusive ownership).
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub granted: BTreeSet<String>,
    /// Config keys that were rejected (already claimed by another service).
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub rejected: BTreeSet<String>,
}

impl WorkloadClaimResultPayload {
    /// Create a new `WorkloadClaimResultPayload`.
    pub fn new(granted: BTreeSet<String>, rejected: BTreeSet<String>) -> Self {
        Self { granted, rejected }
    }
}

/// Service → Controller: voluntarily release config keys.
///
/// Sent when a service no longer wants to serve certain configs (e.g. after
/// a config deletion). The controller releases the keys and makes them
/// available for other services.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadReleasePayload {
    /// Config keys to release.
    pub keys: BTreeSet<String>,
}

impl WorkloadReleasePayload {
    /// Create a new `WorkloadReleasePayload`.
    pub fn new(keys: BTreeSet<String>) -> Self {
        Self { keys }
    }
}

/// Controller → NATS: announce claim state changes for cross-controller sync.
///
/// Published to the `controller` NATS subject after granting or releasing
/// claims. Other controllers update their global claim registry from this.
///
/// **Safe to publish via NATS** — contains no credential material.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimAnnouncementPayload {
    /// The service that owns these claims.
    pub service_id: Uuid,
    /// The controller that granted these claims.
    pub controller_id: Uuid,
    /// Newly claimed keys: `config_key → tenant_id`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub claimed: BTreeMap<String, Uuid>,
    /// Keys that were released.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub released: BTreeSet<String>,
    /// ISO 8601 timestamp when the claims were granted (for conflict resolution).
    pub claimed_at: String,
}

impl WorkloadClaimAnnouncementPayload {
    /// Create a new `WorkloadClaimAnnouncementPayload`.
    pub fn new(
        service_id: Uuid,
        controller_id: Uuid,
        claimed: BTreeMap<String, Uuid>,
        released: BTreeSet<String>,
        claimed_at: String,
    ) -> Self {
        Self {
            service_id,
            controller_id,
            claimed,
            released,
            claimed_at,
        }
    }
}

/// Controller → NATS: request full claim state from all active controllers.
///
/// Published on controller startup to the `controller` NATS subject.
/// Each active controller responds with `WorkloadClaimSyncResponse`.
///
/// **NATS-only** (controller-to-controller), not service-facing.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimSyncRequestPayload {
    /// The requesting controller's ID.
    pub controller_id: Uuid,
}

impl WorkloadClaimSyncRequestPayload {
    /// Create a new `WorkloadClaimSyncRequestPayload`.
    pub fn new(controller_id: Uuid) -> Self {
        Self { controller_id }
    }
}

/// Controller → NATS: respond with full local claim state.
///
/// Sent in response to `WorkloadClaimSyncRequest`. Contains the responding
/// controller's complete local claim map for merging into the requester's
/// global registry.
///
/// **NATS-only** (controller-to-controller), not service-facing.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimSyncResponsePayload {
    /// The responding controller's ID.
    pub controller_id: Uuid,
    /// Full local claim state: `config_key → (service_id, tenant_id)`.
    pub claims: BTreeMap<String, WorkloadClaimSyncEntry>,
}

impl WorkloadClaimSyncResponsePayload {
    /// Create a new `WorkloadClaimSyncResponsePayload`.
    pub fn new(controller_id: Uuid, claims: BTreeMap<String, WorkloadClaimSyncEntry>) -> Self {
        Self {
            controller_id,
            claims,
        }
    }
}

/// A single entry in a `WorkloadClaimSyncResponse`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkloadClaimSyncEntry {
    /// The service that owns this claim.
    pub service_id: Uuid,
    /// The tenant this config key belongs to.
    pub tenant_id: Uuid,
    /// ISO 8601 timestamp when the claim was granted.
    pub claimed_at: String,
}

impl WorkloadClaimSyncEntry {
    /// Create a new `WorkloadClaimSyncEntry`.
    pub fn new(service_id: Uuid, tenant_id: Uuid, claimed_at: String) -> Self {
        Self {
            service_id,
            tenant_id,
            claimed_at,
        }
    }
}

// ── Config test payloads ─────────────────────────────────────────────────────

// Must be `pub use`, not bare `use` — wire's lib.rs does `pub use payloads::*`,
// which only re-exports *pub* items. A private import here would silently drop
// ConfigTestKind from the wire public API and break all 21 non-plugin dependents.
pub use uptrakit_shared_types::ConfigTestKind;

/// Payload for a plugin configuration test request (controller -> agent).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TestPluginConfigPayload {
    /// Unique request ID for correlation (UUID v7).
    pub request_id: String,
    /// Target host machine ID on the agent.
    pub host_machine_id: String,
    /// What to test.
    pub test_kind: ConfigTestKind,
    /// The plugin type to test.
    pub plugin_type: String,
    /// The plugin configuration JSON to test.
    pub config: serde_json::Value,
    /// Package identifier for testing (required for version detection).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package_identifier: Option<String>,
}

impl TestPluginConfigPayload {
    /// Creates a new test plugin config payload.
    pub fn new(
        request_id: String,
        host_machine_id: String,
        test_kind: ConfigTestKind,
        plugin_type: String,
        config: serde_json::Value,
    ) -> Self {
        Self {
            request_id,
            host_machine_id,
            test_kind,
            plugin_type,
            config,
            package_identifier: None,
        }
    }
}

/// Payload for a plugin configuration test result (agent -> controller).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TestPluginConfigResultPayload {
    /// Correlation ID matching the original request.
    pub request_id: String,
    /// Whether the test passed.
    pub success: bool,
    /// Command output or connectivity response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
    /// Error message if the test failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Detected version (for version detection tests).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detected_version: Option<String>,
    /// Test duration in milliseconds.
    pub duration_ms: u64,
}

impl TestPluginConfigResultPayload {
    /// Creates a new test result payload.
    pub fn new(request_id: String, success: bool, duration_ms: u64) -> Self {
        Self {
            request_id,
            success,
            output: None,
            error: None,
            detected_version: None,
            duration_ms,
        }
    }
}

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

    #[test]
    fn test_update_result_payload_resumable_defaults_none() {
        let json = r#"{"update_history_id":"00000000-0000-0000-0000-000000000001","status":"completed","output":""}"#;
        let p: UpdateResultPayload = serde_json::from_str(json).unwrap();
        assert_eq!(p.resumable, None);
    }

    #[test]
    fn test_update_result_payload_resumable_true_round_trips() {
        let p = UpdateResultPayload {
            update_history_id: uuid::Uuid::nil(),
            status: crate::UpdateFinalStatus::Completed,
            from_version: None,
            to_version: None,
            output: String::new(),
            error: None,
            resumable: Some(true),
        };
        let json = serde_json::to_string(&p).unwrap();
        assert!(json.contains("\"resumable\":true"));
        let back: UpdateResultPayload = serde_json::from_str(&json).unwrap();
        assert_eq!(back.resumable, Some(true));
    }

    #[test]
    fn test_version_check_result_not_ready_defaults_none() {
        let json = r#"{"software_item_id":"00000000-0000-0000-0000-000000000001","update_category":"none"}"#;
        let r: VersionCheckResult = serde_json::from_str(json).unwrap();
        assert_eq!(r.not_ready, None);
    }

    #[test]
    fn test_version_check_result_not_ready_true_round_trips() {
        let r = VersionCheckResult {
            software_item_id: uuid::Uuid::nil(),
            installed_version: None,
            latest_version: None,
            error: None,
            update_category: crate::UpdateCategory::default(),
            host_software_item_id: None,
            installed_display_version: None,
            not_ready: Some(true),
        };
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"not_ready\":true"));
        let back: VersionCheckResult = serde_json::from_str(&json).unwrap();
        assert_eq!(back.not_ready, Some(true));
    }
}