oxios 1.7.0

Oxios Agent OS — Agent Operating System powered by oxi-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
use std::path::PathBuf;
use std::sync::Arc;

use axum::Json;
use axum::extract::{Path, Query, State};
use serde::{Deserialize, Serialize};

use crate::api::error::AppError;
use crate::api::server::AppState;

// ---------------------------------------------------------------------------
// Health
// ---------------------------------------------------------------------------

/// GET /health — Liveness check (no auth required).
///
/// Always returns 200 OK if the process is alive.
pub(crate) async fn handle_health(State(_state): State<Arc<AppState>>) -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "status": "ok",
        "version": env!("CARGO_PKG_VERSION"),
    }))
}

/// GET /health/ready — Readiness check (no auth required).
///
/// Checks subsystem health: state store, git repository.
/// Returns 200 if healthy, 503 if degraded.
pub(crate) async fn handle_readiness(
    state: State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, (axum::http::StatusCode, Json<serde_json::Value>)> {
    let mut components = serde_json::Map::new();
    let mut all_healthy = true;

    // State store: check workspace path exists
    let ws_path = state.kernel.state.workspace_path();
    let state_ok = ws_path.exists();
    components.insert(
        "state_store".into(),
        serde_json::json!({"healthy": state_ok}),
    );
    all_healthy &= state_ok;

    // Git: verify repository integrity
    let git_ok = state.kernel.infra.git_verify().unwrap_or(false);
    components.insert("git".into(), serde_json::json!({"healthy": git_ok}));
    // Git failure is degraded, not fatal

    // Memory: always healthy (optional subsystem)
    let (index_size, total) = state.kernel.agents.memory_stats().await;
    components.insert(
        "memory".into(),
        serde_json::json!({"healthy": true, "index_size": index_size, "total_entries": total}),
    );

    let status = if all_healthy { "healthy" } else { "degraded" };
    let body = serde_json::json!({
        "status": status,
        "version": env!("CARGO_PKG_VERSION"),
        "uptime_secs": state.start_time.elapsed().as_secs(),
        "components": components,
    });

    if all_healthy {
        Ok(Json(body))
    } else {
        Err((axum::http::StatusCode::SERVICE_UNAVAILABLE, Json(body)))
    }
}

// ---------------------------------------------------------------------------
// Control
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Component Health Types
// ---------------------------------------------------------------------------

/// Health status of an individual component.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct ComponentStatus {
    /// Whether the component is healthy.
    pub healthy: bool,
    /// Optional detail message.
    pub detail: Option<String>,
}

/// Memory subsystem health.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct MemoryHealth {
    /// Whether memory is enabled.
    pub enabled: bool,
    /// Number of entries in the vector index.
    pub index_size: usize,
    /// Total entries across all memory types.
    pub total_entries: usize,
}

/// Agent subsystem health.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct AgentHealth {
    /// Number of currently active agents.
    pub active_count: usize,
    /// Total agents forked (lifetime).
    pub total_forked: u64,
    /// Total agents completed (lifetime).
    pub total_completed: u64,
    /// Total agents failed (lifetime).
    pub total_failed: u64,
}

/// Aggregate health of all system components.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct ComponentHealth {
    /// State store health.
    pub state_store: ComponentStatus,
    /// Event bus health.
    pub event_bus: ComponentStatus,
    /// Memory subsystem health.
    pub memory: MemoryHealth,
    /// Agent subsystem health.
    pub agents: AgentHealth,
    /// Active spaces count.
    pub spaces_active: usize,
}

/// Response body for the status endpoint.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct StatusResponse {
    /// Service name.
    service: String,
    /// Current status.
    status: String,
    /// Binary (daemon) version.
    version: String,
    /// Web UI frontend version (read from `<web_dist>/version.json` written
    /// by the Vite build, or `"dev"` when not present — e.g. `bun dev`).
    web_version: String,
    /// Registered channels.
    channels: Vec<String>,
    /// Uptime info.
    uptime: String,
    /// Component-level health details.
    components: Option<ComponentHealth>,
}

/// Reads the Web UI version from `<web_dist>/version.json`.
///
/// That file is emitted by the Vite build and carries the version stamped
/// from the root `Cargo.toml` (same source as the binary version), plus an
/// optional `git_sha`. Returns `"dev"` when the file is missing — e.g. when
/// running `bun dev` or serving a workspace `web/dist` that predates the
/// version plugin — so the dashboard always renders a sane badge.
fn read_web_version(web_dist: &Option<PathBuf>) -> String {
    #[derive(Deserialize)]
    struct VersionFile {
        version: Option<String>,
    }

    web_dist
        .as_ref()
        .and_then(|p| std::fs::read(p.join("version.json")).ok())
        .and_then(|b| serde_json::from_slice::<VersionFile>(&b).ok())
        .and_then(|v| v.version)
        .unwrap_or_else(|| "dev".to_string())
}

/// GET /api/status — System status with component health.
pub(crate) async fn handle_status(state: State<Arc<AppState>>) -> Json<StatusResponse> {
    let uptime = state.start_time.elapsed();
    let uptime_str = format!(
        "{}h {}m {}s",
        uptime.as_secs() / 3600,
        (uptime.as_secs() % 3600) / 60,
        uptime.as_secs() % 60
    );

    // State store health — check that the base path exists
    let state_store_healthy = state.kernel.state.workspace_path().exists();

    // Event bus — always healthy if we got this far
    let event_bus_healthy = true;

    // Memory health
    let (mem_index_size, mem_total) = state.kernel.agents.memory_stats().await;
    let memory_health = MemoryHealth {
        enabled: true,
        index_size: mem_index_size,
        total_entries: mem_total,
    };

    // Agent health — count active from supervisor, metrics from export
    let active_count = state
        .kernel
        .agents
        .list()
        .await
        .map(|agents| {
            agents
                .iter()
                .filter(|a| {
                    matches!(
                        a.status,
                        oxios_kernel::AgentStatus::Running
                            | oxios_kernel::AgentStatus::Starting
                            | oxios_kernel::AgentStatus::Idle
                    )
                })
                .count()
        })
        .unwrap_or(0);

    let (total_forked, total_completed, total_failed) = parse_agent_metrics();

    let agent_health = AgentHealth {
        active_count,
        total_forked,
        total_completed,
        total_failed,
    };

    let components = Some(ComponentHealth {
        state_store: ComponentStatus {
            healthy: state_store_healthy,
            detail: if state_store_healthy {
                None
            } else {
                Some("base path not found".to_string())
            },
        },
        event_bus: ComponentStatus {
            healthy: event_bus_healthy,
            detail: None,
        },
        memory: memory_health,
        agents: agent_health,
        spaces_active: state
            .kernel
            .projects
            .as_ref()
            .map(|p| p.list_projects().len())
            .unwrap_or(0),
    });

    // Web UI version — read at runtime from `<web_dist>/version.json`.
    // That file is emitted by the Vite build (`vite.config.ts`) from the root
    // `Cargo.toml` version, so it matches the binary version by construction.
    // Falls back to `"dev"` when the file is absent (e.g. `bun dev`, or a
    // workspace `web/dist` predating this change). Reading on each request is
    // effectively free: the file is tiny and the OS page-caches it, and it lets
    // a daily auto-update of `web/dist/` be reflected without a restart.
    let web_version = read_web_version(&state.web_dist.path());

    Json(StatusResponse {
        service: "oxios".into(),
        status: "running".into(),
        version: env!("CARGO_PKG_VERSION").into(),
        web_version,
        channels: vec!["web".into()],
        uptime: uptime_str,
        components,
    })
}

// ---------------------------------------------------------------------------
// Update
// ---------------------------------------------------------------------------

/// Query params for update check.
#[derive(Debug, Deserialize)]
pub(crate) struct UpdateCheckParams {
    /// Check a specific version instead of latest.
    #[serde(default)]
    pub version: Option<String>,
}

/// Response for `GET /api/update/check`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct UpdateCheckResponse {
    /// Currently running version.
    pub current_version: String,
    /// Latest available version on GitHub.
    pub latest_version: String,
    /// Whether an update is available.
    pub update_available: bool,
    /// Release tag name (e.g. "v1.0.0").
    pub tag_name: String,
    /// URL to the release page.
    pub html_url: String,
    /// Short body / release notes excerpt.
    pub release_notes: String,
    /// Publication date.
    pub published_at: String,
    /// Available download assets.
    pub assets: Vec<AssetInfo>,
}

/// Info about a release asset.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct AssetInfo {
    pub name: String,
    pub size: u64,
    pub download_url: String,
}

/// Body for `POST /api/update/run`.
#[derive(Debug, Deserialize)]
pub(crate) struct UpdateRunBody {
    /// Update binary (default: true).
    #[serde(default = "default_true")]
    pub binary: bool,
    /// Update web UI (default: true).
    #[serde(default = "default_true")]
    pub web: bool,
    /// Target version (default: latest).
    pub version: Option<String>,
}

