routa-core 0.15.2

Routa.js core domain — models, stores, protocols, and JSON-RPC (transport-agnostic)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
//! ACP (Agent Client Protocol) integration.
//!
//! Manages ACP agent processes and provides JSON-RPC communication
//! between the desktop client and coding agents (e.g. OpenCode, Claude, Copilot).
//!
//! Architecture (matches the Next.js `AcpProcessManager`):
//!   - `session/new`    → spawns a child process, sends `initialize` + `session/new`
//!   - `session/prompt` → reuses the live process, sends `session/prompt`
//!   - `session/cancel` → sends cancellation notification
//!   - SSE GET          → subscribes to `broadcast` channel for `session/update` events
//!
//! **Claude Code** uses a different protocol (stream-json) instead of ACP.
//! The `ClaudeCodeProcess` translates Claude's output into ACP-compatible
//! `session/update` notifications for frontend compatibility.
//!
//! **Agent Trace**: All sessions record trace events to JSONL files for
//! attribution tracking (which model/session/tool affected which files and when).

pub mod binary_manager;
pub mod claude_code_process;
pub mod docker;
pub mod installation_state;
pub mod mcp_setup;
pub mod paths;
pub mod process;
pub mod provider_adapter;
pub mod registry_fetch;
pub mod registry_types;
pub mod runtime_manager;
pub mod terminal_manager;
pub mod warmup;

pub use binary_manager::AcpBinaryManager;
pub use claude_code_process::{ClaudeCodeConfig, ClaudeCodeProcess};
pub use installation_state::AcpInstallationState;
pub use paths::AcpPaths;
pub use registry_fetch::{fetch_registry, fetch_registry_json};
pub use registry_types::*;
pub use runtime_manager::{current_platform, AcpRuntimeManager, RuntimeInfo, RuntimeType};
pub use warmup::{AcpWarmupService, WarmupState, WarmupStatus};

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tokio::sync::{broadcast, RwLock};

use crate::trace::{Contributor, TraceConversation, TraceEventType, TraceRecord, TraceWriter};
use process::AcpProcess;

#[cfg(windows)]
pub(crate) const CREATE_NO_WINDOW: u32 = 0x0800_0000;

fn validate_session_cwd(cwd: &str) -> Result<(), String> {
    let path = Path::new(cwd);
    if !path.exists() {
        return Err(format!(
            "Invalid session cwd '{}': directory does not exist",
            cwd
        ));
    }
    if !path.is_dir() {
        return Err(format!(
            "Invalid session cwd '{}': path is not a directory",
            cwd
        ));
    }
    Ok(())
}

// ─── Session Record ─────────────────────────────────────────────────────

/// Record of an active ACP session persisted for UI listing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcpSessionRecord {
    pub session_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub cwd: String,
    pub workspace_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub routa_agent_id: Option<String>,
    pub provider: Option<String>,
    pub role: Option<String>,
    pub mode_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    pub created_at: String,
    #[serde(default)]
    pub first_prompt_sent: bool,
    /// Parent session ID for CRAFTER child sessions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub specialist_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub specialist_system_prompt: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct SessionLaunchOptions {
    pub specialist_id: Option<String>,
    pub specialist_system_prompt: Option<String>,
    pub allowed_native_tools: Option<Vec<String>>,
    pub initialize_timeout_ms: Option<u64>,
    pub provider_args: Option<Vec<String>>,
    pub acp_mcp_servers: Option<Vec<serde_json::Value>>,
}

// ─── Managed Process ────────────────────────────────────────────────────

/// Process type enum to support both ACP and Claude stream-json protocols.
#[derive(Clone)]
enum AgentProcessType {
    /// Standard ACP protocol (opencode, gemini, copilot, etc.)
    Acp(Arc<AcpProcess>),
    /// Claude Code stream-json protocol
    Claude(Arc<ClaudeCodeProcess>),
}

impl AgentProcessType {
    /// Kill the underlying process.
    async fn kill(&self) {
        match self {
            AgentProcessType::Acp(process) => process.kill().await,
            AgentProcessType::Claude(process) => process.kill().await,
        }
    }
}

/// A managed agent process with its metadata.
struct ManagedProcess {
    process: AgentProcessType,
    /// The agent's own session ID (returned by `session/new` or claude's session_id).
    acp_session_id: String,
    preset_id: String,
    #[allow(dead_code)]
    created_at: String,
    /// Trace writer for recording agent activities to JSONL
    trace_writer: TraceWriter,
    /// Working directory (for contributor context)
    #[allow(dead_code)]
    cwd: String,
}

// ─── ACP Manager ────────────────────────────────────────────────────────

/// Manages ACP agent sessions and process lifecycle.
///
/// Each session maps to a long-lived child process that communicates via
/// stdio JSON-RPC. Notifications are forwarded to subscribers via broadcast.
#[derive(Clone)]
pub struct AcpManager {
    /// Our sessionId → session record (for UI listing)
    sessions: Arc<RwLock<HashMap<String, AcpSessionRecord>>>,
    /// Our sessionId → managed process (the live agent)
    processes: Arc<RwLock<HashMap<String, ManagedProcess>>>,
    /// Our sessionId → broadcast sender for SSE notifications
    notification_channels: Arc<RwLock<HashMap<String, broadcast::Sender<serde_json::Value>>>>,
    /// Our sessionId → message history (session/update notifications)
    history: Arc<RwLock<HashMap<String, Vec<serde_json::Value>>>>,
}

impl Default for AcpManager {
    fn default() -> Self {
        Self::new()
    }
}

