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
use std::collections::HashMap;
use std::sync::Arc;

use axum::Json;
use axum::extract::{Path, Query};
use axum::extract::{
    State, WebSocketUpgrade,
    ws::{Message, WebSocket},
};
use axum::response::IntoResponse;
use futures_util::{SinkExt, StreamExt as FuturesStreamExt};
use serde::{Deserialize, Serialize};

use oxios_gateway::message::IncomingMessage;

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

// ---------------------------------------------------------------------------
// Chat
// ---------------------------------------------------------------------------

/// Request body for the chat endpoint.
#[derive(Debug, Deserialize)]
pub(crate) struct ChatRequest {
    /// The user's message content.
    #[serde(alias = "message")]
    content: String,
    /// Optional user identifier (defaults to "default").
    #[serde(default = "default_user")]
    user_id: String,
    /// Optional session ID for multi-turn conversations.
    #[serde(default)]
    session_id: String,
    /// Optional space ID for context partitioning.
    #[serde(default)]
    project_id: String,
    /// RFC-025: comma-separated Mount IDs to bind (primary first).
    #[serde(default)]
    mount_ids: String,
}

pub(crate) fn default_user() -> String {
    "default".into()
}

/// Response body for the chat endpoint.
#[derive(Debug, Serialize)]
pub(crate) struct ChatResponse {
    /// The message ID.
    id: String,
    /// Echo of the user's message.
    echo: String,
    /// The response from the orchestrator.
    reply: String,
    /// Session ID for multi-turn conversations.
    #[serde(skip_serializing_if = "Option::is_none")]
    session_id: Option<String>,
    /// Space ID for context partitioning.
    #[serde(skip_serializing_if = "Option::is_none")]
    project_id: Option<String>,
    /// Phase reached during orchestration.
    #[serde(skip_serializing_if = "Option::is_none")]
    phase: Option<String>,
    /// RFC-014: Space tag decoration.
    #[serde(skip_serializing_if = "Option::is_none")]
    project_tag: Option<String>,
    /// RFC-025: active Mount IDs (comma-separated), primary first.
    #[serde(skip_serializing_if = "Option::is_none")]
    mount_ids: Option<String>,
    /// RFC-025: Mount decoration tag (e.g. "[🔧 oxios + oxi-sdk]").
    #[serde(skip_serializing_if = "Option::is_none")]
    mount_tag: Option<String>,
    /// RFC-014: Seed ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    seed_id: Option<String>,
    /// RFC-014: Evaluation passed.
    #[serde(skip_serializing_if = "Option::is_none")]
    evaluation_passed: Option<bool>,
    /// RFC-014: Duration in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    duration_ms: Option<u64>,
}