fn default_true() -> bool {
    true
}

/// Response for `POST /api/update/run`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct UpdateRunResponse {
    /// Whether the update succeeded.
    pub success: bool,
    /// Version we updated to.
    pub updated_to: String,
    /// What was updated.
    pub binary_updated: bool,
    pub web_updated: bool,
    /// Human-readable message.
    pub message: String,
}

/// Response for `GET /api/update/changelog`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct ChangelogResponse {
    pub tag_name: String,
    pub version: String,
    pub published_at: String,
    pub body: String,
    pub html_url: String,
}

/// GET /api/update/check — Check for available updates from GitHub Releases.
pub(crate) async fn handle_update_check(
    Query(params): Query<UpdateCheckParams>,
) -> Result<Json<UpdateCheckResponse>, AppError> {
    let current = env!("CARGO_PKG_VERSION");

    let release = fetch_github_release(params.version.as_deref()).await?;

    let tag_name = release["tag_name"]
        .as_str()
        .unwrap_or("unknown")
        .to_string();
    let latest_version = tag_name.trim_start_matches('v').to_string();
    let html_url = release["html_url"].as_str().unwrap_or("").to_string();
    let body_text = release["body"]
        .as_str()
        .unwrap_or("No release notes.")
        .to_string();
    let published_at = release["published_at"].as_str().unwrap_or("").to_string();

    let assets: Vec<AssetInfo> = release["assets"]
        .as_array()
        .unwrap_or(&vec![])
        .iter()
        .filter_map(|a| {
            Some(AssetInfo {
                name: a["name"].as_str()?.to_string(),
                size: a["size"].as_u64()?,
                download_url: a["browser_download_url"].as_str()?.to_string(),
            })
        })
        .collect();

    Ok(Json(UpdateCheckResponse {
        current_version: current.to_string(),
        latest_version: latest_version.clone(),
        update_available: latest_version != current,
        tag_name,
        html_url,
        release_notes: body_text,
        published_at,
        assets,
    }))
}

/// Validate a user-supplied version string for the update flow.
///
/// F10: `body.version` is interpolated into the GitHub API URL and passed
/// to `cargo install --version <v>`. While `Command::new` avoids shell
/// injection, an attacker-controlled value could still probe arbitrary
/// release tags or construct a malformed `cargo install` invocation. We
/// accept only SemVer-shaped strings (digits, dots, alphanumerics, `-`),
/// rejecting anything with path traversal, shell metacharacters, or
/// control bytes.
fn validate_update_version(v: &str) -> Result<(), AppError> {
    if v.is_empty() || v.len() > 64 {
        return Err(AppError::BadRequest(
            "version must be 1..64 characters".into(),
        ));
    }
    let ok = v
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '+' || c == '_');
    if !ok {
        return Err(AppError::BadRequest(
            "version contains invalid characters (allowed: alphanumeric, . - + _)".into(),
        ));
    }
    Ok(())
}

/// Maximum download size for the web-dist.zip asset (200 MiB). Guards
/// against a malicious or tampered release asset OOMing the server.
const MAX_DOWNLOAD_BYTES: u64 = 200 * 1024 * 1024;

/// POST /api/update/run — Execute the update (download + install binary/web).
pub(crate) async fn handle_update_run(
    state: State<Arc<AppState>>,
    Json(body): Json<UpdateRunBody>,
) -> Result<Json<UpdateRunResponse>, AppError> {
    let current = env!("CARGO_PKG_VERSION");
    // F10: validate user-supplied version before it reaches the GitHub API
    // URL or `cargo install --version`. Empty (latest) is allowed.
    if let Some(ref v) = body.version {
        validate_update_version(v)?;
    }
    let release = fetch_github_release(body.version.as_deref()).await?;

    let tag_name = release["tag_name"]
        .as_str()
        .unwrap_or("unknown")
        .to_string();
    let target_version = tag_name.trim_start_matches('v').to_string();

    let assets: Vec<(String, String, u64)> = release["assets"]
        .as_array()
        .unwrap_or(&vec![])
        .iter()
        .filter_map(|a| {
            Some((
                a["name"].as_str()?.to_string(),
                a["browser_download_url"].as_str()?.to_string(),
                a["size"].as_u64()?,
            ))
        })
        .collect();

    let client = reqwest::Client::builder()
        .user_agent(format!("oxios/{current}"))
        .build()
        .map_err(|e| AppError::Internal(format!("failed to create HTTP client: {e}")))?;

    let mut binary_updated = false;
    let mut web_updated = false;
    let mut messages: Vec<String> = Vec::new();

    // Update web UI (atomic — RFC-024 SP3)
    if body.web {
        if let Some((name, url, size)) = assets.iter().find(|(n, _, _)| n == "web-dist.zip") {
            tracing::info!(name, size, "Downloading web UI for update");
            let bytes = download_bytes(&client, url, MAX_DOWNLOAD_BYTES).await?;

            // Extract into a fresh versioned staging dir — NEVER the active
            // dir. The active dir is published only after extraction succeeds
            // and validates, so no request ever sees a half-populated dist.
            let web_root = dirs::home_dir()
                .ok_or_else(|| AppError::Internal("cannot determine home directory".into()))?
                .join(".oxios")
                .join("web");
            let staging = web_root.join(format!("dist-{target_version}"));
            if staging.exists() {
                std::fs::remove_dir_all(&staging)
                    .map_err(|e| AppError::Internal(format!("failed to clear staging: {e}")))?;
            }
            std::fs::create_dir_all(&staging)
                .map_err(|e| AppError::Internal(format!("failed to create staging: {e}")))?;

            let cursor = std::io::Cursor::new(&bytes);
            let mut archive = zip::ZipArchive::new(cursor)
                .map_err(|e| AppError::Internal(format!("invalid zip: {e}")))?;

            for i in 0..archive.len() {
                let mut file = archive
                    .by_index(i)
                    .map_err(|e| AppError::Internal(format!("zip read error: {e}")))?;
                let out_path = match file.enclosed_name() {
                    Some(p) => staging.join(p),
                    None => continue,
                };
                if file.is_dir() {
                    std::fs::create_dir_all(&out_path).ok();
                } else {
                    if let Some(p) = out_path.parent() {
                        std::fs::create_dir_all(p).ok();
                    }
                    let mut out_file = std::fs::File::create(&out_path)
                        .map_err(|e| AppError::Internal(format!("write error: {e}")))?;
                    std::io::copy(&mut file, &mut out_file)
                        .map_err(|e| AppError::Internal(format!("write error: {e}")))?;
                }
            }

            // Validate before publishing.
            if !staging.join("index.html").is_file() {
                return Err(AppError::Internal(
                    "extracted dist missing index.html".into(),
                ));
            }

            // Atomic publish: swap the in-memory pointer + persist marker.
            // Previous generation is cleaned up after a grace period.
            let marker = web_root.join(".active");
            state.web_dist.publish(staging, &marker);

            web_updated = true;
            messages.push(format!("Web UI updated to {target_version}"));
        } else {
            messages.push("web-dist.zip not found in release, skipped".to_string());
        }
    }

    // Update binary via cargo
    if body.binary {
        let mut args = vec!["install", "oxios", "locked"];
        if let Some(ref v) = body.version {
            args.push("--version");
            args.push(v.as_str());
        }

        tracing::info!(?args, "Running cargo install for binary update");

        let output = tokio::process::Command::new("cargo")
            .args(&args)
            .output()
            .await
            .map_err(|e| AppError::Internal(format!("failed to run cargo: {e}")))?;

        if output.status.success() {
            binary_updated = true;
            messages.push(format!("Binary updated to {target_version} via cargo"));
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::error!(%stderr, "cargo install failed");
            messages.push(format!(
                "Binary update failed: {}",
                stderr.lines().take(3).collect::<Vec<_>>().join("; ")
            ));
        }
    }

    tracing::info!(
        binary_updated,
        web_updated,
        target_version,
        "Update completed"
    );

    Ok(Json(UpdateRunResponse {
        success: true,
        updated_to: target_version,
        binary_updated,
        web_updated,
        message: messages.join("; "),
    }))
}

/// GET /api/update/changelog — Show release notes for a version.
pub(crate) async fn handle_update_changelog(
    Query(params): Query<UpdateCheckParams>,
) -> Result<Json<ChangelogResponse>, AppError> {
    let release = fetch_github_release(params.version.as_deref()).await?;

    let tag_name = release["tag_name"]
        .as_str()
        .unwrap_or("unknown")
        .to_string();
    let version = tag_name.trim_start_matches('v').to_string();
    let published_at = release["published_at"].as_str().unwrap_or("").to_string();
    let body = release["body"]
        .as_str()
        .unwrap_or("No release notes.")
        .to_string();
    let html_url = release["html_url"].as_str().unwrap_or("").to_string();

    Ok(Json(ChangelogResponse {
        tag_name,
        version,
        published_at,
        body,
        html_url,
    }))
}

// ---------------------------------------------------------------------------
// Update helpers
// ---------------------------------------------------------------------------