impl AcpManager {
    pub fn rewrite_notification_session_id(
        session_id: &str,
        mut notification: serde_json::Value,
    ) -> serde_json::Value {
        if let Some(object) = notification.as_object_mut() {
            object.insert(
                "sessionId".to_string(),
                serde_json::Value::String(session_id.to_string()),
            );
        }
        notification
    }

    pub fn new() -> Self {
        Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            processes: Arc::new(RwLock::new(HashMap::new())),
            notification_channels: Arc::new(RwLock::new(HashMap::new())),
            history: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// List all session records.
    pub async fn list_sessions(&self) -> Vec<AcpSessionRecord> {
        let sessions = self.sessions.read().await;
        sessions.values().cloned().collect()
    }

    /// Get a session record by ID.
    pub async fn get_session(&self, session_id: &str) -> Option<AcpSessionRecord> {
        let sessions = self.sessions.read().await;
        sessions.get(session_id).cloned()
    }

    /// Rename a session.
    /// Returns `Some(())` if the session was found and renamed, `None` if not found.
    pub async fn rename_session(&self, session_id: &str, name: &str) -> Option<()> {
        let mut sessions = self.sessions.write().await;
        let session = sessions.get_mut(session_id)?;
        session.name = Some(name.to_string());
        Some(())
    }

    /// Attach a ROUTA agent ID to an existing session record.
    /// Returns `Some(())` if the session was found, `None` if not found.
    pub async fn set_routa_agent_id(&self, session_id: &str, routa_agent_id: &str) -> Option<()> {
        let mut sessions = self.sessions.write().await;
        let session = sessions.get_mut(session_id)?;
        session.routa_agent_id = Some(routa_agent_id.to_string());
        Some(())
    }

    /// Delete a session.
    /// Returns `Some(())` if the session was found and deleted, `None` if not found.
    pub async fn delete_session(&self, session_id: &str) -> Option<()> {
        let mut sessions = self.sessions.write().await;
        let mut processes = self.processes.write().await;
        let mut channels = self.notification_channels.write().await;
        let mut history = self.history.write().await;

        // Remove session record
        sessions.remove(session_id)?;

        // Kill the process if it exists
        if let Some(managed) = processes.remove(session_id) {
            let _ = managed.process.kill().await;
        }

        // Remove notification channel
        channels.remove(session_id);

        // Remove history
        history.remove(session_id);

        Some(())
    }

    /// Get session message history.
    /// Returns `Some(history)` if the session exists, `None` if not found.
    pub async fn get_session_history(&self, session_id: &str) -> Option<Vec<serde_json::Value>> {
        let history = self.history.read().await;
        history.get(session_id).cloned()
    }

    /// Add a notification to session history.
    /// Child agent notifications (those with `childAgentId`) are NOT stored in the
    /// parent session's history — they would flood out the ROUTA coordinator's own
    /// messages. Child messages are persisted in their own child session's history.
    pub async fn push_to_history(&self, session_id: &str, notification: serde_json::Value) {
        // Skip child agent notifications to prevent flooding parent history
        if notification.get("childAgentId").is_some() {
            return;
        }
        let mut history = self.history.write().await;
        let entries = history.entry(session_id.to_string()).or_default();
        entries.push(notification);
        // Cap at 500 entries (same limit as Next.js backend)
        if entries.len() > 500 {
            let drain_count = entries.len() - 500;
            entries.drain(0..drain_count);
        }
    }

    /// Broadcast a synthetic session/update event and persist it into in-memory history.
    pub async fn emit_session_update(
        &self,
        session_id: &str,
        update: serde_json::Value,
    ) -> Result<(), String> {
        let message = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "session/update",
            "params": {
                "sessionId": session_id,
                "update": update,
            }
        });

