oxios-web 1.2.0

Web dashboard channel for Oxios
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
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::Json;
use serde::{Deserialize, Serialize};

use oxios_kernel::memory::{MemoryEntry, MemoryType};
use oxios_kernel::{SkillEntry, SkillSource, SkillStatus};

use crate::error::AppError;
use crate::routes::{paginate, PageParams};
use crate::server::AppState;

// ---------------------------------------------------------------------------
// Workspace
// ---------------------------------------------------------------------------

/// Query parameters for workspace tree.
#[derive(Debug, Deserialize)]
pub(crate) struct TreeQuery {
    /// Subdirectory to list (optional).
    #[serde(default)]
    pub dir: Option<String>,
}

/// File tree entry.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct TreeEntry {
    /// File or directory name.
    name: String,
    /// Whether this is a directory.
    is_dir: bool,
    /// File size in bytes (0 for directories).
    size: u64,
}

/// GET /api/workspace/tree — File tree of workspace.
pub(crate) async fn handle_workspace_tree(
    state: State<Arc<AppState>>,
    Query(query): Query<TreeQuery>,
) -> Result<Json<Vec<TreeEntry>>, AppError> {
    let base = state.kernel.state.workspace_path();
    let canonical_base = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    let dir = match &query.dir {
        Some(d) => {
            let candidate = base.join(d);
            let canonical = match candidate.canonicalize() {
                Ok(c) => c,
                Err(_) => return Err(AppError::NotFound("directory not found".into())),
            };
            if !canonical.starts_with(&canonical_base) {
                return Err(AppError::Forbidden("path traversal denied".into()));
            }
            canonical
        }
        None => canonical_base,
    };

    let mut entries = Vec::new();
    if let Ok(mut read_dir) = tokio::fs::read_dir(&dir).await {
        while let Ok(Some(entry)) = read_dir.next_entry().await {
            let metadata = match entry.metadata().await {
                Ok(m) => m,
                Err(_) => continue,
            };
            entries.push(TreeEntry {
                name: entry.file_name().to_string_lossy().into_owned(),
                is_dir: metadata.is_dir(),
                size: metadata.len(),
            });
        }
    }

    entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name)));

    Ok(Json(entries))
}

/// GET /api/workspace/file/*path — Read a file.
pub(crate) async fn handle_workspace_file_get(
    state: State<Arc<AppState>>,
    Path(path): Path<String>,
) -> Result<impl IntoResponse, AppError> {
    let base = state.kernel.state.workspace_path();
    let full_path = base.join(&path);

    // Security: ensure the path doesn't escape the workspace
    let canonical_base = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    let canonical_file = match full_path.canonicalize() {
        Ok(p) => p,
        Err(_) => return Err(AppError::NotFound("file not found".into())),
    };

    if !canonical_file.starts_with(&canonical_base) {
        return Err(AppError::Forbidden("path traversal denied".into()));
    }

    match tokio::fs::read_to_string(&canonical_file).await {
        Ok(content) => {
            let mime = guess_mime(&path);
            Ok((
                StatusCode::OK,
                [(axum::http::header::CONTENT_TYPE, mime)],
                content,
            ))
        }
        Err(_) => Err(AppError::NotFound("file not found".into())),
    }
}

/// PUT /api/workspace/file/*path — Write/update a file.
pub(crate) async fn handle_workspace_file_put(
    state: State<Arc<AppState>>,
    Path(path): Path<String>,
    body: String,
) -> Result<(), AppError> {
    // Validate file size (max 1MB)
    const MAX_FILE_SIZE: usize = 1024 * 1024;
    if body.len() > MAX_FILE_SIZE {
        return Err(AppError::PayloadTooLarge {
            size: body.len(),
            limit: MAX_FILE_SIZE,
        });
    }

    let base = state.kernel.state.workspace_path();
    let full_path = base.join(&path);

    // Security: ensure the path doesn't escape the workspace
    let canonical_base = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    if let Some(parent) = full_path.parent() {
        if !parent.exists() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| AppError::Internal(format!("failed to create directory: {e}")))?;
        }
        let canonical_parent = parent
            .canonicalize()
            .map_err(|e| AppError::Internal(format!("failed to resolve path: {e}")))?;
        if !canonical_parent.starts_with(&canonical_base) {
            return Err(AppError::Forbidden("path traversal denied".into()));
        }
    }

    match tokio::fs::write(&full_path, &body).await {
        Ok(_) => {
            tracing::info!(path = %path, "File written");
            Ok(())
        }
        Err(e) => {
            tracing::error!(path = %path, error = %e, "Failed to write file");
            Err(AppError::Internal("failed to write file".into()))
        }
    }
}

// ---------------------------------------------------------------------------
// File Create & Delete
// ---------------------------------------------------------------------------

/// Request body for creating a file.
#[derive(Debug, Deserialize)]
pub(crate) struct CreateFileRequest {
    /// Whether to create a directory instead of a file.
    #[serde(default)]
    pub is_dir: bool,
}

/// POST /api/workspace/file/*path — Create an empty file or directory.
pub(crate) async fn handle_workspace_file_create(
    state: State<Arc<AppState>>,
    Path(path): Path<String>,
    Json(body): Json<CreateFileRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    let base = state.kernel.state.workspace_path();
    let full_path = base.join(&path);

    // Security: path traversal check
    let canonical_base = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    // Ensure parent exists
    if let Some(parent) = full_path.parent() {
        let canonical_parent = parent
            .canonicalize()
            .map_err(|_| AppError::NotFound("parent directory not found".into()))?;
        if !canonical_parent.starts_with(&canonical_base) {
            return Err(AppError::Forbidden("path traversal denied".into()));
        }
    }

    if full_path.exists() {
        return Err(AppError::BadRequest("file already exists".into()));
    }

    if body.is_dir {
        tokio::fs::create_dir_all(&full_path)
            .await
            .map_err(|e| AppError::Internal(format!("failed to create directory: {e}")))?;
    } else {
        // Ensure parent dir exists
        if let Some(parent) = full_path.parent() {
            tokio::fs::create_dir_all(parent).await.ok();
        }
        tokio::fs::write(&full_path, "")
            .await
            .map_err(|e| AppError::Internal(format!("failed to create file: {e}")))?;
    }

    tracing::info!(path = %path, is_dir = body.is_dir, "File created");
    Ok(Json(
        serde_json::json!({ "status": "created", "path": path, "is_dir": body.is_dir }),
    ))
}

/// DELETE /api/workspace/file/*path — Delete a file or empty directory.
pub(crate) async fn handle_workspace_file_delete(
    state: State<Arc<AppState>>,
    Path(path): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    let base = state.kernel.state.workspace_path();
    let full_path = base.join(&path);

    // Security: path traversal check
    let canonical_base = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());
    let canonical = match full_path.canonicalize() {
        Ok(c) => c,
        Err(_) => return Err(AppError::NotFound("file not found".into())),
    };

    if !canonical.starts_with(&canonical_base) {
        return Err(AppError::Forbidden("path traversal denied".into()));
    }

    if canonical.is_dir() {
        // Only delete empty directories
        let mut entries = tokio::fs::read_dir(&canonical)
            .await
            .map_err(|e| AppError::Internal(format!("failed to read directory: {e}")))?;
        if entries
            .next_entry()
            .await
            .map(|e| e.is_some())
            .unwrap_or(true)
        {
            return Err(AppError::BadRequest("directory is not empty".into()));
        }
        tokio::fs::remove_dir(&canonical)
            .await
            .map_err(|e| AppError::Internal(format!("failed to delete directory: {e}")))?;
    } else {
        tokio::fs::remove_file(&canonical)
            .await
            .map_err(|e| AppError::Internal(format!("failed to delete file: {e}")))?;
    }

    tracing::info!(path = %path, "File deleted");
    Ok(Json(
        serde_json::json!({ "status": "deleted", "path": path }),
    ))
}