const GITHUB_OWNER: &str = "a7garden";
const GITHUB_REPO: &str = "oxios";

async fn fetch_github_release(version: Option<&str>) -> Result<serde_json::Value, AppError> {
    let api_url = match version {
        Some(v) => {
            format!("https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/releases/tags/v{v}")
        }
        None => {
            format!("https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/releases/latest")
        }
    };

    let client = reqwest::Client::builder()
        .user_agent(format!("oxios/{}", env!("CARGO_PKG_VERSION")))
        .build()
        .map_err(|e| AppError::Internal(format!("HTTP client error: {e}")))?;

    let resp = client
        .get(&api_url)
        .send()
        .await
        .map_err(|e| AppError::Internal(format!("GitHub API request failed: {e}")))?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(AppError::Internal(format!(
            "GitHub API error {status}: {body}"
        )));
    }

    resp.json()
        .await
        .map_err(|e| AppError::Internal(format!("Failed to parse GitHub response: {e}")))
}

async fn download_bytes(
    client: &reqwest::Client,
    url: &str,
    max_bytes: u64,
) -> Result<Vec<u8>, AppError> {
    let resp = client
        .get(url)
        .send()
        .await
        .map_err(|e| AppError::Internal(format!("Download request failed: {e}")))?;

    let status = resp.status();
    if !status.is_success() {
        return Err(AppError::Internal(format!("Download failed: {status}")));
    }

    // F10: reject oversized payloads up front when the server advertises a
    // Content-Length. This stops a zip-bomb / large-asset OOM before we
    // allocate for it.
    if let Some(cl) = resp.content_length()
        && cl > max_bytes
    {
        return Err(AppError::PayloadTooLarge {
            size: cl as usize,
            limit: max_bytes as usize,
        });
    }

    // Stream the body with a running byte counter so a server that omits
    // Content-Length (chunked encoding) still cannot push us past the cap.
    use futures::StreamExt;
    let mut stream = resp.bytes_stream();
    let mut buf = Vec::new();
    while let Some(chunk) = stream.next().await {
        let chunk =
            chunk.map_err(|e| AppError::Internal(format!("Failed to read download body: {e}")))?;
        let new_len = buf.len().saturating_add(chunk.len());
        if new_len > max_bytes as usize {
            return Err(AppError::PayloadTooLarge {
                size: new_len,
                limit: max_bytes as usize,
            });
        }
        buf.extend_from_slice(&chunk);
    }
    Ok(buf)
}

/// Parse agent metrics from the Prometheus export text.
/// Returns (forked, completed, failed) counters.
fn parse_agent_metrics() -> (u64, u64, u64) {
    let export = oxios_kernel::metrics::registry().export();
    let mut forked = 0u64;
    let mut completed = 0u64;
    let mut failed = 0u64;
    for line in export.lines() {
        if line.starts_with("oxios_agents_forked_total ") {
            forked = line
                .rsplit(' ')
                .next()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);
        } else if line.starts_with("oxios_agents_completed_total ") {
            completed = line
                .rsplit(' ')
                .next()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);
        } else if line.starts_with("oxios_agents_failed_total ") {
            failed = line
                .rsplit(' ')
                .next()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);
        }
    }
    (forked, completed, failed)
}

/// Query params for GET /api/agents.
#[derive(Debug, Deserialize)]
pub(crate) struct AgentQueryParams {
    pub q: Option<String>,
    pub search_field: Option<String>,
    pub status: Option<String>,
    pub session_id: Option<String>,
    pub project_id: Option<String>,
    pub seed_id: Option<String>,
    pub model_id: Option<String>,
    pub tool: Option<String>,
    pub has_error: Option<bool>,
    pub date_from: Option<String>,
    pub date_to: Option<String>,
    pub cost_min: Option<f64>,
    pub cost_max: Option<f64>,
    pub tokens_min: Option<u64>,
    pub tokens_max: Option<u64>,
    pub duration_min: Option<u64>,
    pub duration_max: Option<u64>,
    pub sort_by: Option<String>,
    pub sort_dir: Option<String>,
    #[serde(default = "default_page")]
    pub page: u32,
    #[serde(default = "default_limit")]
    pub per_page: u32,
}

fn default_page() -> u32 {
    1
}
fn default_limit() -> u32 {
    50
}

/// Convert query params to AgentListFilter.
fn params_to_filter(p: &AgentQueryParams) -> oxios_kernel::agent_log_db::AgentListFilter {
    let status = p.status.as_deref().and_then(|s| match s {
        "running" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Running),
        "completed" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Completed),
        "failed" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Failed),
        "stopped" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Stopped),
        "starting" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Starting),
        "idle" => Some(oxios_kernel::agent_log_db::AgentStatusFilter::Idle),
        _ => None,
    });

    let search_field = p.search_field.as_deref().map_or(
        oxios_kernel::agent_log_db::SearchField::All,
        |s| match s {
            "name" => oxios_kernel::agent_log_db::SearchField::Name,
            "error" => oxios_kernel::agent_log_db::SearchField::Error,
            "tool_name" => oxios_kernel::agent_log_db::SearchField::ToolName,
            "tool_output" => oxios_kernel::agent_log_db::SearchField::ToolOutput,
            _ => oxios_kernel::agent_log_db::SearchField::All,
        },
    );

    let sort_by = p
        .sort_by
        .as_deref()
        .map_or(oxios_kernel::agent_log_db::SortBy::CreatedAt, |s| match s {
            "cost" => oxios_kernel::agent_log_db::SortBy::Cost,
            "duration" => oxios_kernel::agent_log_db::SortBy::Duration,
            "tokens" => oxios_kernel::agent_log_db::SortBy::Tokens,
            "name" => oxios_kernel::agent_log_db::SortBy::Name,
            _ => oxios_kernel::agent_log_db::SortBy::CreatedAt,
        });

    let sort_dir = p
        .sort_dir
        .as_deref()
        .map_or(oxios_kernel::agent_log_db::SortDir::Desc, |s| match s {
            "asc" => oxios_kernel::agent_log_db::SortDir::Asc,
            _ => oxios_kernel::agent_log_db::SortDir::Desc,
        });

    let parse_dt = |s: &Option<String>| -> Option<chrono::DateTime<chrono::Utc>> {
        s.as_deref()
            .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.with_timezone(&chrono::Utc))
    };

    oxios_kernel::agent_log_db::AgentListFilter {
        q: p.q.clone(),
        search_field,
        status,
        session_id: p.session_id.clone(),
        project_id: p.project_id.clone(),
        seed_id: p.seed_id.clone(),
        model_id: p.model_id.clone(),
        tool: p.tool.clone(),
        has_error: p.has_error,
        date_from: parse_dt(&p.date_from),
        date_to: parse_dt(&p.date_to),
        cost_min: p.cost_min,
        cost_max: p.cost_max,
        tokens_min: p.tokens_min,
        tokens_max: p.tokens_max,
        duration_min: p.duration_min,
        duration_max: p.duration_max,
        sort_by,
        sort_dir,
        page: p.page,
        per_page: p.per_page,
    }
}

/// GET /api/agents — List agent instances with full filter/search/sort/paginate.
pub(crate) async fn handle_agents_list(
    state: State<Arc<AppState>>,
    Query(params): Query<AgentQueryParams>,
) -> Json<serde_json::Value> {
    let filter = params_to_filter(&params);
    match state.kernel.agents.query(&filter).await {
        Ok(result) => Json(serde_json::json!({
            "items": result.items.iter().map(serialize_agent_summary).collect::<Vec<_>>(),
            "total": result.total,
            "page": result.page,
            "per_page": result.per_page,
            "total_pages": result.total_pages,
            "stats": {
                "total_cost_usd": result.stats.total_cost_usd,
                "total_tokens": result.stats.total_tokens,
                "avg_duration_secs": result.stats.avg_duration_secs,
                "count_running": result.stats.count_running,
                "count_completed": result.stats.count_completed,
                "count_failed": result.stats.count_failed,
            },
        })),
        Err(e) => {
            tracing::error!(error = %e, "Failed to query agents");
            Json(serde_json::json!({
                "items": [],
                "total": 0,
                "page": params.page,
                "per_page": params.per_page,
                "total_pages": 0,
                "stats": {},
            }))
        }
    }
}

/// GET /api/agents/stats — Global agent stats.
pub(crate) async fn handle_agent_stats(state: State<Arc<AppState>>) -> Json<serde_json::Value> {
    match state.kernel.agents.stats().await {
        Ok(s) => Json(serde_json::json!({
            "total_agents": s.total_agents,
            "running": s.running,
            "completed": s.completed,
            "failed": s.failed,
            "total_cost_usd": s.total_cost_usd,
            "total_tokens": s.total_tokens,
            "total_duration_secs": s.total_duration_secs,
            "avg_duration_secs": s.avg_duration_secs,
            "avg_cost_usd": s.avg_cost_usd,
            "total_sessions": s.total_sessions,
            "oldest_agent_at": s.oldest_agent_at.map(|t| t.to_rfc3339()),
            "newest_agent_at": s.newest_agent_at.map(|t| t.to_rfc3339()),
        })),
        Err(e) => {
            tracing::error!(error = %e, "Failed to get agent stats");
            Json(serde_json::json!({"error": e.to_string()}))
        }
    }
}

