aidaemon-nodes 0.24.0

Nodes for aidaemon agents: enrolled hardware companions with server-issued identity, their HTTP Gateway, store, OTA releases, speech, monitoring and the tools that read and command them; implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
use std::sync::Arc;

use chrono::{DateTime, Duration, Utc};
use serde_json::json;
use sqlx::{Row, SqlitePool};

use super::auth;
use super::domain::{AuthenticatedNodeContext, NodeAction, NodeRecord, NodeTurnState};
use super::protocol::{RuntimeRecoveryReport, TurnEvent};

#[derive(Clone)]
pub struct NodeStore {
    pool: SqlitePool,
    instance_key: Arc<[u8; 32]>,
    instance_id: Arc<str>,
}

#[derive(Debug, Clone)]
pub struct PairingOffer {
    pub offer_id: String,
    pub offer_secret: String,
    pub expires_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct EnrollmentResult {
    pub node: NodeRecord,
    pub credential_id: String,
    pub public_key_fingerprint: String,
}

#[derive(Debug, Clone)]
pub struct ChallengeRecord {
    pub challenge_id: String,
    pub credential_id: String,
    pub nonce: String,
    pub public_key_sec1: Vec<u8>,
    pub expires_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct CredentialRotationRecord {
    pub rotation_id: String,
    pub node_id: String,
    pub credential_id: String,
    pub node_session_id: String,
    pub nonce: String,
    pub expires_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct CreatedSession {
    pub context: AuthenticatedNodeContext,
    pub access_token: String,
    pub expires_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct CreateTurnOutcome {
    pub turn_id: String,
    pub state: NodeTurnState,
    pub cursor: u64,
    pub duplicate: bool,
}

#[derive(Debug, Clone)]
pub struct MediaUploadRecord {
    pub slot_id: String,
    pub turn_id: String,
    pub node_id: String,
    pub media_kind: String,
    pub content_type: String,
    pub expected_bytes: u64,
    pub expected_sha256: String,
    pub duration_ms: Option<u64>,
    pub local_path: Option<String>,
    pub state: String,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct LatestSensorReading {
    pub display_name: String,
    pub capability_id: String,
    pub capability_version: u16,
    pub value: f64,
    pub unit: String,
    pub sample_uptime_ms: u64,
    pub received_at: DateTime<Utc>,
    pub node_last_seen_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct NodeCapabilitySnapshot {
    pub capability_id: String,
    pub capability_version: u16,
    pub limits: serde_json::Value,
    pub observed_at: DateTime<Utc>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct NodeAuthorizationSnapshot {
    pub action: String,
    pub constraints: serde_json::Value,
    pub revision: u64,
    pub granted_at: DateTime<Utc>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct NodeHealthSnapshot {
    pub display_name: String,
    pub last_seen_at: Option<DateTime<Utc>>,
    pub runtime_version: Option<String>,
    pub firmware_version: Option<String>,
    pub uptime_ms: Option<u64>,
    pub free_internal_heap: Option<u64>,
    pub largest_internal_allocation: Option<u64>,
    pub psram_free: Option<u64>,
    pub recovery: Option<RuntimeRecoveryReport>,
    /// Capabilities from the latest authenticated Node heartbeat. Their absence
    /// is evidence about the reported protocol surface, not proof about
    /// unreported physical hardware.
    pub capabilities: Vec<NodeCapabilitySnapshot>,
    /// Currently granted gateway actions for the selected Node.
    pub authorizations: Vec<NodeAuthorizationSnapshot>,
}

#[derive(Debug, Clone)]
pub struct AudioAnnouncementTarget {
    pub node_id: String,
    pub display_name: String,
    pub last_seen_at: Option<DateTime<Utc>>,
    pub maximum_audio_bytes: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct QueuedAudioAnnouncement {
    pub cursor: u64,
    pub node_id: String,
    pub display_name: String,
    pub size_bytes: u64,
    pub expires_at: DateTime<Utc>,
    pub last_seen_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone)]
pub struct NodeOutboxReceipt {
    pub status: String,
    pub detail_code: Option<String>,
    pub acknowledged_at: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct OutboundMediaCleanup {
    pub media_id: String,
    pub local_path: String,
}

fn parse_timestamp(value: &str) -> anyhow::Result<DateTime<Utc>> {
    Ok(DateTime::parse_from_rfc3339(value)?.with_timezone(&Utc))
}

fn action_name(action: NodeAction) -> &'static str {
    match action {
        NodeAction::SubmitTextTurn => "submit_text_turn",
        NodeAction::SubmitAudioTurn => "submit_audio_turn",
        NodeAction::SubmitStillImage => "submit_still_image",
        NodeAction::ReportTelemetry => "report_telemetry",
        NodeAction::ReportSensor => "report_sensor",
        NodeAction::ReceiveAudio => "receive_audio",
        NodeAction::ReceiveDisplayCommand => "receive_display_command",
        NodeAction::ReceiveActuatorCommand => "receive_actuator_command",
        NodeAction::ReceiveOta => "receive_ota",
        NodeAction::DeviceRestart => "device_restart",
    }
}

pub async fn migrate(pool: &SqlitePool) -> anyhow::Result<()> {
    let statements = [
        r#"CREATE TABLE IF NOT EXISTS nodes (
            node_id TEXT PRIMARY KEY,
            owner_id TEXT NOT NULL,
            kind TEXT NOT NULL,
            display_name TEXT NOT NULL,
            policy_profile TEXT NOT NULL,
            policy_revision INTEGER NOT NULL DEFAULT 1,
            authorization_revision INTEGER NOT NULL DEFAULT 1,
            created_at TEXT NOT NULL,
            revoked_at TEXT,
            last_seen_at TEXT,
            last_runtime_version TEXT,
            last_firmware_version TEXT,
            last_health_json TEXT
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_credentials (
            credential_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            public_key_sec1 BLOB NOT NULL,
            public_key_fingerprint TEXT NOT NULL,
            state TEXT NOT NULL DEFAULT 'active' CHECK(state IN ('pending','active','retired','revoked')),
            revision INTEGER NOT NULL DEFAULT 1,
            created_at TEXT NOT NULL,
            expires_at TEXT,
            revoked_at TEXT
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_pairing_offers (
            offer_id TEXT PRIMARY KEY,
            secret_digest BLOB NOT NULL,
            owner_id TEXT NOT NULL,
            expected_kind TEXT NOT NULL,
            display_name TEXT NOT NULL,
            policy_profile TEXT NOT NULL,
            conversation_session_id TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            attempts INTEGER NOT NULL DEFAULT 0,
            consumed_at TEXT,
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_auth_challenges (
            challenge_id TEXT PRIMARY KEY,
            credential_id TEXT NOT NULL REFERENCES node_credentials(credential_id) ON DELETE CASCADE,
            nonce TEXT NOT NULL,
            protocol_major INTEGER NOT NULL,
            expires_at TEXT NOT NULL,
            used_at TEXT,
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_credential_rotation_challenges (
            rotation_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            credential_id TEXT NOT NULL REFERENCES node_credentials(credential_id) ON DELETE CASCADE,
            node_session_id TEXT NOT NULL REFERENCES node_sessions(node_session_id) ON DELETE CASCADE,
            nonce TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            used_at TEXT,
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_sessions (
            node_session_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            credential_id TEXT NOT NULL REFERENCES node_credentials(credential_id) ON DELETE CASCADE,
            token_digest BLOB NOT NULL UNIQUE,
            credential_revision INTEGER NOT NULL,
            policy_revision INTEGER NOT NULL,
            authorization_revision INTEGER NOT NULL,
            protocol_major INTEGER NOT NULL,
            boot_id TEXT NOT NULL,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            last_seen_at TEXT NOT NULL,
            closed_at TEXT,
            close_reason TEXT
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_channels (
            node_channel_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            conversation_session_id TEXT NOT NULL UNIQUE,
            principal_id TEXT NOT NULL,
            memory_scope TEXT NOT NULL DEFAULT 'disabled',
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_capabilities (
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            capability_id TEXT NOT NULL,
            capability_version INTEGER NOT NULL,
            limits_json TEXT NOT NULL,
            observed_session_id TEXT,
            observed_at TEXT NOT NULL,
            PRIMARY KEY(node_id, capability_id)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_authorizations (
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            action TEXT NOT NULL,
            constraints_json TEXT NOT NULL DEFAULT '{}',
            revision INTEGER NOT NULL,
            granted_at TEXT NOT NULL,
            revoked_at TEXT,
            PRIMARY KEY(node_id, action)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_sensor_readings_latest (
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            capability_id TEXT NOT NULL,
            capability_version INTEGER NOT NULL,
            value REAL NOT NULL,
            unit TEXT NOT NULL,
            sample_uptime_ms INTEGER NOT NULL,
            request_id TEXT NOT NULL,
            observed_session_id TEXT NOT NULL,
            received_at TEXT NOT NULL,
            PRIMARY KEY(node_id, capability_id)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_sensor_readings_history (
            reading_id INTEGER PRIMARY KEY AUTOINCREMENT,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            capability_id TEXT NOT NULL,
            capability_version INTEGER NOT NULL,
            value REAL NOT NULL,
            unit TEXT NOT NULL,
            sample_uptime_ms INTEGER NOT NULL,
            request_id TEXT NOT NULL,
            observed_session_id TEXT NOT NULL,
            received_at TEXT NOT NULL,
            UNIQUE(node_id, capability_id, request_id)
        )"#,
        r#"CREATE INDEX IF NOT EXISTS idx_node_sensor_history_capability_time
            ON node_sensor_readings_history(node_id, capability_id, received_at DESC)"#,
        r#"CREATE TABLE IF NOT EXISTS node_monitors (
            monitor_id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            owner_session_id TEXT NOT NULL,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            capability_id TEXT NOT NULL,
            capability_version INTEGER NOT NULL,
            unit TEXT NOT NULL,
            comparison TEXT NOT NULL CHECK(comparison IN ('above','below')),
            threshold REAL NOT NULL,
            clear_threshold REAL NOT NULL,
            duration_seconds INTEGER NOT NULL CHECK(duration_seconds BETWEEN 0 AND 86400),
            stale_after_seconds INTEGER NOT NULL CHECK(stale_after_seconds BETWEEN 30 AND 86400),
            offline_after_seconds INTEGER NOT NULL CHECK(offline_after_seconds BETWEEN 30 AND 86400),
            repeat_seconds INTEGER NOT NULL CHECK(repeat_seconds BETWEEN 0 AND 604800),
            send_recovery INTEGER NOT NULL DEFAULT 1 CHECK(send_recovery IN (0,1)),
            status TEXT NOT NULL DEFAULT 'active'
                CHECK(status IN ('active','paused','suspended','cancelled','expired')),
            condition_since TEXT,
            threshold_triggered_at TEXT,
            last_threshold_alert_at TEXT,
            availability_state TEXT NOT NULL DEFAULT 'normal'
                CHECK(availability_state IN ('normal','stale','offline')),
            last_availability_alert_at TEXT,
            last_value REAL,
            last_received_at TEXT,
            mandate_id TEXT REFERENCES mandates(id) ON DELETE SET NULL,
            mandate_goal_id TEXT,
            mandate_version INTEGER,
            expires_at TEXT NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )"#,
        r#"CREATE INDEX IF NOT EXISTS idx_node_monitors_evaluation
            ON node_monitors(status, node_id, capability_id, expires_at)"#,
        r#"CREATE INDEX IF NOT EXISTS idx_node_monitors_owner
            ON node_monitors(owner_session_id, created_at DESC)"#,
        r#"CREATE TABLE IF NOT EXISTS node_monitor_events (
            event_id TEXT PRIMARY KEY,
            monitor_id TEXT NOT NULL REFERENCES node_monitors(monitor_id) ON DELETE CASCADE,
            event_kind TEXT NOT NULL,
            evidence_json TEXT NOT NULL,
            notification_id TEXT NOT NULL UNIQUE,
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE INDEX IF NOT EXISTS idx_node_monitor_events_monitor_time
            ON node_monitor_events(monitor_id, created_at DESC)"#,
        r#"CREATE TABLE IF NOT EXISTS node_turns (
            turn_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            node_channel_id TEXT NOT NULL REFERENCES node_channels(node_channel_id) ON DELETE CASCADE,
            request_id TEXT NOT NULL,
            input_kind TEXT NOT NULL,
            input_text TEXT,
            state TEXT NOT NULL,
            deadline_at TEXT NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            error_code TEXT,
            result_text TEXT,
            UNIQUE(node_id, request_id)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_uploads (
            slot_id TEXT PRIMARY KEY,
            turn_id TEXT NOT NULL REFERENCES node_turns(turn_id) ON DELETE CASCADE,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            media_kind TEXT NOT NULL CHECK(media_kind IN ('audio','still_image')),
            content_type TEXT NOT NULL,
            expected_bytes INTEGER NOT NULL,
            expected_sha256 TEXT NOT NULL,
            duration_ms INTEGER,
            state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','uploaded','consumed','deleted')),
            local_path TEXT,
            received_at TEXT,
            created_at TEXT NOT NULL,
            UNIQUE(turn_id)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_outbox (
            cursor INTEGER PRIMARY KEY AUTOINCREMENT,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            turn_id TEXT REFERENCES node_turns(turn_id) ON DELETE CASCADE,
            event_type TEXT NOT NULL,
            payload_json TEXT NOT NULL,
            priority INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_outbox_receipts (
            cursor INTEGER NOT NULL REFERENCES node_outbox(cursor) ON DELETE CASCADE,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            status TEXT NOT NULL CHECK(status IN ('played','failed','dismissed')),
            detail_code TEXT,
            acknowledged_at TEXT NOT NULL,
            PRIMARY KEY(cursor, node_id)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_outbound_media (
            media_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            outbox_cursor INTEGER NOT NULL UNIQUE REFERENCES node_outbox(cursor) ON DELETE CASCADE,
            content_type TEXT NOT NULL,
            size_bytes INTEGER NOT NULL,
            sha256 TEXT NOT NULL,
            local_path TEXT NOT NULL,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            deleted_at TEXT
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_response_media (
            media_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            turn_id TEXT NOT NULL REFERENCES node_turns(turn_id) ON DELETE CASCADE,
            content_type TEXT NOT NULL,
            size_bytes INTEGER NOT NULL,
            local_path TEXT NOT NULL,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_request_dedup (
            node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
            operation TEXT NOT NULL,
            idempotency_key TEXT NOT NULL,
            request_digest BLOB NOT NULL,
            result_id TEXT NOT NULL,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            PRIMARY KEY(node_id, operation, idempotency_key)
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_audit_events (
            audit_id INTEGER PRIMARY KEY AUTOINCREMENT,
            node_id TEXT,
            event_type TEXT NOT NULL,
            detail_json TEXT NOT NULL DEFAULT '{}',
            created_at TEXT NOT NULL
        )"#,
        r#"CREATE TABLE IF NOT EXISTS node_restart_commands (
            command_id TEXT PRIMARY KEY,
            node_id TEXT NOT NULL,
            reason TEXT NOT NULL,
            state TEXT NOT NULL,
            created_at TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            delivered_at TEXT,
            delivered_boot_id TEXT,
            delivered_uptime_ms INTEGER,
            finished_at TEXT
        )"#,
        "CREATE UNIQUE INDEX IF NOT EXISTS idx_node_restart_one_active ON node_restart_commands(node_id) WHERE state IN ('pending', 'delivered')",
        "CREATE INDEX IF NOT EXISTS idx_node_sessions_node_expiry ON node_sessions(node_id, expires_at)",
        "CREATE INDEX IF NOT EXISTS idx_node_outbox_node_cursor ON node_outbox(node_id, cursor)",
        "CREATE INDEX IF NOT EXISTS idx_node_outbound_media_expiry ON node_outbound_media(expires_at, deleted_at)",
        "CREATE INDEX IF NOT EXISTS idx_node_turns_node_created ON node_turns(node_id, created_at)",
        "CREATE INDEX IF NOT EXISTS idx_node_challenges_expiry ON node_auth_challenges(expires_at)",
    ];

    for statement in statements {
        sqlx::query(statement).execute(pool).await?;
    }
    Ok(())
}

impl NodeStore {
    pub fn new(pool: SqlitePool, instance_key: [u8; 32]) -> Self {
        let instance_digest = auth::keyed_digest(&instance_key, "instance-id", b"local-instance");
        let instance_id = format!(
            "aid_{}",
            instance_digest[..8]
                .iter()
                .map(|byte| format!("{byte:02x}"))
                .collect::<String>()
        );
        Self {
            pool,
            instance_key: Arc::new(instance_key),
            instance_id: Arc::from(instance_id),
        }
    }

    pub fn pool(&self) -> &SqlitePool {
        &self.pool
    }

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

    pub async fn create_pairing_offer(
        &self,
        owner_id: &str,
        expected_kind: &str,
        display_name: &str,
        policy_profile: &str,
        ttl_seconds: u64,
    ) -> anyhow::Result<PairingOffer> {
        super::domain::validate_node_kind(expected_kind)?;
        super::domain::validate_policy_profile(policy_profile)?;
        anyhow::ensure!(
            !owner_id.trim().is_empty() && owner_id.len() <= 128,
            "owner id is invalid"
        );
        anyhow::ensure!(
            !display_name.trim().is_empty() && display_name.len() <= 80,
            "display name is invalid"
        );
        let now = Utc::now();
        let expires_at = now + Duration::seconds(ttl_seconds.clamp(60, 3600) as i64);
        let offer_id = format!("offer_{}", uuid::Uuid::new_v4().simple());
        let offer_secret = auth::random_secret(32);
        let digest =
            auth::keyed_digest(&self.instance_key, "pairing-offer", offer_secret.as_bytes());
        let conversation_session_id =
            format!("node:conversation:{}", uuid::Uuid::new_v4().simple());
        sqlx::query(
            "INSERT INTO node_pairing_offers
             (offer_id, secret_digest, owner_id, expected_kind, display_name, policy_profile,
              conversation_session_id, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&offer_id)
        .bind(digest)
        .bind(owner_id.trim())
        .bind(expected_kind)
        .bind(display_name.trim())
        .bind(policy_profile)
        .bind(conversation_session_id)
        .bind(expires_at.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&self.pool)
        .await?;
        Ok(PairingOffer {
            offer_id,
            offer_secret,
            expires_at,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn redeem_enrollment(
        &self,
        offer_id: &str,
        offer_secret: &str,
        node_kind: &str,
        public_key_sec1: &[u8],
        runtime_version: &str,
        firmware_version: &str,
        capabilities: &[super::domain::CapabilityObservation],
    ) -> anyhow::Result<EnrollmentResult> {
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let row = sqlx::query(
            "SELECT secret_digest, owner_id, expected_kind, display_name, policy_profile,
                    conversation_session_id, expires_at, consumed_at, attempts
             FROM node_pairing_offers WHERE offer_id = ?",
        )
        .bind(offer_id)
        .fetch_optional(&mut *transaction)
        .await?
        .ok_or_else(|| anyhow::anyhow!("pairing offer not found"))?;

        let attempts: i64 = row.get("attempts");
        anyhow::ensure!(attempts < 8, "pairing offer attempt limit exceeded");
        sqlx::query("UPDATE node_pairing_offers SET attempts = attempts + 1 WHERE offer_id = ?")
            .bind(offer_id)
            .execute(&mut *transaction)
            .await?;
        let consumed_at: Option<String> = row.get("consumed_at");
        anyhow::ensure!(consumed_at.is_none(), "pairing offer was already consumed");
        let expires_at: String = row.get("expires_at");
        anyhow::ensure!(
            parse_timestamp(&expires_at)? > Utc::now(),
            "pairing offer expired"
        );
        let expected_kind: String = row.get("expected_kind");
        anyhow::ensure!(
            expected_kind == node_kind,
            "Node kind does not match pairing offer"
        );
        let stored_digest: Vec<u8> = row.get("secret_digest");
        anyhow::ensure!(
            auth::constant_time_digest_matches(
                &self.instance_key,
                "pairing-offer",
                offer_secret.as_bytes(),
                &stored_digest,
            ),
            "pairing offer secret is invalid"
        );

        let node_id = format!("node_{}", uuid::Uuid::new_v4().simple());
        let credential_id = format!("cred_{}", uuid::Uuid::new_v4().simple());
        let node_channel_id = format!("nch_{}", uuid::Uuid::new_v4().simple());
        let now = Utc::now();
        let owner_id: String = row.get("owner_id");
        let display_name: String = row.get("display_name");
        let policy_profile: String = row.get("policy_profile");
        let conversation_session_id: String = row.get("conversation_session_id");
        let fingerprint = auth::public_key_fingerprint(public_key_sec1);

        sqlx::query(
            "INSERT INTO nodes
             (node_id, owner_id, kind, display_name, policy_profile, created_at,
              last_runtime_version, last_firmware_version)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&node_id)
        .bind(&owner_id)
        .bind(node_kind)
        .bind(&display_name)
        .bind(&policy_profile)
        .bind(now.to_rfc3339())
        .bind(runtime_version)
        .bind(firmware_version)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_credentials
             (credential_id, node_id, public_key_sec1, public_key_fingerprint, created_at)
             VALUES (?, ?, ?, ?, ?)",
        )
        .bind(&credential_id)
        .bind(&node_id)
        .bind(public_key_sec1)
        .bind(&fingerprint)
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_channels
             (node_channel_id, node_id, conversation_session_id, principal_id, memory_scope, created_at)
             VALUES (?, ?, ?, ?, 'disabled', ?)",
        )
        .bind(&node_channel_id)
        .bind(&node_id)
        .bind(&conversation_session_id)
        .bind(format!("node-principal:{node_id}"))
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        for action in [NodeAction::SubmitTextTurn, NodeAction::ReportTelemetry] {
            sqlx::query(
                "INSERT INTO node_authorizations
                 (node_id, action, constraints_json, revision, granted_at)
                 VALUES (?, ?, '{}', 1, ?)",
            )
            .bind(&node_id)
            .bind(action_name(action))
            .bind(now.to_rfc3339())
            .execute(&mut *transaction)
            .await?;
        }
        for capability in capabilities.iter().take(32) {
            sqlx::query(
                "INSERT INTO node_capabilities
                 (node_id, capability_id, capability_version, limits_json, observed_at)
                 VALUES (?, ?, ?, ?, ?)",
            )
            .bind(&node_id)
            .bind(&capability.capability_id)
            .bind(i64::from(capability.version))
            .bind(serde_json::to_string(&capability.limits)?)
            .bind(now.to_rfc3339())
            .execute(&mut *transaction)
            .await?;
        }
        sqlx::query(
            "UPDATE node_pairing_offers SET consumed_at = ? WHERE offer_id = ? AND consumed_at IS NULL",
        )
        .bind(now.to_rfc3339())
        .bind(offer_id)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_audit_events (node_id, event_type, detail_json, created_at)
             VALUES (?, 'node_enrolled', ?, ?)",
        )
        .bind(&node_id)
        .bind(json!({"kind": node_kind, "policy": policy_profile}).to_string())
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;

        Ok(EnrollmentResult {
            node: NodeRecord {
                node_id,
                owner_id,
                kind: node_kind.to_string(),
                display_name,
                policy_profile,
                policy_revision: 1,
                authorization_revision: 1,
                conversation_session_id,
                node_channel_id,
                created_at: now,
                revoked_at: None,
                last_seen_at: None,
            },
            credential_id,
            public_key_fingerprint: fingerprint,
        })
    }

    pub async fn create_challenge(
        &self,
        credential_id: &str,
        protocol_major: u16,
        ttl_seconds: u64,
    ) -> anyhow::Result<ChallengeRecord> {
        let row = sqlx::query(
            "SELECT c.public_key_sec1
             FROM node_credentials c JOIN nodes n ON n.node_id = c.node_id
             WHERE c.credential_id = ? AND c.state = 'active' AND c.revoked_at IS NULL
               AND n.revoked_at IS NULL",
        )
        .bind(credential_id)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("credential is unavailable"))?;
        let now = Utc::now();
        let expires_at = now + Duration::seconds(ttl_seconds.clamp(15, 300) as i64);
        let record = ChallengeRecord {
            challenge_id: format!("chal_{}", uuid::Uuid::new_v4().simple()),
            credential_id: credential_id.to_string(),
            nonce: auth::random_secret(24),
            public_key_sec1: row.get("public_key_sec1"),
            expires_at,
        };
        sqlx::query(
            "INSERT INTO node_auth_challenges
             (challenge_id, credential_id, nonce, protocol_major, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
        )
        .bind(&record.challenge_id)
        .bind(&record.credential_id)
        .bind(&record.nonce)
        .bind(i64::from(protocol_major))
        .bind(record.expires_at.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&self.pool)
        .await?;
        Ok(record)
    }

    pub async fn get_challenge(
        &self,
        challenge_id: &str,
        credential_id: &str,
    ) -> anyhow::Result<ChallengeRecord> {
        let row = sqlx::query(
            "SELECT a.challenge_id, a.credential_id, a.nonce, a.expires_at, a.used_at,
                    c.public_key_sec1
             FROM node_auth_challenges a
             JOIN node_credentials c ON c.credential_id = a.credential_id
             JOIN nodes n ON n.node_id = c.node_id
             WHERE a.challenge_id = ? AND a.credential_id = ?
               AND c.state = 'active' AND c.revoked_at IS NULL AND n.revoked_at IS NULL",
        )
        .bind(challenge_id)
        .bind(credential_id)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("challenge is unavailable"))?;
        let used_at: Option<String> = row.get("used_at");
        anyhow::ensure!(used_at.is_none(), "challenge was already used");
        let expires_at = parse_timestamp(row.get::<String, _>("expires_at").as_str())?;
        anyhow::ensure!(expires_at > Utc::now(), "challenge expired");
        Ok(ChallengeRecord {
            challenge_id: row.get("challenge_id"),
            credential_id: row.get("credential_id"),
            nonce: row.get("nonce"),
            public_key_sec1: row.get("public_key_sec1"),
            expires_at,
        })
    }

    pub async fn consume_challenge_and_create_session(
        &self,
        challenge: &ChallengeRecord,
        protocol_major: u16,
        boot_id: &str,
        session_ttl_seconds: u64,
    ) -> anyhow::Result<CreatedSession> {
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let now = Utc::now();
        let updated = sqlx::query(
            "UPDATE node_auth_challenges SET used_at = ?
             WHERE challenge_id = ? AND credential_id = ? AND used_at IS NULL AND expires_at > ?",
        )
        .bind(now.to_rfc3339())
        .bind(&challenge.challenge_id)
        .bind(&challenge.credential_id)
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        anyhow::ensure!(
            updated.rows_affected() == 1,
            "challenge was already consumed or expired"
        );
        let row = sqlx::query(
            "SELECT n.node_id, n.kind, n.policy_profile, n.policy_revision,
                    n.authorization_revision, c.revision AS credential_revision,
                    ch.node_channel_id, ch.conversation_session_id
             FROM node_credentials c
             JOIN nodes n ON n.node_id = c.node_id
             JOIN node_channels ch ON ch.node_id = n.node_id
             WHERE c.credential_id = ? AND c.state = 'active' AND c.revoked_at IS NULL
               AND n.revoked_at IS NULL",
        )
        .bind(&challenge.credential_id)
        .fetch_optional(&mut *transaction)
        .await?
        .ok_or_else(|| anyhow::anyhow!("credential was revoked"))?;
        let access_token = auth::random_secret(32);
        let token_digest =
            auth::keyed_digest(&self.instance_key, "node-session", access_token.as_bytes());
        let node_session_id = format!("ns_{}", uuid::Uuid::new_v4().simple());
        let expires_at = now + Duration::seconds(session_ttl_seconds.clamp(60, 3600) as i64);
        let context = AuthenticatedNodeContext {
            node_id: row.get("node_id"),
            node_session_id: node_session_id.clone(),
            credential_id: challenge.credential_id.clone(),
            kind: row.get("kind"),
            policy_profile: row.get("policy_profile"),
            policy_revision: row.get::<i64, _>("policy_revision") as u64,
            authorization_revision: row.get::<i64, _>("authorization_revision") as u64,
            conversation_session_id: row.get("conversation_session_id"),
            node_channel_id: row.get("node_channel_id"),
        };
        sqlx::query(
            "INSERT INTO node_sessions
             (node_session_id, node_id, credential_id, token_digest, credential_revision,
              policy_revision, authorization_revision, protocol_major, boot_id, created_at,
              expires_at, last_seen_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&node_session_id)
        .bind(&context.node_id)
        .bind(&context.credential_id)
        .bind(token_digest)
        .bind(row.get::<i64, _>("credential_revision"))
        .bind(context.policy_revision as i64)
        .bind(context.authorization_revision as i64)
        .bind(i64::from(protocol_major))
        .bind(boot_id)
        .bind(now.to_rfc3339())
        .bind(expires_at.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;
        Ok(CreatedSession {
            context,
            access_token,
            expires_at,
        })
    }

    pub async fn authenticate(
        &self,
        access_token: &str,
    ) -> anyhow::Result<AuthenticatedNodeContext> {
        anyhow::ensure!(
            (32..=128).contains(&access_token.len()),
            "session token is invalid"
        );
        let token_digest =
            auth::keyed_digest(&self.instance_key, "node-session", access_token.as_bytes());
        let now = Utc::now().to_rfc3339();
        let row = sqlx::query(
            "SELECT s.node_session_id, s.credential_id, n.node_id, n.kind, n.policy_profile,
                    n.policy_revision, n.authorization_revision,
                    ch.node_channel_id, ch.conversation_session_id
             FROM node_sessions s
             JOIN nodes n ON n.node_id = s.node_id
             JOIN node_credentials c ON c.credential_id = s.credential_id
             JOIN node_channels ch ON ch.node_id = n.node_id
             WHERE s.token_digest = ? AND s.closed_at IS NULL AND s.expires_at > ?
               AND n.revoked_at IS NULL AND c.revoked_at IS NULL AND c.state = 'active'
               AND s.credential_revision = c.revision
               AND s.policy_revision = n.policy_revision
               AND s.authorization_revision = n.authorization_revision",
        )
        .bind(token_digest)
        .bind(&now)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("Node Session is invalid, expired, stale, or revoked"))?;
        sqlx::query("UPDATE node_sessions SET last_seen_at = ? WHERE node_session_id = ?")
            .bind(now)
            .bind(row.get::<String, _>("node_session_id"))
            .execute(&self.pool)
            .await?;
        Ok(AuthenticatedNodeContext {
            node_id: row.get("node_id"),
            node_session_id: row.get("node_session_id"),
            credential_id: row.get("credential_id"),
            kind: row.get("kind"),
            policy_profile: row.get("policy_profile"),
            policy_revision: row.get::<i64, _>("policy_revision") as u64,
            authorization_revision: row.get::<i64, _>("authorization_revision") as u64,
            conversation_session_id: row.get("conversation_session_id"),
            node_channel_id: row.get("node_channel_id"),
        })
    }

    pub async fn create_credential_rotation_challenge(
        &self,
        context: &AuthenticatedNodeContext,
        ttl_seconds: u64,
    ) -> anyhow::Result<CredentialRotationRecord> {
        let now = Utc::now();
        let record = CredentialRotationRecord {
            rotation_id: format!("rot_{}", uuid::Uuid::new_v4().simple()),
            node_id: context.node_id.clone(),
            credential_id: context.credential_id.clone(),
            node_session_id: context.node_session_id.clone(),
            nonce: auth::random_secret(24),
            expires_at: now + Duration::seconds(ttl_seconds.clamp(15, 300) as i64),
        };
        sqlx::query(
            "INSERT INTO node_credential_rotation_challenges
             (rotation_id, node_id, credential_id, node_session_id, nonce, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&record.rotation_id)
        .bind(&record.node_id)
        .bind(&record.credential_id)
        .bind(&record.node_session_id)
        .bind(&record.nonce)
        .bind(record.expires_at.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&self.pool)
        .await?;
        Ok(record)
    }

    pub async fn credential_rotation_challenge(
        &self,
        context: &AuthenticatedNodeContext,
        rotation_id: &str,
    ) -> anyhow::Result<CredentialRotationRecord> {
        let row = sqlx::query(
            "SELECT rotation_id, node_id, credential_id, node_session_id, nonce, expires_at, used_at
             FROM node_credential_rotation_challenges
             WHERE rotation_id = ? AND node_id = ? AND credential_id = ? AND node_session_id = ?",
        )
        .bind(rotation_id)
        .bind(&context.node_id)
        .bind(&context.credential_id)
        .bind(&context.node_session_id)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("credential rotation challenge is unavailable"))?;
        anyhow::ensure!(
            row.get::<Option<String>, _>("used_at").is_none(),
            "credential rotation challenge was already used"
        );
        let expires_at = parse_timestamp(row.get::<String, _>("expires_at").as_str())?;
        anyhow::ensure!(
            expires_at > Utc::now(),
            "credential rotation challenge expired"
        );
        Ok(CredentialRotationRecord {
            rotation_id: row.get("rotation_id"),
            node_id: row.get("node_id"),
            credential_id: row.get("credential_id"),
            node_session_id: row.get("node_session_id"),
            nonce: row.get("nonce"),
            expires_at,
        })
    }

    pub async fn consume_credential_rotation(
        &self,
        record: &CredentialRotationRecord,
        new_public_key_sec1: &[u8],
    ) -> anyhow::Result<EnrollmentResult> {
        let now = Utc::now();
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let consumed = sqlx::query(
            "UPDATE node_credential_rotation_challenges SET used_at = ?
             WHERE rotation_id = ? AND used_at IS NULL AND expires_at > ?",
        )
        .bind(now.to_rfc3339())
        .bind(&record.rotation_id)
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        anyhow::ensure!(
            consumed.rows_affected() == 1,
            "credential rotation replayed or expired"
        );

        let node = sqlx::query(
            "SELECT n.node_id, n.owner_id, n.kind, n.display_name, n.policy_profile,
                    n.policy_revision, n.authorization_revision, n.created_at, n.revoked_at,
                    n.last_seen_at, ch.conversation_session_id, ch.node_channel_id
             FROM nodes n JOIN node_channels ch ON ch.node_id = n.node_id
             WHERE n.node_id = ? AND n.revoked_at IS NULL",
        )
        .bind(&record.node_id)
        .fetch_optional(&mut *transaction)
        .await?
        .ok_or_else(|| anyhow::anyhow!("Node is unavailable"))?;
        let credential_id = format!("cred_{}", uuid::Uuid::new_v4().simple());
        let fingerprint = auth::public_key_fingerprint(new_public_key_sec1);
        sqlx::query(
            "INSERT INTO node_credentials
             (credential_id, node_id, public_key_sec1, public_key_fingerprint, created_at)
             VALUES (?, ?, ?, ?, ?)",
        )
        .bind(&credential_id)
        .bind(&record.node_id)
        .bind(new_public_key_sec1)
        .bind(&fingerprint)
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "UPDATE node_credentials SET state = 'retired', revoked_at = ?
             WHERE credential_id = ? AND node_id = ? AND state = 'active'",
        )
        .bind(now.to_rfc3339())
        .bind(&record.credential_id)
        .bind(&record.node_id)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "UPDATE node_sessions SET closed_at = ?, close_reason = 'credential_rotated'
             WHERE node_id = ? AND closed_at IS NULL",
        )
        .bind(now.to_rfc3339())
        .bind(&record.node_id)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_audit_events (node_id, event_type, detail_json, created_at)
             VALUES (?, 'credential_rotated', ?, ?)",
        )
        .bind(&record.node_id)
        .bind(json!({"new_public_key_fingerprint": fingerprint}).to_string())
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;

        Ok(EnrollmentResult {
            node: node_from_row(node)?,
            credential_id,
            public_key_fingerprint: fingerprint,
        })
    }

    pub async fn is_authorized(&self, node_id: &str, action: NodeAction) -> anyhow::Result<bool> {
        let exists: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM node_authorizations
             WHERE node_id = ? AND action = ? AND revoked_at IS NULL",
        )
        .bind(node_id)
        .bind(action_name(action))
        .fetch_one(&self.pool)
        .await?;
        Ok(exists == 1)
    }

    pub async fn set_authorization(
        &self,
        node_id: &str,
        action: NodeAction,
        enabled: bool,
        constraints: serde_json::Value,
    ) -> anyhow::Result<()> {
        let now = Utc::now().to_rfc3339();
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let next_revision: i64 = sqlx::query_scalar(
            "UPDATE nodes SET authorization_revision = authorization_revision + 1
             WHERE node_id = ? AND revoked_at IS NULL RETURNING authorization_revision",
        )
        .bind(node_id)
        .fetch_one(&mut *transaction)
        .await?;
        if enabled {
            sqlx::query(
                "INSERT INTO node_authorizations
                 (node_id, action, constraints_json, revision, granted_at, revoked_at)
                 VALUES (?, ?, ?, ?, ?, NULL)
                 ON CONFLICT(node_id, action) DO UPDATE SET
                   constraints_json = excluded.constraints_json,
                   revision = excluded.revision,
                   granted_at = excluded.granted_at,
                   revoked_at = NULL",
            )
            .bind(node_id)
            .bind(action_name(action))
            .bind(serde_json::to_string(&constraints)?)
            .bind(next_revision)
            .bind(&now)
            .execute(&mut *transaction)
            .await?;
        } else {
            sqlx::query(
                "UPDATE node_authorizations SET revoked_at = ?, revision = ?
                 WHERE node_id = ? AND action = ?",
            )
            .bind(&now)
            .bind(next_revision)
            .bind(node_id)
            .bind(action_name(action))
            .execute(&mut *transaction)
            .await?;
        }
        sqlx::query(
            "UPDATE node_sessions SET closed_at = ?, close_reason = 'authorization_changed'
             WHERE node_id = ? AND closed_at IS NULL",
        )
        .bind(&now)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;
        Ok(())
    }

    pub async fn record_heartbeat(
        &self,
        context: &AuthenticatedNodeContext,
        heartbeat: &super::protocol::HeartbeatRequest,
    ) -> anyhow::Result<()> {
        let now = Utc::now().to_rfc3339();
        let health = json!({
            "boot_id": heartbeat.boot_id,
            "uptime_ms": heartbeat.uptime_ms,
            "battery_percent": heartbeat.battery_percent,
            "free_internal_heap": heartbeat.free_internal_heap,
            "largest_internal_allocation": heartbeat.largest_internal_allocation,
            "psram_free": heartbeat.psram_free,
            "recovery": heartbeat.recovery.as_ref(),
        });
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        sqlx::query(
            "UPDATE nodes SET last_seen_at = ?, last_runtime_version = ?,
                    last_firmware_version = ?, last_health_json = ?
             WHERE node_id = ? AND revoked_at IS NULL",
        )
        .bind(&now)
        .bind(&heartbeat.runtime_version)
        .bind(&heartbeat.firmware_version)
        .bind(health.to_string())
        .bind(&context.node_id)
        .execute(&mut *transaction)
        .await?;
        for capability in heartbeat.capabilities.iter().take(32) {
            sqlx::query(
                "INSERT INTO node_capabilities
                 (node_id, capability_id, capability_version, limits_json,
                  observed_session_id, observed_at)
                 VALUES (?, ?, ?, ?, ?, ?)
                 ON CONFLICT(node_id, capability_id) DO UPDATE SET
                   capability_version = excluded.capability_version,
                   limits_json = excluded.limits_json,
                   observed_session_id = excluded.observed_session_id,
                   observed_at = excluded.observed_at",
            )
            .bind(&context.node_id)
            .bind(&capability.capability_id)
            .bind(i64::from(capability.version))
            .bind(serde_json::to_string(&capability.limits)?)
            .bind(&context.node_session_id)
            .bind(&now)
            .execute(&mut *transaction)
            .await?;
        }
        transaction.commit().await?;
        Ok(())
    }

    pub async fn record_sensor_readings(
        &self,
        context: &AuthenticatedNodeContext,
        request: &super::protocol::ReportSensorReadingsRequest,
        monitoring: Option<&crate::config::NodeMonitoringConfig>,
    ) -> anyhow::Result<DateTime<Utc>> {
        let received_at = Utc::now();
        let received_at_text = received_at.to_rfc3339();
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        for reading in &request.readings {
            if monitoring.is_some_and(|config| config.enabled) {
                let duplicate: Option<i64> = sqlx::query_scalar(
                    "SELECT reading_id FROM node_sensor_readings_history
                     WHERE node_id = ? AND capability_id = ? AND request_id = ?",
                )
                .bind(&context.node_id)
                .bind(&reading.capability_id)
                .bind(&request.request_id)
                .fetch_optional(&mut *transaction)
                .await?;
                if duplicate.is_some() {
                    continue;
                }
            }
            let observed_version: Option<i64> = sqlx::query_scalar(
                "SELECT capability_version FROM node_capabilities
                 WHERE node_id = ? AND capability_id = ?",
            )
            .bind(&context.node_id)
            .bind(&reading.capability_id)
            .fetch_optional(&mut *transaction)
            .await?;
            anyhow::ensure!(
                observed_version == Some(i64::from(reading.capability_version)),
                "sensor capability is not currently observed at the reported version"
            );
            sqlx::query(
                "INSERT INTO node_sensor_readings_latest
                 (node_id, capability_id, capability_version, value, unit,
                  sample_uptime_ms, request_id, observed_session_id, received_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                 ON CONFLICT(node_id, capability_id) DO UPDATE SET
                   capability_version = excluded.capability_version,
                   value = excluded.value,
                   unit = excluded.unit,
                   sample_uptime_ms = excluded.sample_uptime_ms,
                   request_id = excluded.request_id,
                   observed_session_id = excluded.observed_session_id,
                   received_at = excluded.received_at",
            )
            .bind(&context.node_id)
            .bind(&reading.capability_id)
            .bind(i64::from(reading.capability_version))
            .bind(reading.value)
            .bind(&reading.unit)
            .bind(request.sample_uptime_ms as i64)
            .bind(&request.request_id)
            .bind(&context.node_session_id)
            .bind(&received_at_text)
            .execute(&mut *transaction)
            .await?;
            if let Some(config) = monitoring.filter(|config| config.enabled) {
                sqlx::query(
                    "INSERT OR IGNORE INTO node_sensor_readings_history
                     (node_id, capability_id, capability_version, value, unit,
                      sample_uptime_ms, request_id, observed_session_id, received_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                )
                .bind(&context.node_id)
                .bind(&reading.capability_id)
                .bind(i64::from(reading.capability_version))
                .bind(reading.value)
                .bind(&reading.unit)
                .bind(request.sample_uptime_ms as i64)
                .bind(&request.request_id)
                .bind(&context.node_session_id)
                .bind(&received_at_text)
                .execute(&mut *transaction)
                .await?;
                sqlx::query(
                    "DELETE FROM node_sensor_readings_history
                     WHERE node_id = ? AND capability_id = ? AND reading_id NOT IN (
                       SELECT reading_id FROM node_sensor_readings_history
                       WHERE node_id = ? AND capability_id = ?
                       ORDER BY received_at DESC, reading_id DESC LIMIT ?
                     )",
                )
                .bind(&context.node_id)
                .bind(&reading.capability_id)
                .bind(&context.node_id)
                .bind(&reading.capability_id)
                .bind(config.max_history_rows_per_capability as i64)
                .execute(&mut *transaction)
                .await?;
            }
        }
        transaction.commit().await?;
        Ok(received_at)
    }

    pub async fn create_text_turn(
        &self,
        context: &AuthenticatedNodeContext,
        idempotency_key: &str,
        request_id: &str,
        text: &str,
    ) -> anyhow::Result<CreateTurnOutcome> {
        let request_digest = auth::keyed_digest(
            &self.instance_key,
            "turn-request",
            format!("text\0{request_id}\0{text}").as_bytes(),
        );
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        if let Some(row) = sqlx::query(
            "SELECT request_digest, result_id FROM node_request_dedup
             WHERE node_id = ? AND operation = 'create_turn' AND idempotency_key = ?",
        )
        .bind(&context.node_id)
        .bind(idempotency_key)
        .fetch_optional(&mut *transaction)
        .await?
        {
            let stored: Vec<u8> = row.get("request_digest");
            anyhow::ensure!(
                stored == request_digest,
                "idempotency key conflicts with another request"
            );
            let turn_id: String = row.get("result_id");
            let state: String =
                sqlx::query_scalar("SELECT state FROM node_turns WHERE turn_id = ?")
                    .bind(&turn_id)
                    .fetch_one(&mut *transaction)
                    .await?;
            let cursor: i64 = sqlx::query_scalar(
                "SELECT COALESCE(MAX(cursor), 0) FROM node_outbox WHERE turn_id = ?",
            )
            .bind(&turn_id)
            .fetch_one(&mut *transaction)
            .await?;
            transaction.commit().await?;
            return Ok(CreateTurnOutcome {
                turn_id,
                state: parse_turn_state(&state),
                cursor: cursor as u64,
                duplicate: true,
            });
        }

        let now = Utc::now();
        let turn_id = format!("turn_{}", uuid::Uuid::new_v4().simple());
        let deadline = now + Duration::seconds(120);
        sqlx::query(
            "INSERT INTO node_turns
             (turn_id, node_id, node_channel_id, request_id, input_kind, input_text,
              state, deadline_at, created_at, updated_at)
             VALUES (?, ?, ?, ?, 'text', ?, 'accepted', ?, ?, ?)",
        )
        .bind(&turn_id)
        .bind(&context.node_id)
        .bind(&context.node_channel_id)
        .bind(request_id)
        .bind(text)
        .bind(deadline.to_rfc3339())
        .bind(now.to_rfc3339())
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        let cursor = append_event_tx(
            &mut transaction,
            &context.node_id,
            Some(&turn_id),
            "turn.accepted",
            json!({"state": "accepted"}),
        )
        .await?;
        sqlx::query(
            "INSERT INTO node_request_dedup
             (node_id, operation, idempotency_key, request_digest, result_id, created_at, expires_at)
             VALUES (?, 'create_turn', ?, ?, ?, ?, ?)",
        )
        .bind(&context.node_id)
        .bind(idempotency_key)
        .bind(request_digest)
        .bind(&turn_id)
        .bind(now.to_rfc3339())
        .bind((now + Duration::hours(24)).to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;
        Ok(CreateTurnOutcome {
            turn_id,
            state: NodeTurnState::Accepted,
            cursor,
            duplicate: false,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn create_media_turn(
        &self,
        context: &AuthenticatedNodeContext,
        idempotency_key: &str,
        request_id: &str,
        media_kind: &str,
        content_type: &str,
        size_bytes: u64,
        sha256: &str,
        duration_ms: Option<u64>,
    ) -> anyhow::Result<(CreateTurnOutcome, String)> {
        anyhow::ensure!(
            matches!(media_kind, "audio" | "still_image"),
            "unsupported media kind"
        );
        let request_digest = auth::keyed_digest(
            &self.instance_key,
            "turn-request",
            format!(
                "{media_kind}\0{request_id}\0{content_type}\0{size_bytes}\0{sha256}\0{:?}",
                duration_ms
            )
            .as_bytes(),
        );
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        if let Some(row) = sqlx::query(
            "SELECT request_digest, result_id FROM node_request_dedup
             WHERE node_id = ? AND operation = 'create_turn' AND idempotency_key = ?",
        )
        .bind(&context.node_id)
        .bind(idempotency_key)
        .fetch_optional(&mut *transaction)
        .await?
        {
            anyhow::ensure!(
                row.get::<Vec<u8>, _>("request_digest") == request_digest,
                "idempotency key conflicts with another request"
            );
            let turn_id: String = row.get("result_id");
            let upload = sqlx::query("SELECT slot_id FROM node_uploads WHERE turn_id = ?")
                .bind(&turn_id)
                .fetch_one(&mut *transaction)
                .await?;
            let state: String =
                sqlx::query_scalar("SELECT state FROM node_turns WHERE turn_id = ?")
                    .bind(&turn_id)
                    .fetch_one(&mut *transaction)
                    .await?;
            let cursor: i64 = sqlx::query_scalar(
                "SELECT COALESCE(MAX(cursor), 0) FROM node_outbox WHERE turn_id = ?",
            )
            .bind(&turn_id)
            .fetch_one(&mut *transaction)
            .await?;
            transaction.commit().await?;
            return Ok((
                CreateTurnOutcome {
                    turn_id,
                    state: parse_turn_state(&state),
                    cursor: cursor as u64,
                    duplicate: true,
                },
                upload.get("slot_id"),
            ));
        }
        let now = Utc::now();
        let turn_id = format!("turn_{}", uuid::Uuid::new_v4().simple());
        let slot_id = format!("slot_{}", uuid::Uuid::new_v4().simple());
        sqlx::query(
            "INSERT INTO node_turns
             (turn_id, node_id, node_channel_id, request_id, input_kind, state, deadline_at, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, 'accepted', ?, ?, ?)",
        ).bind(&turn_id).bind(&context.node_id).bind(&context.node_channel_id).bind(request_id)
            .bind(media_kind).bind((now + Duration::seconds(120)).to_rfc3339())
            .bind(now.to_rfc3339()).bind(now.to_rfc3339()).execute(&mut *transaction).await?;
        sqlx::query(
            "INSERT INTO node_uploads
             (slot_id, turn_id, node_id, media_kind, content_type, expected_bytes, expected_sha256, duration_ms, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        ).bind(&slot_id).bind(&turn_id).bind(&context.node_id).bind(media_kind).bind(content_type)
            .bind(size_bytes as i64).bind(sha256).bind(duration_ms.map(|value| value as i64))
            .bind(now.to_rfc3339()).execute(&mut *transaction).await?;
        let cursor = append_event_tx(
            &mut transaction,
            &context.node_id,
            Some(&turn_id),
            "turn.accepted",
            json!({"state":"accepted", "upload_required":true}),
        )
        .await?;
        sqlx::query(
            "INSERT INTO node_request_dedup
             (node_id, operation, idempotency_key, request_digest, result_id, created_at, expires_at)
             VALUES (?, 'create_turn', ?, ?, ?, ?, ?)",
        ).bind(&context.node_id).bind(idempotency_key).bind(request_digest).bind(&turn_id)
            .bind(now.to_rfc3339()).bind((now + Duration::hours(24)).to_rfc3339()).execute(&mut *transaction).await?;
        transaction.commit().await?;
        Ok((
            CreateTurnOutcome {
                turn_id,
                state: NodeTurnState::Accepted,
                cursor,
                duplicate: false,
            },
            slot_id,
        ))
    }

    pub async fn upload_slot(
        &self,
        node_id: &str,
        slot_id: &str,
    ) -> anyhow::Result<MediaUploadRecord> {
        let row = sqlx::query(
            "SELECT slot_id, turn_id, node_id, media_kind, content_type, expected_bytes,
                    expected_sha256, duration_ms, local_path, state
             FROM node_uploads WHERE slot_id = ? AND node_id = ?",
        )
        .bind(slot_id)
        .bind(node_id)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("upload slot not found"))?;
        Ok(MediaUploadRecord {
            slot_id: row.get("slot_id"),
            turn_id: row.get("turn_id"),
            node_id: row.get("node_id"),
            media_kind: row.get("media_kind"),
            content_type: row.get("content_type"),
            expected_bytes: row.get::<i64, _>("expected_bytes") as u64,
            expected_sha256: row.get("expected_sha256"),
            duration_ms: row
                .get::<Option<i64>, _>("duration_ms")
                .map(|value| value as u64),
            local_path: row.get("local_path"),
            state: row.get("state"),
        })
    }

    pub async fn mark_slot_uploaded(
        &self,
        node_id: &str,
        slot_id: &str,
        local_path: &str,
    ) -> anyhow::Result<()> {
        let changed = sqlx::query(
            "UPDATE node_uploads SET state = 'uploaded', local_path = ?, received_at = ?
             WHERE slot_id = ? AND node_id = ? AND state = 'pending'",
        )
        .bind(local_path)
        .bind(Utc::now().to_rfc3339())
        .bind(slot_id)
        .bind(node_id)
        .execute(&self.pool)
        .await?;
        anyhow::ensure!(
            changed.rows_affected() == 1,
            "upload slot is unavailable or already used"
        );
        Ok(())
    }

    pub async fn mark_slot_consumed(
        &self,
        node_id: &str,
        slot_id: &str,
        deleted: bool,
    ) -> anyhow::Result<()> {
        sqlx::query("UPDATE node_uploads SET state = ? WHERE slot_id = ? AND node_id = ?")
            .bind(if deleted { "deleted" } else { "consumed" })
            .bind(slot_id)
            .bind(node_id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    pub async fn turn_input_text(&self, node_id: &str, turn_id: &str) -> anyhow::Result<String> {
        sqlx::query_scalar(
            "SELECT input_text FROM node_turns WHERE turn_id = ? AND node_id = ? AND input_kind = 'text'",
        )
        .bind(turn_id)
        .bind(node_id)
        .fetch_optional(&self.pool)
        .await?
        .flatten()
        .ok_or_else(|| anyhow::anyhow!("text turn not found"))
    }

    pub async fn update_turn(
        &self,
        node_id: &str,
        turn_id: &str,
        state: NodeTurnState,
        payload: serde_json::Value,
    ) -> anyhow::Result<u64> {
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let now = Utc::now().to_rfc3339();
        let result_text = payload.get("text").and_then(|value| value.as_str());
        let error_code = payload.get("code").and_then(|value| value.as_str());
        let updated = sqlx::query(
            "UPDATE node_turns SET state = ?, updated_at = ?, result_text = COALESCE(?, result_text),
                    error_code = COALESCE(?, error_code)
             WHERE turn_id = ? AND node_id = ? AND state NOT IN ('cancelled')",
        )
        .bind(state.as_str())
        .bind(&now)
        .bind(result_text)
        .bind(error_code)
        .bind(turn_id)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        anyhow::ensure!(
            updated.rows_affected() == 1,
            "turn is unavailable or cancelled"
        );
        let cursor = append_event_tx(
            &mut transaction,
            node_id,
            Some(turn_id),
            &format!("turn.{}", state.as_str()),
            payload,
        )
        .await?;
        transaction.commit().await?;
        Ok(cursor)
    }

    pub async fn begin_turn_processing(&self, node_id: &str, turn_id: &str) -> anyhow::Result<u64> {
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let changed = sqlx::query(
            "UPDATE node_turns SET state = 'thinking', updated_at = ?
             WHERE turn_id = ? AND node_id = ? AND state = 'accepted'",
        )
        .bind(Utc::now().to_rfc3339())
        .bind(turn_id)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        anyhow::ensure!(
            changed.rows_affected() == 1,
            "turn is already processing or unavailable"
        );
        let cursor = append_event_tx(
            &mut transaction,
            node_id,
            Some(turn_id),
            "turn.thinking",
            json!({"state":"thinking"}),
        )
        .await?;
        transaction.commit().await?;
        Ok(cursor)
    }

    pub async fn cancel_turn(&self, node_id: &str, turn_id: &str) -> anyhow::Result<NodeTurnState> {
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let current: String =
            sqlx::query_scalar("SELECT state FROM node_turns WHERE turn_id = ? AND node_id = ?")
                .bind(turn_id)
                .bind(node_id)
                .fetch_optional(&mut *transaction)
                .await?
                .ok_or_else(|| anyhow::anyhow!("turn not found"))?;
        if matches!(current.as_str(), "complete" | "error" | "cancelled") {
            transaction.commit().await?;
            return Ok(parse_turn_state(&current));
        }
        let now = Utc::now().to_rfc3339();
        sqlx::query("UPDATE node_turns SET state = 'cancelled', updated_at = ? WHERE turn_id = ?")
            .bind(&now)
            .bind(turn_id)
            .execute(&mut *transaction)
            .await?;
        append_event_tx(
            &mut transaction,
            node_id,
            Some(turn_id),
            "turn.cancelled",
            json!({"state": "cancelled"}),
        )
        .await?;
        transaction.commit().await?;
        Ok(NodeTurnState::Cancelled)
    }

    pub async fn turn_is_cancelled(&self, node_id: &str, turn_id: &str) -> anyhow::Result<bool> {
        let state: Option<String> =
            sqlx::query_scalar("SELECT state FROM node_turns WHERE turn_id = ? AND node_id = ?")
                .bind(turn_id)
                .bind(node_id)
                .fetch_optional(&self.pool)
                .await?;
        Ok(state.as_deref() == Some("cancelled"))
    }

    pub async fn events_after(
        &self,
        node_id: &str,
        turn_id: &str,
        after: u64,
        limit: usize,
    ) -> anyhow::Result<Vec<TurnEvent>> {
        let owns: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM node_turns WHERE turn_id = ? AND node_id = ?")
                .bind(turn_id)
                .bind(node_id)
                .fetch_one(&self.pool)
                .await?;
        anyhow::ensure!(owns == 1, "turn not found");
        let rows = sqlx::query(
            "SELECT cursor, turn_id, event_type, payload_json, created_at
             FROM node_outbox WHERE node_id = ? AND turn_id = ? AND cursor > ?
             ORDER BY cursor ASC LIMIT ?",
        )
        .bind(node_id)
        .bind(turn_id)
        .bind(after as i64)
        .bind(limit.clamp(1, 100) as i64)
        .fetch_all(&self.pool)
        .await?;
        rows.into_iter()
            .map(|row| {
                Ok(TurnEvent {
                    cursor: row.get::<i64, _>("cursor") as u64,
                    turn_id: row.get("turn_id"),
                    event_type: row.get("event_type"),
                    created_at: row.get("created_at"),
                    payload: serde_json::from_str(&row.get::<String, _>("payload_json"))?,
                })
            })
            .collect()
    }

    pub async fn append_outbound_for_conversation(
        &self,
        conversation_session_id: &str,
        text: &str,
    ) -> anyhow::Result<u64> {
        let row = sqlx::query(
            "SELECT ch.node_id FROM node_channels ch JOIN nodes n ON n.node_id = ch.node_id
             WHERE ch.conversation_session_id = ? AND n.revoked_at IS NULL",
        )
        .bind(conversation_session_id)
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("Node Channel is unavailable"))?;
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let cursor = append_event_tx(
            &mut transaction,
            row.get::<String, _>("node_id").as_str(),
            None,
            "channel.text",
            json!({"text": text}),
        )
        .await?;
        transaction.commit().await?;
        Ok(cursor)
    }

    pub async fn resolve_audio_announcement_target(
        &self,
        selector: Option<&str>,
    ) -> anyhow::Result<AudioAnnouncementTarget> {
        let rows = if let Some(selector) = selector.map(str::trim).filter(|value| !value.is_empty())
        {
            sqlx::query(
                "SELECT n.node_id, n.display_name, n.last_seen_at, c.limits_json
                 FROM nodes n
                 JOIN node_capabilities c ON c.node_id = n.node_id
                 JOIN node_authorizations a ON a.node_id = n.node_id
                 WHERE n.revoked_at IS NULL
                   AND (n.node_id = ? OR n.display_name = ? COLLATE NOCASE)
                   AND c.capability_id = 'output.audio'
                   AND c.capability_version >= 1
                   AND c.observed_at = n.last_seen_at
                   AND a.action = 'receive_audio'
                   AND a.revoked_at IS NULL
                 ORDER BY n.created_at ASC",
            )
            .bind(selector)
            .bind(selector)
            .fetch_all(&self.pool)
            .await?
        } else {
            sqlx::query(
                "SELECT n.node_id, n.display_name, n.last_seen_at, c.limits_json
                 FROM nodes n
                 JOIN node_capabilities c ON c.node_id = n.node_id
                 JOIN node_authorizations a ON a.node_id = n.node_id
                 WHERE n.revoked_at IS NULL
                   AND c.capability_id = 'output.audio'
                   AND c.capability_version >= 1
                   AND c.observed_at = n.last_seen_at
                   AND a.action = 'receive_audio'
                   AND a.revoked_at IS NULL
                 ORDER BY n.created_at ASC",
            )
            .fetch_all(&self.pool)
            .await?
        };
        anyhow::ensure!(
            !rows.is_empty(),
            "No active Node matches the target with current output.audio capability and receive_audio authorization"
        );
        anyhow::ensure!(
            rows.len() == 1,
            "More than one eligible Node matches; specify the exact Node display name"
        );
        let row = &rows[0];
        let last_seen_at: Option<String> = row.get("last_seen_at");
        let limits: String = row.get("limits_json");
        let maximum_audio_bytes = serde_json::from_str::<serde_json::Value>(&limits)
            .ok()
            .and_then(|value| value.get("max_bytes").and_then(serde_json::Value::as_u64));
        Ok(AudioAnnouncementTarget {
            node_id: row.get("node_id"),
            display_name: row.get("display_name"),
            last_seen_at: last_seen_at.as_deref().map(parse_timestamp).transpose()?,
            maximum_audio_bytes,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn queue_audio_announcement(
        &self,
        target: &AudioAnnouncementTarget,
        content_type: &str,
        size_bytes: u64,
        sha256: &str,
        local_path: &str,
        ttl_seconds: u64,
        max_pending: usize,
    ) -> anyhow::Result<QueuedAudioAnnouncement> {
        let now = Utc::now();
        let expires_at = now + Duration::seconds(ttl_seconds as i64);
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let eligible: i64 = sqlx::query_scalar(
            "SELECT COUNT(*)
             FROM nodes n
             JOIN node_capabilities c ON c.node_id = n.node_id
             JOIN node_authorizations a ON a.node_id = n.node_id
             WHERE n.node_id = ? AND n.revoked_at IS NULL
               AND c.capability_id = 'output.audio'
               AND c.capability_version >= 1
               AND c.observed_at = n.last_seen_at
               AND a.action = 'receive_audio' AND a.revoked_at IS NULL",
        )
        .bind(&target.node_id)
        .fetch_one(&mut *transaction)
        .await?;
        anyhow::ensure!(
            eligible == 1,
            "Node announcement eligibility changed before queueing"
        );
        let pending: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM node_outbox o
             WHERE o.node_id = ? AND o.turn_id IS NULL AND o.event_type = 'channel.audio'
               AND o.expires_at > ?
               AND NOT EXISTS (
                   SELECT 1 FROM node_outbox_receipts r
                   WHERE r.cursor = o.cursor AND r.node_id = o.node_id
               )",
        )
        .bind(&target.node_id)
        .bind(now.to_rfc3339())
        .fetch_one(&mut *transaction)
        .await?;
        anyhow::ensure!(
            pending < max_pending as i64,
            "Node announcement queue is full; wait for delivery or expiry"
        );
        let media_id = format!("media_{}", uuid::Uuid::new_v4().simple());
        let payload = json!({
            "audio": {
                "media_id": media_id,
                "content_type": content_type,
                "size_bytes": size_bytes,
                "sha256": sha256,
                "download_path": format!("/node/v1/media/{media_id}")
            }
        });
        let inserted = sqlx::query(
            "INSERT INTO node_outbox
             (node_id, turn_id, event_type, payload_json, priority, created_at, expires_at)
             VALUES (?, NULL, 'channel.audio', ?, 50, ?, ?)",
        )
        .bind(&target.node_id)
        .bind(payload.to_string())
        .bind(now.to_rfc3339())
        .bind(expires_at.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        let cursor = inserted.last_insert_rowid() as u64;
        sqlx::query(
            "INSERT INTO node_outbound_media
             (media_id, node_id, outbox_cursor, content_type, size_bytes, sha256,
              local_path, created_at, expires_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&media_id)
        .bind(&target.node_id)
        .bind(cursor as i64)
        .bind(content_type)
        .bind(size_bytes as i64)
        .bind(sha256)
        .bind(local_path)
        .bind(now.to_rfc3339())
        .bind(expires_at.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_audit_events (node_id, event_type, detail_json, created_at)
             VALUES (?, 'audio_announcement_queued', ?, ?)",
        )
        .bind(&target.node_id)
        .bind(json!({"cursor": cursor, "size_bytes": size_bytes}).to_string())
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;
        Ok(QueuedAudioAnnouncement {
            cursor,
            node_id: target.node_id.clone(),
            display_name: target.display_name.clone(),
            size_bytes,
            expires_at,
            last_seen_at: target.last_seen_at,
        })
    }

    pub async fn pending_node_outbox(
        &self,
        node_id: &str,
        after: u64,
        limit: usize,
    ) -> anyhow::Result<Vec<super::protocol::NodeOutboxEvent>> {
        let rows = sqlx::query(
            "SELECT o.cursor, o.event_type, o.payload_json, o.created_at, o.expires_at
             FROM node_outbox o
             WHERE o.node_id = ? AND o.turn_id IS NULL AND o.cursor > ?
               AND o.expires_at > ?
               AND NOT EXISTS (
                   SELECT 1 FROM node_outbox_receipts r
                   WHERE r.cursor = o.cursor AND r.node_id = o.node_id
               )
             ORDER BY o.priority DESC, o.cursor ASC LIMIT ?",
        )
        .bind(node_id)
        .bind(after as i64)
        .bind(Utc::now().to_rfc3339())
        .bind(limit.clamp(1, 8) as i64)
        .fetch_all(&self.pool)
        .await?;
        rows.into_iter()
            .map(|row| {
                Ok(super::protocol::NodeOutboxEvent {
                    cursor: row.get::<i64, _>("cursor") as u64,
                    event_type: row.get("event_type"),
                    created_at: row.get("created_at"),
                    expires_at: row.get("expires_at"),
                    payload: serde_json::from_str(&row.get::<String, _>("payload_json"))?,
                })
            })
            .collect()
    }

    pub async fn acknowledge_node_outbox(
        &self,
        node_id: &str,
        cursor: u64,
        status: super::protocol::NodeOutboxAckStatus,
        detail_code: Option<&str>,
    ) -> anyhow::Result<Option<OutboundMediaCleanup>> {
        let now = Utc::now();
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let event_exists: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM node_outbox
             WHERE cursor = ? AND node_id = ? AND turn_id IS NULL AND event_type = 'channel.audio'",
        )
        .bind(cursor as i64)
        .bind(node_id)
        .fetch_one(&mut *transaction)
        .await?;
        anyhow::ensure!(event_exists == 1, "Node outbox event was not found");
        sqlx::query(
            "INSERT INTO node_outbox_receipts
             (cursor, node_id, status, detail_code, acknowledged_at)
             VALUES (?, ?, ?, ?, ?)
             ON CONFLICT(cursor, node_id) DO NOTHING",
        )
        .bind(cursor as i64)
        .bind(node_id)
        .bind(status.as_str())
        .bind(detail_code)
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_audit_events (node_id, event_type, detail_json, created_at)
             VALUES (?, 'audio_announcement_acknowledged', ?, ?)",
        )
        .bind(node_id)
        .bind(
            json!({"cursor": cursor, "status": status.as_str(), "detail_code": detail_code})
                .to_string(),
        )
        .bind(now.to_rfc3339())
        .execute(&mut *transaction)
        .await?;
        let media = sqlx::query(
            "SELECT media_id, local_path FROM node_outbound_media
             WHERE node_id = ? AND outbox_cursor = ? AND deleted_at IS NULL",
        )
        .bind(node_id)
        .bind(cursor as i64)
        .fetch_optional(&mut *transaction)
        .await?
        .map(|row| OutboundMediaCleanup {
            media_id: row.get("media_id"),
            local_path: row.get("local_path"),
        });
        transaction.commit().await?;
        Ok(media)
    }

    pub async fn node_outbox_receipt(
        &self,
        node_id: &str,
        cursor: u64,
    ) -> anyhow::Result<Option<NodeOutboxReceipt>> {
        let row = sqlx::query(
            "SELECT status, detail_code, acknowledged_at FROM node_outbox_receipts
             WHERE node_id = ? AND cursor = ?",
        )
        .bind(node_id)
        .bind(cursor as i64)
        .fetch_optional(&self.pool)
        .await?;
        row.map(|row| {
            let acknowledged_at: String = row.get("acknowledged_at");
            Ok(NodeOutboxReceipt {
                status: row.get("status"),
                detail_code: row.get("detail_code"),
                acknowledged_at: parse_timestamp(&acknowledged_at)?,
            })
        })
        .transpose()
    }

    pub async fn outbound_media_cleanup_candidates(
        &self,
        node_id: Option<&str>,
    ) -> anyhow::Result<Vec<OutboundMediaCleanup>> {
        let rows = sqlx::query(
            "SELECT m.media_id, m.local_path
             FROM node_outbound_media m
             WHERE m.deleted_at IS NULL AND (? IS NULL OR m.node_id = ?)
               AND (m.expires_at <= ? OR EXISTS (
                   SELECT 1 FROM node_outbox_receipts r
                   WHERE r.cursor = m.outbox_cursor AND r.node_id = m.node_id
               ))
             ORDER BY m.created_at ASC LIMIT 32",
        )
        .bind(node_id)
        .bind(node_id)
        .bind(Utc::now().to_rfc3339())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .map(|row| OutboundMediaCleanup {
                media_id: row.get("media_id"),
                local_path: row.get("local_path"),
            })
            .collect())
    }

    pub async fn mark_outbound_media_deleted(&self, media_id: &str) -> anyhow::Result<()> {
        sqlx::query(
            "UPDATE node_outbound_media SET deleted_at = COALESCE(deleted_at, ?)
             WHERE media_id = ?",
        )
        .bind(Utc::now().to_rfc3339())
        .bind(media_id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    pub async fn register_response_media(
        &self,
        node_id: &str,
        turn_id: &str,
        content_type: &str,
        size_bytes: u64,
        local_path: &str,
    ) -> anyhow::Result<String> {
        let media_id = format!("media_{}", uuid::Uuid::new_v4().simple());
        let now = Utc::now();
        sqlx::query(
            "INSERT INTO node_response_media
             (media_id, node_id, turn_id, content_type, size_bytes, local_path, created_at, expires_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        ).bind(&media_id).bind(node_id).bind(turn_id).bind(content_type).bind(size_bytes as i64).bind(local_path)
            .bind(now.to_rfc3339()).bind((now + Duration::minutes(30)).to_rfc3339()).execute(&self.pool).await?;
        Ok(media_id)
    }

    pub async fn response_media(
        &self,
        node_id: &str,
        media_id: &str,
    ) -> anyhow::Result<(String, String, u64)> {
        let row = sqlx::query(
            "SELECT local_path, content_type, size_bytes FROM node_response_media
             WHERE media_id = ? AND node_id = ? AND expires_at > ?
             UNION ALL
             SELECT local_path, content_type, size_bytes FROM node_outbound_media
             WHERE media_id = ? AND node_id = ? AND expires_at > ? AND deleted_at IS NULL
             LIMIT 1",
        )
        .bind(media_id)
        .bind(node_id)
        .bind(Utc::now().to_rfc3339())
        .bind(media_id)
        .bind(node_id)
        .bind(Utc::now().to_rfc3339())
        .fetch_optional(&self.pool)
        .await?
        .ok_or_else(|| anyhow::anyhow!("response media not found or expired"))?;
        Ok((
            row.get("local_path"),
            row.get("content_type"),
            row.get::<i64, _>("size_bytes") as u64,
        ))
    }

    pub async fn list_nodes(&self) -> anyhow::Result<Vec<NodeRecord>> {
        let rows = sqlx::query(
            "SELECT n.node_id, n.owner_id, n.kind, n.display_name, n.policy_profile,
                    n.policy_revision, n.authorization_revision, n.created_at, n.revoked_at,
                    n.last_seen_at, ch.conversation_session_id, ch.node_channel_id
             FROM nodes n JOIN node_channels ch ON ch.node_id = n.node_id
             ORDER BY n.created_at ASC",
        )
        .fetch_all(&self.pool)
        .await?;
        rows.into_iter().map(node_from_row).collect()
    }

    pub async fn latest_sensor_readings(
        &self,
        node_selector: Option<&str>,
    ) -> anyhow::Result<Vec<LatestSensorReading>> {
        latest_sensor_readings(&self.pool, node_selector).await
    }

    pub async fn revoke_node(&self, node_id: &str) -> anyhow::Result<bool> {
        let now = Utc::now().to_rfc3339();
        let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let changed = sqlx::query(
            "UPDATE nodes SET revoked_at = COALESCE(revoked_at, ?),
                    policy_revision = policy_revision + 1,
                    authorization_revision = authorization_revision + 1
             WHERE node_id = ? AND revoked_at IS NULL",
        )
        .bind(&now)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        if changed.rows_affected() == 0 {
            transaction.commit().await?;
            return Ok(false);
        }
        sqlx::query(
            "UPDATE node_credentials SET state = 'revoked', revoked_at = ? WHERE node_id = ?",
        )
        .bind(&now)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "UPDATE node_sessions SET closed_at = ?, close_reason = 'node_revoked'
             WHERE node_id = ? AND closed_at IS NULL",
        )
        .bind(&now)
        .bind(node_id)
        .execute(&mut *transaction)
        .await?;
        sqlx::query(
            "INSERT INTO node_audit_events (node_id, event_type, created_at)
             VALUES (?, 'node_revoked', ?)",
        )
        .bind(node_id)
        .bind(&now)
        .execute(&mut *transaction)
        .await?;
        transaction.commit().await?;
        Ok(true)
    }
}

pub async fn latest_sensor_readings(
    pool: &SqlitePool,
    node_selector: Option<&str>,
) -> anyhow::Result<Vec<LatestSensorReading>> {
    let active_nodes = sqlx::query(
        "SELECT node_id, display_name FROM nodes
             WHERE revoked_at IS NULL ORDER BY created_at ASC",
    )
    .fetch_all(pool)
    .await?;
    let selected = if let Some(selector) = node_selector.map(str::trim).filter(|s| !s.is_empty()) {
        let mut matches = active_nodes.iter().filter(|row| {
            row.get::<String, _>("node_id") == selector
                || row
                    .get::<String, _>("display_name")
                    .eq_ignore_ascii_case(selector)
        });
        let first = matches
            .next()
            .ok_or_else(|| anyhow::anyhow!("No active Node matches '{selector}'"))?;
        anyhow::ensure!(matches.next().is_none(), "Node selector is ambiguous");
        first.get::<String, _>("node_id")
    } else {
        anyhow::ensure!(!active_nodes.is_empty(), "No active Nodes are enrolled");
        anyhow::ensure!(
            active_nodes.len() == 1,
            "Multiple active Nodes are enrolled; specify one by display name"
        );
        active_nodes[0].get::<String, _>("node_id")
    };
    let rows = sqlx::query(
        "SELECT n.display_name, n.last_seen_at, r.capability_id,
                    r.capability_version, r.value, r.unit, r.sample_uptime_ms, r.received_at
             FROM node_sensor_readings_latest r
             JOIN nodes n ON n.node_id = r.node_id
             WHERE r.node_id = ? AND n.revoked_at IS NULL
             ORDER BY r.capability_id ASC",
    )
    .bind(selected)
    .fetch_all(pool)
    .await?;
    rows.into_iter()
        .map(|row| {
            let received_at: String = row.get("received_at");
            let last_seen_at: Option<String> = row.get("last_seen_at");
            Ok(LatestSensorReading {
                display_name: row.get("display_name"),
                capability_id: row.get("capability_id"),
                capability_version: row.get::<i64, _>("capability_version") as u16,
                value: row.get("value"),
                unit: row.get("unit"),
                sample_uptime_ms: row.get::<i64, _>("sample_uptime_ms") as u64,
                received_at: parse_timestamp(&received_at)?,
                node_last_seen_at: last_seen_at.as_deref().map(parse_timestamp).transpose()?,
            })
        })
        .collect()
}

pub async fn node_health_snapshot(
    pool: &SqlitePool,
    node_selector: Option<&str>,
) -> anyhow::Result<NodeHealthSnapshot> {
    let active_nodes = sqlx::query(
        "SELECT node_id, display_name FROM nodes
         WHERE revoked_at IS NULL ORDER BY created_at ASC",
    )
    .fetch_all(pool)
    .await?;
    let selected = if let Some(selector) = node_selector.map(str::trim).filter(|s| !s.is_empty()) {
        let mut matches = active_nodes.iter().filter(|row| {
            row.get::<String, _>("node_id") == selector
                || row
                    .get::<String, _>("display_name")
                    .eq_ignore_ascii_case(selector)
        });
        let first = matches
            .next()
            .ok_or_else(|| anyhow::anyhow!("No active Node matches '{selector}'"))?;
        anyhow::ensure!(matches.next().is_none(), "Node selector is ambiguous");
        first.get::<String, _>("node_id")
    } else {
        anyhow::ensure!(!active_nodes.is_empty(), "No active Nodes are enrolled");
        anyhow::ensure!(
            active_nodes.len() == 1,
            "Multiple active Nodes are enrolled; specify one by display name"
        );
        active_nodes[0].get::<String, _>("node_id")
    };
    let row = sqlx::query(
        "SELECT display_name, last_seen_at, last_runtime_version,
                last_firmware_version, last_health_json
         FROM nodes WHERE node_id = ? AND revoked_at IS NULL",
    )
    .bind(&selected)
    .fetch_one(pool)
    .await?;
    let capability_rows = sqlx::query(
        "SELECT capability_id, capability_version, limits_json, observed_at
         FROM node_capabilities WHERE node_id = ? ORDER BY capability_id ASC",
    )
    .bind(&selected)
    .fetch_all(pool)
    .await?;
    let capabilities = capability_rows
        .into_iter()
        .map(|row| {
            let limits_json: String = row.get("limits_json");
            let observed_at: String = row.get("observed_at");
            Ok(NodeCapabilitySnapshot {
                capability_id: row.get("capability_id"),
                capability_version: row.get::<i64, _>("capability_version") as u16,
                limits: serde_json::from_str(&limits_json)?,
                observed_at: parse_timestamp(&observed_at)?,
            })
        })
        .collect::<anyhow::Result<Vec<_>>>()?;
    let authorization_rows = sqlx::query(
        "SELECT action, constraints_json, revision, granted_at
         FROM node_authorizations
         WHERE node_id = ? AND revoked_at IS NULL ORDER BY action ASC",
    )
    .bind(&selected)
    .fetch_all(pool)
    .await?;
    let authorizations = authorization_rows
        .into_iter()
        .map(|row| {
            let constraints_json: String = row.get("constraints_json");
            let granted_at: String = row.get("granted_at");
            Ok(NodeAuthorizationSnapshot {
                action: row.get("action"),
                constraints: serde_json::from_str(&constraints_json)?,
                revision: row.get::<i64, _>("revision") as u64,
                granted_at: parse_timestamp(&granted_at)?,
            })
        })
        .collect::<anyhow::Result<Vec<_>>>()?;
    let last_seen_at: Option<String> = row.get("last_seen_at");
    let health_json: Option<String> = row.get("last_health_json");
    let health: serde_json::Value = health_json
        .as_deref()
        .map(serde_json::from_str)
        .transpose()?
        .unwrap_or_else(|| json!({}));
    let recovery = health
        .get("recovery")
        .filter(|value| !value.is_null())
        .cloned()
        .map(serde_json::from_value)
        .transpose()?;
    Ok(NodeHealthSnapshot {
        display_name: row.get("display_name"),
        last_seen_at: last_seen_at.as_deref().map(parse_timestamp).transpose()?,
        runtime_version: row.get("last_runtime_version"),
        firmware_version: row.get("last_firmware_version"),
        uptime_ms: health.get("uptime_ms").and_then(serde_json::Value::as_u64),
        free_internal_heap: health
            .get("free_internal_heap")
            .and_then(serde_json::Value::as_u64),
        largest_internal_allocation: health
            .get("largest_internal_allocation")
            .and_then(serde_json::Value::as_u64),
        psram_free: health.get("psram_free").and_then(serde_json::Value::as_u64),
        recovery,
        capabilities,
        authorizations,
    })
}

async fn append_event_tx(
    transaction: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    node_id: &str,
    turn_id: Option<&str>,
    event_type: &str,
    payload: serde_json::Value,
) -> anyhow::Result<u64> {
    let now = Utc::now();
    let result = sqlx::query(
        "INSERT INTO node_outbox
         (node_id, turn_id, event_type, payload_json, created_at, expires_at)
         VALUES (?, ?, ?, ?, ?, ?)",
    )
    .bind(node_id)
    .bind(turn_id)
    .bind(event_type)
    .bind(payload.to_string())
    .bind(now.to_rfc3339())
    .bind((now + Duration::hours(24)).to_rfc3339())
    .execute(&mut **transaction)
    .await?;
    Ok(result.last_insert_rowid() as u64)
}

fn parse_turn_state(value: &str) -> NodeTurnState {
    match value {
        "accepted" => NodeTurnState::Accepted,
        "thinking" => NodeTurnState::Thinking,
        "complete" => NodeTurnState::Complete,
        "cancelled" => NodeTurnState::Cancelled,
        _ => NodeTurnState::Error,
    }
}

fn node_from_row(row: sqlx::sqlite::SqliteRow) -> anyhow::Result<NodeRecord> {
    let created_at: String = row.get("created_at");
    let revoked_at: Option<String> = row.get("revoked_at");
    let last_seen_at: Option<String> = row.get("last_seen_at");
    Ok(NodeRecord {
        node_id: row.get("node_id"),
        owner_id: row.get("owner_id"),
        kind: row.get("kind"),
        display_name: row.get("display_name"),
        policy_profile: row.get("policy_profile"),
        policy_revision: row.get::<i64, _>("policy_revision") as u64,
        authorization_revision: row.get::<i64, _>("authorization_revision") as u64,
        conversation_session_id: row.get("conversation_session_id"),
        node_channel_id: row.get("node_channel_id"),
        created_at: parse_timestamp(&created_at)?,
        revoked_at: revoked_at.as_deref().map(parse_timestamp).transpose()?,
        last_seen_at: last_seen_at.as_deref().map(parse_timestamp).transpose()?,
    })
}