/// Guess MIME type from file extension.
fn guess_mime(path: &str) -> String {
    match path.rsplit('.').next() {
        Some("md") => "text/markdown; charset=utf-8".into(),
        Some("json") => "application/json".into(),
        Some("toml") => "application/toml".into(),
        Some("yaml" | "yml") => "application/yaml".into(),
        Some("txt") => "text/plain; charset=utf-8".into(),
        Some("html") => "text/html".into(),
        Some("css") => "text/css".into(),
        Some("js") => "application/javascript".into(),
        _ => "text/plain; charset=utf-8".into(),
    }
}

// ---------------------------------------------------------------------------
// Seeds
// ---------------------------------------------------------------------------

/// Seed summary for listing.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct SeedSummary {
    /// Seed unique ID.
    id: String,
    /// The goal of this seed.
    goal: String,
    /// Number of constraints.
    constraints_count: usize,
    /// Creation timestamp.
    created_at: String,
}

/// GET /api/seeds — List Ouroboros seeds.
pub(crate) async fn handle_seeds_list(
    state: State<Arc<AppState>>,
    Query(params): Query<PageParams>,
) -> Json<serde_json::Value> {
    let mut summaries = Vec::new();

    if let Ok(names) = state.kernel.state.list_category("seeds").await {
        for name in names {
            if let Ok(Some(content)) = state.kernel.state.load_markdown("seeds", &name).await {
                // Try to parse as JSON (seeds stored as JSON)
                if let Ok(seed) = serde_json::from_str::<oxios_ouroboros::Seed>(&content) {
                    summaries.push(SeedSummary {
                        id: seed.id.to_string(),
                        goal: seed.goal,
                        constraints_count: seed.constraints.len(),
                        created_at: seed.created_at.to_rfc3339(),
                    });
                } else {
                    // Raw markdown seed
                    summaries.push(SeedSummary {
                        id: name.clone(),
                        goal: content.lines().next().unwrap_or(&name).into(),
                        constraints_count: 0,
                        created_at: String::new(),
                    });
                }
            }
        }
    }

    Json(paginate(&summaries, &params))
}

/// GET /api/seeds/:id — Get a specific seed.
pub(crate) async fn handle_seed_get(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Try JSON first, then markdown
    if let Ok(Some(content)) = state.kernel.state.load_markdown("seeds", &id).await {
        if let Ok(seed) = serde_json::from_str::<oxios_ouroboros::Seed>(&content) {
            return Ok(Json(serde_json::to_value(&seed).unwrap_or_default()));
        }
        return Ok(Json(serde_json::json!({
            "id": id,
            "content": content,
        })));
    }

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

/// Evolution lineage entry for a seed.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct EvolutionEntry {
    /// Seed ID.
    id: String,
    /// Generation number.
    generation: u32,
    /// Goal at this generation.
    goal: String,
    /// Parent seed ID (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    parent_id: Option<String>,
    /// Evaluation score (if evaluated).
    #[serde(skip_serializing_if = "Option::is_none")]
    score: Option<f64>,
    /// Whether evaluation passed.
    #[serde(skip_serializing_if = "Option::is_none")]
    passed: Option<bool>,
}