fn serialize_agent_summary(a: &oxios_kernel::types::AgentInfo) -> serde_json::Value {
    serde_json::json!({
        "id": a.id.to_string(),
        "name": a.name,
        "status": a.status.to_string(),
        "created_at": a.created_at.to_rfc3339(),
        "started_at": a.started_at.map(|t| t.to_rfc3339()),
        "completed_at": a.completed_at.map(|t| t.to_rfc3339()),
        "seed_id": a.seed_id.map(|s| s.to_string()),
        "project_id": a.project_id.map(|id| id.to_string()),
        "session_id": a.session_id,
        "error": a.error,
        "steps_completed": a.steps_completed,
        "steps_total": a.steps_total,
        "tokens_used": a.tokens_input + a.tokens_output,
        "cost_usd": a.cost_usd,
        "model_id": a.model_id,
        "duration_secs": a.completed_at.zip(a.started_at)
            .map(|(end, start)| (end - start).num_seconds().max(0)),
    })
}

/// GET /api/agents/{id} — Agent detail (from memory or SQLite).
pub(crate) async fn handle_agent_get(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Try in-memory first
    if let Ok(agents) = state.kernel.agents.list().await
        && let Some(agent) = agents.into_iter().find(|a| a.id.to_string() == id)
    {
        return Ok(Json(agent_detail_json(&agent, &state)));
    }

    // Fall back to SQLite (or filesystem)
    let agent = state.kernel.agents.get(&id).await?;
    match agent {
        Some(agent) => Ok(Json(agent_detail_json(&agent, &state))),
        None => Err(AppError::NotFound("agent not found".into())),
    }
}

fn agent_detail_json(
    agent: &oxios_kernel::types::AgentInfo,
    state: &Arc<AppState>,
) -> serde_json::Value {
    let budget = state.kernel.agents.check_budget(&agent.id);
    serde_json::json!({
        "id": agent.id.to_string(),
        "name": agent.name,
        "status": agent.status.to_string(),
        "created_at": agent.created_at.to_rfc3339(),
        "seed_id": agent.seed_id.map(|s| s.to_string()),
        "project_id": agent.project_id.map(|id| id.to_string()),
        "session_id": agent.session_id,
        "started_at": agent.started_at.map(|t| t.to_rfc3339()),
        "completed_at": agent.completed_at.map(|t| t.to_rfc3339()),
        "error": agent.error,
        "steps_completed": agent.steps_completed,
        "steps_total": agent.steps_total,
        "tokens_used": agent.tokens_input + agent.tokens_output,
        "cost_usd": agent.cost_usd,
        "model_id": agent.model_id,
        "budget": {
            "tokens_remaining": budget.tokens_remaining,
            "calls_remaining": budget.calls_remaining,
            "window_remaining_secs": budget.window_remaining_secs,
            "is_exhausted": budget.is_exhausted,
        },
    })
}

pub(crate) async fn handle_agent_trace(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Try in-memory first
    if let Ok(agents) = state.kernel.agents.list().await
        && let Some(agent) = agents.into_iter().find(|a| a.id.to_string() == id)
    {
        return Ok(Json(trace_json(&agent)));
    }

    // Fallback: load from SQLite
    if let Ok(Some(agent)) = state.kernel.agents.get(&id).await {
        return Ok(Json(trace_json(&agent)));
    }

    Err(AppError::NotFound("agent not found".into()))
}

fn trace_json(agent: &oxios_kernel::types::AgentInfo) -> serde_json::Value {
    let steps: Vec<serde_json::Value> = agent
        .tool_calls
        .iter()
        .enumerate()
        .map(|(i, tc)| {
            serde_json::json!({
                "index": i,
                "tool_name": tc.tool,
                "action": tc.tool,
                "input": tc.input,
                "output": tc.output,
                "started_at": tc.timestamp.map(|t| t.to_rfc3339()).unwrap_or_default(),
                "duration_ms": tc.duration_ms,
                "status": if tc.is_error { "failed" } else { "completed" },
            })
        })
        .collect();

    serde_json::json!({
        "agent_id": agent.id.to_string(),
        "steps": steps,
        "completed_at": agent.completed_at.map(|t| t.to_rfc3339()),
    })
}

/// GET /api/agents/{id}/logs — Agent execution logs.
pub(crate) async fn handle_agent_logs(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Try in-memory first
    let agent = if let Ok(agents) = state.kernel.agents.list().await {
        agents.into_iter().find(|a| a.id.to_string() == id)
    } else {
        None
    };

    // Fallback: load from SQLite
    let agent = match agent {
        Some(a) => a,
        None => match state.kernel.agents.get(&id).await {
            Ok(Some(a)) => a,
            _ => return Err(AppError::NotFound("agent not found".into())),
        },
    };

    let mut entries = Vec::new();

    if let Some(started) = agent.started_at {
        entries.push(serde_json::json!({
            "timestamp": started.to_rfc3339(),
            "level": "info",
            "message": format!("Agent started: {}", agent.name),
        }));
    }

    for (i, tc) in agent.tool_calls.iter().enumerate() {
        let ts = tc.timestamp.map(|t| t.to_rfc3339()).unwrap_or_default();
        entries.push(serde_json::json!({
            "timestamp": ts,
            "level": "info",
            "message": format!("[Step {}] {} ({}) → {}",
                i + 1, tc.tool, format_duration(tc.duration_ms),
                truncate_str(&tc.output, 120)),
        }));
    }

    if let Some(completed) = agent.completed_at {
        let (level, msg) = if let Some(ref err) = agent.error {
            ("error", format!("Agent failed: {err}"))
        } else {
            (
                "info",
                format!("Agent completed ({} steps)", agent.steps_completed),
            )
        };
        entries.push(serde_json::json!({
            "timestamp": completed.to_rfc3339(),
            "level": level,
            "message": msg,
        }));
    }

    Ok(Json(serde_json::json!({
        "agent_id": id,
        "entries": entries,
    })))
}