/// POST /api/chat — Send a message to the kernel via gateway and get response.
pub(crate) async fn handle_chat(
    state: State<Arc<AppState>>,
    Json(body): Json<ChatRequest>,
) -> Result<Json<ChatResponse>, AppError> {
    // Validate chat content size (max 64KB for user message)
    const MAX_CHAT_LENGTH: usize = 64 * 1024;
    if body.content.len() > MAX_CHAT_LENGTH {
        return Err(AppError::PayloadTooLarge {
            size: body.content.len(),
            limit: MAX_CHAT_LENGTH,
        });
    }
    tracing::info!(
        content_len = body.content.len(),
        content_preview = %body.content.chars().take(50).collect::<String>(),
        user = %body.user_id,
        "Chat message received"
    );

    // Build the incoming message.
    let mut msg = IncomingMessage::new("web", &body.user_id, &body.content);

    // Include session_id from request if provided (for multi-turn conversations).
    if !body.session_id.is_empty() {
        msg.metadata
            .insert("session_id".to_owned(), body.session_id.clone());
    }

    // RFC-025: Request project_id drives both context (orchestrator) and
    // session grouping (sidebar tree). Capture it for session persistence.
    let request_project_id = if !body.project_id.is_empty() {
        Some(body.project_id.clone())
    } else {
        None
    };
    if let Some(ref pid) = request_project_id {
        msg.metadata.insert("project_ids".to_owned(), pid.clone());
    }
    // RFC-025: include mount_ids from request (multi-path injection).
    if !body.mount_ids.is_empty() {
        msg.metadata
            .insert("mount_ids".to_owned(), body.mount_ids.clone());
    }

    let msg_id = msg.id.to_string();
    let content_echo = body.content.clone();

    // Send and wait for response from the gateway pipeline.
    tracing::info!("Sending message to gateway...");
    match state.bridge.send_and_wait(msg).await {
        Ok(response) => {
            tracing::info!(reply_len = response.content.len(), "Chat response received");

            // Extract from typed meta (RFC-014) or fall back to metadata HashMap
            let meta = response.meta.as_ref();
            let session_id = meta
                .and_then(|m| m.session_id.clone())
                .or_else(|| response.metadata.get("session_id").cloned());
            let project_id = meta
                .and_then(|m| m.project_id.clone())
                .or_else(|| response.metadata.get("project_ids").cloned());
            let phase = meta
                .map(|m| m.phase.clone())
                .or_else(|| response.metadata.get("phase").cloned());
            let project_tag = meta.and_then(|m| m.project_tag.clone());
            // RFC-025: active Mount IDs + tag (from channel metadata set by the gateway).
            let mount_ids = response.metadata.get("mount_ids").cloned();
            let mount_tag = response.metadata.get("mount_tag").cloned();
            let seed_id = meta.and_then(|m| m.seed_id.clone());
            let evaluation_passed = meta.and_then(|m| m.evaluation_passed);
            let duration_ms = meta.and_then(|m| m.duration_ms);
            let mode = meta.and_then(|m| m.mode.clone());

            // Persist session
            {
                // RFC-015: parse tool_calls into trajectory step records.
                let trajectory_steps: Vec<oxios_kernel::state_store::TrajectoryStepRecord> =
                    response
                        .metadata
                        .get("tool_calls")
                        .and_then(|v| serde_json::from_str::<Vec<serde_json::Value>>(v).ok())
                        .map(|calls| {
                            calls
                                .into_iter()
                                .enumerate()
                                .map(|(i, c)| oxios_kernel::state_store::TrajectoryStepRecord {
                                    tool_name: c
                                        .get("tool")
                                        .and_then(|v| v.as_str())
                                        .unwrap_or("")
                                        .to_string(),
                                    tool_args: c
                                        .get("input")
                                        .cloned()
                                        .unwrap_or(serde_json::Value::Null),
                                    output_summary: c
                                        .get("output")
                                        .and_then(|v| v.as_str())
                                        .unwrap_or("")
                                        .to_string(),
                                    duration_ms: c
                                        .get("duration_ms")
                                        .and_then(|v| v.as_u64())
                                        .unwrap_or(0),
                                    is_error: false,
                                    tool_call_id: format!("legacy-{i}"),
                                    timestamp: chrono::Utc::now(),
                                })
                                .collect()
                        })
                        .unwrap_or_default();

                let session_id_for_save = session_id.clone().unwrap_or_else(|| msg_id.clone());
                let sid = oxios_kernel::state_store::SessionId(session_id_for_save.clone());
                match state.kernel.state.load_session(&sid).await {
                    Ok(Some(mut session)) => {
                        session.add_user_message(&content_echo);
                        // Capture existing trajectory length before extending
                        let traj_start = session.trajectory_steps.len();
                        session.extend_trajectory(trajectory_steps);
                        let traj_end = session.trajectory_steps.len();
                        session.add_agent_response(oxios_kernel::state_store::AgentResponse {
                            content: response.content.clone(),
                            session_id: Some(sid.0.clone()),
                            seed_id: seed_id.clone(),
                            phase_reached: phase.clone(),
                            evaluation_passed,
                            timestamp: chrono::Utc::now(),
                            trajectory_range: if traj_end > traj_start {
                                Some(oxios_kernel::state_store::TrajectoryRange {
                                    start: traj_start,
                                    end: traj_end,
                                })
                            } else {
                                None
                            },
                        });
                        // RFC-025: Set top-level project_id for grouping.
                        // User-requested project_id takes priority; otherwise
                        // keep the existing grouping.
                        if let Some(ref pid) = request_project_id {
                            session.project_id = Some(pid.clone());
                        }
                        // Persist execution mode (chat/ouroboros) in session metadata
                        if let Some(ref m) = mode {
                            session.set_metadata("mode", serde_json::json!(m));
                        }
                        if let Err(e) = state.kernel.state.save_session(&session).await {
                            tracing::warn!(error = %e, "Failed to persist session");
                        }
                    }
                    Ok(None) => {
                        // Create new session
                        let mut session =
                            oxios_kernel::state_store::Session::new(body.user_id.clone());
                        session.id = oxios_kernel::state_store::SessionId(session_id_for_save);
                        session.add_user_message(&content_echo);
                        // New session: trajectory starts at 0
                        let traj_start = 0usize;
                        session.extend_trajectory(trajectory_steps);
                        let traj_end = session.trajectory_steps.len();
                        session.add_agent_response(oxios_kernel::state_store::AgentResponse {
                            content: response.content.clone(),
                            session_id: Some(sid.0.clone()),
                            seed_id: seed_id.clone(),
                            phase_reached: phase.clone(),
                            evaluation_passed,
                            timestamp: chrono::Utc::now(),
                            trajectory_range: if traj_end > traj_start {
                                Some(oxios_kernel::state_store::TrajectoryRange {
                                    start: traj_start,
                                    end: traj_end,
                                })
                            } else {
                                None
                            },
                        });
                        // RFC-025: Set top-level project_id for grouping.
                        if let Some(ref pid) = request_project_id {
                            session.project_id = Some(pid.clone());
                        }
                        // Persist execution mode for new session
                        if let Some(ref m) = mode {
                            session.set_metadata("mode", serde_json::json!(m));
                        }
                        if let Err(e) = state.kernel.state.save_session(&session).await {
                            tracing::warn!(error = %e, "Failed to create session");
                        }
                    }
                    Err(e) => tracing::warn!(error = %e, "Failed to load/create session"),
                }

                // Auto-prune sessions if configured (throttled to once per hour)
                let cfg = state.config.read();
                if cfg.session.auto_prune && state.kernel.state.should_auto_prune() {
                    let prune_config = oxios_kernel::state_store::PruneConfig {
                        max_sessions: cfg.session.max_sessions,
                        ttl_hours: cfg.session.ttl_hours,
                    };
                    drop(cfg); // release read lock before async
                    let kernel = state.kernel.clone();
                    tokio::spawn(async move {
                        if let Err(e) = kernel.state.prune_sessions(&prune_config).await {
                            tracing::warn!(error = %e, "Session auto-prune failed");
                        }
                    });
                }
            }

            Ok(Json(ChatResponse {
                id: msg_id,
                echo: content_echo,
                reply: response.content,
                session_id: session_id.clone(),
                project_id: project_id.clone(),
                phase,
                project_tag,
                mount_ids,
                mount_tag,
                seed_id,
                evaluation_passed,
                duration_ms,
            }))
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to get response from gateway");
            // RFC-024 C1 / F14: distinguish timeout (504) from other
            // failures (500) by error variant, not by grepping the error
            // message. A string-match classification would silently
            // regress to 500 if the message is ever reworded or wrapped.
            match e {
                BridgeSendError::Timeout => Err(AppError::GatewayTimeout(e.to_string())),
                BridgeSendError::SendFailed(_) | BridgeSendError::ChannelDropped => {
                    Err(AppError::Internal("gateway response failed".into()))
                }
            }
        }
    }
}

/// Query parameters for WebSocket connections.
#[derive(Debug, serde::Deserialize)]
pub(crate) struct WsParams {
    /// One-time ticket for authentication (preferred).
    ticket: Option<String>,
    /// Bearer token for authentication (fallback).
    token: Option<String>,
}

/// POST /api/chat/ticket — Generate a one-time WebSocket ticket.
pub(crate) async fn handle_chat_ticket(
    state: State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Auth middleware already validated Bearer token if auth is enabled.
    let ticket = state.kernel.security.generate_ws_ticket();
    Ok(Json(serde_json::json!({ "ticket": ticket })))
}

/// GET /api/chat/stream — WebSocket endpoint for real-time chat streaming.
pub(crate) async fn handle_chat_stream(
    ws: WebSocketUpgrade,
    state: State<Arc<AppState>>,
    Query(params): Query<WsParams>,
) -> impl axum::response::IntoResponse {
    // Authenticate if auth is enabled
    if state.config.read().security.auth_enabled {
        let authenticated = if let Some(ref ticket) = params.ticket {
            state.kernel.security.validate_ws_ticket(ticket)
        } else if let Some(ref token) = params.token {
            state.kernel.security.validate_token(token)
        } else {
            false
        };
        if !authenticated {
            return axum::http::StatusCode::UNAUTHORIZED.into_response();
        }
    }
    ws.on_upgrade(move |socket| handle_chat_websocket(socket, state.0))
}