/// GET /api/seeds/:id/evolution — Get evolution lineage for a seed.
pub(crate) async fn handle_seed_evolution(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<Vec<EvolutionEntry>>, AppError> {
    use oxios_ouroboros::Seed;
    // Helper to build lineage by following parent IDs.
    // Build lineage iteratively using a work stack.
    fn build_lineage_iterative(
        kernel: Arc<oxios_kernel::KernelHandle>,
        seed_id: String,
    ) -> Pin<Box<dyn Future<Output = anyhow::Result<Vec<EvolutionEntry>>> + Send>> {
        Box::pin(async move {
            let mut lineage = Vec::new();
            let mut stack = vec![seed_id];

            while let Some(current_id) = stack.pop() {
                let content = match kernel.state.load_markdown("seeds", &current_id).await {
                    Ok(Some(c)) => c,
                    _ => continue,
                };
                let seed: Seed = match serde_json::from_str(&content) {
                    Ok(s) => s,
                    Err(e) => {
                        tracing::warn!(error = %e, "Skipping invalid seed");
                        continue;
                    }
                };

                // Push parent first so it's processed before children (reversed order).
                if let Some(ref parent_id) = seed.parent_seed_id {
                    stack.push(parent_id.to_string());
                }

                let (score, passed) = {
                    let eval_name = format!("{current_id}-eval");
                    if let Ok(Some(eval_content)) =
                        kernel.state.load_markdown("evals", &eval_name).await
                    {
                        if let Ok(eval) =
                            serde_json::from_str::<oxios_ouroboros::EvaluationResult>(&eval_content)
                        {
                            (Some(eval.score), Some(eval.all_passed()))
                        } else {
                            (None, None)
                        }
                    } else {
                        (None, None)
                    }
                };

                lineage.push(EvolutionEntry {
                    id: seed.id.to_string(),
                    generation: seed.generation,
                    goal: seed.goal,
                    parent_id: seed.parent_seed_id.map(|p| p.to_string()),
                    score,
                    passed,
                });
            }

            lineage.reverse(); // Reverse so parent comes first.
            Ok(lineage)
        })
    }

    match build_lineage_iterative(state.kernel.clone(), id).await {
        Ok(lineage) if !lineage.is_empty() => Ok(Json(lineage)),
        _ => Err(AppError::NotFound("seed evolution not found".into())),
    }
}

// ---------------------------------------------------------------------------
// Skills
// ---------------------------------------------------------------------------

/// Compact a file path for display (replace home dir with ~).
fn compact_path(path: &std::path::Path) -> String {
    if let Some(home) = dirs::home_dir() {
        let home_str = home.to_string_lossy();
        let path_str = path.to_string_lossy();
        if let Some(rest) = path_str.strip_prefix(home_str.as_ref()) {
            return format!("~{rest}");
        }
    }
    path.to_string_lossy().into_owned()
}

/// Convert a SkillEntry to its JSON API representation (RFC-009 §5.1).
fn skill_entry_to_json(entry: &SkillEntry) -> serde_json::Value {
    let meta = entry.metadata.as_ref();
    let source_str = match entry.source {
        SkillSource::Bundled => "bundled",
        SkillSource::Managed => "managed",
        SkillSource::Workspace => "workspace",
    };
    let status_str = match entry.status {
        SkillStatus::Ready => "ready",
        SkillStatus::NeedsSetup => "needs_setup",
        SkillStatus::Disabled => "disabled",
    };

    let requirements = meta
        .map(|m| {
            serde_json::json!({
                "bins": m.requires.bins,
                "anyBins": m.requires.any_bins,
                "env": m.requires.env,
                "config": m.requires.config,
            })
        })
        .unwrap_or(serde_json::json!({
            "bins": [],
            "anyBins": [],
            "env": [],
            "config": [],
        }));

    let missing = serde_json::json!({
        "bins": entry.eligibility.missing_bins,
        "anyBins": entry.eligibility.missing_any_bins,
        "env": entry.eligibility.missing_env,
        "config": entry.eligibility.missing_config,
    });

    let install: Vec<serde_json::Value> = meta
        .map(|m| {
            m.install
                .iter()
                .map(|spec| {
                    let label = match spec.kind {
                        oxios_kernel::InstallKind::Brew => {
                            let name = spec.formula.as_deref().unwrap_or("unknown");
                            format!("Install {name} (brew)")
                        }
                        oxios_kernel::InstallKind::Node => {
                            let name = spec.package.as_deref().unwrap_or("unknown");
                            format!("Install {name} (npm)")
                        }
                        oxios_kernel::InstallKind::Go => {
                            let name = spec.module.as_deref().unwrap_or("unknown");
                            format!("Install {name} (go)")
                        }
                        oxios_kernel::InstallKind::Uv => {
                            let name = spec.package.as_deref().unwrap_or("unknown");
                            format!("Install {name} (uv)")
                        }
                        oxios_kernel::InstallKind::Download => "Download".to_string(),
                    };
                    let bins: Vec<String> = match spec.kind {
                        oxios_kernel::InstallKind::Brew => spec
                            .formula
                            .as_ref()
                            .map(|f| vec![f.clone()])
                            .unwrap_or_default(),
                        oxios_kernel::InstallKind::Node => spec
                            .package
                            .as_ref()
                            .map(|p| vec![p.clone()])
                            .unwrap_or_default(),
                        oxios_kernel::InstallKind::Go => spec
                            .module
                            .as_ref()
                            .map(|m| vec![m.clone()])
                            .unwrap_or_default(),
                        oxios_kernel::InstallKind::Uv => spec
                            .package
                            .as_ref()
                            .map(|p| vec![p.clone()])
                            .unwrap_or_default(),
                        oxios_kernel::InstallKind::Download => vec![],
                    };
                    serde_json::json!({
                        "kind": spec.kind.to_string(),
                        "label": label,
                        "bins": bins,
                    })
                })
                .collect()
        })
        .unwrap_or_default();

    let os = meta.map(|m| m.os.clone()).unwrap_or_default();

    let config_checks: Vec<serde_json::Value> = entry
        .eligibility
        .config_checks
        .iter()
        .map(|c| serde_json::json!({ "path": c.path, "satisfied": c.satisfied }))
        .collect();

    serde_json::json!({
        "name": entry.skill.name,
        "description": entry.skill.description,
        "author": meta.and_then(|m| m.author.clone()).unwrap_or_default(),
        "version": meta.and_then(|m| m.version.clone()).unwrap_or_default(),
        "emoji": meta.and_then(|m| m.emoji.clone()).unwrap_or_default(),
        "homepage": meta.and_then(|m| m.homepage.clone()).unwrap_or_default(),
        "source": source_str,
        "bundled": entry.bundled,
        "status": status_str,
        "eligible": entry.eligibility.eligible,
        "always": meta.map(|m| m.always).unwrap_or(false),
        "user_invocable": entry.invocation.user_invocable,
        "file_path": compact_path(&entry.skill.file_path),
        "requirements": requirements,
        "missing": missing,
        "os": os,
        "install": install,
        "config_checks": config_checks,
        "format": entry.format.to_string(),
    })
}

/// GET /api/skills — List all skills (RFC-009 §5.1).
pub(crate) async fn handle_skills_list(
    state: State<Arc<AppState>>,
    Query(_params): Query<PageParams>,
) -> Json<serde_json::Value> {
    let entries = state.kernel.extensions.list_skills_entries().await;
    let skills: Vec<serde_json::Value> = entries.iter().map(skill_entry_to_json).collect();
    Json(serde_json::json!({ "skills": skills }))
}

/// GET /api/skills/:name — Get skill details (RFC-009 §5.1).
pub(crate) async fn handle_skill_get(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    match state.kernel.extensions.get_skill_entry(&name).await {
        Some(entry) => Ok(Json(skill_entry_to_json(&entry))),
        None => Err(AppError::NotFound("skill not found".into())),
    }
}

/// POST /api/skills/:name/enable — Enable a skill.
pub(crate) async fn handle_skill_enable(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    state
        .kernel
        .extensions
        .enable_skill(&name)
        .await
        .map_err(|e| AppError::BadRequest(e.to_string()))?;
    tracing::info!(skill = %name, "Skill enabled via API");
    Ok(Json(
        serde_json::json!({ "status": "enabled", "name": name }),
    ))
}

/// POST /api/skills/:name/disable — Disable a skill.
pub(crate) async fn handle_skill_disable(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    state
        .kernel
        .extensions
        .disable_skill(&name)
        .await
        .map_err(|e| AppError::BadRequest(e.to_string()))?;
    tracing::info!(skill = %name, "Skill disabled via API");
    Ok(Json(
        serde_json::json!({ "status": "disabled", "name": name }),
    ))
}

/// GET /api/skills/:name/content — Get SKILL.md content.
pub(crate) async fn handle_skill_content(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    let content = state
        .kernel
        .extensions
        .skill_manager()
        .get_skill_content(&name)
        .await;
    match content {
        Some(md) => Ok(Json(serde_json::json!({
            "name": name,
            "content": md,
        }))),
        None => Err(AppError::NotFound("skill not found".into())),
    }
}

/// Request body for creating a skill.
#[derive(Debug, Deserialize)]
pub(crate) struct SkillCreateRequest {
    /// Skill name.
    name: String,
    /// Skill description.
    description: String,
    /// Skill markdown content.
    #[serde(default)]
    content: String,
}

/// POST /api/skills — Create a new skill.
pub(crate) async fn handle_skill_create(
    state: State<Arc<AppState>>,
    Json(body): Json<SkillCreateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Validate skill content size (max 64KB)
    const MAX_SKILL_CONTENT: usize = 64 * 1024;
    if body.content.len() > MAX_SKILL_CONTENT {
        return Err(AppError::PayloadTooLarge {
            size: body.content.len(),
            limit: MAX_SKILL_CONTENT,
        });
    }

    state
        .kernel
        .extensions
        .create_skill(&body.name, &body.description, &body.content)
        .await
        .map_err(|e| {
            tracing::error!(error = %e, skill = %body.name, "Failed to create skill");
            AppError::BadRequest(e.to_string())
        })?;

    tracing::info!(skill = %body.name, "Skill created via API");
    Ok(Json(serde_json::json!({
        "status": "created",
        "name": body.name,
    })))
}

/// DELETE /api/skills/:name — Delete a skill.
pub(crate) async fn handle_skill_delete(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    state
        .kernel
        .extensions
        .delete_skill(&name)
        .await
        .map_err(|e| {
            tracing::error!(error = %e, skill = %name, "Failed to delete skill");
            AppError::BadRequest(e.to_string())
        })?;

    tracing::info!(skill = %name, "Skill deleted via API");
    Ok(Json(serde_json::json!({
        "status": "deleted",
        "name": name,
    })))
}

// ---------------------------------------------------------------------------
// Memory
// ---------------------------------------------------------------------------

/// Memory entry summary.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct MemorySummary {
    /// Entry name.
    name: String,
    /// Category (memory type).
    category: String,
}