        if let Some(channel) = self
            .notification_channels
            .read()
            .await
            .get(session_id)
            .cloned()
        {
            let _ = channel.send(message.clone());
        } else {
            let params = message
                .get("params")
                .cloned()
                .ok_or_else(|| "Missing params in synthetic session/update".to_string())?;
            self.push_to_history(
                session_id,
                Self::rewrite_notification_session_id(session_id, params),
            )
            .await;
        }
        Ok(())
    }

    /// Mark a session as having had its first prompt dispatched.
    pub async fn mark_first_prompt_sent(&self, session_id: &str) {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.first_prompt_sent = true;
        }
    }

    /// Create a new ACP session: spawn agent process, initialize, create session.
    /// Supports both static presets and registry-based agents.
    /// **Claude** uses stream-json protocol instead of ACP.
    ///
    /// Returns `(our_session_id, agent_session_id)`.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_session(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider: Option<String>,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        tool_mode: Option<String>,
        mcp_profile: Option<String>,
    ) -> Result<(String, String), String> {
        self.create_session_with_options(
            session_id,
            cwd,
            workspace_id,
            provider,
            role,
            model,
            parent_session_id,
            tool_mode,
            mcp_profile,
            SessionLaunchOptions::default(),
        )
        .await
    }

    /// Resume a persisted ACP session using the provider's native session/load path.
    ///
    /// Returns `(our_session_id, agent_session_id)`.
    #[allow(clippy::too_many_arguments)]
    pub async fn load_session_with_options(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider: Option<String>,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        tool_mode: Option<String>,
        mcp_profile: Option<String>,
        provider_session_id: Option<String>,
        options: SessionLaunchOptions,
    ) -> Result<(String, String), String> {
        validate_session_cwd(&cwd)?;
        let provider_name = provider.as_deref().unwrap_or("opencode");
        let acp_mcp_servers = if matches!(provider_name, "codex" | "codex-acp") {
            options.acp_mcp_servers.clone().unwrap_or_else(|| {
                mcp_setup::build_acp_http_mcp_servers(
                    &workspace_id,
                    &session_id,
                    tool_mode.as_deref(),
                    mcp_profile.as_deref(),
                )
            })
        } else {
            Vec::new()
        };

        if provider_name == "claude" {
            return Err("Native session/load is not supported for Claude".to_string());
        }

        let (ntx, _) = broadcast::channel::<serde_json::Value>(256);
        let preset = get_preset_by_id_with_registry(provider_name).await?;

        if let Some(summary) = mcp_setup::ensure_mcp_for_provider(
            provider_name,
            &cwd,
            &workspace_id,
            &session_id,
            tool_mode.as_deref(),
            mcp_profile.as_deref(),
        )
        .await?
        {
            tracing::info!("[AcpManager] {}", summary);
        }

        let mut extra_args: Vec<String> = preset.args.clone();
        if matches!(provider_name, "codex" | "codex-acp") {
            for override_arg in mcp_setup::codex_cli_overrides(&cwd)? {
                extra_args.push("-c".to_string());
                extra_args.push(override_arg);
            }
        }
        if let Some(provider_args) = options.provider_args.clone() {
            extra_args.extend(provider_args);
        }
        if let Some(ref m) = model {
            if !m.is_empty() {
                extra_args.push("-m".to_string());
                extra_args.push(m.clone());
            }
        }

        let preset_command = resolve_preset_command(&preset);
        let process = AcpProcess::spawn(
            &preset_command,
            &extra_args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            &cwd,
            ntx.clone(),
            &preset.name,
            &session_id,
        )
        .await?;

        process
            .initialize_with_timeout(options.initialize_timeout_ms)
            .await?;

        let resolved_provider_session_id =
            provider_session_id.unwrap_or_else(|| session_id.clone());
        let acp_session_id = process
            .load_session(&resolved_provider_session_id, &cwd, &acp_mcp_servers)
            .await?;

        self.register_managed_session(
            session_id.clone(),
            cwd.clone(),
            workspace_id.clone(),
            provider_name.to_string(),
            role.clone(),
            model.clone(),
            parent_session_id.clone(),
            &options,
            AgentProcessType::Acp(Arc::new(process)),
            acp_session_id.clone(),
            ntx.clone(),
        )
        .await;

        tracing::info!(
            "[AcpManager] Session {} loaded (provider: {}, agent session: {})",
            session_id,
            provider_name,
            acp_session_id,
        );

        Ok((session_id, acp_session_id))
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn load_session(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider: Option<String>,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        tool_mode: Option<String>,
        mcp_profile: Option<String>,
        provider_session_id: Option<String>,
    ) -> Result<(String, String), String> {
        self.load_session_with_options(
            session_id,
            cwd,
            workspace_id,
            provider,
            role,
            model,
            parent_session_id,
            tool_mode,
            mcp_profile,
            provider_session_id,
            SessionLaunchOptions::default(),
        )
        .await
    }

    fn spawn_history_mirror(&self, session_id: &str, ntx: &broadcast::Sender<serde_json::Value>) {
        let history_manager = self.clone();
        let history_session_id = session_id.to_string();
        let mut history_rx = ntx.subscribe();
        tokio::spawn(async move {
            loop {
                match history_rx.recv().await {
                    Ok(message) => {
                        let params = match message.get("params") {
                            Some(value) => value.clone(),
                            None => continue,
                        };
                        history_manager
                            .push_to_history(
                                &history_session_id,
                                Self::rewrite_notification_session_id(&history_session_id, params),
                            )
                            .await;
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
                        tracing::warn!(
                            "[AcpManager] Dropped {} session/update notifications for {}",
                            skipped,
                            history_session_id
                        );
                    }
                }
            }
        });
    }

    #[allow(clippy::too_many_arguments)]
    async fn register_managed_session(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider_name: String,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        options: &SessionLaunchOptions,
        process_type: AgentProcessType,
        acp_session_id: String,
        ntx: broadcast::Sender<serde_json::Value>,
    ) {
        let created_at = chrono::Utc::now().to_rfc3339();
        let trace_writer = TraceWriter::new(&cwd);
        let record = AcpSessionRecord {
            session_id: session_id.clone(),
            name: None,
            cwd: cwd.clone(),
            workspace_id: workspace_id.clone(),
            routa_agent_id: None,
            provider: Some(provider_name.clone()),
            role: role.clone().or(Some("CRAFTER".to_string())),
            mode_id: None,
            model: model.clone(),
            created_at: created_at.clone(),
            first_prompt_sent: false,
            parent_session_id: parent_session_id.clone(),
            specialist_id: options.specialist_id.clone(),
            specialist_system_prompt: options.specialist_system_prompt.clone(),
        };

        self.sessions
            .write()
            .await
            .insert(session_id.clone(), record);
        self.processes.write().await.insert(
            session_id.clone(),
            ManagedProcess {
                process: process_type,
                acp_session_id: acp_session_id.clone(),
                preset_id: provider_name.clone(),
                created_at,
                trace_writer: trace_writer.clone(),
                cwd: cwd.clone(),
            },
        );
        self.notification_channels
            .write()
            .await
            .insert(session_id.clone(), ntx.clone());
        self.spawn_history_mirror(&session_id, &ntx);

        let trace = TraceRecord::new(
            &session_id,
            TraceEventType::SessionStart,
            Contributor::new(&provider_name, None),
        )
        .with_workspace_id(&workspace_id)
        .with_metadata(
            "role",
            serde_json::json!(role.as_deref().unwrap_or("CRAFTER")),
        )
        .with_metadata("cwd", serde_json::json!(cwd));

        trace_writer.append_safe(&trace).await;
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn create_session_from_inline(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider_name: String,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        command: String,
        args: Vec<String>,
        options: SessionLaunchOptions,
    ) -> Result<(String, String), String> {
        validate_session_cwd(&cwd)?;
        let (ntx, _) = broadcast::channel::<serde_json::Value>(256);

        let process = AcpProcess::spawn(
            &command,
            &args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            &cwd,
            ntx.clone(),
            &provider_name,
            &session_id,
        )
        .await?;

        process
            .initialize_with_timeout(options.initialize_timeout_ms)
            .await?;

        let acp_session_id = process
            .new_session(&cwd, options.acp_mcp_servers.as_deref().unwrap_or(&[]))
            .await?;
        self.register_managed_session(
            session_id.clone(),
            cwd.clone(),
            workspace_id.clone(),
            provider_name.clone(),
            role.clone(),
            model.clone(),
            parent_session_id.clone(),
            &options,
            AgentProcessType::Acp(Arc::new(process)),
            acp_session_id.clone(),
            ntx.clone(),
        )
        .await;

        tracing::info!(
            "[AcpManager] Session {} created from inline command (provider: {}, agent session: {})",
            session_id,
            provider_name,
            acp_session_id,
        );

        Ok((session_id, acp_session_id))
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn load_session_from_inline(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider_name: String,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        command: String,
        args: Vec<String>,
        provider_session_id: Option<String>,
        options: SessionLaunchOptions,
    ) -> Result<(String, String), String> {
        validate_session_cwd(&cwd)?;
        let (ntx, _) = broadcast::channel::<serde_json::Value>(256);

        let process = AcpProcess::spawn(
            &command,
            &args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            &cwd,
            ntx.clone(),
            &provider_name,
            &session_id,
        )
        .await?;

        process
            .initialize_with_timeout(options.initialize_timeout_ms)
            .await?;

        let resolved_provider_session_id =
            provider_session_id.unwrap_or_else(|| session_id.clone());
        let acp_session_id = process
            .load_session(
                &resolved_provider_session_id,
                &cwd,
                options.acp_mcp_servers.as_deref().unwrap_or(&[]),
            )
            .await?;

        self.register_managed_session(
            session_id.clone(),
            cwd.clone(),
            workspace_id.clone(),
            provider_name.clone(),
            role.clone(),
            model.clone(),
            parent_session_id.clone(),
            &options,
            AgentProcessType::Acp(Arc::new(process)),
            acp_session_id.clone(),
            ntx.clone(),
        )
        .await;

        tracing::info!(
            "[AcpManager] Session {} loaded from inline command (provider: {}, agent session: {})",
            session_id,
            provider_name,
            acp_session_id,
        );

        Ok((session_id, acp_session_id))
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn create_session_with_options(
        &self,
        session_id: String,
        cwd: String,
        workspace_id: String,
        provider: Option<String>,
        role: Option<String>,
        model: Option<String>,
        parent_session_id: Option<String>,
        tool_mode: Option<String>,
        mcp_profile: Option<String>,
        options: SessionLaunchOptions,
    ) -> Result<(String, String), String> {
        validate_session_cwd(&cwd)?;
        let provider_name = provider.as_deref().unwrap_or("opencode");
        let acp_mcp_servers = if matches!(provider_name, "codex" | "codex-acp") {
            options.acp_mcp_servers.clone().unwrap_or_else(|| {
                mcp_setup::build_acp_http_mcp_servers(
                    &workspace_id,
                    &session_id,
                    tool_mode.as_deref(),
                    mcp_profile.as_deref(),
                )
            })
        } else {
            Vec::new()
        };

        // Create the notification broadcast channel for this session
        let (ntx, _) = broadcast::channel::<serde_json::Value>(256);
        let claude_mcp_config = if provider_name == "claude" {
            Some(mcp_setup::build_claude_mcp_config(
                &workspace_id,
                &session_id,
                tool_mode.as_deref(),
                mcp_profile.as_deref(),
            ))
        } else {
            None
        };

        // Check if this is Claude (uses stream-json protocol, not ACP)
        let (process_type, acp_session_id) = if provider_name == "claude" {
            // Use Claude Code stream-json protocol
            let config = ClaudeCodeConfig {
                command: "claude".to_string(),
                cwd: cwd.clone(),
                display_name: format!("Claude-{}", &session_id[..8.min(session_id.len())]),
                permission_mode: Some("bypassPermissions".to_string()),
                mcp_configs: claude_mcp_config.into_iter().collect(),
                append_system_prompt: options.specialist_system_prompt.clone(),
                allowed_tools: options.allowed_native_tools.clone(),
            };

            let claude_process = ClaudeCodeProcess::spawn(config, ntx.clone()).await?;
            let claude_session_id = claude_process
                .session_id()
                .await
                .unwrap_or_else(|| format!("claude-{}", &session_id[..8.min(session_id.len())]));

            (
                AgentProcessType::Claude(Arc::new(claude_process)),
                claude_session_id,
            )
        } else {
            // Use standard ACP protocol
            let preset = get_preset_by_id_with_registry(provider_name).await?;

            if let Some(summary) = mcp_setup::ensure_mcp_for_provider(
                provider_name,
                &cwd,
                &workspace_id,
                &session_id,
                tool_mode.as_deref(),
                mcp_profile.as_deref(),
            )
            .await?
            {
                tracing::info!("[AcpManager] {}", summary);
            }

            // Build args: preset args + optional model flag
            let mut extra_args: Vec<String> = preset.args.clone();
            if matches!(provider_name, "codex" | "codex-acp") {
                for override_arg in mcp_setup::codex_cli_overrides(&cwd)? {
                    extra_args.push("-c".to_string());
                    extra_args.push(override_arg);
                }
            }
            if let Some(provider_args) = options.provider_args.clone() {
                extra_args.extend(provider_args);
            }
            if let Some(ref m) = model {
                if !m.is_empty() {
                    // opencode (and future providers) accept -m <model>
                    extra_args.push("-m".to_string());
                    extra_args.push(m.clone());
                }
            }

            let preset_command = resolve_preset_command(&preset);
            let process = AcpProcess::spawn(
                &preset_command,
                &extra_args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                &cwd,
                ntx.clone(),
                &preset.name,
                &session_id,
            )
            .await?;

            // Initialize the protocol
            process
                .initialize_with_timeout(options.initialize_timeout_ms)
                .await?;

            // Create the agent session
            let agent_session_id = process.new_session(&cwd, &acp_mcp_servers).await?;

            (AgentProcessType::Acp(Arc::new(process)), agent_session_id)
        };

        self.register_managed_session(
            session_id.clone(),
            cwd.clone(),
            workspace_id.clone(),
            provider_name.to_string(),
            role.clone(),
            model.clone(),
            parent_session_id.clone(),
            &options,
            process_type,
            acp_session_id.clone(),
            ntx.clone(),
        )
        .await;

        tracing::info!(
            "[AcpManager] Session {} created (provider: {}, agent session: {})",
            session_id,
            provider_name,
            acp_session_id,
        );

        Ok((session_id, acp_session_id))
    }

    /// Send a prompt to an existing session's agent process.
    pub async fn prompt(&self, session_id: &str, text: &str) -> Result<serde_json::Value, String> {
        self.mark_first_prompt_sent(session_id).await;

        let (process, acp_session_id, preset_id, trace_writer) = {
            let processes = self.processes.read().await;
            let managed = processes
                .get(session_id)
                .ok_or_else(|| format!("No agent process for session: {}", session_id))?;
            (
                managed.process.clone(),
                managed.acp_session_id.clone(),
                managed.preset_id.clone(),
                managed.trace_writer.clone(),
            )
        };

        let is_alive = match &process {
            AgentProcessType::Acp(p) => p.is_alive(),
            AgentProcessType::Claude(p) => p.is_alive(),
        };

        if !is_alive {
            return Err(format!("Agent ({}) process is not running", preset_id));
        }

        // Record UserMessage trace
        let trace = TraceRecord::new(
            session_id,
            TraceEventType::UserMessage,
            Contributor::new(&preset_id, None),
        )
        .with_conversation(TraceConversation {
            turn: None,
            role: Some("user".to_string()),
            content_preview: Some(truncate_content(text, 500)),
            full_content: None,
        });

        trace_writer.append_safe(&trace).await;

        tracing::info!(
            target: "routa_acp_prompt",
            session_id = %session_id,
            preset_id = %preset_id,
            acp_session_id = %acp_session_id,
            prompt_len = text.len(),
            "acp prompt start"
        );

        let result = match &process {
            AgentProcessType::Acp(p) => p.prompt(&acp_session_id, text).await,
            AgentProcessType::Claude(p) => {
                let stop_reason = p.prompt(text).await?;
                Ok(serde_json::json!({ "stopReason": stop_reason }))
            }
        };

        match &result {
            Ok(_) => tracing::info!(
                target: "routa_acp_prompt",
                session_id = %session_id,
                preset_id = %preset_id,
                "acp prompt success"
            ),
            Err(error) => tracing::error!(
                target: "routa_acp_prompt",
                session_id = %session_id,
                preset_id = %preset_id,
                error = %error,
                "acp prompt failed"
            ),
        }

        result
    }

    /// Cancel the current prompt in a session.
    pub async fn cancel(&self, session_id: &str) {
        let processes = self.processes.read().await;
        if let Some(managed) = processes.get(session_id) {
            match &managed.process {
                AgentProcessType::Acp(p) => p.cancel(&managed.acp_session_id).await,
                AgentProcessType::Claude(p) => p.cancel().await,
            }
        }
    }

    /// Kill a session's agent process and remove it.
    pub async fn kill_session(&self, session_id: &str) {
        // Kill the process
        if let Some(managed) = self.processes.write().await.remove(session_id) {
            // Record SessionEnd trace before killing
            let trace = TraceRecord::new(
                session_id,
                TraceEventType::SessionEnd,
                Contributor::new(&managed.preset_id, None),
            );
            managed.trace_writer.append_safe(&trace).await;

            match &managed.process {
                AgentProcessType::Acp(p) => p.kill().await,
                AgentProcessType::Claude(p) => p.kill().await,
            }
        }
        // Remove session record
        self.sessions.write().await.remove(session_id);
        // Remove notification channel
        self.notification_channels.write().await.remove(session_id);
    }

    /// Subscribe to SSE notifications for a session.
    /// Returns a broadcast receiver that yields `session/update` JSON-RPC messages.
    pub async fn subscribe(
        &self,
        session_id: &str,
    ) -> Option<broadcast::Receiver<serde_json::Value>> {
        let channels = self.notification_channels.read().await;
        channels.get(session_id).map(|tx| tx.subscribe())
    }

    /// Check if a session's agent process is alive.
    pub async fn is_alive(&self, session_id: &str) -> bool {
        let processes = self.processes.read().await;
        processes
            .get(session_id)
            .map(|m| match &m.process {
                AgentProcessType::Acp(p) => p.is_alive(),
                AgentProcessType::Claude(p) => p.is_alive(),
            })
            .unwrap_or(false)
    }

    /// Get the managed ACP session id for a live session.
    pub async fn get_acp_session_id(&self, session_id: &str) -> Option<String> {
        let processes = self.processes.read().await;
        processes
            .get(session_id)
            .map(|managed| managed.acp_session_id.clone())
    }

    /// Get the preset ID for a session.
    pub async fn get_preset_id(&self, session_id: &str) -> Option<String> {
        let processes = self.processes.read().await;
        processes.get(session_id).map(|m| m.preset_id.clone())
    }

    /// Check if a session uses Claude (stream-json protocol, not ACP).
    pub async fn is_claude_session(&self, session_id: &str) -> bool {
        let processes = self.processes.read().await;
        processes
            .get(session_id)
            .map(|m| matches!(&m.process, AgentProcessType::Claude(_)))
            .unwrap_or(false)
    }

    /// Send a prompt to Claude session and return immediately.
    /// The actual response is streamed via the broadcast channel.
    /// Use `subscribe()` to receive notifications.
    pub async fn prompt_claude_async(&self, session_id: &str, text: &str) -> Result<(), String> {
        let processes = self.processes.read().await;
        let managed = processes
            .get(session_id)
            .ok_or_else(|| format!("No agent process for session: {}", session_id))?;

        // Record trace
        let trace = TraceRecord::new(
            session_id,
            TraceEventType::UserMessage,
            Contributor::new(&managed.preset_id, None),
        )
        .with_conversation(TraceConversation {
            turn: None,
            role: Some("user".to_string()),
            content_preview: Some(truncate_content(text, 500)),
            full_content: Some(text.to_string()),
        });

        managed.trace_writer.append_safe(&trace).await;

        match &managed.process {
            AgentProcessType::Claude(p) => {
                // Spawn the prompt in a background task so we can return immediately
                let process = Arc::clone(p);
                let text = text.to_string();
                tokio::spawn(async move {
                    let _ = process.prompt(&text).await;
                });
                Ok(())
            }
            AgentProcessType::Acp(_) => {
                Err("prompt_claude_async is only for Claude sessions".to_string())
            }
        }
    }
}

// ─── ACP Presets ────────────────────────────────────────────────────────

/// Resume/continuation capability metadata for a provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResumeCapability {
    pub supported: bool,
    /// "native" | "replay" | "both"
    pub mode: String,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supports_fork: Option<bool>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supports_list: Option<bool>,
}

/// ACP provider presets for known coding agents.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcpPreset {
    /// Unique identifier (lowercase, e.g., "claude", "opencode")
    pub id: String,
    /// Human-readable display name (e.g., "Claude Code", "OpenCode")
    pub name: String,
    pub command: String,
    pub args: Vec<String>,
    pub description: String,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env_bin_override: Option<String>,
    /// Resume/continuation capabilities for this provider.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume: Option<ResumeCapability>,
}

/// Get the list of known ACP agent presets (static/builtin only).
pub fn get_presets() -> Vec<AcpPreset> {
    vec![
        AcpPreset {
            id: "opencode".to_string(),
            name: "OpenCode".to_string(),
            command: "opencode".to_string(),
            args: vec!["acp".to_string()],
            description: "OpenCode AI coding agent".to_string(),
            env_bin_override: Some("OPENCODE_BIN".to_string()),
            resume: Some(ResumeCapability {
                supported: true,
                mode: "replay".to_string(),
                supports_fork: None,
                supports_list: None,
            }),
        },
        AcpPreset {
            id: "gemini".to_string(),
            name: "Gemini".to_string(),
            command: "gemini".to_string(),
            args: vec!["--experimental-acp".to_string()],
            description: "Google Gemini CLI".to_string(),
            env_bin_override: None,
            resume: None,
        },
        AcpPreset {
            id: "codex-acp".to_string(),
            name: "Codex".to_string(),
            command: "codex-acp".to_string(),
            args: vec![],
            description: "OpenAI Codex CLI (codex-acp wrapper)".to_string(),
            env_bin_override: Some("CODEX_ACP_BIN".to_string()),
            resume: Some(ResumeCapability {
                supported: true,
                mode: "both".to_string(),
                supports_fork: None,
                supports_list: Some(true),
            }),
        },
        AcpPreset {
            id: "copilot".to_string(),
            name: "GitHub Copilot".to_string(),
            command: "copilot".to_string(),
            args: vec![
                "--acp".to_string(),
                "--allow-all-tools".to_string(),
                "--no-ask-user".to_string(),
            ],
            description: "GitHub Copilot CLI".to_string(),
            env_bin_override: Some("COPILOT_BIN".to_string()),
            resume: None,
        },
        AcpPreset {
            id: "auggie".to_string(),
            name: "Auggie".to_string(),
            command: "auggie".to_string(),
            args: vec!["--acp".to_string()],
            description: "Augment Code's AI agent".to_string(),
            env_bin_override: None,
            resume: None,
        },
        AcpPreset {
            id: "kimi".to_string(),
            name: "Kimi".to_string(),
            command: "kimi".to_string(),
            args: vec!["acp".to_string()],
            description: "Moonshot AI's Kimi CLI".to_string(),
            env_bin_override: None,
            resume: None,
        },
        AcpPreset {
            id: "kiro".to_string(),
            name: "Kiro".to_string(),
            command: "kiro-cli".to_string(),
            args: vec!["acp".to_string()],
            description: "Amazon Kiro AI coding agent".to_string(),
            env_bin_override: Some("KIRO_BIN".to_string()),
            resume: None,
        },
        AcpPreset {
            id: "qoder".to_string(),
            name: "Qoder".to_string(),
            command: "qodercli".to_string(),
            args: vec!["--acp".to_string()],
            description: "Qoder AI coding agent".to_string(),
            env_bin_override: Some("QODER_BIN".to_string()),
            resume: None,
        },
        AcpPreset {
            id: "claude".to_string(),
            name: "Claude Code".to_string(),
            command: "claude".to_string(),
            // Claude Code uses stream-json protocol, not ACP flags
            // Args are unused since we use ClaudeCodeProcess directly
            args: vec![],
            description: "Anthropic Claude Code (stream-json protocol)".to_string(),
            env_bin_override: Some("CLAUDE_BIN".to_string()),
            resume: Some(ResumeCapability {
                supported: true,
                mode: "replay".to_string(),
                supports_fork: Some(true),
                supports_list: None,
            }),
        },
    ]
}

/// Get a static preset by ID (synchronous, no registry lookup).
pub fn get_preset_by_id(id: &str) -> Option<AcpPreset> {
    let normalized_id = match id {
        "codex" => "codex-acp",
        "qodercli" => "qoder",
        other => other,
    };
    get_presets().into_iter().find(|p| p.id == normalized_id)
}

/// Get the resume capability for a provider ID (synchronous).
pub fn get_resume_capability(provider: &str) -> Option<ResumeCapability> {
    get_preset_by_id(provider).and_then(|p| p.resume)
}

/// Get a preset by ID, checking both static presets and registry.
/// Static presets take precedence.
///
/// Supports suffixed IDs like "auggie-registry" to explicitly request
/// the registry version when both built-in and registry versions exist.
pub async fn get_preset_by_id_with_registry(id: &str) -> Result<AcpPreset, String> {
    let normalized_id = match id {
        "codex" => "codex-acp",
        "qodercli" => "qoder",
        other => other,
    };

    // Handle suffixed IDs (e.g., "auggie-registry")
    // This allows explicit selection of registry version when both exist
    const REGISTRY_SUFFIX: &str = "-registry";
    if let Some(base_id) = normalized_id.strip_suffix(REGISTRY_SUFFIX) {
        let mut preset = get_registry_preset(base_id).await?;
        // Keep the suffixed ID in the returned preset for consistency
        preset.id = id.to_string();
        return Ok(preset);
    }

    // Check static presets first (match by id, not name)
    if let Some(mut preset) = get_presets().into_iter().find(|p| p.id == normalized_id) {
        if preset.id != id {
            preset.id = id.to_string();
        }
        return Ok(preset);
    }

    // Fall back to registry
    let mut preset = get_registry_preset(normalized_id).await?;
    if preset.id != id {
        preset.id = id.to_string();
    }
    Ok(preset)
}

/// Get a preset from the ACP registry by ID.
async fn get_registry_preset(id: &str) -> Result<AcpPreset, String> {
    let registry: AcpRegistry = fetch_registry().await?;

    // Find the agent
    let agent = registry
        .agents
        .into_iter()
        .find(|a| a.id == id)
        .ok_or_else(|| format!("Agent '{}' not found in registry", id))?;

    // Build command from distribution
    let (command, args) = if let Some(ref npx) = agent.distribution.npx {
        let mut args = vec!["-y".to_string(), npx.package.clone()];
        args.extend(npx.args.clone());
        ("npx".to_string(), args)
    } else if let Some(ref uvx) = agent.distribution.uvx {
        let mut args = vec![uvx.package.clone()];
        args.extend(uvx.args.clone());
        ("uvx".to_string(), args)
    } else {
        return Err(format!(
            "Agent '{}' has no supported distribution (npx/uvx)",
            id
        ));
    };

    Ok(AcpPreset {
        id: agent.id.clone(),
        name: agent.name,
        command,
        args,
        description: agent.description,
        env_bin_override: None,
        resume: None,
    })
}

fn resolve_preset_command(preset: &AcpPreset) -> String {
    if let Some(env_var) = &preset.env_bin_override {
        if let Ok(custom_command) = std::env::var(env_var) {
            let trimmed = custom_command.trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
    }

    crate::shell_env::which(&preset.command).unwrap_or_else(|| preset.command.clone())
}

// ─── Utility Functions ─────────────────────────────────────────────────────

/// Truncate content to a maximum length for storage in traces.
fn truncate_content(text: &str, max_len: usize) -> String {
    if text.chars().count() <= max_len {
        text.to_string()
    } else if max_len <= 3 {
        text.chars().take(max_len).collect()
    } else {
        let truncated: String = text.chars().take(max_len - 3).collect();
        format!("{truncated}...")
    }
}

#[cfg(test)]
mod tests {
    use super::{
        get_preset_by_id_with_registry, get_presets, truncate_content, validate_session_cwd,
        AcpManager, AcpSessionRecord,
    };
    use std::collections::HashMap;
    use std::fs;
    use std::sync::Arc;
    use tokio::sync::RwLock;

    #[test]
    fn static_presets_include_codex_acp_for_codex_alias() {
        let presets = get_presets();
        assert!(presets.iter().any(|preset| preset.id == "codex-acp"));
    }

    #[test]
    fn static_presets_include_qoder() {
        let presets = get_presets();
        assert!(presets.iter().any(|preset| preset.id == "qoder"));
    }

    #[tokio::test]
    async fn qodercli_alias_resolves_to_qoder_preset() {
        let preset = get_preset_by_id_with_registry("qodercli")
            .await
            .expect("qodercli alias should resolve");
        assert_eq!(preset.id, "qodercli");
        assert_eq!(preset.command, "qodercli");
        assert_eq!(preset.args, vec!["--acp".to_string()]);
    }

    #[test]
    fn validate_session_cwd_rejects_missing_or_non_directory_paths() {
        let temp = tempfile::tempdir().expect("tempdir should create");
        let missing = temp.path().join("missing-dir");
        let file_path = temp.path().join("not-a-dir.txt");
        fs::write(&file_path, "content").expect("file should write");

        let missing_error = validate_session_cwd(missing.to_string_lossy().as_ref())
            .expect_err("missing directory should fail");
        assert!(missing_error.contains("directory does not exist"));

        let file_error = validate_session_cwd(file_path.to_string_lossy().as_ref())
            .expect_err("file path should fail");
        assert!(file_error.contains("path is not a directory"));

        validate_session_cwd(temp.path().to_string_lossy().as_ref())
            .expect("existing directory should pass");
    }

    #[tokio::test]
    async fn mark_first_prompt_sent_updates_live_session_record() {
        let manager = AcpManager::new();
        let session_id = "session-1".to_string();
        manager.sessions.write().await.insert(
            session_id.clone(),
            AcpSessionRecord {
                session_id: session_id.clone(),
                name: None,
                cwd: ".".to_string(),
                workspace_id: "default".to_string(),
                routa_agent_id: None,
                provider: Some("opencode".to_string()),
                role: Some("CRAFTER".to_string()),
                mode_id: None,
                model: None,
                created_at: chrono::Utc::now().to_rfc3339(),
                first_prompt_sent: false,
                parent_session_id: None,
                specialist_id: None,
                specialist_system_prompt: None,
            },
        );

        manager.mark_first_prompt_sent(&session_id).await;

        let session = manager.get_session(&session_id).await.expect("session");
        assert!(session.first_prompt_sent);
    }

    #[tokio::test]
    async fn push_to_history_skips_parent_child_forwarding_noise() {
        let manager = AcpManager {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            processes: Arc::new(RwLock::new(HashMap::new())),
            notification_channels: Arc::new(RwLock::new(HashMap::new())),
            history: Arc::new(RwLock::new(HashMap::new())),
        };

        manager
            .push_to_history(
                "parent",
                serde_json::json!({
                    "sessionId": "parent",
                    "childAgentId": "child-1",
                    "update": { "sessionUpdate": "agent_message", "content": { "type": "text", "text": "delegated" } }
                }),
            )
            .await;

        let history = manager
            .get_session_history("parent")
            .await
            .unwrap_or_default();
        assert!(history.is_empty());
    }

    #[tokio::test]
    async fn emit_session_update_broadcasts_when_channel_exists() {
        let (tx, mut rx) = tokio::sync::broadcast::channel(8);
        let manager = AcpManager {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            processes: Arc::new(RwLock::new(HashMap::new())),
            notification_channels: Arc::new(RwLock::new(HashMap::from([(
                "session-1".to_string(),
                tx,
            )]))),
            history: Arc::new(RwLock::new(HashMap::new())),
        };

        manager
            .emit_session_update(
                "session-1",
                serde_json::json!({
                    "sessionUpdate": "turn_complete",
                    "stopReason": "cancelled"
                }),
            )
            .await
            .expect("emit should succeed");

        let broadcast = rx.recv().await.expect("broadcast event");
        assert_eq!(
            broadcast["params"]["update"]["sessionUpdate"].as_str(),
            Some("turn_complete")
        );
        assert_eq!(
            broadcast["params"]["update"]["stopReason"].as_str(),
            Some("cancelled")
        );
    }

    #[tokio::test]
    async fn emit_session_update_persists_history_without_channel() {
        let manager = AcpManager {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            processes: Arc::new(RwLock::new(HashMap::new())),
            notification_channels: Arc::new(RwLock::new(HashMap::new())),
            history: Arc::new(RwLock::new(HashMap::new())),
        };

        manager
            .emit_session_update(
                "session-1",
                serde_json::json!({
                    "sessionUpdate": "turn_complete",
                    "stopReason": "cancelled"
                }),
            )
            .await
            .expect("emit should succeed");

        let history = manager
            .get_session_history("session-1")
            .await
            .expect("history should exist");
        assert_eq!(history.len(), 1);
        assert_eq!(
            history[0]["update"]["sessionUpdate"].as_str(),
            Some("turn_complete")
        );
    }

    #[test]
    fn rewrite_notification_session_id_overrides_provider_session_id() {
        let rewritten = AcpManager::rewrite_notification_session_id(
            "child-session",
            serde_json::json!({
                "sessionId": "provider-session",
                "update": { "sessionUpdate": "agent_message_chunk", "content": { "text": "hi" } }
            }),
        );

        assert_eq!(rewritten["sessionId"].as_str(), Some("child-session"));
    }

    #[test]
    fn truncate_content_handles_unicode_boundaries() {
        assert_eq!(truncate_content("你好世界ABC", 5), "你好...");
        assert_eq!(truncate_content("你好世界ABC", 3), "你好世");
        assert_eq!(truncate_content("短文本", 10), "短文本");
    }
}