/// POST /api/agents/{id}/kill — Kill an agent.
pub(crate) async fn handle_agent_kill(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<(), AppError> {
    tracing::info!(agent_id = %id, "Kill agent requested");
    state.kernel.agents.kill(&id).await.map_err(|e| {
        tracing::warn!(error = %e, "Agent not found");
        AppError::NotFound("agent not found".into())
    })
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

/// GET /api/config — Get current configuration.
pub(crate) async fn handle_config_get(
    state: State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Serialize the actual config from AppState (read lock).
    let config = state.config.read();
    match serde_json::to_value(&*config) {
        Ok(mut json) => {
            // Mask API key in response — never expose plaintext
            if let Some(engine) = json.get_mut("engine")
                && let Some(api_key) = engine.get_mut("api_key")
                && api_key.as_str().is_some_and(|k| !k.is_empty())
            {
                *api_key = serde_json::Value::String("***".to_string());
            }
            // Add api_key_set flag so the frontend knows if a key is currently set
            json["engine"]["api_key_set"] =
                serde_json::Value::Bool(config.engine.api_key.is_some());
            Ok(Json(json))
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to serialize config");
            Err(AppError::Internal("failed to serialize config".into()))
        }
    }
}

/// Deep-merge a patch into a base `serde_json::Value` (both must be objects).
///
/// Sections and fields present in `patch` override those in `base`.
/// Sections and fields absent from `patch` are preserved from `base`.
/// This implements PATCH semantics so that a partial config update does not
/// reset fields the caller did not intend to change.
///
/// Conflict policy:
/// - If both sides have a non-null object at the same path, recurse.
/// - Otherwise `patch` wins.
fn deep_merge_json(base: &mut serde_json::Value, patch: serde_json::Value) {
    use serde_json::Value;
    if let Value::Object(patch_map) = patch {
        if !base.is_object() {
            *base = Value::Object(serde_json::Map::new());
        }
        let base_map = base.as_object_mut().expect("just ensured object");
        for (key, patch_val) in patch_map {
            match base_map.get_mut(&key) {
                Some(existing) if existing.is_object() && patch_val.is_object() => {
                    deep_merge_json(existing, patch_val);
                }
                _ => {
                    base_map.insert(key, patch_val);
                }
            }
        }
    }
}

/// PUT /api/config — Update configuration (alias of PATCH).
///
/// Like the PATCH handler, the request body is **deep-merged** into the
/// current in-memory config. Sections and fields the caller omits are
/// preserved, not reset to defaults. Despite the HTTP verb, this is
/// NOT a full-config replacement — it has the same semantics as
/// `PATCH /api/config`.
///
/// Why is PUT exposed at all? Some HTTP clients, automation tooling,
/// and older Oxios versions send PUT instead of PATCH. The handler
/// is kept so that those callers still work; new code should prefer
/// `PATCH /api/config`, which also returns the hot-reload
/// classification report (`ConfigPatchResponse`) that PUT does not.
///
/// Engine configuration (`engine.*`) is rejected by PATCH with 400;
/// PUT keeps the same restriction. Use the typed engine endpoints
/// (`/api/engine/api-key`, `/api/engine/model`,
/// `/api/engine/provider-options`) for those.
pub(crate) async fn handle_config_put(
    state: State<Arc<AppState>>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, AppError> {
    tracing::info!("Config update requested");

    // Reject engine.* fields — same restriction as PATCH. The bulk PUT path
    // does not encrypt or mask, so accepting `engine.api_key` here would
    // write the key in plaintext to config.toml and bypass the typed
    // `/api/engine/api-key` endpoint (which handles encryption/masking).
    if let Some(forbidden) = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS) {
        tracing::warn!(key = %forbidden, "PUT /api/config rejected forbidden key");
        return Err(AppError::BadRequest(format!(
            "PUT /api/config does not accept '{forbidden}' fields. \
             Use the typed endpoint instead: \
             /api/engine/api-key (POST), /api/engine/model (PUT), \
             /api/engine/provider-options (PUT)."
        )));
    }

    // Deep-merge the patch into the current config so omitted fields are preserved.
    let mut current_value = {
        let cfg = state.config.read();
        serde_json::to_value(&*cfg).map_err(|e| {
            tracing::error!(error = %e, "Failed to serialize current config");
            AppError::Internal("failed to serialize current config".into())
        })?
    };
    deep_merge_json(&mut current_value, body);

    // Validate the merged result by parsing as OxiosConfig.
    let updated: oxios_kernel::OxiosConfig = match serde_json::from_value(current_value.clone()) {
        Ok(cfg) => cfg,
        Err(e) => {
            tracing::warn!(error = %e, "Invalid config shape");
            return Err(AppError::BadRequest(format!("Invalid config: {e}")));
        }
    };

    // Run the kernel validator too (catches semantic errors like
    // default_timeout > max_timeout) before we touch disk.
    let (errors, warnings) = updated.validate();
    for w in &warnings {
        tracing::warn!(config_warning = %w, "Config validation warning");
    }
    if !errors.is_empty() {
        let msg = errors.join("; ");
        tracing::warn!(error = %msg, "Config validation failed");
        return Err(AppError::BadRequest(format!("Invalid config: {msg}")));
    }

    // Persist the merged config to disk.
    let content = toml::to_string_pretty(&updated)
        .map_err(|e: toml::ser::Error| AppError::Internal(e.to_string()))?;
    if let Err(e) = tokio::fs::write(&state.config_path, content).await {
        tracing::error!(error = %e, "Failed to persist config");
        return Err(AppError::Internal(e.to_string()));
    }
    tracing::info!(path = %state.config_path.display(), "Config persisted");

    // Hot-reload: update in-memory config.
    let updated_config = updated;
    *state.config.write() = updated_config.clone();

    // Propagate hot-reloadable config to kernel subsystems.
    // Each subsystem gets its relevant slice of the config.

    // ExecApi — allowlist, shell mode, timeouts
    *state.kernel.exec.shared_config().write() = updated_config.exec.clone();

    // AgentScheduler — concurrency, rate limit, zombie timeout
    state.kernel.infra.scheduler().update_config(
        updated_config.scheduler.max_concurrent,
        updated_config.scheduler.rate_limit_per_minute,
        updated_config.scheduler.zombie_timeout_secs,
    );

    // ResourceMonitor — CPU/memory/load thresholds
    use oxios_kernel::resource_monitor::OverloadThreshold;
    state
        .kernel
        .infra
        .resource_monitor()
        .set_overload_threshold(OverloadThreshold {
            cpu_percent: updated_config.resource_monitor.cpu_threshold,
            memory_percent: updated_config.resource_monitor.memory_threshold,
            load_avg: updated_config.resource_monitor.load_threshold,
        });

    tracing::info!(
        "Config hot-reloaded (web + kernel subsystems) from {}",
        state.config_path.display()
    );

    // Return the merged, masked config (same shape as GET /api/config) so
    // the caller never receives an echoed plaintext api_key from its own
    // request body.
    let mut response = current_value;
    if let Some(engine) = response.get_mut("engine")
        && let Some(api_key) = engine.get_mut("api_key")
        && api_key.as_str().is_some_and(|k| !k.is_empty())
    {
        *api_key = serde_json::Value::String("***".to_string());
    }
    if let Some(engine) = response.get_mut("engine") {
        engine["api_key_set"] = serde_json::Value::Bool(updated_config.engine.api_key.is_some());
    }
    Ok(Json(response))
}

// ---------------------------------------------------------------------------
// PATCH /api/config — Partial config update with hot-reload metadata
// ---------------------------------------------------------------------------

/// List of top-level config sections whose fields are propagated to the
/// running kernel at PATCH time (no daemon restart required).
///
/// Each entry is `(section_name, restart_scope)`. `restart_scope` describes
/// the runtime subsystem that needs to pick up the change (used in logs and
/// tooltips on the frontend).
///
/// IMPORTANT: this list MUST match what `handle_config_patch` actually
/// propagates. Sections not listed here (security, audit, orchestrator,
/// context, session, logging, kernel, memory, …) are persisted to disk
/// but the running daemon keeps the boot-time values, so they are
/// classified as `requires_restart`. Adding a section to this list
/// without wiring the propagation in `handle_config_patch` would lie
/// to the user about whether the change took effect.
const HOT_RELOADABLE_SECTIONS: &[(&str, &str)] = &[
    ("exec", "exec_api"),
    ("scheduler", "scheduler"),
    ("resource_monitor", "resource_monitor"),
];

/// Subset of fields that always require a restart even inside a
/// hot-reloadable section (e.g. `memory.embedding.provider` swaps a
/// model that was loaded at boot).
const RESTART_REQUIRED_FIELDS: &[&str] = &[
    "memory.embedding.provider",
    "memory.embedding.dimension",
    "memory.sqlite.path",
    "memory.sqlite.embedding_dim",
    "memory.bridge.sync_enabled",
    "memory.bridge.interval_secs",
    "engine.default_model",
    "engine.api_key",
    "engine.provider_options",
    "engine.routing_enabled",
    "engine.prefer_cost_efficient",
    "engine.fallback_models",
    "engine.excluded_models",
    "gateway.host",
    "gateway.port",
    "daemon.pid_file",
    "daemon.log_dir",
    "channels.enabled",
    "channels.telegram.bot_token_env",
    "channels.telegram.allowed_users",
    "channels.telegram.session.rotation_hours",
    "channels.telegram.session.max_messages",
    "surfaces",
    "otel.enabled",
    "otel.endpoint",
    "otel.service_name",
    "otel.sampling_ratio",
    "cron",
    "mcp",
    "browser",
    "persona",
    "marketplace",
    "budget",
    "git",
    "memory.consolidation.preset",
];

/// Response body for `PATCH /api/config`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct ConfigPatchResponse {
    /// Echo of the saved patch (deep-merged view of the modified config).
    pub config: serde_json::Value,
    /// Hot-reload classification of the changes that were applied.
    pub hot_reload: HotReloadReport,
}

/// Hot-reload classification of a config patch.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct HotReloadReport {
    /// Dotted field paths that were applied to running subsystems immediately.
    pub applied_immediately: Vec<String>,
    /// Dotted field paths that require a daemon restart to take full effect.
    pub requires_restart: Vec<String>,
    /// Total number of changed fields (sum of both lists).
    pub total_changed: usize,
}

/// Classify a JSON patch against the current config into hot-reloadable vs
/// restart-required field paths. Walks both `base` and `patch` recursively,
/// emitting the dotted path of every key whose value actually changed.
fn classify_patch(
    base: &serde_json::Value,
    patch: &serde_json::Value,
    prefix: &str,
    applied: &mut Vec<String>,
    restart: &mut Vec<String>,
) {
    use serde_json::Value;
    let Value::Object(patch_map) = patch else {
        return;
    };
    for (key, patch_val) in patch_map {
        let path = if prefix.is_empty() {
            key.clone()
        } else {
            format!("{prefix}.{key}")
        };

        // Recurse into nested objects so we report the exact changed field.
        if patch_val.is_object() {
            let base_child = base.get(key).cloned().unwrap_or(Value::Null);
            classify_patch(&base_child, patch_val, &path, applied, restart);
            continue;
        }

        // Scalar / array — compare for actual change.
        let base_val = base.get(key);
        if base_val == Some(patch_val) {
            continue;
        }

        if is_restart_required(&path) {
            restart.push(path);
        } else {
            applied.push(path);
        }
    }
}