/// GET /api/memory — List memory entries.
pub(crate) async fn handle_memory_list(
    state: State<Arc<AppState>>,
    Query(params): Query<PageParams>,
) -> Json<serde_json::Value> {
    let mut entries = Vec::new();

    // List all memory categories
    for category in [
        "memory/facts",
        "memory/episodes",
        "memory/knowledge",
        "memory/sessions",
    ] {
        if let Ok(names) = state.kernel.state.list_category(category).await {
            let cat = category.split('/').nth(1).unwrap_or("fact");
            for name in names {
                entries.push(MemorySummary {
                    name,
                    category: cat.into(),
                });
            }
        }
    }

    Json(paginate(&entries, &params))
}

/// All memory categories the web UI may need to look up. Kept in sync
/// with the iteration order used by `handle_memory_map` and the
/// `MemoryType::category()` map in the kernel.
const MEMORY_CATEGORIES: &[&str] = &[
    "memory/facts",
    "memory/episodes",
    "memory/knowledge",
    "memory/sessions",
    "memory/conversations",
    "memory/skills",
    "memory/preferences",
    "memory/decisions",
    "memory/profiles",
];

/// GET /api/memory/:name — Get a specific memory entry.
pub(crate) async fn handle_memory_get(
    state: State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<impl IntoResponse, AppError> {
    // Memory entries are stored as JSON, not markdown.
    // Try all known memory categories to find the entry.
    for category in MEMORY_CATEGORIES {
        if let Ok(Some(entry)) = state
            .kernel
            .state
            .load::<oxios_kernel::memory::MemoryEntry>(category, &name)
            .await
        {
            return Ok(Json(serde_json::json!({
                "id": entry.id,
                "name": entry.id,
                "category": entry.memory_type.label(),
                "content": entry.content,
                "tags": entry.tags,
                "importance": entry.importance,
                "created_at": entry.created_at.to_rfc3339(),
            }))
            .into_response());
        }
    }

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

// ---------------------------------------------------------------------------
// Memory map (RFC-T1-B): 2D projection + neighbor edges
// ---------------------------------------------------------------------------

/// Cache for memory map projections. Keyed by a coarse epoch (5 minutes)
/// plus the set of memory IDs, so a small memory mutation does not
/// invalidate the cache for every call. The full cache is held in-process
/// (no disk writes); the per-key TTL is short and the projection is
/// cheap enough that we are happy to recompute on TTL expiry.
#[derive(Default, Clone)]
pub struct MemoryMapCache {
    inner: std::sync::Arc<std::sync::Mutex<Option<MemoryMapCacheEntry>>>,
}

#[derive(Clone)]
struct MemoryMapCacheEntry {
    /// Epoch seconds (5-minute resolution).
    epoch: u64,
    /// Sorted ID list that was used to compute the projection.
    ids: Vec<String>,
    /// 64-bit content hash over (id, content_hash, tier, mem_type) for
    /// every entry in the projection. Detects content edits that do not
    /// change the id-set (the projection depends on the actual TF-IDF
    /// vectors, not just the set of entries).
    content_signature: u64,
    /// Pre-computed map entries (coords_2d + neighbors).
    entries: Vec<oxios_kernel::memory::MemoryMapEntry>,
}

impl MemoryMapCache {
    /// Try to get a cached entry. Returns `None` if the epoch is stale,
    /// the ID set has changed, or the per-entry content signature differs.
    fn get(
        &self,
        epoch: u64,
        ids: &[String],
        content_signature: u64,
    ) -> Option<Vec<oxios_kernel::memory::MemoryMapEntry>> {
        let guard = self.inner.lock().ok()?;
        let entry = guard.as_ref()?;
        if entry.epoch != epoch {
            return None;
        }
        if entry.ids != ids {
            return None;
        }
        if entry.content_signature != content_signature {
            return None;
        }
        Some(entry.entries.clone())
    }

    /// Store a fresh entry.
    fn put(
        &self,
        epoch: u64,
        ids: Vec<String>,
        content_signature: u64,
        entries: Vec<oxios_kernel::memory::MemoryMapEntry>,
    ) {
        if let Ok(mut guard) = self.inner.lock() {
            *guard = Some(MemoryMapCacheEntry {
                epoch,
                ids,
                content_signature,
                entries,
            });
        }
    }
}

/// Compute a stable signature over the projection-relevant fields of
/// each entry. Used as part of the memory-map cache key so that an
/// edit to a memory's `content` (which does not change the id set)
/// still invalidates the cache.
fn memory_map_content_signature(entries: &[MemoryEntry]) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    // Sort by id for a stable hash independent of iteration order.
    let mut sorted: Vec<&MemoryEntry> = entries.iter().collect();
    sorted.sort_by(|a, b| a.id.cmp(&b.id));
    for e in sorted {
        e.id.hash(&mut hasher);
        e.content.hash(&mut hasher);
        // tier is a Copy enum; convert to a stable string for hashing.
        let tier_str = match e.tier {
            oxios_kernel::memory::MemoryTier::Hot => "hot",
            oxios_kernel::memory::MemoryTier::Warm => "warm",
            oxios_kernel::memory::MemoryTier::Cold => "cold",
        };
        tier_str.hash(&mut hasher);
        // Use the singular label for parity with `mem_type` filtering.
        e.memory_type.label().hash(&mut hasher);
    }
    hasher.finish()
}

/// Query parameters for the memory map endpoint.
#[derive(Debug, Deserialize)]
pub(crate) struct MemoryMapQuery {
    /// Optional tier filter.
    #[serde(default)]
    pub tier: Option<String>,
    /// Optional memory type filter.
    #[serde(default)]
    pub mem_type: Option<String>,
    /// Max entries to include (default 500, hard cap 2000).
    #[serde(default)]
    pub limit: Option<usize>,
}

/// 5-minute epoch for the memory map cache.
const MEMORY_MAP_EPOCH_SECS: u64 = 300;

/// GET /api/memory/map — 2D projection of memory entries for the Web UI map.
///
/// Returns one [`MemoryMapEntry`] per matching memory, with pre-computed
/// 2D coordinates and top similar neighbors. The projection uses PCA
/// over the in-memory TF-IDF vectors (see `embedding_viz`); results are
/// cached in-process for 5 minutes per (epoch, id-set) tuple.
pub(crate) async fn handle_memory_map(
    state: State<Arc<AppState>>,
    Query(params): Query<MemoryMapQuery>,
) -> Result<Json<serde_json::Value>, AppError> {
    let limit = params.limit.unwrap_or(500).clamp(1, 2000);

    // Load matching entries from state store. We deliberately bypass the
    // in-memory vector index here because the index may not include
    // entries that were stored by other channels (e.g. compaction).
    let mut entries: Vec<MemoryEntry> = Vec::new();
    for category in [
        "memory/facts",
        "memory/episodes",
        "memory/knowledge",
        "memory/sessions",
        "memory/conversations",
        "memory/skills",
        "memory/preferences",
        "memory/decisions",
        "memory/profiles",
    ] {
        let Ok(names) = state.kernel.state.list_category(category).await else {
            continue;
        };
        for name in names {
            if entries.len() >= limit {
                break;
            }
            let Ok(Some(entry)) = state
                .kernel
                .state
                .load::<MemoryEntry>(category, &name)
                .await
            else {
                continue;
            };
            // Per-entry filters: `mem_type` matches the singular label()
            // (e.g. "fact") returned by the frontend, NOT the plural
            // category short name ("facts"). The `tier` filter is
            // matched in the same place for symmetry.
            if let Some(ref want) = params.mem_type {
                if entry.memory_type.label() != want.as_str() {
                    continue;
                }
            }
            if let Some(ref want_tier) = params.tier {
                let tier_str = match entry.tier {
                    oxios_kernel::memory::MemoryTier::Hot => "hot",
                    oxios_kernel::memory::MemoryTier::Warm => "warm",
                    oxios_kernel::memory::MemoryTier::Cold => "cold",
                };
                if tier_str != want_tier.as_str() {
                    continue;
                }
            }
            entries.push(entry);
        }
        if entries.len() >= limit {
            break;
        }
    }

    // Cap again (in case we broke out of the inner loop early).
    entries.truncate(limit);

    // Compute 2D projection + neighbors.
    let map_entries = compute_memory_map_entries(&state, &entries).await;

    Ok(Json(serde_json::json!({
        "count": map_entries.len(),
        "epoch": current_epoch_secs() / MEMORY_MAP_EPOCH_SECS,
        "entries": map_entries,
    })))
}

/// Compute (or fetch from cache) the MemoryMapEntry list for a given
/// set of MemoryEntry values.
async fn compute_memory_map_entries(
    state: &Arc<AppState>,
    entries: &[MemoryEntry],
) -> Vec<oxios_kernel::memory::MemoryMapEntry> {
    use oxios_kernel::embedding::EmbeddingProvider;
    use oxios_kernel::memory::{compute_pca_2d, compute_top_neighbors, MemoryMapEntry};

    if entries.is_empty() {
        return Vec::new();
    }

    let ids: Vec<String> = entries.iter().map(|e| e.id.clone()).collect();
    let epoch = current_epoch_secs() / MEMORY_MAP_EPOCH_SECS;
    let content_signature = memory_map_content_signature(entries);

    // Cache lookup.
    if let Some(cached) = state.memory_map_cache.get(epoch, &ids, content_signature) {
        return cached;
    }

    // Build embeddings via the kernel's TF-IDF provider. We collapse
    // the term-frequency map to a sorted (term, weight) list, then
    // encode as a sparse f32 vector keyed by term index for PCA.
    let provider = oxios_kernel::embedding::TfIdfEmbeddingProvider;
    let mut term_index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
    let mut tf_vecs: Vec<Vec<(u32, f32)>> = Vec::with_capacity(entries.len());
    for entry in entries {
        let Ok(emb) = provider.embed(&entry.content).await else {
            tf_vecs.push(Vec::new());
            continue;
        };
        let oxios_kernel::embedding::EmbeddingVector::Sparse(tf) = emb else {
            // Dense vectors are also fine, but rare on the TF-IDF path.
            tf_vecs.push(Vec::new());
            continue;
        };
        let mut pairs: Vec<(u32, f32)> = tf
            .into_iter()
            .map(|(term, w)| {
                let next = term_index.len() as u32;
                let idx = *term_index.entry(term).or_insert(next);
                (idx, w as f32)
            })
            .collect();
        pairs.sort_by_key(|(idx, _)| *idx);
        // De-duplicate by index (sum weights if a term somehow appears twice).
        pairs.dedup_by_key(|(idx, _)| *idx);
        tf_vecs.push(pairs);
    }

    // Convert sparse pairs to dense f32 vectors aligned to `term_index`.
    let dim = term_index.len();
    let dense: Vec<Vec<f32>> = tf_vecs
        .iter()
        .map(|pairs| {
            let mut v = vec![0.0_f32; dim];
            for (idx, w) in pairs {
                if let Some(slot) = v.get_mut(*idx as usize) {
                    *slot = *w;
                }
            }
            v
        })
        .collect();

    // Project to 2D and compute neighbor lists.
    let coords = compute_pca_2d(&dense);
    let top_n = compute_top_neighbors(&dense, &ids, 5, 0.7);

    let map_entries: Vec<MemoryMapEntry> = entries
        .iter()
        .zip(coords.iter().zip(top_n.iter()))
        .map(|(entry, (xy, nbrs))| MemoryMapEntry {
            id: entry.id.clone(),
            tier: match entry.tier {
                oxios_kernel::memory::MemoryTier::Hot => "hot".into(),
                oxios_kernel::memory::MemoryTier::Warm => "warm".into(),
                oxios_kernel::memory::MemoryTier::Cold => "cold".into(),
            },
            mem_type: entry.memory_type.label().to_string(),
            content_preview: content_preview(&entry.content, 120),
            created_at: entry.created_at.to_rfc3339(),
            access_count: entry.access_count,
            coords_2d: *xy,
            top_neighbors: nbrs.clone(),
        })
        .collect();

    state
        .memory_map_cache
        .put(epoch, ids, content_signature, map_entries.clone());

    map_entries
}

/// Truncate content to a short preview suitable for hover tooltips.
fn content_preview(content: &str, max_chars: usize) -> String {
    let trimmed: String = content.chars().take(max_chars).collect();
    if content.chars().count() > max_chars {
        format!("{trimmed}\u{2026}")
    } else {
        trimmed
    }
}

/// Current wall-clock time as Unix seconds.
fn current_epoch_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

// ---------------------------------------------------------------------------
// Memory CRUD
// ---------------------------------------------------------------------------

/// Request body for creating a memory entry.
#[derive(Debug, Deserialize)]
pub(crate) struct MemoryCreateRequest {
    /// Memory content.
    content: String,
    /// Memory type: fact, episode, or knowledge.
    #[serde(default = "default_memory_type")]
    memory_type: String,
    /// Tags for search.
    #[serde(default)]
    tags: Vec<String>,
    /// Importance (0.0-1.0).
    #[serde(default = "default_importance")]
    importance: f32,
}

fn default_memory_type() -> String {
    "fact".to_string()
}

fn default_importance() -> f32 {
    0.5
}

/// POST /api/memory — Create a memory entry.
pub(crate) async fn handle_memory_create(
    state: State<Arc<AppState>>,
    Json(body): Json<MemoryCreateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Validate memory entry size (max 32KB)
    const MAX_MEMORY_ENTRY: usize = 32 * 1024;
    if body.content.len() > MAX_MEMORY_ENTRY {
        return Err(AppError::PayloadTooLarge {
            size: body.content.len(),
            limit: MAX_MEMORY_ENTRY,
        });
    }

    let memory_type = match body.memory_type.as_str() {
        "fact" => MemoryType::Fact,
        "episode" => MemoryType::Episode,
        "knowledge" => MemoryType::Knowledge,
        _ => {
            return Err(AppError::BadRequest(
                "memory_type must be fact, episode, or knowledge".into(),
            ))
        }
    };
    let entry = MemoryEntry {
        id: uuid::Uuid::new_v4().to_string(),
        memory_type,
        tier: memory_type.initial_tier(),
        content: body.content.clone(),
        content_hash: oxios_kernel::memory::content_hash(&body.content),
        source: "api".to_string(),
        session_id: None,
        tags: body.tags.clone(),
        importance: body.importance,
        pinned: false,
        protection: oxios_kernel::memory::ProtectionLevel::None,
        auto_classified: false,
        session_appearances: 0,
        user_corrected: false,
        seen_in_sessions: vec![],
        created_at: chrono::Utc::now(),
        accessed_at: chrono::Utc::now(),
        modified_at: chrono::Utc::now(),
        access_count: 0,
        decay_score: 1.0,
        compaction_level: 0,
        compacted_from: vec![],
        related_ids: vec![],
        contradicts: None,
    };

    // Use memory manager from kernel
    let id = state
        .kernel
        .agents
        .remember(entry)
        .await
        .map_err(|e| AppError::Internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "id": id, "status": "created" })))
}