/// Handles a WebSocket connection for chat streaming.
///
/// Protocol:
/// - **Incoming** (frontend → backend):
///   `{ type: "message", content: "...", session_id?: "...", project_id?: "..." }`
/// - **Outgoing token** (backend → frontend):
///   `{ type: "token", content: "...", session_id?, project_id? }`
/// - **Outgoing done** (backend → frontend):
///   `{ type: "done", session_id?, project_id?, phase?, evaluation_passed? }`
pub(crate) async fn handle_chat_websocket(socket: WebSocket, state: Arc<AppState>) {
    // Assign a unique connection ID for point-to-point message routing.
    // Prevents cross-tab message leakage in multi-session scenarios.
    let conn_id = uuid::Uuid::new_v4().to_string();
    // Clone for recv_task (send_task gets its own clone below).
    let conn_id_for_recv = conn_id.clone();
    let conn_id_for_send = conn_id.clone();
    let (mut ws_tx, mut ws_rx) = socket.split();

    // Subscribe to outgoing messages from the web channel (not kernel event bus).
    // WebChannel::send() broadcasts OutgoingMessage here; the kernel event bus
    // carries KernelEvents which are a different type entirely.
    let mut outgoing_rx = state.bridge.subscribe();
    // RFC-015: subscribe to kernel event bus for real-time chat transparency
    // events (tool execution, token usage, memory recall, reasoning fragments).
    // Filtered by session_id in the recv loop to avoid leaking other agents' events.
    let mut kernel_event_rx = state.kernel.infra.subscribe();

    // Clone handles for the spawned tasks.
    let incoming_tx = state.bridge.incoming_tx.clone();
    let state_store = state.kernel.state.store().clone();

    // Read session prune config
    let prune_config = {
        let cfg = state.config.read();
        if cfg.session.auto_prune {
            Some(oxios_kernel::state_store::PruneConfig {
                max_sessions: cfg.session.max_sessions,
                ttl_hours: cfg.session.ttl_hours,
            })
        } else {
            None
        }
    };

    // Track in-flight user messages for session persistence.
    // The send_task inserts before forwarding to gateway (keyed by message
    // ID); the recv_task removes the matching entry when the response arrives.
    //
    // RFC-025 Web-M3: this is a HashMap, not a single Option slot. A single
    // slot caused the first message + response pair to be silently dropped
    // when a user sent a second message before the first response arrived
    // (the second insert overwrote the first, so the first response's
    // `pending_id == msg_id` check failed and persistence was skipped).
    //
    // Bounded by the number of in-flight requests: each entry is removed by
    // its matching response. If a response never arrives (e.g. agent killed),
    // the entry stays — this is acceptable since in-flight counts are small.
    let pending_user_msg: Arc<tokio::sync::Mutex<HashMap<uuid::Uuid, PendingMessage>>> =
        Arc::new(tokio::sync::Mutex::new(HashMap::new()));

    let pending_for_send = pending_user_msg.clone();
    let bridge_for_resume = state.bridge.clone();

    // ── Forward gateway responses → WebSocket client ──
    //
    // Each chunk carries session_id + project_id so the frontend can
    // maintain multi-turn context. After the "done" chunk we persist
    // the session to disk (same as the POST handler).
    //
    // RFC-015: also forward real-time kernel events (tool execution, token
    // usage, memory recall, reasoning fragments) as WS chunks so the
    // frontend can show live progress.
    let mut recv_task = tokio::spawn(async move {
        // Track the active session so we only forward events tagged with it.
        // Multi-turn conversations keep the same session_id across messages.
        let mut active_session_id: Option<String> = None;

        loop {
            tokio::select! {
                // Bias toward gateway messages (text streaming + done).
                biased;
                msg_result = outgoing_rx.recv() => {
                    let Ok(msg) = msg_result else { break };

                    // Filter by target_conn_id: only process messages addressed
                    // to this connection (or broadcast messages with None).
                    if msg.target_conn_id.as_ref().is_some_and(|id| id != &conn_id_for_recv) {
                        continue;
                    }

                    let msg_id = msg.id;
                    let session_id = msg
                        .meta
                        .as_ref()
                        .and_then(|m| m.session_id.clone())
                        .or_else(|| msg.metadata.get("session_id").cloned());
                    let project_id = msg
                        .meta
                        .as_ref()
                        .and_then(|m| m.project_id.clone())
                        .or_else(|| msg.metadata.get("project_ids").cloned());
                    let phase = msg
                        .meta
                        .as_ref()
                        .map(|m| m.phase.clone())
                        .or_else(|| msg.metadata.get("phase").cloned());
                    let evaluation_passed = msg.meta.as_ref().and_then(|m| m.evaluation_passed);
                    let project_tag = msg.meta.as_ref().and_then(|m| m.project_tag.clone());
                    let seed_id = msg.meta.as_ref().and_then(|m| m.seed_id.clone());
                    let duration_ms = msg.meta.as_ref().and_then(|m| m.duration_ms);

                    // Remember the session we are forwarding for. Subsequent
                    // kernel events without a session_id are still forwarded
                    // (some events are system-wide).
                    if session_id.is_some() {
                        active_session_id = session_id.clone();
                    }

                    // RFC-024 SP2 / C2: a synthetic `type: "resync"` message
                    // (broadcast by the bridge when a resume cursor was
                    // older than the replay buffer) is forwarded as a
                    // resync chunk and *skips* persistence / token / done
                    // emission — the client is expected to pull state via
                    // the regular HTTP API after seeing it.
                    if msg.metadata.get("type").map(|v| v.as_str()) == Some("resync") {
                        let chunk = serde_json::json!({"type": "resync"});
                        if ws_tx
                            .send(Message::Text(chunk.to_string().into()))
                            .await
                            .is_err()
                        {
                            break;
                        }
                        continue;
                    }

                    // ── Persist session to disk FIRST ──
                    // Always persist, even if WS send fails later. This ensures
                    // the exchange is durable even if the connection drops mid-stream.
                    //
                    // RFC-025 Web-M3: check-and-remove happen under a single
                    // lock so there is no TOCTOU window between peeking the
                    // pending slot and taking it. The lock is released before
                    // the async persist_session call.
                    if let Some(ref sid) = session_id {
                        let pm = {
                            let mut guard = pending_user_msg.lock().await;
                            guard.remove(&msg_id)
                        };
                        // lock released here, before async I/O
                        if let Some(pm) = pm {
                            persist_session(
                                &state_store,
                                sid,
                                pm.content.as_str(),
                                pm.user_id.as_str(),
                                &msg.content,
                                project_id.as_deref(),
                                &msg.metadata,
                                prune_config.clone(),
                            )
                            .await;
                        }
                    }

                    // ── Forward to WebSocket client ──
                    //
                    // Chat UI redesign: when `meta.interview_questions` is
                    // present, send an `interview` chunk (structured widgets)
                    // and skip the token chunk — the questions are already
                    // carried by the interview payload. When absent, fall
                    // back to the existing token + done sequence.
                    let has_interview = msg.meta.as_ref().and_then(|m| m.interview_questions.as_ref()).is_some();

                    if has_interview {
                        // Send interview chunk with structured questions
                        let interview_chunk = serde_json::json!({
                            "type": "interview",
                            "session_id": session_id,
                            "project_id": project_id,
                            "questions": msg.meta.as_ref().and_then(|m| m.interview_questions.clone()),
                            "round": msg.meta.as_ref().and_then(|m| m.interview_round),
                            "ambiguity": msg.meta.as_ref().and_then(|m| m.interview_ambiguity),
                        });
                        let json = match serde_json::to_string(&interview_chunk) {
                            Ok(j) => j,
                            Err(e) => {
                                tracing::error!(error = %e, "Failed to serialize interview chunk");
                                continue;
                            }
                        };
                        if ws_tx.send(Message::Text(json.into())).await.is_err() {
                            break;
                        }
                    } else {
                        // Standard token chunk
                        let token_chunk = serde_json::json!({
                            "type": "token",
                            "content": msg.content,
                            "session_id": session_id,
                            "project_id": project_id,
                        });
                        let json = match serde_json::to_string(&token_chunk) {
                            Ok(j) => j,
                            Err(e) => {
                                tracing::error!(error = %e, "Failed to serialize outgoing message");
                                continue;
                            }
                        };
                        if ws_tx.send(Message::Text(json.into())).await.is_err() {
                            break; // WS closed — session was already persisted above
                        }
                    }

                    // Send done chunk with final metadata
                    let done_chunk = serde_json::json!({
                        "type": "done",
                        "session_id": session_id,
                        "project_id": project_id,
                        "phase": phase,
                        "evaluation_passed": evaluation_passed,
                        "project_tag": project_tag,
                        "seed_id": seed_id,
                        "duration_ms": duration_ms,
                        // RFC-025: surface detected mount info to the frontend.
                        "mount_tag": msg.metadata.get("mount_tag"),
                        "mount_ids": msg.metadata.get("mount_ids"),
                        // TODO: populate tool_calls from trajectory_steps once kernel provides them
                        "tool_calls": msg.metadata.get("tool_calls")
                            .and_then(|v| serde_json::from_str::<serde_json::Value>(v).ok())
                            .unwrap_or(serde_json::json!([])),
                        "mode": msg.meta.as_ref().and_then(|m| m.mode.clone()),
                    });
                    let done_json = match serde_json::to_string(&done_chunk) {
                        Ok(j) => j,
                        Err(_) => break,
                    };
                    if ws_tx.send(Message::Text(done_json.into())).await.is_err() {
                        break; // WS closed — session was already persisted above
                    }
                }
                event_result = kernel_event_rx.recv() => {
                    // Convert KernelEvent → WS chunk when relevant.
                    let Ok(event) = event_result else {
                        // Lagged or closed — skip and keep waiting.
                        continue;
                    };
                    if let Some(chunk) = kernel_event_to_ws_chunk(&event, &active_session_id) {
                        let json = match serde_json::to_string(&chunk) {
                            Ok(j) => j,
                            Err(e) => {
                                tracing::warn!(error = %e, "Failed to serialize transparency chunk");
                                continue;
                            }
                        };
                        if ws_tx.send(Message::Text(json.into())).await.is_err() {
                            break;
                        }
                    }
                }
            }
        }
    });

    // ── Receive from WebSocket client → gateway ──
    //
    // Frontend sends JSON:
    //   `{ type: "message", content: "...", session_id?, project_id? }`
    let mut send_task = tokio::spawn(async move {
        while let Some(Ok(msg)) = FuturesStreamExt::next(&mut ws_rx).await {
            match msg {
                Message::Text(text) => {
                    let parsed: serde_json::Value = match serde_json::from_str(&text) {
                        Ok(v) => v,
                        Err(_) => continue,
                    };

                    let msg_type = parsed
                        .get("type")
                        .and_then(|v| v.as_str())
                        .unwrap_or("message");

                    let incoming_session_id = parsed
                        .get("session_id")
                        .and_then(|v| v.as_str())
                        .filter(|s| !s.is_empty())
                        .map(String::from);

                    let incoming_project_id = parsed
                        .get("project_id")
                        .and_then(|v| v.as_str())
                        .filter(|s| !s.is_empty())
                        .map(String::from);
                    // RFC-025: mount_ids (comma-separated, primary first).
                    let incoming_mount_ids = parsed
                        .get("mount_ids")
                        .and_then(|v| v.as_str())
                        .filter(|s| !s.is_empty())
                        .map(String::from);

                    let incoming_mode = parsed
                        .get("mode")
                        .and_then(|v| v.as_str())
                        .map(String::from);

                    match msg_type {
                        // RFC-024 SP2 / C2 (replay): client announces its
                        // last-seen seq and asks the server to replay any
                        // messages it missed while disconnected. The bridge
                        // broadcasts the replayed slice (or a synthetic
                        // `type: "resync"` message) which the recv_task
                        // forwards to the client. We do NOT treat this as a
                        // user message, so we `continue` without touching
                        // the gateway.
                        "resume" => {
                            let last_seq: u64 =
                                parsed.get("last_seq").and_then(|v| v.as_u64()).unwrap_or(0);
                            tracing::debug!(
                                conn_id = %conn_id_for_send,
                                last_seq,
                                "WS resume: replaying since last_seq"
                            );
                            bridge_for_resume.replay_after(last_seq);
                            continue;
                        }
                        // Chat UI redesign: user submits structured interview
                        // answers. Convert to natural language and forward as
                        // a regular message so the Orchestrator's existing
                        // multi-turn interview path handles it without any
                        // special treatment.
                        "interview_response" => {
                            let answers = parsed
                                .get("answers")
                                .and_then(|v| v.as_array())
                                .cloned()
                                .unwrap_or_default();

                            // Prefer the pre-formatted Q&A text from the frontend
                            // (includes question context so the LLM understands
                            // the answers). Fall back to raw values if absent.
                            let answer_text = parsed
                                .get("text")
                                .and_then(|v| v.as_str())
                                .filter(|s| !s.is_empty())
                                .map(String::from)
                                .unwrap_or_else(|| {
                                    answers
                                        .iter()
                                        .filter_map(|a| {
                                            let value = a.get("value")?.as_str()?;
                                            if value.is_empty() {
                                                return None;
                                            }
                                            Some(value.to_string())
                                        })
                                        .collect::<Vec<_>>()
                                        .join("\n")
                                });

                            if answer_text.is_empty() {
                                continue;
                            }

                            let mut incoming =
                                IncomingMessage::new("web", "default", answer_text.clone());
                            if let Some(ref sid) = incoming_session_id {
                                incoming.metadata.insert("session_id".into(), sid.clone());
                            }
                            if let Some(ref vid) = incoming_project_id {
                                incoming.metadata.insert("project_ids".into(), vid.clone());
                            }
                            if let Some(ref mids) = incoming_mount_ids {
                                incoming.metadata.insert("mount_ids".into(), mids.clone());
                            }
                            incoming
                                .metadata
                                .insert("conn_id".into(), conn_id_for_send.clone());
                            if let Some(m) = incoming_mode.clone() {
                                incoming.metadata.insert("mode".into(), m);
                            }

                            {
                                let mut pending = pending_for_send.lock().await;
                                pending.insert(
                                    incoming.id,
                                    PendingMessage {
                                        content: answer_text,
                                        user_id: "default".to_string(),
                                    },
                                );
                            }

                            if incoming_tx.send(incoming).await.is_err() {
                                break;
                            }
                        }
                        // Default: regular chat message
                        _ => {
                            let content = parsed
                                .get("content")
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string();

                            if content.is_empty() {
                                continue;
                            }

                            let mut incoming =
                                IncomingMessage::new("web", "default", content.clone());

                            if let Some(ref sid) = incoming_session_id {
                                incoming.metadata.insert("session_id".into(), sid.clone());
                            }
                            if let Some(ref vid) = incoming_project_id {
                                incoming.metadata.insert("project_ids".into(), vid.clone());
                            }
                            if let Some(ref mids) = incoming_mount_ids {
                                incoming.metadata.insert("mount_ids".into(), mids.clone());
                            }
                            incoming
                                .metadata
                                .insert("conn_id".into(), conn_id_for_send.clone());
                            if let Some(m) = incoming_mode.clone() {
                                incoming.metadata.insert("mode".into(), m);
                            }

                            {
                                let mut pending = pending_for_send.lock().await;
                                pending.insert(
                                    incoming.id,
                                    PendingMessage {
                                        content,
                                        user_id: "default".to_string(),
                                    },
                                );
                            }

                            if incoming_tx.send(incoming).await.is_err() {
                                break;
                            }
                        }
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
    });
    // F7: when one side finishes, abort the other so its broadcast
    // subscribers and WebSocket half are released promptly. Without this,
    // a client that stops reading but leaves the socket half-open lets
    // the recv_task block forever on `ws_tx.send().await`, leaking a
    // broadcast subscriber and its buffer per abandoned connection — a
    // trivial memory/subscriber-exhaustion DoS.
    tokio::select! {
        _ = &mut recv_task => {
            send_task.abort();
        }
        _ = &mut send_task => {
            recv_task.abort();
        }
    }
    // Drain both handles (the aborted one resolves immediately with a
    // JoinError; the finished one with Ok) so no task is leaked.
    let _ = recv_task.await;
    let _ = send_task.await;
}

/// User message awaiting a gateway response for session persistence.
struct PendingMessage {
    content: String,
    user_id: String,
}

/// Persist a chat exchange (user message + agent response) to the session store.
///
/// Mirrors the logic in the POST `/api/chat` handler so that WebSocket-based
/// conversations are also durable across tab switches and browser restarts.
#[allow(clippy::too_many_arguments)]
async fn persist_session(
    state_store: &oxios_kernel::state_store::StateStore,
    session_id: &str,
    user_content: &str,
    user_id: &str,
    agent_content: &str,
    project_id: Option<&str>,
    metadata: &std::collections::HashMap<String, String>,
    prune_config: Option<oxios_kernel::state_store::PruneConfig>,
) {
    let sid = oxios_kernel::state_store::SessionId(session_id.to_string());
    // RFC-015: parse tool_calls JSON into trajectory step records.
    let trajectory_steps: Vec<oxios_kernel::state_store::TrajectoryStepRecord> = metadata
        .get("tool_calls")
        .and_then(|v| serde_json::from_str::<Vec<serde_json::Value>>(v).ok())
        .map(|calls| {
            calls
                .into_iter()
                .enumerate()
                .map(|(i, c)| oxios_kernel::state_store::TrajectoryStepRecord {
                    tool_name: c
                        .get("tool")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                    tool_args: c.get("input").cloned().unwrap_or(serde_json::Value::Null),
                    output_summary: c
                        .get("output")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                    duration_ms: c.get("duration_ms").and_then(|v| v.as_u64()).unwrap_or(0),
                    is_error: false,
                    tool_call_id: format!("legacy-{i}"),
                    timestamp: chrono::Utc::now(),
                })
                .collect()
        })
        .unwrap_or_default();

    match state_store.load_session(&sid).await {
        Ok(Some(mut session)) => {
            session.add_user_message(user_content);
            // Capture existing trajectory length before extending
            let traj_start = session.trajectory_steps.len();
            session.extend_trajectory(trajectory_steps);
            let traj_end = session.trajectory_steps.len();
            session.add_agent_response(oxios_kernel::state_store::AgentResponse {
                content: agent_content.to_string(),
                session_id: Some(sid.0.clone()),
                seed_id: metadata.get("seed_id").cloned(),
                phase_reached: metadata.get("phase").cloned(),
                evaluation_passed: metadata
                    .get("evaluation_passed")
                    .and_then(|v| v.parse().ok()),
                timestamp: chrono::Utc::now(),
                trajectory_range: if traj_end > traj_start {
                    Some(oxios_kernel::state_store::TrajectoryRange {
                        start: traj_start,
                        end: traj_end,
                    })
                } else {
                    None
                },
            });
            // RFC-025: set top-level project_id field (was metadata key — caused
            // singular/plural mismatch with list_sessions and GET endpoint).
            if let Some(vid) = project_id {
                session.project_id = Some(vid.to_string());
            }
            // Persist execution mode in session metadata
            if let Some(mode) = metadata.get("mode") {
                session.set_metadata("mode", serde_json::json!(mode));
            }
            if let Err(e) = state_store.save_session(&session).await {
                tracing::warn!(error = %e, "WS: failed to persist session");
            }
        }
        Ok(None) => {
            let mut session = oxios_kernel::state_store::Session::new(user_id);
            session.id = oxios_kernel::state_store::SessionId(session_id.to_string());
            session.add_user_message(user_content);
            // New session: trajectory starts at 0
            let traj_start = 0usize;
            session.extend_trajectory(trajectory_steps);
            let traj_end = session.trajectory_steps.len();
            session.add_agent_response(oxios_kernel::state_store::AgentResponse {
                content: agent_content.to_string(),
                session_id: Some(sid.0.clone()),
                seed_id: metadata.get("seed_id").cloned(),
                phase_reached: metadata.get("phase").cloned(),
                evaluation_passed: metadata
                    .get("evaluation_passed")
                    .and_then(|v| v.parse().ok()),
                timestamp: chrono::Utc::now(),
                trajectory_range: if traj_end > traj_start {
                    Some(oxios_kernel::state_store::TrajectoryRange {
                        start: traj_start,
                        end: traj_end,
                    })
                } else {
                    None
                },
            });
            // RFC-025: set top-level project_id field.
            if let Some(vid) = project_id {
                session.project_id = Some(vid.to_string());
            }
            // Persist execution mode for new session
            if let Some(mode) = metadata.get("mode") {
                session.set_metadata("mode", serde_json::json!(mode));
            }
            if let Err(e) = state_store.save_session(&session).await {
                tracing::warn!(error = %e, "WS: failed to create session");
            }
        }
        Err(e) => {
            tracing::warn!(error = %e, "WS: failed to load/create session");
        }
    }

    // Auto-prune in background after session save (throttled)
    if let Some(config) = prune_config {
        // Only prune if at least 1 hour has passed since the last prune.
        // Uses a process-global throttle to avoid spawning on every message.
        static LAST_PRUNE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let last = LAST_PRUNE.load(std::sync::atomic::Ordering::Relaxed);
        if now_secs.saturating_sub(last) >= 3600 {
            LAST_PRUNE.store(now_secs, std::sync::atomic::Ordering::Relaxed);
            let store = state_store.clone();
            tokio::spawn(async move {
                if let Err(e) = store.prune_sessions(&config).await {
                    tracing::warn!(error = %e, "WS: session auto-prune failed");
                }
            });
        }
    }
}

/// Convert a `KernelEvent` into a WebSocket chunk for chat transparency
/// (RFC-015). Returns `None` when the event is not relevant to chat
/// progress (e.g. agent lifecycle events unrelated to the current
/// session) or when it does not belong to the active session.
fn kernel_event_to_ws_chunk(
    event: &oxios_kernel::event_bus::KernelEvent,
    active_session_id: &Option<String>,
) -> Option<serde_json::Value> {
    use oxios_kernel::event_bus::KernelEvent;

    // Helper: skip events that do not belong to the active session.
    // Events without a session_id (e.g. project lifecycle) are always passed
    // through — they are not high-frequency and can be useful context.
    let event_session_id: Option<&str> = match event {
        KernelEvent::ToolExecutionStarted { session_id, .. } => Some(session_id),
        KernelEvent::ToolExecutionFinished { session_id, .. } => Some(session_id),
        KernelEvent::ToolExecutionProgress { session_id, .. } => Some(session_id),
        KernelEvent::MemoryRecallUsed { session_id, .. } => Some(session_id),
        KernelEvent::TokenUsageUpdate { session_id, .. } => Some(session_id),
        KernelEvent::ReasoningFragment { session_id, .. } => Some(session_id),
        _ => None,
    };
    if let (Some(eid), Some(active)) = (event_session_id, active_session_id.as_ref())
        && eid != active.as_str()
    {
        return None;
    }

    match event {
        KernelEvent::ToolExecutionStarted {
            tool_name,
            tool_call_id,
            tool_args,
            context,
            ..
        } => Some(serde_json::json!({
            "type": "tool_start",
            "tool_name": tool_name,
            "tool_call_id": tool_call_id,
            "tool_args": tool_args,
            "context": context,
        })),
        KernelEvent::ToolExecutionFinished {
            tool_name,
            tool_call_id,
            duration_ms,
            is_error,
            output_summary,
            ..
        } => Some(serde_json::json!({
            "type": "tool_end",
            "tool_name": tool_name,
            "tool_call_id": tool_call_id,
            "duration_ms": duration_ms,
            "is_error": is_error,
            "output_summary": output_summary,
        })),
        KernelEvent::ToolExecutionProgress {
            tool_call_id,
            tool_name,
            progress,
            tab_id,
            context,
            ..
        } => {
            let mut obj = serde_json::json!({
                "type": "tool_progress",
                "tool_call_id": tool_call_id,
                "tool_name": tool_name,
                "progress": progress,
            });
            if let Some(id) = tab_id {
                obj["tab_id"] = serde_json::json!(id.to_string());
            }
            if let Some(ctx) = context {
                obj["context"] = ctx.clone();
            }
            Some(obj)
        }
        KernelEvent::MemoryRecallUsed {
            query,
            count,
            source,
            ..
        } => Some(serde_json::json!({
            "type": "memory",
            "action": "recall",
            "query": query,
            "count": count,
            "source": source,
        })),
        KernelEvent::TokenUsageUpdate {
            input_tokens,
            output_tokens,
            ..
        } => Some(serde_json::json!({
            "type": "usage",
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
        })),
        KernelEvent::ReasoningFragment {
            content, source, ..
        } => Some(serde_json::json!({
            "type": "reasoning",
            "content": content,
            "source": source,
        })),
        // PhaseStarted / PhaseCompleted are not included in the WS stream
        // here because the orchestrator already publishes them with extra
        // metadata (result_summary) and we don't want to double-emit. The
        // global /api/events SSE channel carries them for the events page.
        KernelEvent::ApprovalRequested {
            id,
            tool_name,
            reason,
            session_id,
            ..
        } => {
            // Filter by active session
            if let (Some(eid), Some(active)) = (session_id.as_ref(), active_session_id.as_ref())
                && eid != active.as_str()
            {
                return None;
            }
            Some(serde_json::json!({
                "type": "tool_approval",
                "id": id.to_string(),
                "tool_name": tool_name,
                "reason": reason,
            }))
        }
        _ => None,
    }
}

/// GET /api/sessions/{id}/tool-calls — Get tool call timeline for a session.
pub(crate) async fn handle_session_tool_calls(
    _state: State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Session tool calls are not yet stored persistently.
    // Return empty array for now — will be populated when trajectory_steps
    // are persisted to sessions.
    Ok(Json(serde_json::json!({
        "session_id": id,
        "tool_calls": []
    })))
}

// ---------------------------------------------------------------------------
// Tool Approval (RFC-017: runtime capability escalation)
// ---------------------------------------------------------------------------

/// POST /api/chat/tool-approval/{id}/respond — Approve or deny a pending
/// tool approval request. Resolves the oneshot the GatedTool is waiting on.
pub(crate) async fn handle_tool_approval_respond(
    state: State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(body): Json<ToolApprovalResponseBody>,
) -> Result<Json<serde_json::Value>, AppError> {
    let approval_id = uuid::Uuid::parse_str(&id)
        .map_err(|e| AppError::BadRequest(format!("invalid approval id: {e}")))?;

    let result = if body.approved {
        oxios_kernel::tools::ToolApprovalResult::Approved
    } else {
        oxios_kernel::tools::ToolApprovalResult::Denied
    };

    state
        .kernel
        .infra
        .pending_tool_approvals()
        .resolve(approval_id, result)
        .ok_or_else(|| {
            AppError::NotFound(format!("tool approval {id} not found or already resolved"))
        })?;

    tracing::info!(
        approval_id = %id,
        approved = body.approved,
        "Tool approval resolved"
    );

    Ok(Json(serde_json::json!({ "status": "ok" })))
}

#[derive(Debug, serde::Deserialize)]
pub(crate) struct ToolApprovalResponseBody {
    /// Whether the user approved the tool access.
    pub approved: bool,
}

#[cfg(test)]
mod rfc015_tests {
    use super::*;
    use oxios_kernel::AgentId;
    use oxios_kernel::event_bus::KernelEvent;

    /// Every RFC-015 KernelEvent should map to the documented WS chunk type
    /// (tool_start, tool_end, memory, usage, reasoning). This is the wire
    /// contract the frontend `chunkToActivity` depends on, so a regression
    /// here breaks the entire chat transparency UI.
    #[test]
    fn tool_started_emits_tool_start() {
        let event = KernelEvent::ToolExecutionStarted {
            session_id: "s1".into(),
            tool_name: "read_file".into(),
            tool_call_id: "c1".into(),
            tool_args: serde_json::json!({"path": "/x"}),
            context: None,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "tool_start");
        assert_eq!(chunk["tool_name"], "read_file");
        assert_eq!(chunk["tool_call_id"], "c1");
        assert_eq!(chunk["tool_args"]["path"], "/x");
    }

    #[test]
    fn tool_finished_emits_tool_end() {
        let event = KernelEvent::ToolExecutionFinished {
            session_id: "s1".into(),
            tool_call_id: "c1".into(),
            tool_name: "read_file".into(),
            duration_ms: 123,
            is_error: false,
            output_summary: "ok".into(),
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "tool_end");
        assert_eq!(chunk["duration_ms"], 123);
        assert_eq!(chunk["is_error"], false);
    }

    /// Real-time tool progress (RFC-015 v0.12) must be forwarded as a
    /// `tool_progress` chunk so the Web UI can show a spinner and the
    /// latest progress text while the tool is still running. When the
    /// upstream event carries a `tab_id`, it must be included in the
    /// chunk so the frontend can badge concurrent tab activity.
    #[test]
    fn tool_progress_emits_tool_progress_chunk() {
        let tab_id = uuid::Uuid::new_v4();
        let event = KernelEvent::ToolExecutionProgress {
            session_id: "s1".into(),
            tool_call_id: "c1".into(),
            tool_name: "browse".into(),
            progress: "loading https://example.com".into(),
            tab_id: Some(tab_id),
            context: None,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "tool_progress");
        assert_eq!(chunk["tool_call_id"], "c1");
        assert_eq!(chunk["tool_name"], "browse");
        assert_eq!(chunk["progress"], "loading https://example.com");
        assert_eq!(chunk["tab_id"], tab_id.to_string());
    }

    /// Progress events must be filtered by session_id, same as start/end.
    #[test]
    fn tool_progress_foreign_session_is_filtered() {
        let event = KernelEvent::ToolExecutionProgress {
            session_id: "other".into(),
            tool_call_id: "c1".into(),
            tool_name: "browse".into(),
            progress: "leak me".into(),
            tab_id: None,
            context: None,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into()));
        assert!(chunk.is_none(), "foreign progress should be filtered");
    }

    /// When `tab_id` is `None` (legacy oxi-agent versions), the chunk must
    /// omit the `tab_id` key entirely so the frontend treats it as
    /// "no badge" rather than rendering `null`.
    #[test]
    fn tool_progress_chunk_omits_tab_id_when_none() {
        let event = KernelEvent::ToolExecutionProgress {
            session_id: "s1".into(),
            tool_call_id: "c1".into(),
            tool_name: "browse".into(),
            progress: "step 1".into(),
            tab_id: None,
            context: None,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert!(
            chunk.get("tab_id").is_none(),
            "tab_id key should be absent when None; got: {chunk}"
        );
    }

    #[test]
    fn memory_recall_emits_memory_chunk() {
        let event = KernelEvent::MemoryRecallUsed {
            session_id: "s1".into(),
            query: "rust errors".into(),
            count: 3,
            source: "warm".into(),
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "memory");
        assert_eq!(chunk["action"], "recall");
        assert_eq!(chunk["count"], 3);
    }

    #[test]
    fn token_usage_emits_usage_chunk() {
        let event = KernelEvent::TokenUsageUpdate {
            session_id: "s1".into(),
            input_tokens: 100,
            output_tokens: 50,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "usage");
        assert_eq!(chunk["input_tokens"], 100);
        assert_eq!(chunk["output_tokens"], 50);
    }

    #[test]
    fn reasoning_emits_reasoning_chunk() {
        let event = KernelEvent::ReasoningFragment {
            session_id: "s1".into(),
            content: "compaction done".into(),
            source: "compaction".into(),
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into())).unwrap();
        assert_eq!(chunk["type"], "reasoning");
        assert_eq!(chunk["content"], "compaction done");
        assert_eq!(chunk["source"], "compaction");
    }

    /// Events tagged with a different session must be dropped — otherwise
    /// unrelated agents' tool calls would leak into the wrong chat.
    #[test]
    fn foreign_session_is_filtered() {
        let event = KernelEvent::ToolExecutionStarted {
            session_id: "other".into(),
            tool_name: "bash".into(),
            tool_call_id: "x".into(),
            tool_args: serde_json::Value::Null,
            context: None,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &Some("s1".into()));
        assert!(chunk.is_none(), "foreign session should not be forwarded");
    }

    /// When no active session is set (e.g. mid-connect), the filter is
    /// effectively a no-op. Session-scoped events still pass through
    /// because we cannot distinguish "this agent is for me" from "this
    /// agent is for someone else" without a session tag. The first
    /// gateway message will populate `active_session_id`, and from that
    /// point foreign sessions are filtered correctly.
    #[test]
    fn no_active_session_passes_session_scoped_events() {
        let event = KernelEvent::TokenUsageUpdate {
            session_id: "s1".into(),
            input_tokens: 1,
            output_tokens: 1,
        };
        let chunk = kernel_event_to_ws_chunk(&event, &None);
        assert!(
            chunk.is_some(),
            "filter is inactive without an active session"
        );
        assert_eq!(chunk.unwrap()["type"], "usage");
    }

    /// Lifecycle events (AgentStarted, PhaseCompleted, …) should not be
    /// forwarded as RFC-015 chunks — the global /api/events SSE handles
    /// them. Returning None keeps the WS stream clean.
    #[test]
    fn lifecycle_events_are_skipped() {
        let event = KernelEvent::AgentStarted {
            id: AgentId::new_v4(),
        };
        let chunk = kernel_event_to_ws_chunk(&event, &None);
        assert!(chunk.is_none());
    }
}

// ---------------------------------------------------------------------------
// RFC-016: Knowledge Save API
// ---------------------------------------------------------------------------

/// GET /api/chat/{session_id}/knowledge-saves
///   → Returns the knowledge save records for a session.
pub(crate) async fn handle_knowledge_saves(
    state: State<Arc<AppState>>,
    Path(session_id): Path<String>,
) -> Result<Json<serde_json::Value>, AppError> {
    let saves: Vec<serde_json::Value> = state
        .kernel
        .state
        .load("knowledge-saves", &session_id)
        .await
        .ok()
        .flatten()
        .unwrap_or_default();
    Ok(Json(serde_json::json!({ "saves": saves })))
}

/// Request body for saving a message to knowledge.
#[derive(Debug, Deserialize)]
pub(crate) struct SaveToKnowledgeRequest {
    /// Optional path hint for the knowledge note.
    #[serde(default)]
    path: Option<String>,
}

/// POST /api/chat/{session_id}/messages/{message_index}/save-to-knowledge
///   → Saves the message content to the knowledge vault.
pub(crate) async fn handle_save_to_knowledge(
    state: State<Arc<AppState>>,
    Path((session_id, message_index)): Path<(String, usize)>,
    Json(_body): Json<SaveToKnowledgeRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
    // Check if already saved
    let existing: Vec<serde_json::Value> = state
        .kernel
        .state
        .load("knowledge-saves", &session_id)
        .await
        .ok()
        .flatten()
        .unwrap_or_default();

    for save in &existing {
        if save.get("message_index").and_then(|v| v.as_u64()) == Some(message_index as u64) {
            let path = save
                .get("knowledge_path")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            return Ok(Json(serde_json::json!({
                "error": "already_saved",
                "path": path,
            })));
        }
    }

    // Load the session to get the message content
    let session = state
        .kernel
        .state
        .load_session(&oxios_kernel::state_store::SessionId(session_id.clone()))
        .await?;

    let session = match session {
        Some(s) => s,
        None => return Err(AppError::from(anyhow::anyhow!("Session not found"))),
    };

    // Find the agent response at the given index
    let response = match session.agent_responses.get(message_index) {
        Some(r) => r,
        None => {
            return Err(AppError::from(anyhow::anyhow!(
                "Message index out of range"
            )));
        }
    };

    let content = &response.content;
    if content.is_empty() {
        return Err(AppError::from(anyhow::anyhow!("Message content is empty")));
    }

    // Generate path
    let path = _body.path.clone().unwrap_or_else(|| {
        let slug: String = content
            .lines()
            .find(|l| l.starts_with("# ") || l.starts_with("## "))
            .map(|l| l.trim_start_matches('#').trim().to_string())
            .unwrap_or_else(|| "note".to_string());
        let slug: String = slug
            .to_lowercase()
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == '-' || c == '_' {
                    c
                } else {
                    '-'
                }
            })
            .collect();
        let date = chrono::Local::now().format("%Y-%m-%d").to_string();
        format!("notes/{slug}-{date}.md")
    });

    // Write to KnowledgeBase with provenance metadata (RFC-022)
    let meta = oxios_markdown::types::NoteMeta {
        author: "agent".to_string(),
        source: oxios_markdown::types::NoteSource::Ui,
        quality: oxios_markdown::types::NoteQuality::Raw,
        needs_review: true,
        session_id: Some(session_id.clone()),
        message_index: Some(message_index),
        saved_at: Some(chrono::Utc::now().to_rfc3339()),
    };
    match state
        .kernel
        .knowledge
        .note_write_with_meta(&path, content, &meta)
    {
        Ok(true) => {}
        Ok(false) => {
            // Path is a user-authored file — force write via plain note_write
            state.kernel.knowledge.note_write(&path, content)?;
        }
        Err(e) => return Err(AppError::from(e)),
    }

    // Record the save
    let record = serde_json::json!({
        "message_index": message_index,
        "knowledge_path": path,
        "saved_at": chrono::Utc::now().to_rfc3339(),
        "source": "user",
    });
    let mut saves = existing;
    saves.push(record);
    state
        .kernel
        .state
        .save("knowledge-saves", &session_id, &saves)
        .await?;

    // Publish event
    let _ = state
        .kernel
        .infra
        .publish(oxios_kernel::event_bus::KernelEvent::KnowledgePersisted {
            session_id: session_id.clone(),
            message_index,
            path: path.clone(),
            source: "user".to_string(),
        });

    Ok(Json(serde_json::json!({ "path": path })))
}

/// DELETE /api/chat/{session_id}/messages/{message_index}/knowledge-save
///   → Removes a knowledge note that was saved from this message.
pub(crate) async fn handle_remove_knowledge_save(
    state: State<Arc<AppState>>,
    Path((session_id, message_index)): Path<(String, usize)>,
) -> Result<Json<serde_json::Value>, AppError> {
    let existing: Vec<serde_json::Value> = state
        .kernel
        .state
        .load("knowledge-saves", &session_id)
        .await
        .ok()
        .flatten()
        .unwrap_or_default();

    let target = existing.iter().find(|save| {
        save.get("message_index").and_then(|v| v.as_u64()) == Some(message_index as u64)
    });

    let target = match target {
        Some(t) => t.clone(),
        None => {
            return Err(AppError::from(anyhow::anyhow!(
                "No save found for this message"
            )));
        }
    };

    let path = target
        .get("knowledge_path")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // Delete from KnowledgeBase
    if !path.is_empty() {
        let _ = state.kernel.knowledge.note_delete(path);
    }

    // Remove the record
    let updated: Vec<serde_json::Value> = existing
        .into_iter()
        .filter(|save| {
            save.get("message_index").and_then(|v| v.as_u64()) != Some(message_index as u64)
        })
        .collect();
    state
        .kernel
        .state
        .save("knowledge-saves", &session_id, &updated)
        .await?;

    // Publish removal event
    let _ = state
        .kernel
        .infra
        .publish(oxios_kernel::event_bus::KernelEvent::KnowledgeRemoved {
            session_id: session_id.clone(),
            message_index,
        });

    Ok(Json(serde_json::json!({ "deleted_path": path })))
}