/// Returns true if a dotted config path requires a daemon restart to apply.
fn is_restart_required(path: &str) -> bool {
    if RESTART_REQUIRED_FIELDS.contains(&path) {
        return true;
    }
    // Top-level sections not in HOT_RELOADABLE_SECTIONS are restart-only.
    let top = path.split('.').next().unwrap_or(path);
    !HOT_RELOADABLE_SECTIONS.iter().any(|(s, _)| *s == top)
}

/// Top-level config keys that the PATCH endpoint must refuse, even
/// though they exist in `OxiosConfig`. The engine subsystem manages
/// its own typed endpoints (`/api/engine/api-key`, `/api/engine/model`,
/// `/api/engine/provider-options`) which handle encryption, masking,
/// and provider-scoped semantics. A bulk PATCH that overwrites
/// `engine.api_key: ""` would silently wipe the stored key.
const PATCH_FORBIDDEN_TOP_LEVEL_KEYS: &[&str] = &["engine"];

/// Walk a PATCH body and return the first forbidden top-level key it
/// contains, or `None` if the body is acceptable. Used by
/// `handle_config_patch` to reject engine.* writes before they reach
/// the deep-merge step.
fn find_forbidden_patch_key(body: &serde_json::Value, forbidden: &[&str]) -> Option<String> {
    use serde_json::Value;
    let Value::Object(map) = body else {
        return None;
    };
    for key in map.keys() {
        if forbidden.iter().any(|f| *f == key) {
            return Some(key.clone());
        }
    }
    None
}

/// `PATCH /api/config` — Partial config update.
///
/// Body: a subset of `OxiosConfig` (e.g. `{"exec": {"allowlist_mode":
/// "enforced"}}`). The patch is deep-merged into the current config so
/// sections and fields the caller omits are preserved.
///
/// Engine configuration (`engine.api_key`, `engine.provider_options`,
/// `engine.default_model`, …) MUST NOT be sent via this endpoint.
/// Use the typed engine endpoints (`/api/engine/api-key`,
/// `/api/engine/model`, `/api/engine/provider-options`) instead — they
/// handle encryption, masking, and provider scoping correctly. A PATCH
/// containing engine.* fields is rejected with HTTP 400.
///
/// Response includes a `hot_reload` object classifying which changed
/// fields were applied immediately and which require a daemon restart.
pub(crate) async fn handle_config_patch(
    state: State<Arc<AppState>>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<ConfigPatchResponse>, AppError> {
    tracing::info!("Config PATCH requested");

    if !body.is_object() {
        return Err(AppError::BadRequest(
            "PATCH body must be a JSON object".into(),
        ));
    }

    // Reject engine.* fields. They are managed by the typed engine
    // endpoints; sending them here risks wiping the encrypted api_key
    // (the bulk path does not mask or encrypt).
    if let Some(forbidden) = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS) {
        tracing::warn!(key = %forbidden, "PATCH /api/config rejected forbidden key");
        return Err(AppError::BadRequest(format!(
            "PATCH /api/config does not accept '{forbidden}' fields. \
             Use the typed endpoint instead: \
             /api/engine/api-key (POST), /api/engine/model (PUT), \
             /api/engine/provider-options (PUT)."
        )));
    }

    // Snapshot the current config as JSON for both merging and classification.
    let mut current_value = {
        let cfg = state.config.read();
        serde_json::to_value(&*cfg).map_err(|e| {
            tracing::error!(error = %e, "Failed to serialize current config");
            AppError::Internal("failed to serialize current config".into())
        })?
    };

    // Capture the pre-merge value so we can detect which fields actually changed.
    let before_patch = current_value.clone();

    // Deep-merge the patch into the current config.
    deep_merge_json(&mut current_value, body.clone());

    // Classify every changed field into hot-reloadable vs restart-required.
    let mut applied: Vec<String> = Vec::new();
    let mut restart: Vec<String> = Vec::new();
    classify_patch(&before_patch, &body, "", &mut applied, &mut restart);
    applied.sort();
    restart.sort();

    // Validate the merged result.
    let updated: oxios_kernel::OxiosConfig = match serde_json::from_value(current_value.clone()) {
        Ok(cfg) => cfg,
        Err(e) => {
            tracing::warn!(error = %e, "Invalid config shape");
            return Err(AppError::BadRequest(format!("Invalid config: {e}")));
        }
    };
    let (errors, warnings) = updated.validate();
    for w in &warnings {
        tracing::warn!(config_warning = %w, "Config validation warning");
    }
    if !errors.is_empty() {
        let msg = errors.join("; ");
        tracing::warn!(error = %msg, "Config validation failed");
        return Err(AppError::BadRequest(format!("Invalid config: {msg}")));
    }

    // Persist merged config to disk.
    let content = toml::to_string_pretty(&updated)
        .map_err(|e: toml::ser::Error| AppError::Internal(e.to_string()))?;
    if let Err(e) = tokio::fs::write(&state.config_path, content).await {
        tracing::error!(error = %e, "Failed to persist config");
        return Err(AppError::Internal(e.to_string()));
    }
    tracing::info!(path = %state.config_path.display(), "Config persisted");

    // Hot-reload in-memory config.
    *state.config.write() = updated.clone();

    // Propagate hot-reloadable slices to kernel subsystems.
    *state.kernel.exec.shared_config().write() = updated.exec.clone();
    state.kernel.infra.scheduler().update_config(
        updated.scheduler.max_concurrent,
        updated.scheduler.rate_limit_per_minute,
        updated.scheduler.zombie_timeout_secs,
    );
    use oxios_kernel::resource_monitor::OverloadThreshold;
    state
        .kernel
        .infra
        .resource_monitor()
        .set_overload_threshold(OverloadThreshold {
            cpu_percent: updated.resource_monitor.cpu_threshold,
            memory_percent: updated.resource_monitor.memory_threshold,
            load_avg: updated.resource_monitor.load_threshold,
        });

    let total = applied.len() + restart.len();
    tracing::info!(
        applied = applied.len(),
        restart = restart.len(),
        "Config PATCH applied"
    );

    Ok(Json(ConfigPatchResponse {
        config: body,
        hot_reload: HotReloadReport {
            applied_immediately: applied,
            requires_restart: restart,
            total_changed: total,
        },
    }))
}

#[cfg(test)]
mod patch_tests {
    //! Unit tests for the PATCH /api/config hot-reload classification.

    use super::{classify_patch, is_restart_required};
    use serde_json::json;

    #[test]
    fn classify_hot_reloadable_field() {
        let base = json!({"exec": {"allowed_commands": ["ls", "cat"]}});
        let patch = json!({"exec": {"allowed_commands": ["ls", "cat", "rg"]}});
        let mut applied = Vec::new();
        let mut restart = Vec::new();
        classify_patch(&base, &patch, "", &mut applied, &mut restart);
        assert_eq!(applied, vec!["exec.allowed_commands"]);
        assert!(restart.is_empty());
    }

    #[test]
    fn classify_restart_required_field() {
        let base = json!({"gateway": {"port": 4200}});
        let patch = json!({"gateway": {"port": 4300}});
        let mut applied = Vec::new();
        let mut restart = Vec::new();
        classify_patch(&base, &patch, "", &mut applied, &mut restart);
        assert!(applied.is_empty());
        assert_eq!(restart, vec!["gateway.port"]);
    }

    #[test]
    fn classify_mixed_changes() {
        // `exec.allowed_commands` is hot-reloadable, `gateway.port` is not.
        let base = json!({
            "exec": {"allowed_commands": ["ls"]},
            "gateway": {"port": 4200},
        });
        let patch = json!({
            "exec": {"allowed_commands": ["ls", "rg"]},
            "gateway": {"port": 4300},
        });
        let mut applied = Vec::new();
        let mut restart = Vec::new();
        classify_patch(&base, &patch, "", &mut applied, &mut restart);
        applied.sort();
        restart.sort();
        assert_eq!(applied, vec!["exec.allowed_commands"]);
        assert_eq!(restart, vec!["gateway.port"]);
    }

    #[test]
    fn classify_skips_unchanged_fields() {
        // Patch contains a value equal to the base — should not be reported.
        let base = json!({"exec": {"allowed_commands": ["ls"]}});
        let patch = json!({"exec": {"allowed_commands": ["ls"]}});
        let mut applied = Vec::new();
        let mut restart = Vec::new();
        classify_patch(&base, &patch, "", &mut applied, &mut restart);
        assert!(applied.is_empty());
        assert!(restart.is_empty());
    }

    #[test]
    fn classify_recurses_into_nested_objects() {
        // Memory embedding provider change → restart-required.
        let base = json!({
            "memory": {"embedding": {"provider": "gguf", "dimension": 256}}
        });
        let patch = json!({
            "memory": {"embedding": {"provider": "mlx", "dimension": 256}}
        });
        let mut applied = Vec::new();
        let mut restart = Vec::new();
        classify_patch(&base, &patch, "", &mut applied, &mut restart);
        assert!(applied.is_empty());
        assert_eq!(restart, vec!["memory.embedding.provider"]);
    }