#[derive(Debug, Deserialize)]
pub(crate) struct MemorySearchRequest {
    query: String,
    memory_type: Option<String>,
    limit: Option<usize>,
}

/// POST /api/memory/search — Search memory entries.
pub(crate) async fn handle_memory_search(
    state: State<Arc<AppState>>,
    Json(body): Json<MemorySearchRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    let type_filter = body.memory_type.as_deref().and_then(|s| match s {
        "conversation" => Some(MemoryType::Conversation),
        "session" => Some(MemoryType::Session),
        "fact" => Some(MemoryType::Fact),
        "episode" => Some(MemoryType::Episode),
        "knowledge" => Some(MemoryType::Knowledge),
        _ => None,
    });
    let limit = body.limit.unwrap_or(10);

    // Use memory manager from kernel
    let entries = state
        .kernel
        .agents
        .search_memory(&body.query, type_filter, limit)
        .await
        .map_err(|e| AppError::Internal(e.to_string()))?;
    let results: Vec<serde_json::Value> = entries
        .iter()
        .map(|e| {
            serde_json::json!({
                "id": e.id,
                "type": e.memory_type.label(),
                "content": e.content,
                "tags": e.tags,
                "importance": e.importance,
                "created_at": e.created_at.to_rfc3339(),
            })
        })
        .collect();
    Ok(Json(
        serde_json::json!({ "count": results.len(), "entries": results }),
    ))
}