    #[test]
    fn unknown_top_level_section_is_restart_required() {
        // `otel` is not in HOT_RELOADABLE_SECTIONS.
        assert!(is_restart_required("otel.enabled"));
        assert!(is_restart_required("otel.endpoint"));
    }

    #[test]
    fn hot_reloadable_sections_are_immediate() {
        // Only sections that `handle_config_patch` actually propagates
        // to the running kernel are marked hot-reloadable. security,
        // audit, etc. are NOT propagated (subsystem constructed at
        // boot) so they must be classified as restart-required.
        assert!(!is_restart_required("exec.allowed_commands"));
        assert!(!is_restart_required("scheduler.max_concurrent"));
        assert!(!is_restart_required("resource_monitor.cpu_threshold"));
    }

    #[test]
    fn security_section_is_restart_required() {
        // security.cors_origins used to be classified hot-reloadable,
        // but AccessManager is constructed at boot. PATCH persists
        // the new value but the running subsystem keeps the boot
        // configuration until restart. Must be classified as
        // restart-required to avoid lying to the user.
        assert!(is_restart_required("security.cors_origins"));
        assert!(is_restart_required("security.auth_enabled"));
        assert!(is_restart_required("security.rate_limit_per_minute"));
    }

    #[test]
    fn audit_section_is_restart_required() {
        // Audit writer is constructed at boot with its rotating file
        // handle. PATCH persists but does not reopen the writer.
        assert!(is_restart_required("audit.max_entries"));
        assert!(is_restart_required("audit.enabled"));
    }

    #[test]
    fn memory_section_is_restart_required() {
        // Memory subsystem is constructed at boot (SQLite handle,
        // embedding model, SONA). Toggling `enabled` or any sub-field
        // is restart-only.
        assert!(is_restart_required("memory.enabled"));
        assert!(is_restart_required("memory.embedding.provider"));
        assert!(is_restart_required("memory.consolidation.dream_enabled"));
        assert!(is_restart_required("memory.learning.sona_enabled"));
    }

    #[test]
    fn channels_telegram_session_requires_restart() {
        // Telegram channel is launched at boot — session changes need restart.
        assert!(is_restart_required(
            "channels.telegram.session.rotation_hours"
        ));
        assert!(is_restart_required("channels.telegram.allowed_users"));
    }

    #[test]
    fn memory_consolidation_preset_requires_restart() {
        // Preset triggers `apply_preset()` which mutates many sibling fields.
        assert!(is_restart_required("memory.consolidation.preset"));
    }
}

#[cfg(test)]
mod patch_rejection_tests {
    //! Engine.* fields must be rejected by PATCH /api/config. They are
    //! managed by the typed engine endpoints (which handle encryption,
    //! masking, and provider-scoped semantics) and sending them via the
    //! bulk PATCH would risk wiping the encrypted api_key.

    use super::{PATCH_FORBIDDEN_TOP_LEVEL_KEYS, find_forbidden_patch_key};
    use serde_json::json;

    #[test]
    fn rejects_engine_api_key() {
        let body = json!({"engine": {"api_key": "sk-secret"}});
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert_eq!(found.as_deref(), Some("engine"));
    }

    #[test]
    fn rejects_engine_provider_options() {
        let body = json!({"engine": {"provider_options": {"temperature": 0.7}}});
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert_eq!(found.as_deref(), Some("engine"));
    }

    #[test]
    fn rejects_engine_default_model() {
        let body = json!({"engine": {"default_model": "anthropic/claude-3"}});
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert_eq!(found.as_deref(), Some("engine"));
    }

    #[test]
    fn accepts_non_engine_sections() {
        let body = json!({
            "exec": {"allowlist_mode": "enforced"},
            "scheduler": {"max_concurrent": 5},
        });
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert!(found.is_none());
    }

    #[test]
    fn accepts_mixed_payload_without_engine() {
        // The check is for the *top-level* `engine` key, not a field
        // anywhere in the body. A nested object containing the word
        // "engine" elsewhere is fine.
        let body = json!({"exec": {"allowed_commands": ["engine-status"]}});
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert!(found.is_none());
    }

    #[test]
    fn empty_body_is_acceptable() {
        let body = json!({});
        let found = find_forbidden_patch_key(&body, PATCH_FORBIDDEN_TOP_LEVEL_KEYS);
        assert!(found.is_none());
    }
}

#[cfg(test)]
mod deep_merge_tests {
    use super::deep_merge_json;
    use serde_json::json;

    #[test]
    fn preserves_omitted_top_level_sections() {
        let mut base = json!({
            "kernel": {"workspace": "~/.oxios/workspace", "max_agents": 10},
            "exec": {"allowed_commands": ["ls", "cat"], "allowlist_mode": "enforced"},
        });
        let patch = json!({
            "kernel": {"max_agents": 20},
        });
        deep_merge_json(&mut base, patch);
        assert_eq!(base["kernel"]["workspace"], "~/.oxios/workspace");
        assert_eq!(base["kernel"]["max_agents"], 20);
        assert_eq!(base["exec"]["allowed_commands"][0], "ls");
        assert_eq!(base["exec"]["allowlist_mode"], "enforced");
    }

    #[test]
    fn patch_value_replaces_scalar() {
        let mut base = json!({"engine": {"default_model": "old/model"}});
        deep_merge_json(&mut base, json!({"engine": {"default_model": "new/model"}}));
        assert_eq!(base["engine"]["default_model"], "new/model");
    }

    #[test]
    fn patch_object_replaces_object() {
        let mut base = json!({"security": {"auth_enabled": false, "cors_origins": ["http://a"]}});
        deep_merge_json(&mut base, json!({"security": {"auth_enabled": true}}));
        assert_eq!(base["security"]["auth_enabled"], true);
        assert_eq!(base["security"]["cors_origins"][0], "http://a");
    }

    #[test]
    fn empty_patch_is_noop() {
        let mut base = json!({"exec": {"allowed_commands": ["ls"]}});
        let original = base.clone();
        deep_merge_json(&mut base, json!({}));
        assert_eq!(base, original);
    }
}

// ---------------------------------------------------------------------------
// System Tools (Doctor, Audit Verify, Backup, Log)
// ---------------------------------------------------------------------------

/// A single diagnostic check result.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct DoctorCheck {
    /// Check name.
    pub name: String,
    /// Status: pass, warn, fail.
    pub status: String,
    /// Human-readable detail.
    pub message: String,
}

/// Response for `POST /api/system/doctor`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct DoctorResponse {
    /// Total checks performed.
    pub checks: u32,
    /// Number of issues found.
    pub issues: u32,
    /// Per-check results.
    pub results: Vec<DoctorCheck>,
    /// List of actionable issues.
    pub action_items: Vec<String>,
}

/// POST /api/system/doctor — Run system diagnostics.
pub(crate) async fn handle_doctor(state: State<Arc<AppState>>) -> Json<DoctorResponse> {
    // Clone what we need from config, don't hold the lock across await points
    let (default_model, api_key, workspace, _daemon_log_dir) = {
        let config = state.config.read();
        (
            config.engine.default_model.clone(),
            config.api_key(),
            config.kernel.workspace.clone(),
            config.daemon.log_dir.clone(),
        )
    };
    let mut results = Vec::new();
    let mut action_items = Vec::new();

    // 1. Config file
    if state.config_path.exists() {
        results.push(DoctorCheck {
            name: "config_file".into(),
            status: "pass".into(),
            message: format!("Config file present ({})", state.config_path.display()),
        });
    } else {
        results.push(DoctorCheck {
            name: "config_file".into(),
            status: "fail".into(),
            message: "Config file missing".into(),
        });
        action_items.push("Config file not found. Run `oxios onboard` to create it.".into());
    }

    // 2. Credentials
    let provider = oxios_kernel::CredentialStore::provider_from_model(&default_model);
    match provider {
        Some(p) => match oxios_kernel::CredentialStore::resolve(p, api_key.as_deref()) {
            Some((_key, source)) => {
                // F11: do not echo any part of the API key — even a
                // 4+4 char preview leaks most of a short key and helps
                // brute-force. Report presence + source only. The
                // `api_key_set` boolean from GET /api/config already
                // tells the frontend whether a key is configured.
                results.push(DoctorCheck {
                    name: "credentials".into(),
                    status: "pass".into(),
                    message: format!("Credentials found (via {source:?})"),
                });
            }
            None => {
                results.push(DoctorCheck {
                    name: "credentials".into(),
                    status: "fail".into(),
                    message: format!("No credentials for provider '{p}'"),
                });
                action_items.push(format!(
                    "No API key for '{p}'. Configure in Settings → Engine."
                ));
            }
        },
        None => {
            results.push(DoctorCheck {
                name: "credentials".into(),
                status: "fail".into(),
                message: "No model configured".into(),
            });
            action_items.push("No model set. Configure in Settings → Engine.".into());
        }
    }

    // 3. Workspace directory
    let workspace = oxios_kernel::config::expand_home(&workspace);
    if workspace.exists() {
        results.push(DoctorCheck {
            name: "workspace".into(),
            status: "pass".into(),
            message: format!("Workspace directory ({})", workspace.display()),
        });
    } else {
        results.push(DoctorCheck {
            name: "workspace".into(),
            status: "warn".into(),
            message: format!("Workspace directory missing ({})", workspace.display()),
        });
        action_items.push("Workspace directory not found. It will be created on first run.".into());
    }

    // 4. Default model
    if !default_model.is_empty() {
        results.push(DoctorCheck {
            name: "model".into(),
            status: "pass".into(),
            message: format!("Default model: {default_model}"),
        });
    } else {
        results.push(DoctorCheck {
            name: "model".into(),
            status: "fail".into(),
            message: "No default model set".into(),
        });
        action_items.push("No default model configured.".into());
    }

    // 5. MCP servers
    let mcp_count = state.kernel.mcp.server_count();
    if mcp_count > 0 {
        results.push(DoctorCheck {
            name: "mcp_servers".into(),
            status: "pass".into(),
            message: format!("{mcp_count} MCP server(s) connected"),
        });
    } else {
        results.push(DoctorCheck {
            name: "mcp_servers".into(),
            status: "warn".into(),
            message: "No MCP servers configured".into(),
        });
    }

    // 6. Git repository
    let git_ok = state.kernel.infra.git_verify().unwrap_or(false);
    if git_ok {
        results.push(DoctorCheck {
            name: "git".into(),
            status: "pass".into(),
            message: "Git repository intact".into(),
        });
    } else {
        results.push(DoctorCheck {
            name: "git".into(),
            status: "warn".into(),
            message: "Git repository verification failed".into(),
        });
    }

    // 7. State store
    let ws_path = state.kernel.state.workspace_path();
    if ws_path.exists() {
        results.push(DoctorCheck {
            name: "state_store".into(),
            status: "pass".into(),
            message: format!("State store path exists ({})", ws_path.display()),
        });
    } else {
        results.push(DoctorCheck {
            name: "state_store".into(),
            status: "warn".into(),
            message: "State store path not found".into(),
        });
    }

    // 8. Memory subsystem
    let (index_size, total) = state.kernel.agents.memory_stats().await;
    results.push(DoctorCheck {
        name: "memory".into(),
        status: "pass".into(),
        message: format!("Memory: {index_size} indexed, {total} total entries"),
    });

    // 9. Web dist directory
    if let Some(web_dist) = state.web_dist.path() {
        if web_dist.exists() {
            results.push(DoctorCheck {
                name: "web_dist".into(),
                status: "pass".into(),
                message: format!("Web UI dist ({})", web_dist.display()),
            });
        } else {
            results.push(DoctorCheck {
                name: "web_dist".into(),
                status: "warn".into(),
                message: "Web UI dist directory not found".into(),
            });
        }
    } else {
        results.push(DoctorCheck {
            name: "web_dist".into(),
            status: "pass".into(),
            message: "Web UI served from embedded assets".into(),
        });
    }

    let checks = results.len() as u32;
    let issues = action_items.len() as u32;

    Json(DoctorResponse {
        checks,
        issues,
        results,
        action_items,
    })
}

/// Response for `POST /api/system/audit-verify`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct AuditVerifyResponse {
    pub valid: bool,
    pub entries_checked: u64,
    pub message: String,
}

/// POST /api/system/audit-verify — Verify audit trail integrity.
pub(crate) async fn handle_audit_verify_api(
    state: State<Arc<AppState>>,
) -> Json<AuditVerifyResponse> {
    let audit = &state.kernel.security;
    match audit.verify_chain() {
        Ok(valid) => Json(AuditVerifyResponse {
            valid,
            entries_checked: 0,
            message: if valid {
                "Audit trail verified successfully.".into()
            } else {
                "Audit trail verification failed.".into()
            },
        }),
        Err(e) => Json(AuditVerifyResponse {
            valid: false,
            entries_checked: 0,
            message: format!("Audit trail verification failed: {e}"),
        }),
    }
}

/// Response for `POST /api/system/backup`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct BackupResponse {
    pub success: bool,
    pub path: String,
    pub size_bytes: u64,
    pub message: String,
}

/// POST /api/system/backup — Create a backup of Oxios state.
pub(crate) async fn handle_backup(_state: State<Arc<AppState>>) -> Json<BackupResponse> {
    let home = match dirs::home_dir() {
        Some(h) => h,
        None => {
            return Json(BackupResponse {
                success: false,
                path: String::new(),
                size_bytes: 0,
                message: "Cannot determine home directory.".into(),
            });
        }
    };
    let oxios_home = home.join(".oxios");

    let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S");
    let backup_name = format!("oxios-backup-{timestamp}.tar.gz");
    let backup_path = oxios_home.join(&backup_name);

    tracing::info!(path = %backup_path.display(), "Creating backup");

    // Use tar command for simplicity
    let output = match tokio::process::Command::new("tar")
        .args([
            "-czf",
            match backup_path.to_str() {
                Some(s) => s,
                None => {
                    return Json(BackupResponse {
                        success: false,
                        path: String::new(),
                        size_bytes: 0,
                        message: "Invalid backup path.".into(),
                    });
                }
            },
            "-C",
            oxios_home.to_str().unwrap_or("."),
            "config.toml",
            "workspace",
            "knowledge",
        ])
        .output()
        .await
    {
        Ok(o) => o,
        Err(e) => {
            return Json(BackupResponse {
                success: false,
                path: String::new(),
                size_bytes: 0,
                message: format!("tar failed: {e}"),
            });
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Json(BackupResponse {
            success: false,
            path: String::new(),
            size_bytes: 0,
            message: format!("Backup failed: {stderr}"),
        });
    }

    let size = std::fs::metadata(&backup_path)
        .map(|m| m.len())
        .unwrap_or(0);

    tracing::info!(
        path = %backup_path.display(),
        size,
        "Backup created"
    );

    Json(BackupResponse {
        success: true,
        path: backup_path.display().to_string(),
        size_bytes: size,
        message: format!(
            "Backup created: {backup_name} ({})",
            format_size_helper(size)
        ),
    })
}

/// Response for `GET /api/system/log`.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct LogResponse {
    pub lines: Vec<String>,
    pub total: usize,
}

/// GET /api/system/log — Read recent daemon log entries.
pub(crate) async fn handle_log(state: State<Arc<AppState>>) -> Json<LogResponse> {
    let log_dir = {
        let config = state.config.read();
        oxios_kernel::config::expand_home(&config.daemon.log_dir)
    };
    let log_file = log_dir.join("oxios.log");

    if !log_file.exists() {
        return Json(LogResponse {
            lines: vec!["No log file found.".into()],
            total: 1,
        });
    }

    // F8: read only a bounded tail of the log so a multi-GB daemon log
    // cannot OOM the server on a single request. We scan at most the last
    // 256 KiB, drop the leading partial line if we seeked into the middle
    // of the file, then take the last 50 lines.
    let (lines, total) = read_log_tail(&log_file, 50, 256 * 1024);

    Json(LogResponse { lines, total })
}

/// Read the last `max_lines` lines from a file, loading at most
/// `max_bytes` into memory. Returns the lines and the total number of
/// lines within the scanned window (approximate for large files — exact
/// only when the whole file fit in the window).
fn read_log_tail(path: &std::path::Path, max_lines: usize, max_bytes: u64) -> (Vec<String>, usize) {
    use std::io::{Read, Seek, SeekFrom};
    let Ok(metadata) = std::fs::metadata(path) else {
        return (Vec::new(), 0);
    };
    let size = metadata.len();
    let Ok(mut file) = std::fs::File::open(path) else {
        return (Vec::new(), 0);
    };

    let window = size.min(max_bytes);
    if size > max_bytes && file.seek(SeekFrom::End(-(window as i64))).is_err() {
        return (Vec::new(), 0);
    }
    let mut bytes = Vec::with_capacity(window as usize);
    if file.read_to_end(&mut bytes).is_err() {
        return (Vec::new(), 0);
    }

    // If we seeked into the middle of the file, drop the first partial
    // line (it may begin mid-UTF-8-char and would be garbled).
    if size > max_bytes
        && let Some(nl) = bytes.iter().position(|&b| b == b'\n')
    {
        bytes.drain(..=nl);
    }

    let content = String::from_utf8_lossy(&bytes);
    let all_lines: Vec<&str> = content.lines().collect();
    let total = all_lines.len();
    let start = all_lines.len().saturating_sub(max_lines);
    let lines = all_lines[start..].iter().map(|s| s.to_string()).collect();
    (lines, total)
}

fn format_size_helper(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{bytes} B")
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    }
}

/// Format milliseconds into a human-readable duration.
fn format_duration(ms: u64) -> String {
    if ms < 1000 {
        format!("{ms}ms")
    } else {
        format!("{:.1}s", ms as f64 / 1000.0)
    }
}

/// Truncate a string to `max_len` characters, appending "..." if needed.
fn truncate_str(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_len - 3).collect();
        format!("{truncated}...")
    }
}