// ---------------------------------------------------------------------------
// Semantic search (HNSW-powered)
// ---------------------------------------------------------------------------

/// Request body for semantic search.
#[derive(Debug, Deserialize)]
pub(crate) struct SemanticSearchRequest {
    query: String,
    memory_type: Option<String>,
    limit: Option<usize>,
}

/// POST /api/memory/semantic — Semantic search using HNSW index.
///
/// Uses approximate nearest neighbor search for fast,
/// high-quality similarity matching.
pub(crate) async fn handle_memory_semantic_search(
    state: State<Arc<AppState>>,
    Json(body): Json<SemanticSearchRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    let type_filter = body.memory_type.as_deref().and_then(|s| match s {
        "conversation" => Some(MemoryType::Conversation),
        "session" => Some(MemoryType::Session),
        "fact" => Some(MemoryType::Fact),
        "episode" => Some(MemoryType::Episode),
        "knowledge" => Some(MemoryType::Knowledge),
        _ => None,
    });
    let limit = body.limit.unwrap_or(10);

    // Use semantic search from kernel (HNSW-powered)
    let hits = state
        .kernel
        .agents
        .semantic_search_memory(&body.query, type_filter, limit)
        .await
        .map_err(|e| AppError::Internal(e.to_string()))?;

    let results: Vec<serde_json::Value> = hits
        .iter()
        .map(|hit| {
            serde_json::json!({
                "id": hit.entry.id,
                "type": hit.entry.memory_type.label(),
                "content": hit.entry.content,
                "tags": hit.entry.tags,
                "importance": hit.entry.importance,
                "similarity": hit.similarity,
                "distance": hit.distance,
                "created_at": hit.entry.created_at.to_rfc3339(),
            })
        })
        .collect();

    Ok(Json(serde_json::json!({
        "count": results.len(),
        "entries": results,
        "engine": "hnsw",
    })))
}

// ---------------------------------------------------------------------------
// Memory stats, pin, delete, dream
// ---------------------------------------------------------------------------

/// GET /api/memory/stats — Aggregate memory statistics.
#[allow(dead_code)]
pub(crate) async fn handle_memory_stats(
    state: State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, AppError> {
    let (_index_size, _total) = state.kernel.agents.memory_stats().await;

    // Count by category
    let mut by_type = serde_json::Map::new();
    let mut count = 0usize;
    for category in [
        "memory/facts",
        "memory/episodes",
        "memory/knowledge",
        "memory/sessions",
    ] {
        if let Ok(names) = state.kernel.state.list_category(category).await {
            let cat = category.split('/').nth(1).unwrap_or("unknown");
            by_type.insert(
                cat.to_string(),
                serde_json::Value::Number(names.len().into()),
            );
            count += names.len();
        }
    }

    Ok(Json(serde_json::json!({
        "total": count,
        "by_tier": { "hot": 0, "warm": count, "cold": 0 },
        "by_type": by_type,
        "by_protection": { "none": count, "low": 0, "medium": 0, "high": 0, "permanent": 0 },
        "dream": {
            "status": "idle",
            "last_run": null,
            "last_report_id": null,
        }
    })))
}

/// Request body for pinning a memory entry.
#[derive(Debug, Deserialize)]
pub(crate) struct PinRequest {
    pinned: bool,
}

/// PUT /api/memory/{id}/pin — Toggle pin status on a memory entry.
#[allow(dead_code)]
pub(crate) async fn handle_memory_pin(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(body): Json<PinRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    for category in [
        "memory/facts",
        "memory/episodes",
        "memory/knowledge",
        "memory/sessions",
    ] {
        if let Ok(Some(mut entry)) = state.kernel.state.load::<MemoryEntry>(category, &id).await {
            entry.pinned = body.pinned;
            state
                .kernel
                .state
                .save(category, &id, &entry)
                .await
                .map_err(|e| AppError::Internal(e.to_string()))?;
            return Ok(Json(serde_json::json!({ "id": id, "pinned": body.pinned })));
        }
    }
    Err(AppError::NotFound("memory entry not found".into()))
}

/// DELETE /api/memory/{id} — Delete a memory entry.
#[allow(dead_code)]
pub(crate) async fn handle_memory_delete(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    for category in [
        "memory/facts",
        "memory/episodes",
        "memory/knowledge",
        "memory/sessions",
    ] {
        if let Ok(Some(_)) = state
            .kernel
            .state
            .load::<serde_json::Value>(category, &id)
            .await
        {
            state
                .kernel
                .state
                .delete(category, &id)
                .await
                .map_err(|e| AppError::Internal(e.to_string()))?;
            return Ok(Json(serde_json::json!({ "id": id, "deleted": true })));
        }
    }
    Err(AppError::NotFound("memory entry not found".into()))
}

/// GET /api/memory/dream/reports — List dream reports.
#[allow(dead_code)]
pub(crate) async fn handle_dream_reports(_state: State<Arc<AppState>>) -> Json<serde_json::Value> {
    // Placeholder — return empty list until dream persistence is implemented
    Json(serde_json::json!({ "reports": [] }))
}

/// GET /api/memory/dream/status — Dream status.
#[allow(dead_code)]
pub(crate) async fn handle_dream_status(_state: State<Arc<AppState>>) -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "status": "idle",
        "last_run": null,
        "checkpoint_exists": false,
    }))
}

// ---------------------------------------------------------------------------
// Seed agents
// ---------------------------------------------------------------------------

/// GET /api/seeds/{id}/agents — List agents spawned from this seed.
#[allow(dead_code)]
pub(crate) async fn handle_seed_agents(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    let agents = state
        .kernel
        .agents
        .list()
        .await
        .map_err(|e| AppError::Internal(e.to_string()))?;
    let filtered: Vec<serde_json::Value> = agents
        .into_iter()
        .filter(|a| a.seed_id.as_ref().map(|s| s.to_string()) == Some(id.clone()))
        .map(|a| {
            serde_json::json!({
                "id": a.id.to_string(),
                "name": a.name,
                "status": a.status.to_string(),
                "steps_completed": 0,
                "created_at": a.created_at.to_rfc3339(),
            })
        })
        .collect();
    Ok(Json(serde_json::json!({ "agents": filtered })))
}

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

    // -----------------------------------------------------------------------
    // TreeEntry serialization
    // -----------------------------------------------------------------------

    #[test]
    fn test_tree_entry_serialization() {
        let entry = TreeEntry {
            name: "hello.md".into(),
            is_dir: false,
            size: 1024,
        };
        let json = serde_json::to_value(&entry).unwrap();
        assert_eq!(json["name"], "hello.md");
        assert_eq!(json["is_dir"], false);
        assert_eq!(json["size"], 1024);

        let dir_entry = TreeEntry {
            name: "src".into(),
            is_dir: true,
            size: 0,
        };
        let json = serde_json::to_value(&dir_entry).unwrap();
        assert_eq!(json["is_dir"], true);
        assert_eq!(json["size"], 0);
    }

    // -----------------------------------------------------------------------
    // Pagination
    // -----------------------------------------------------------------------

    #[test]
    fn test_pagination_bounds() {
        let items: Vec<i32> = (1..=10).collect();

        // Page 1, limit 3 → items [1, 2, 3]
        let p1 = PageParams { page: 1, limit: 3 };
        let result = paginate(&items, &p1);
        assert_eq!(result["total"], 10);
        assert_eq!(result["page"], 1);
        assert_eq!(result["limit"], 3);
        let returned: Vec<i32> = serde_json::from_value(result["items"].clone()).unwrap();
        assert_eq!(returned, vec![1, 2, 3]);

        // Page 4, limit 3 → items [10]
        let p4 = PageParams { page: 4, limit: 3 };
        let result = paginate(&items, &p4);
        let returned: Vec<i32> = serde_json::from_value(result["items"].clone()).unwrap();
        assert_eq!(returned, vec![10]);

        // Page 0 (underflow) → offset wraps to 0 via saturating_sub
        let p0 = PageParams { page: 0, limit: 3 };
        let result = paginate(&items, &p0);
        let returned: Vec<i32> = serde_json::from_value(result["items"].clone()).unwrap();
        assert_eq!(returned, vec![1, 2, 3]);

        // Limit capped at 500
        let big = PageParams {
            page: 1,
            limit: 9999,
        };
        let result = paginate(&items, &big);
        assert_eq!(result["limit"], 500);
    }

    // -----------------------------------------------------------------------
    // MIME guessing
    // -----------------------------------------------------------------------

    #[test]
    fn test_guess_mime_common_types() {
        assert_eq!(guess_mime("main.rs"), "text/plain; charset=utf-8");
        assert_eq!(guess_mime("Cargo.toml"), "application/toml");
        assert_eq!(guess_mime("README.md"), "text/markdown; charset=utf-8");
        assert_eq!(guess_mime("data.json"), "application/json");
        assert_eq!(guess_mime("app.js"), "application/javascript");
        assert_eq!(guess_mime("index.html"), "text/html");
        assert_eq!(guess_mime("unknown.bin"), "text/plain; charset=utf-8");
    }

    // -----------------------------------------------------------------------
    // Memory type validation
    // -----------------------------------------------------------------------

    #[test]
    fn test_memory_type_validation() {
        // Valid types — these should map to MemoryType variants correctly.
        let valid = vec!["fact", "episode", "knowledge"];
        for t in valid {
            let mt = match t {
                "fact" => Some(MemoryType::Fact),
                "episode" => Some(MemoryType::Episode),
                "knowledge" => Some(MemoryType::Knowledge),
                _ => None,
            };
            assert!(mt.is_some(), "expected '{t}' to be a valid memory type");
        }

        // Invalid types should not match any variant.
        let invalid = vec!["invalid", "", "FACT", "EpIsOdE"];
        for t in invalid {
            let mt: Option<MemoryType> = match t {
                "fact" => Some(MemoryType::Fact),
                "episode" => Some(MemoryType::Episode),
                "knowledge" => Some(MemoryType::Knowledge),
                _ => None,
            };
            assert!(mt.is_none(), "expected '{t}' to be rejected");
        }
    }

    // -----------------------------------------------------------------------
    // File size limit enforcement
    // -----------------------------------------------------------------------

    #[test]
    fn test_file_size_limit_enforcement() {
        // MAX_FILE_SIZE in handle_workspace_file_put is 1MB.
        const MAX_FILE_SIZE: usize = 1024 * 1024;

        // A body exactly at the limit should be accepted by the size check.
        let body_at_limit = "x".repeat(MAX_FILE_SIZE);
        assert_eq!(body_at_limit.len(), MAX_FILE_SIZE);
        assert!(body_at_limit.len() <= MAX_FILE_SIZE);

        // A body one byte over the limit should be rejected.
        let body_over_limit = "x".repeat(MAX_FILE_SIZE + 1);
        assert!(body_over_limit.len() > MAX_FILE_SIZE);

        // Simulate the check done in handle_workspace_file_put:
        // if body.len() > MAX_FILE_SIZE { return PayloadTooLarge }
        assert!(body_over_limit.len() > MAX_FILE_SIZE);

        // Skill content limit (64KB)
        const MAX_SKILL_CONTENT: usize = 64 * 1024;
        let big_skill = "a".repeat(MAX_SKILL_CONTENT + 1);
        assert!(big_skill.len() > MAX_SKILL_CONTENT);

        // Memory entry limit (32KB)
        const MAX_MEMORY_ENTRY: usize = 32 * 1024;
        let big_memory = "m".repeat(MAX_MEMORY_ENTRY + 1);
        assert!(big_memory.len() > MAX_MEMORY_ENTRY);
    }

    // -----------------------------------------------------------------------
    // MemoryMapCache (RFC-T1-B)
    // -----------------------------------------------------------------------

    fn make_entry(id: &str) -> oxios_kernel::memory::MemoryMapEntry {
        oxios_kernel::memory::MemoryMapEntry {
            id: id.into(),
            tier: "hot".into(),
            mem_type: "fact".into(),
            content_preview: "x".into(),
            created_at: "2026-06-04T00:00:00Z".into(),
            access_count: 0,
            coords_2d: (0.0, 0.0),
            top_neighbors: vec![],
        }
    }

    fn make_memory_entry(
        id: &str,
        content: &str,
        tier: oxios_kernel::memory::MemoryTier,
        mem_type: oxios_kernel::memory::MemoryType,
    ) -> MemoryEntry {
        MemoryEntry {
            id: id.into(),
            memory_type: mem_type,
            tier,
            content: content.into(),
            content_hash: oxios_kernel::memory::content_hash(content),
            source: "test".into(),
            session_id: None,
            tags: vec![],
            importance: 0.5,
            pinned: false,
            protection: oxios_kernel::memory::ProtectionLevel::None,
            auto_classified: false,
            session_appearances: 0,
            user_corrected: false,
            seen_in_sessions: vec![],
            created_at: chrono::Utc::now(),
            accessed_at: chrono::Utc::now(),
            modified_at: chrono::Utc::now(),
            access_count: 0,
            decay_score: 1.0,
            compaction_level: 0,
            compacted_from: vec![],
            related_ids: vec![],
            contradicts: None,
        }
    }

    #[test]
    fn test_memory_map_cache_misses_on_empty() {
        let cache = MemoryMapCache::default();
        assert!(cache.get(0, &[], 0).is_none());
    }

    #[test]
    fn test_memory_map_cache_round_trip() {
        let cache = MemoryMapCache::default();
        let ids = vec!["a".to_string(), "b".to_string()];
        let entries = vec![
            oxios_kernel::memory::MemoryMapEntry {
                id: "a".into(),
                tier: "hot".into(),
                mem_type: "fact".into(),
                content_preview: "alpha".into(),
                created_at: "2026-06-04T00:00:00Z".into(),
                access_count: 1,
                coords_2d: (0.0, 0.0),
                top_neighbors: vec![],
            },
            oxios_kernel::memory::MemoryMapEntry {
                id: "b".into(),
                tier: "warm".into(),
                mem_type: "episode".into(),
                content_preview: "beta".into(),
                created_at: "2026-06-04T00:00:00Z".into(),
                access_count: 2,
                coords_2d: (0.5, -0.5),
                top_neighbors: vec![oxios_kernel::memory::MemoryNeighbor {
                    id: "a".into(),
                    similarity: 0.81,
                }],
            },
        ];
        let entries_for_sig = vec![
            make_memory_entry(
                "a",
                "alpha",
                oxios_kernel::memory::MemoryTier::Hot,
                oxios_kernel::memory::MemoryType::Fact,
            ),
            make_memory_entry(
                "b",
                "beta",
                oxios_kernel::memory::MemoryTier::Warm,
                oxios_kernel::memory::MemoryType::Episode,
            ),
        ];
        let sig = memory_map_content_signature(&entries_for_sig);
        cache.put(42, ids.clone(), sig, entries.clone());
        let got = cache.get(42, &ids, sig).expect("hit");
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].id, "a");
        assert_eq!(got[1].top_neighbors[0].similarity, 0.81);
    }

    #[test]
    fn test_memory_map_cache_stale_epoch_misses() {
        let cache = MemoryMapCache::default();
        let ids = vec!["a".to_string()];
        cache.put(1, ids.clone(), 0, vec![make_entry("a")]);
        assert!(cache.get(2, &ids, 0).is_none());
    }

    #[test]
    fn test_memory_map_cache_id_change_misses() {
        let cache = MemoryMapCache::default();
        let ids_a = vec!["a".to_string()];
        cache.put(1, ids_a.clone(), 0, vec![make_entry("a")]);
        // Same epoch, different id set => miss.
        let ids_b = vec!["a".to_string(), "b".to_string()];
        assert!(cache.get(1, &ids_b, 0).is_none());
    }

    #[test]
    fn test_memory_map_cache_content_change_misses() {
        // P1-1: editing a memory's `content` (which does not change the
        // id-set) must invalidate the cache. The signature is computed
        // from the content text, so any content edit changes the hash.
        let cache = MemoryMapCache::default();
        let ids = vec!["a".to_string()];
        let original = make_memory_entry(
            "a",
            "original content",
            oxios_kernel::memory::MemoryTier::Hot,
            oxios_kernel::memory::MemoryType::Fact,
        );
        let edited = make_memory_entry(
            "a",
            "edited content",
            oxios_kernel::memory::MemoryTier::Hot,
            oxios_kernel::memory::MemoryType::Fact,
        );
        let sig_original = memory_map_content_signature(&[original]);
        let sig_edited = memory_map_content_signature(&[edited]);
        assert_ne!(
            sig_original, sig_edited,
            "signature must differ when only the content changes"
        );
        cache.put(1, ids.clone(), sig_original, vec![make_entry("a")]);
        // Same epoch, same id-set, but content changed => miss.
        assert!(cache.get(1, &ids, sig_edited).is_none());
        // Original signature still hits (defensive).
        assert!(cache.get(1, &ids, sig_original).is_some());
    }

    #[test]
    fn test_memory_map_content_signature_is_stable_under_reorder() {
        // The signature is order-independent so iteration order from
        // StateStore does not flip the cache key.
        let a = make_memory_entry(
            "a",
            "alpha",
            oxios_kernel::memory::MemoryTier::Hot,
            oxios_kernel::memory::MemoryType::Fact,
        );
        let b = make_memory_entry(
            "b",
            "beta",
            oxios_kernel::memory::MemoryTier::Warm,
            oxios_kernel::memory::MemoryType::Episode,
        );
        let s1 = memory_map_content_signature(&[a.clone(), b.clone()]);
        let s2 = memory_map_content_signature(&[b, a]);
        assert_eq!(s1, s2);
    }

    #[test]
    fn test_content_preview_truncates_with_ellipsis() {
        let long = "x".repeat(200);
        let preview = content_preview(&long, 120);
        assert_eq!(preview.chars().count(), 121); // 120 + ellipsis
        assert!(preview.ends_with('\u{2026}'));
    }

    #[test]
    fn test_content_preview_keeps_short_content() {
        let preview = content_preview("hello", 120);
        assert_eq!(preview, "hello");
    }

    #[test]
    fn test_content_preview_handles_empty() {
        let preview = content_preview("", 120);
        assert_eq!(preview, "");
    }

    // -----------------------------------------------------------------------
    // handle_memory_map filter (P0-1)
    // -----------------------------------------------------------------------
    //
    // The per-entry mem_type filter must compare against
    // `MemoryType::label()` (singular: "fact", "episode", "knowledge", …),
    // NOT the plural category short name ("facts", "episodes", …).
    // The category short name is "memory/facts" → "facts" (plural), so
    // a `params.mem_type = "fact"` filter must NOT match it.
    //
    // The 4-category vs 9-category scoping is tested at the route level
    // (would require a full AppState harness); here we pin the label()
    // values that the filter must use.

    #[test]
    fn test_memory_type_labels_match_filter_strings() {
        // Every singular label here is what the frontend `<Select>`
        // submits as `params.mem_type`. The filter must accept all of
        // these against entries of the corresponding type.
        let cases = [
            (MemoryType::Fact, "fact"),
            (MemoryType::Episode, "episode"),
            (MemoryType::Knowledge, "knowledge"),
            (MemoryType::Skill, "skill"),
            (MemoryType::Preference, "preference"),
            (MemoryType::Decision, "decision"),
            (MemoryType::Conversation, "conversation"),
            (MemoryType::Session, "session"),
            (MemoryType::UserProfile, "user_profile"),
        ];
        for (mt, label) in cases {
            assert_eq!(
                mt.label(),
                label,
                "{mt:?} label must be the singular {label} (not the plural category)"
            );
            // Category short name is the plural — confirm they differ
            // for every type except `Knowledge` (where they accidentally
            // coincide; that is the only case the old, broken code
            // happened to handle correctly).
            let cat_short = mt.category().split('/').nth(1).unwrap_or("");
            if mt != MemoryType::Knowledge {
                assert_ne!(
                    cat_short, label,
                    "category short name ({cat_short}) must not equal label ({label})"
                );
            }
        }
    }
}