travelagent 1.10.3

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

// `forbid` would prevent a narrow, justified opt-out in mcp_socket for the
// `libc::kill(pid, 0)` liveness probe. `deny` still fails the build on any
// unsafe block unless explicitly allowed with a local justification.
#![cfg_attr(not(test), deny(unsafe_code))]

mod app;
mod cli;
mod demo;
mod external_editor;
mod forge_detect;
mod handler;
mod input;
mod mcp_bridge;
#[cfg(unix)]
mod mcp_socket;
mod output;
mod pr_list_app;
mod remote;
mod startup;
#[cfg(test)]
mod test_support;
mod text_edit;
mod theme;
mod ui;
mod update;

use std::fs::File;
use std::io::{self, Write};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use crossterm::{
    cursor::{Hide, Show},
    event::{
        self, DisableBracketedPaste, EnableBracketedPaste, Event, KeyEventKind,
        KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{
        EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
        supports_keyboard_enhancement,
    },
};
use ratatui::{Terminal, backend::CrosstermBackend};

use app::{App, FocusedPanel, InputMode};
use clap::Parser;
use handler::{
    handle_command_action, handle_command_palette_action, handle_comment_action,
    handle_comment_template_picker_action, handle_commit_select_action,
    handle_commit_selector_action, handle_confirm_action, handle_diff_action,
    handle_file_list_action, handle_help_action, handle_mental_model_edit_action,
    handle_reaction_picker_action, handle_review_submit_action, handle_search_action,
    handle_visual_action,
};

use cli::Cli;
use input::{Action, map_key_to_action};
use tokio::sync::mpsc::Receiver;
use travelagent_core::error::TrvError;
use travelagent_core::live::{LiveEvent, LiveWatcherHandle, spawn_live_watcher};

/// Timeout for the "press Ctrl+C again to exit" feature
const CTRL_C_EXIT_TIMEOUT: Duration = Duration::from_secs(2);
/// Hide the file list by default on narrow terminals.
const MIN_WIDTH_FOR_FILE_LIST: u16 = 100;
/// Debounce window for the per-tick autosave check. Mutations made
/// inside the window coalesce into a single flush at the end so a
/// tour-step `]` (which touches multiple fields) doesn't fsync the
/// session file several times in a row.
const AUTOSAVE_DEBOUNCE_MS: u64 = 2000;

fn main() -> anyhow::Result<()> {
    // Restore terminal state before the default panic handler runs.
    startup::install_panic_hook();

    // Parse CLI arguments and resolve theme
    // This also configures syntax highlighting colors before diff parsing
    let mut cli_args = Cli::parse();

    // Handle shell-completion generation before any other setup so it works
    // even outside a repo and never touches the terminal state.
    if let Some(shell) = cli_args.completions {
        let mut cmd = <Cli as clap::CommandFactory>::command();
        clap_complete::generate(shell, &mut cmd, "trv", &mut io::stdout());
        return Ok(());
    }

    // --session-gc: explicit session-directory rotation. Short-circuits
    // before any TUI or forge setup; runs the same GC the transparent
    // per-load purge uses but with the full config + CLI overrides,
    // prints a human-readable report, and exits.
    if cli_args.session_gc {
        return run_session_gc_command(&cli_args);
    }

    // --attach: short-circuit before any TUI setup. Connect the caller's
    // stdin/stdout to a running `trv --mcp-socket` session's Unix socket and
    // proxy bytes in both directions until the socket closes. Unix only.
    #[cfg(unix)]
    if let Some(target) = cli_args.attach.as_deref() {
        return run_attach(target);
    }
    #[cfg(not(unix))]
    if cli_args.attach.is_some() {
        eprintln!("Error: --attach is only supported on Unix-like systems.");
        std::process::exit(2);
    }

    // Check keyboard enhancement support before enabling raw mode.
    // Skip when --stdout or --mcp-alongside is used because the probe writes
    // escape sequences to stdout, which would leak into the captured export
    // output or into the MCP protocol stream.
    let render_to_tty = cli_args.output_to_stdout || cli_args.mcp_alongside;
    let keyboard_enhancement_supported = startup::keyboard_enhancement_supported_for(render_to_tty);

    startup::apply_path_filter_implies_working_tree(&mut cli_args);
    let mut startup_warnings = Vec::new();
    let (mut config_outcome, theme) =
        startup::load_global_config_and_theme(&cli_args, &mut startup_warnings);

    // Phase H1: own a single shared tokio runtime at the binary root.
    // Every async consumer (forge calls, live watcher, MCP bridge/socket,
    // PR list picker) takes a `Handle` off this runtime instead of
    // constructing its own. The runtime stays alive for all of `main()`
    // so spawned work keeps its executor.
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    let runtime_handle = runtime.handle().clone();

    // Start update check in background (non-blocking)
    let update_rx = if cli_args.no_update_check {
        None
    } else {
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            let result = update::check_for_updates();
            let _ = tx.send(result); // Ignore send error if receiver dropped
        });
        Some(rx)
    };

    // --tour REVSET resolves a revset and loads it as a commit range, then
    // seeds a default tour plan (one commit per stop). An agent connected via
    // --mcp-alongside can refine the plan with trv_tour_set_plan.
    if let Some(ref revset) = cli_args.tour {
        // Share the revset with the existing commit-range loader below.
        cli_args.revisions = Some(revset.clone());
    }

    // --list: show a picker and convert the chosen PR into the --pr argument.
    if cli_args.list {
        match pr_list_app::run_picker(&theme, &config_outcome, &runtime_handle) {
            Ok((pr_list_app::PickOutcome::Picked(item), _owner, _repo, _host, _forge_type)) => {
                cli_args.pr = Some(item.number.to_string());
            }
            Ok((pr_list_app::PickOutcome::Cancelled, ..)) => {
                // User cancelled — exit quietly.
                return Ok(());
            }
            Err(e) => {
                eprintln!("Error: {e}");
                eprintln!(
                    "\nFailed to list PRs. Check your authentication token and network connectivity."
                );
                std::process::exit(1);
            }
        }
    }

    // Initialize app -- demo mode, remote PR mode, or local VCS mode
    let mut app = if cli_args.demo {
        match demo::create_demo_app(
            theme,
            config_outcome
                .config
                .as_ref()
                .and_then(|cfg| cfg.comment_types.clone()),
            cli_args.output_to_stdout,
            runtime_handle.clone(),
        ) {
            Ok(mut app) => {
                app.supports_keyboard_enhancement = keyboard_enhancement_supported;
                if let Some(message) = startup_warnings.first() {
                    app.set_warning(message.clone());
                }
                app
            }
            Err(e) => {
                eprintln!("Error: {e}");
                eprintln!("\nFailed to construct demo mode app.");
                std::process::exit(1);
            }
        }
    } else if let Some(ref pr_arg) = cli_args.pr {
        match remote::create_remote_app(
            &cli_args,
            pr_arg,
            theme,
            &config_outcome,
            runtime_handle.clone(),
        ) {
            Ok(mut app) => {
                app.supports_keyboard_enhancement = keyboard_enhancement_supported;
                if let Some(message) = startup_warnings.first() {
                    app.set_warning(message.clone());
                }
                app
            }
            Err(e) => {
                eprintln!("Error: {e}");
                eprintln!(
                    "\nCheck your PR number/URL, authentication tokens, and network connectivity."
                );
                std::process::exit(1);
            }
        }
    } else {
        match App::new(
            theme,
            config_outcome
                .config
                .as_ref()
                .and_then(|cfg| cfg.comment_types.clone()),
            cli_args.output_to_stdout,
            cli_args.revisions.as_deref(),
            cli_args.working_tree,
            cli_args.path_filter.as_deref(),
            cli_args.file_path.as_deref(),
            runtime_handle.clone(),
        ) {
            Ok(mut app) => {
                app.supports_keyboard_enhancement = keyboard_enhancement_supported;
                if let Some(message) = startup_warnings.first() {
                    app.set_warning(message.clone());
                }
                app
            }
            Err(e) => {
                eprintln!("Error: {e}");
                if matches!(e, TrvError::NotARepository | TrvError::NoChanges) {
                    eprintln!(
                        "\ntravelagent needs a git, jujutsu, or mercurial repository with changes to review.\n\
                         \n\
                         Quick fixes:\n  \
                         \u{2022} cd into a repo with uncommitted changes or recent commits, then run `trv`\n  \
                         \u{2022} Try `trv --demo` to explore the TUI with mock data\n  \
                         \u{2022} Review a PR by URL: `trv <github-or-gitlab-url>`\n\
                         \n\
                         See `trv --help` for more options."
                    );
                } else {
                    eprintln!(
                        "\nMake sure you're in a git, jujutsu, or mercurial repository with commits or staged/unstaged changes."
                    );
                }
                std::process::exit(1);
            }
        }
    };

    startup::apply_repo_config_overrides(
        &mut app,
        &cli_args,
        &mut config_outcome,
        &mut startup_warnings,
    );
    startup::apply_blind_tests_config(&mut app, &cli_args, &mut startup_warnings);
    startup::try_enter_spar_mode(&mut app, &cli_args, &mut startup_warnings);

    // Setup terminal
    // When --stdout or --mcp-alongside is used, render TUI to /dev/tty so
    // stdout is free for export output or the MCP protocol stream.
    enable_raw_mode()?;
    let mut tty_output: Box<dyn Write> = if render_to_tty {
        Box::new(File::options().write(true).open("/dev/tty")?)
    } else {
        Box::new(io::stdout())
    };
    execute!(tty_output, EnterAlternateScreen, EnableBracketedPaste)?;

    // Enable keyboard enhancement for better modifier key detection (e.g., Alt+Enter)
    // This is supported by modern terminals like Kitty, iTerm2, WezTerm, etc.
    if keyboard_enhancement_supported {
        let _ = execute!(
            tty_output,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
    let backend = CrosstermBackend::new(tty_output);
    let mut terminal = Terminal::new(backend)?;

    // Apply config-driven defaults
    if let Some(ref cfg) = config_outcome.config {
        startup::apply_config_defaults_to_app(&mut app, cfg);
    }
    startup::apply_narrow_terminal_default(&mut app);
    startup::seed_tour_plan_if_requested(&mut app, &cli_args);

    // MCP hub: shared peer registry + single notify-drain task that fans
    // events out to every attached agent. Built once when *any* transport
    // is active so `--mcp-alongside` and `--mcp-socket` share one drain
    // and an event emitted on the TUI side reaches every connected peer.
    let mcp_needed = cli_args.mcp_alongside || cfg!(unix) && cli_args.mcp_socket.is_some();
    let mut mcp_hub = if mcp_needed {
        Some(mcp_bridge::McpHub::start(&runtime_handle))
    } else {
        None
    };

    // Start MCP server on background thread when --mcp-alongside is active.
    // The server reads from stdin / writes to stdout (which is safe because the
    // TUI renders to /dev/tty above). Tool calls arrive via the channel and
    // are processed on this thread so they see the live App state.
    let mcp_rx = if cli_args.mcp_alongside {
        let hub = mcp_hub
            .as_ref()
            .expect("mcp_hub built because --mcp-alongside is on");
        Some(mcp_bridge::start_mcp_alongside(runtime_handle.clone(), hub))
    } else {
        None
    };

    // --mcp-socket: bind a Unix socket so agents can attach to the running
    // session via `trv --attach <path>`. Holds a `SocketGuard` for the
    // TUI's lifetime; dropped on clean exit and best-effort cleaned on panic
    // by the path-unlink closure below.
    //
    // The command channel is created once, up front, and its `Sender`
    // (`socket_tx`) is kept alive so the runtime `:mcp-on` reconcile in the
    // main loop can hand a clone to a freshly-spawned listener. The single
    // `Receiver` is consumed lazily: it starts in `socket_rx_pending` and is
    // claimed by whichever path binds the socket first (startup `--mcp-socket`
    // here, or the first `:mcp-on` in the loop). `socket_guard` is `mut`
    // because the runtime toggle binds and drops it as the listener starts
    // and drains.
    #[cfg(unix)]
    let (socket_tx, socket_rx_proto) = mpsc::channel::<mcp_bridge::McpCommand>();
    #[cfg(unix)]
    let mut socket_rx: Option<mpsc::Receiver<mcp_bridge::McpCommand>> = None;
    #[cfg(unix)]
    let mut socket_rx_pending: Option<mpsc::Receiver<mcp_bridge::McpCommand>> =
        Some(socket_rx_proto);
    #[cfg(unix)]
    let mut socket_guard: Option<mcp_socket::SocketGuard> = None;
    #[cfg(unix)]
    if let Some(ref raw) = cli_args.mcp_socket {
        let explicit = if raw.is_empty() {
            None
        } else {
            Some(raw.as_str())
        };
        match mcp_socket::resolve_socket_path(explicit) {
            Ok(path) => {
                if let Some(dir) = mcp_socket::sessions_dir() {
                    mcp_socket::sweep_stale_sockets(&dir);
                }
                let hub = mcp_hub
                    .as_ref()
                    .expect("mcp_hub built because --mcp-socket is on");
                match mcp_socket::spawn_mcp_socket_server(
                    path.clone(),
                    socket_tx.clone(),
                    runtime_handle.clone(),
                    hub,
                ) {
                    Ok(guard) => {
                        // Belt-and-suspenders cleanup: unlink on panic via the
                        // existing panic hook would be nice, but the hook is
                        // already set above — we lean on SocketGuard::drop.
                        app.set_message(format!("MCP socket: {}", path.display()));
                        socket_rx = socket_rx_pending.take();
                        socket_guard = Some(guard);
                        // Reflect the flag-launched socket in the runtime
                        // toggle so a subsequent `:mcp-off` works symmetrically.
                        app.mcp_listener.request_on();
                    }
                    Err(e) => {
                        app.set_warning(format!(
                            "Failed to bind MCP socket at {}: {e}",
                            path.display()
                        ));
                    }
                }
            }
            Err(e) => {
                app.set_warning(format!("Failed to resolve socket path: {e}"));
            }
        }
    }
    #[cfg(not(unix))]
    let socket_rx: Option<mpsc::Receiver<mcp_bridge::McpCommand>> = None;

    // Live review mode plumbing. The watcher lives in travelagent-core but
    // needs a tokio runtime to drive its debounce pump — it shares the
    // process-wide runtime built at the top of `main`. `--live` and
    // `:live` both work by flipping `app.live.active`; the main-loop
    // reconciliation below notices the flag change and spawns/drops the
    // watcher accordingly.
    let mut live_watcher: Option<LiveWatcherHandle> = None;
    let mut live_rx: Option<Receiver<LiveEvent>> = None;
    if cli_args.live {
        // --live only makes sense for local diffs (the only kind the file
        // watcher can meaningfully observe). Remote PR sessions fall back
        // to a warning rather than a hard error because users may have
        // `alias trv='trv --live'` and still occasionally review PRs.
        if matches!(app.diff_source, app::DiffSource::Remote { .. }) {
            app.set_warning("--live only supports local diffs; ignoring");
        } else {
            app.live.activate();
        }
    }

    if cli_args.no_risk_colors {
        app.risk_border_colors = false;
    }

    // Track pending z command for zz centering
    let mut pending_z = false;
    // Track pending Z command for ZZ export+quit / ZQ quit
    let mut pending_shift_z = false;
    // Track pending d command for dd delete
    let mut pending_d = false;
    // Track pending `]` / `[` for `]]` / `[[` tour-stop stepping
    let mut pending_rbracket = false;
    let mut pending_lbracket = false;
    // Track pending `g` for `gg` (GoToTop) / `gf` (OpenInEditor). Other
    // second keys fall through to GoToTop so the pre-chord single-`g`
    // binding still fires.
    let mut pending_g = false;
    // Track pending Ctrl+C for "press twice to exit" (with timestamp for 2s timeout)
    let mut pending_ctrl_c: Option<Instant> = None;
    // Debounced autosave bookkeeping. `None` means "no autosave has
    // fired yet this session"; the debounce check treats that as
    // "window elapsed" so the first dirty tick flushes immediately.
    // Kept as a local so construct.rs / test harness don't need a
    // new App field — all mutation points already set `app.dirty`.
    let mut last_autosave: Option<Instant> = None;
    // Dedup consecutive identical autosave failures. Without this, a
    // persistent error (disk full, read-only mount, EPERM) clobbers the
    // status bar every 2s and the user can't read anything else. We
    // surface the *first* occurrence and then stay quiet until either
    // the error string changes or a save succeeds.
    let mut last_autosave_error: Option<String> = None;
    let autosave_debounce = Duration::from_millis(AUTOSAVE_DEBOUNCE_MS);

    // Debounced MCP peer-count refresh. The `:tour` connection gate reads
    // `app.mcp_peer_count` (a relaxed atomic); we refresh it from the hub's
    // registry roughly once per second so the gate sees a near-fresh count
    // without locking the registry every tick. `None` = "never refreshed",
    // treated as "window elapsed" so the first tick syncs immediately.
    let mut last_peer_count_refresh: Option<Instant> = None;
    let peer_count_refresh_interval = Duration::from_secs(1);

    // Main loop
    loop {
        // Reconcile live-mode state: if the user flipped `app.live.active`
        // via `:live` / `:live!` (or it was set from --live on startup),
        // spawn or drop the watcher to match. Reconciling here — rather
        // than inside the command handler — keeps the tokio runtime and
        // notify handle out of the handler's (sync) concern and gives us a
        // single place to swallow startup errors.
        match (app.live.active, live_watcher.is_some()) {
            (true, false) => {
                let root = app.vcs_info.root_path.clone();
                let spawn_result = runtime_handle.block_on(async move { spawn_live_watcher(root) });
                match spawn_result {
                    Ok((handle, rx)) => {
                        live_watcher = Some(handle);
                        live_rx = Some(rx);
                    }
                    Err(e) => {
                        app.set_error(format!("Failed to start live watcher: {e}"));
                        app.live.deactivate();
                    }
                }
            }
            (false, true) => {
                if let Some(handle) = live_watcher.take() {
                    handle.stop();
                }
                live_rx = None;
            }
            _ => {}
        }

        // Reconcile the runtime MCP socket listener (`:mcp-on` / `:mcp-off`).
        // Mirrors the `:live` pattern above: the handler flips
        // `app.mcp_listener`, this block owns the tokio runtime + socket
        // guard and reacts. The MCP hub is started lazily on the first
        // `:mcp-on` for sessions launched without any `--mcp-*` flag; it's
        // never torn down on `:mcp-off` (cheap to keep idle, fast to re-arm).
        #[cfg(unix)]
        match (app.mcp_listener.state(), socket_guard.is_some()) {
            (app::ListenerState::On, false) => {
                match mcp_socket::default_socket_path() {
                    Some(path) => {
                        let hub = mcp_hub
                            .get_or_insert_with(|| mcp_bridge::McpHub::start(&runtime_handle));
                        if let Some(dir) = mcp_socket::sessions_dir() {
                            mcp_socket::sweep_stale_sockets(&dir);
                        }
                        match mcp_socket::spawn_mcp_socket_server(
                            path.clone(),
                            socket_tx.clone(),
                            runtime_handle.clone(),
                            hub,
                        ) {
                            Ok(guard) => {
                                socket_guard = Some(guard);
                                // Claim the command receiver on first start;
                                // on a re-arm (`:mcp-off` then `:mcp-on`) the
                                // existing `socket_rx` is reused since the
                                // sender is shared across listener instances.
                                if socket_rx.is_none() {
                                    socket_rx = socket_rx_pending.take();
                                }
                                // PID is what an agent needs to attach
                                // (TRV_MCP_ATTACH=<pid> derives the socket
                                // path automatically); the full path is
                                // noise for the human reading the status
                                // line. Path is in `app.mcp_listener` if
                                // anyone needs it later.
                                app.set_message(format!(
                                    "MCP listening · pid {}",
                                    std::process::id()
                                ));
                            }
                            Err(e) => {
                                app.set_error(format!("MCP listener failed: {e}"));
                                app.mcp_listener.force_off();
                            }
                        }
                    }
                    None => {
                        app.set_error("MCP listener failed: no usable socket directory");
                        app.mcp_listener.force_off();
                    }
                }
            }
            (app::ListenerState::Draining, _) => {
                // Fan out the hang-up notification exactly once on entry.
                if app.mcp_listener.just_entered_draining()
                    && let Some(hub) = &mcp_hub
                {
                    let _ = hub.notify_tx.try_send(app::McpNotify::Hangup {
                        deadline_ms: 5000,
                        reason: "user requested :mcp-off".into(),
                    });
                }
                // Close once the deadline expires OR every peer has
                // disconnected. The peer-empty check uses the shared runtime
                // to block briefly on the registry mutex — cheap and bounded.
                let peers_empty = mcp_hub
                    .as_ref()
                    .map(|hub| runtime_handle.block_on(hub.registry.is_empty()))
                    .unwrap_or(true);
                if app.mcp_listener.drain_expired(Instant::now()) || peers_empty {
                    // Drop the guard → unlinks the socket file. The detached
                    // accept-loop thread errors on its next iteration; we don't
                    // join it (same fire-and-forget model as the startup path).
                    socket_guard = None;
                    app.mcp_listener.force_off();
                    app.set_message("MCP listener: stopped");
                }
            }
            _ => {}
        }

        // Drain debounced live-watcher events. Each Rescan rebuilds the
        // local diff via the same entry point `:reload` uses. Rescans are
        // silent (no status message) so the diff just updates under the
        // user — only the "last refresh" timestamp in the status bar
        // changes. WatcherError auto-disables live mode and surfaces the
        // failure.
        //
        // L3 deferral: if the user is mid-Comment/Command/Search, we don't
        // reload under their cursor. Instead we set `pending_live_rescan`
        // and let the next return to `InputMode::Normal` drain it.
        if let Some(ref mut rx) = live_rx {
            // try_recv drains non-blockingly. The watcher runs on its own
            // runtime worker; the channel is the only synchronisation
            // point.
            while let Ok(evt) = rx.try_recv() {
                match evt {
                    LiveEvent::Rescan => {
                        if app.nav.input_mode != InputMode::Normal {
                            // Defer — multiple rescans collapse to one flag.
                            app.live.request_rescan();
                        } else {
                            match app.reload_diff_files() {
                                Ok(_) => {
                                    app.live.mark_refreshed();
                                    app.push_notify(app::McpNotify::FileChanged {
                                        files: Vec::new(),
                                    });
                                }
                                Err(e) => {
                                    app.set_error(format!("Live rescan failed: {e}"));
                                }
                            }
                        }
                    }
                    LiveEvent::WatcherError(msg) => {
                        app.set_error(msg);
                        app.live.deactivate();
                    }
                }
            }
        }

        // L3: drain a deferred rescan once we're back in Normal mode. The
        // mode-exit paths (handlers, modes.rs) may not have direct access
        // to `reload_diff_files`; rather than teach every exit point to
        // call it, we poll here each tick. Idempotent: if nothing is
        // pending, this is a single boolean check.
        if app.nav.input_mode == InputMode::Normal && app.live.drain_rescan() {
            match app.reload_diff_files() {
                Ok(_) => {
                    app.live.mark_refreshed();
                    // Emit the display path of every current diff file so
                    // agents subscribed to `review://diff/{file}` get a
                    // `notifications/resources/updated` for each one. The
                    // live watcher doesn't track which files actually
                    // changed across a rescan, so fan out the superset —
                    // agents can de-dupe via content hashes on their side.
                    let files: Vec<String> = app
                        .diff_files
                        .iter()
                        .map(|f| f.display_path_lossy().to_string_lossy().to_string())
                        .collect();
                    app.push_notify(app::McpNotify::FileChanged { files });
                }
                Err(e) => {
                    app.set_error(format!("Live rescan failed: {e}"));
                }
            }
        }

        // Drain any pagination warnings the forge client queued via its
        // warn-handler callback into the status bar + error-log ring. No-op
        // when the queue is empty (most ticks). Runs before render so
        // freshly-drained warnings show on the same frame.
        app.drain_forge_warnings();

        // Phase E final: expire a `Pending` forge confirmation that sat
        // past `CONFIRMATION_TIMEOUT`. No-op when nothing is pending.
        // Runs before render so the modal disappears on the same frame
        // the timeout fires.
        app.tick_agent_action_timeout();

        // Phase E followups: poll the oneshot the spawned forge
        // `submit_review` task reports back on. Non-blocking — returns
        // immediately when no completion is pending. On ready, drives
        // the final `Executing → Succeeded / Failed` transition,
        // session-bookkeeping update, and `forge_action_decided`
        // notification. Paired with `approve_pending_agent_action` so
        // the TUI thread stays responsive during the forge HTTP round
        // trip (WARNING 1).
        app.poll_forge_completion();

        // Debounced autosave: if the session has unsaved mutations
        // (MCP comment add, tour step, AI summary write, triage
        // change, reanchor, comment edit, …) and the debounce window
        // has elapsed since the last flush, sync tour state into the
        // session mirror and write to disk. Quiet on success — no
        // `set_message` — so the status bar isn't clobbered while the
        // user reads it. Errors surface via `set_error` (same channel
        // as `:w` failures) so a disk-full / permissions issue isn't
        // silently swallowed.
        if app.dirty
            && last_autosave
                .map(|t| t.elapsed() >= autosave_debounce)
                .unwrap_or(true)
        {
            app.sync_tour_to_session();
            match travelagent_core::persistence::save_session(app.engine.session()) {
                Ok(_) => {
                    app.dirty = false;
                    last_autosave_error = None;
                }
                Err(e) => {
                    let msg = format!("Autosave failed: {e}");
                    if last_autosave_error.as_ref() != Some(&msg) {
                        app.set_error(msg.clone());
                        last_autosave_error = Some(msg);
                    }
                }
            }
            last_autosave = Some(Instant::now());
        }

        // Render
        terminal.draw(|frame| {
            ui::render(frame, &mut app);
        })?;

        // Drain pending MCP commands (non-blocking). Each command mutates
        // App and replies over the command's reply channel.
        if let Some(ref rx) = mcp_rx {
            while let Ok(cmd) = rx.try_recv() {
                mcp_bridge::process_mcp_command(&mut app, cmd);
            }
        }
        if let Some(ref rx) = socket_rx {
            while let Ok(cmd) = rx.try_recv() {
                mcp_bridge::process_mcp_command(&mut app, cmd);
            }
        }

        // Refresh the MCP peer count roughly once per second so the `:tour`
        // connection gate (which reads `app.mcp_peer_count`) sees a near-fresh
        // value without locking the registry every tick. When no hub is
        // attached the count is forced to zero so the gate rejects `:tour`.
        if last_peer_count_refresh
            .map(|t| t.elapsed() >= peer_count_refresh_interval)
            .unwrap_or(true)
        {
            let count = mcp_hub
                .as_ref()
                .map(|hub| runtime_handle.block_on(hub.registry.len()))
                .unwrap_or(0);
            app.mcp_peer_count
                .store(count, std::sync::atomic::Ordering::Relaxed);
            last_peer_count_refresh = Some(Instant::now());
        }

        // Drain a pending `:tour` request queued by the command handler. The
        // handler is sync and the hub's notify sink lives here, so it stuffs
        // the commit-id scope into `app.pending_tour_request` (mirrors the
        // `live.pending_rescan` split) and we convert it into a queued
        // `McpNotify::TourRequest`, forwarded to the hub by the block below.
        if let Some(commit_ids) = app.pending_tour_request.take() {
            app.push_notify(app::McpNotify::TourRequest { commit_ids });
        }

        // Forward any TUI-queued notifications into the shared MCP hub's
        // notify sink. `try_send` so a full channel doesn't block the
        // event loop. The drain task fans out to every peer (alongside
        // stdio + every live socket client).
        if let Some(ref hub) = mcp_hub {
            while let Some(notify) = app.notify_queue.pop_front() {
                if let Err(e) = hub.notify_tx.try_send(notify.clone()) {
                    use tokio::sync::mpsc::error::TrySendError;
                    match e {
                        TrySendError::Full(_) => {
                            // Full — push the event back and stop; we'll
                            // retry next tick when the drain task catches up.
                            app.notify_queue.push_front(notify);
                            break;
                        }
                        TrySendError::Closed(_) => {
                            // Drain task is dead — no point holding onto
                            // queued events.
                            app.notify_queue.clear();
                            break;
                        }
                    }
                }
            }
        } else if !app.notify_queue.is_empty() {
            // No MCP hub at all — nothing will ever drain the queue. Clear
            // so that agent comments (impossible in this branch but belt-
            // and-suspenders) and live rescans don't leak memory.
            app.notify_queue.clear();
        }

        // Check for update result (non-blocking)
        if let Some(ref rx) = update_rx
            && let Ok(
                update::UpdateCheckResult::UpdateAvailable(info)
                | update::UpdateCheckResult::AheadOfRelease(info),
            ) = rx.try_recv()
        {
            app.update_info = Some(info);
        }

        // Auto-clear expired pending Ctrl+C state and message
        if let Some(first_press) = pending_ctrl_c
            && first_press.elapsed() >= CTRL_C_EXIT_TIMEOUT
        {
            pending_ctrl_c = None;
            app.message = None;
        }

        // Handle events
        if event::poll(Duration::from_millis(100))? {
            let event = event::read()?;
            match event {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    // Handle Ctrl+C twice to exit (works across all input modes)
                    // In Comment mode, first Ctrl+C also cancels the comment
                    if key.code == crossterm::event::KeyCode::Char('c')
                        && key
                            .modifiers
                            .contains(crossterm::event::KeyModifiers::CONTROL)
                    {
                        // If in comment mode, cancel the comment first
                        if app.nav.input_mode == InputMode::Comment {
                            app.exit_comment_mode();
                        }

                        if let Some(first_press) = pending_ctrl_c
                            && first_press.elapsed() < CTRL_C_EXIT_TIMEOUT
                        {
                            // Second Ctrl+C within timeout - exit immediately
                            app.should_quit = true;
                            continue;
                        }
                        // First Ctrl+C (or timeout expired) - show warning and start timer
                        pending_ctrl_c = Some(Instant::now());
                        app.set_message("Press Ctrl+C again to exit");
                        continue;
                    }

                    // Any other key clears the pending Ctrl+C state and message
                    if pending_ctrl_c.is_some() {
                        pending_ctrl_c = None;
                        app.message = None;
                    }

                    // Handle pending z command:
                    //   `zz` → CenterOnCursor (existing vim chord)
                    //   `z<anything-else>` → ToggleFileCollapse for the
                    //      original `z`, then process the second key normally
                    //      (so `zj` collapses and moves down, etc.)
                    if pending_z {
                        pending_z = false;
                        if key.code == crossterm::event::KeyCode::Char('z') {
                            handler::handle_diff_action(&mut app, Action::CenterOnCursor);
                            continue;
                        }
                        handler::handle_diff_action(&mut app, Action::ToggleFileCollapse);
                        // Fall through so the second key is processed normally.
                    }

                    // Handle pending g command:
                    //   `gg` → GoToTop (vim convention)
                    //   `gf` → OpenInEditor (open source file under cursor
                    //          in $VISUAL/$EDITOR at the cursor's line)
                    //   `g<Esc>` / `g<Ctrl-c>` → silently cancel the chord
                    //          without dispatching — matches vim's "Esc
                    //          clears the prefix buffer" contract, so users
                    //          who pressed `g` by accident can bail without
                    //          a jarring jump to the top.
                    //   `g<anything-else>` → GoToTop and fall through, so
                    //          the pre-chord single-`g` muscle memory still
                    //          works (e.g., `gj` goes to top then moves down).
                    if pending_g {
                        pending_g = false;
                        match key.code {
                            crossterm::event::KeyCode::Char('g') => {
                                handler::handle_diff_action(&mut app, Action::GoToTop);
                                continue;
                            }
                            crossterm::event::KeyCode::Char('f') => {
                                handler::handle_diff_action(&mut app, Action::OpenInEditor);
                                continue;
                            }
                            crossterm::event::KeyCode::Esc => {
                                continue;
                            }
                            crossterm::event::KeyCode::Char('c')
                                if key
                                    .modifiers
                                    .contains(crossterm::event::KeyModifiers::CONTROL) =>
                            {
                                continue;
                            }
                            _ => {
                                handler::handle_diff_action(&mut app, Action::GoToTop);
                                // Fall through so the second key is processed normally.
                            }
                        }
                    }

                    // Handle pending Z command for ZZ (export+quit) / ZQ (quit)
                    if pending_shift_z {
                        pending_shift_z = false;
                        match key.code {
                            crossterm::event::KeyCode::Char('Z') => {
                                // ZZ: save session, export, and quit (same as :wq)
                                app.sync_tour_to_session();
                                let _ = travelagent_core::persistence::save_session(
                                    app.engine.session(),
                                );
                                app.dirty = false;
                                if app.engine.session().has_comments() {
                                    handler::handle_export_and_quit(&mut app);
                                } else {
                                    app.should_quit = true;
                                }
                                continue;
                            }
                            crossterm::event::KeyCode::Char('Q') => {
                                // ZQ: quit without exporting AND discard
                                // unsaved changes (vim idiom: `!` / `Q`
                                // means "force, throw away"). The on-exit
                                // autosave flush honors `discard_on_exit`.
                                app.discard_on_exit = true;
                                app.should_quit = true;
                                continue;
                            }
                            _ => {} // Fall through to normal handling
                        }
                    }

                    // Handle pending d command for dd delete comment
                    if pending_d {
                        pending_d = false;
                        if key.code == crossterm::event::KeyCode::Char('d') {
                            if !app.delete_comment_at_cursor() {
                                app.set_message("No comment at cursor");
                            }
                            continue;
                        }
                        // Otherwise fall through to normal handling
                    }

                    // `]]` / `[[` step through tour stops. A single `]` / `[`
                    // falls back to hunk navigation so existing muscle memory
                    // still works outside tour mode.
                    if pending_rbracket {
                        pending_rbracket = false;
                        if key.code == crossterm::event::KeyCode::Char(']') {
                            if app.tour.plan.is_some() {
                                let _ = app.tour_next();
                            } else {
                                app.set_message("No active tour");
                            }
                            continue;
                        }
                        app.next_hunk();
                        continue;
                    }
                    if pending_lbracket {
                        pending_lbracket = false;
                        if key.code == crossterm::event::KeyCode::Char('[') {
                            if app.tour.plan.is_some() {
                                let _ = app.tour_prev();
                            } else {
                                app.set_message("No active tour");
                            }
                            continue;
                        }
                        app.prev_hunk();
                        continue;
                    }

                    let action = map_key_to_action(key, app.nav.input_mode);

                    // Handle pending command setters (these work in any mode)
                    match action {
                        Action::PendingZCommand => {
                            pending_z = true;
                            app.pending_count = None;
                            continue;
                        }
                        Action::PendingShiftZCommand => {
                            pending_shift_z = true;
                            app.pending_count = None;
                            continue;
                        }
                        Action::PendingDCommand => {
                            pending_d = true;
                            app.pending_count = None;
                            continue;
                        }
                        Action::PendingRBracketCommand => {
                            pending_rbracket = true;
                            app.pending_count = None;
                            continue;
                        }
                        Action::PendingLBracketCommand => {
                            pending_lbracket = true;
                            app.pending_count = None;
                            continue;
                        }
                        Action::PendingGCommand => {
                            pending_g = true;
                            app.pending_count = None;
                            continue;
                        }
                        _ => {}
                    }

                    // Handle digit accumulation for {N}G jump-to-line (Normal mode only)
                    if app.nav.input_mode == InputMode::Normal {
                        match action {
                            // Digits 1..=5 switch panels in remote mode
                            // when no line-count is in flight. `5` is
                            // gated on `spar_mode` by
                            // `RemotePanel::from_digit` so it can still
                            // participate in `{N}G` count accumulation
                            // in non-sparring reviews.
                            Action::Digit(d)
                                if matches!(
                                    app.diff_source,
                                    crate::app::DiffSource::Remote { .. }
                                ) && app.pending_count.is_none()
                                    && crate::app::RemotePanel::from_digit(d, app.spar_mode)
                                        .is_some() =>
                            {
                                let Some(panel) =
                                    crate::app::RemotePanel::from_digit(d, app.spar_mode)
                                else {
                                    unreachable!("guarded by `is_some()` match-guard above");
                                };
                                if let Some(r) = app.remote_mut() {
                                    r.remote_panel = panel;
                                }
                                // Phase I5-2b: refresh spec↔test linkage
                                // the moment the user enters the Sparring
                                // panel so they never see a stale status
                                // column after generating tests in
                                // another terminal or on a previous run.
                                if panel == crate::app::RemotePanel::Sparring {
                                    app.refresh_spec_statuses();
                                }
                                continue;
                            }
                            Action::Digit(0) if app.pending_count.is_none() => {
                                // Plain `0` with no pending count means "go to
                                // start of line" in vim. Only accumulate into
                                // a count when a non-zero digit kicked it off.
                                handler::handle_diff_action(&mut app, Action::GoToLineStart);
                                continue;
                            }
                            Action::Digit(d) => {
                                let n = app.pending_count.unwrap_or(0);
                                app.pending_count = Some(
                                    (n.saturating_mul(10).saturating_add(d as usize)).min(999_999),
                                );
                                continue;
                            }
                            Action::GoToBottom if app.pending_count.is_some() => {
                                // Clamp to 1 since source lines are 1-indexed; 0G behaves like 1G
                                let count = app.pending_count.unwrap().max(1);
                                app.pending_count = None;
                                // Safe cast: count is clamped to 999_999 which fits in u32
                                app.go_to_source_line(count as u32);
                                continue;
                            }
                            _ => {
                                app.pending_count = None;
                            }
                        }
                    }

                    // AI summary panel captures scroll/close keys while it's
                    // open (in Normal mode). Other modes keep their usual
                    // behaviour so text entry isn't hijacked by an open panel.
                    if app.ai.show_panel && app.nav.input_mode == InputMode::Normal {
                        use crossterm::event::{KeyCode, KeyModifiers};
                        let handled = match (key.code, key.modifiers) {
                            (KeyCode::Char('a'), KeyModifiers::CONTROL)
                            | (KeyCode::Char('q') | KeyCode::Esc, KeyModifiers::NONE) => {
                                app.toggle_ai_summary();
                                true
                            }
                            (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE) => {
                                app.ai_summary_scroll_down(1);
                                true
                            }
                            (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE) => {
                                app.ai_summary_scroll_up(1);
                                true
                            }
                            (KeyCode::Char('d'), KeyModifiers::CONTROL)
                            | (KeyCode::PageDown, KeyModifiers::NONE) => {
                                app.ai_summary_scroll_down(10);
                                true
                            }
                            (KeyCode::Char('u'), KeyModifiers::CONTROL)
                            | (KeyCode::PageUp, KeyModifiers::NONE) => {
                                app.ai_summary_scroll_up(10);
                                true
                            }
                            (KeyCode::Char('g'), KeyModifiers::NONE) => {
                                app.ai.scroll = 0;
                                true
                            }
                            _ => false,
                        };
                        if handled {
                            continue;
                        }
                    }

                    // Phase E final: the forge-write confirmation modal
                    // captures `y` / `n` / `Enter` / `Esc` so the human
                    // can decide without first bouncing back to Normal
                    // mode. Other keys fall through so the human can
                    // still scroll the diff while deciding.
                    //
                    // Gated on `InputMode::Normal` (mirrors the AI-summary
                    // gate above at main.rs:946): if the human is typing a
                    // comment body, review body, command, or search
                    // pattern, a literal `y` / `n` in their text must land
                    // in the text buffer — not silently approve / reject a
                    // forge write. That would be the exact silent-mis-
                    // approval scenario the whole confirmation design is
                    // meant to prevent. See `App::forge_modal_should_capture`.
                    if app.forge_modal_should_capture() {
                        use crossterm::event::{KeyCode, KeyModifiers};
                        match (key.code, key.modifiers) {
                            (KeyCode::Char('y'), KeyModifiers::NONE)
                            | (KeyCode::Char('Y'), KeyModifiers::NONE)
                            | (KeyCode::Enter, KeyModifiers::NONE) => {
                                app.approve_pending_agent_action();
                                continue;
                            }
                            (KeyCode::Char('n'), KeyModifiers::NONE)
                            | (KeyCode::Char('N'), KeyModifiers::NONE)
                            | (KeyCode::Esc, KeyModifiers::NONE) => {
                                app.reject_pending_agent_action();
                                continue;
                            }
                            _ => {}
                        }
                    }

                    // Dispatch by input mode
                    match app.nav.input_mode {
                        InputMode::Help => handle_help_action(&mut app, action),
                        InputMode::Command => handle_command_action(&mut app, action),
                        InputMode::CommandPalette => {
                            handle_command_palette_action(&mut app, action);
                        }
                        InputMode::Search => handle_search_action(&mut app, action),
                        InputMode::Comment => handle_comment_action(&mut app, action),
                        InputMode::Confirm => handle_confirm_action(&mut app, action),
                        InputMode::CommitSelect => handle_commit_select_action(&mut app, action),
                        InputMode::VisualSelect => handle_visual_action(&mut app, action),
                        InputMode::ReviewSubmit => handle_review_submit_action(&mut app, action),
                        InputMode::ReactionPicker => {
                            handle_reaction_picker_action(&mut app, action);
                        }
                        InputMode::CommentTemplatePicker => {
                            handle_comment_template_picker_action(&mut app, action);
                        }
                        InputMode::MentalModelEdit => {
                            handle_mental_model_edit_action(&mut app, action);
                        }
                        InputMode::Normal => match app.nav.focused_panel {
                            FocusedPanel::FileList => handle_file_list_action(&mut app, action),
                            FocusedPanel::Diff => handle_diff_action(&mut app, action),
                            FocusedPanel::CommitSelector => {
                                handle_commit_selector_action(&mut app, action);
                            }
                        },
                    }
                }
                Event::Paste(text) => handler::handle_paste(&mut app, &text),
                _ => {}
            }
        }

        // Launch the external editor when a comment-mode handler flagged
        // it. This has to happen outside the event `match` so we can cleanly
        // suspend/restore the ratatui terminal around the child process.
        if app.pending_external_edit {
            app.pending_external_edit = false;
            match run_external_editor(&mut terminal, &app.comment.buffer) {
                Ok(new_buffer) => {
                    app.comment.buffer = new_buffer;
                    app.comment.cursor = app.comment.buffer.len();
                }
                Err(e) => app.set_error(format!("External editor failed: {e}")),
            }
        }

        // `gf` — open the source file under the cursor in $EDITOR at the
        // cursor's line. Same suspend/restore pattern as the comment-mode
        // editor above.
        if let Some((path, line)) = app.pending_open_file_editor.take() {
            let root = app.vcs_info.root_path.clone();
            if let Err(e) = run_external_editor_on_file(&mut terminal, &root, &path, line) {
                app.set_error(format!("Failed to open file in editor: {e}"));
            }
        }

        if app.should_quit {
            // Best-effort final flush of queued MCP notifications before we
            // tear down the bridge thread. Without this, a `ReviewSubmitted`
            // event queued by a `:Z` / `--stdout` export during this same
            // tick would never reach the agent — the next tick's drain
            // never runs because we break out of the loop. We deliberately
            // don't block on the tokio mpsc backpressure: `try_send` is
            // enough because the notify channel is sized generously (64)
            // and realistic pre-quit drain fits in one shot.
            if let Some(ref hub) = mcp_hub {
                while let Some(notify) = app.notify_queue.pop_front() {
                    if hub.notify_tx.try_send(notify).is_err() {
                        break;
                    }
                }
            }
            break;
        }
    }

    // Final best-effort autosave flush. Covers the paths the debounced
    // per-tick save can't reach: second-Ctrl+C exit (sets `should_quit`
    // without calling `save_session`), plus any mutation that landed
    // inside the 2s debounce window immediately before quit. Errors
    // ignored — the terminal is about to be torn down and there's no
    // good channel to surface them on. `:w` / `:wq` / `ZZ` still run
    // explicitly inside the handler and are not affected: if they
    // already cleared `app.dirty`, this is a no-op.
    //
    // `:q!` / `ZQ` set `discard_on_exit = true` to skip this flush —
    // the vim idiom is "`!` means force, discard unsaved work".
    if app.dirty && !app.discard_on_exit {
        app.sync_tour_to_session();
        let _ = travelagent_core::persistence::save_session(app.engine.session());
        app.dirty = false;
    }

    // Shut down the live watcher (if any) before tearing down the
    // terminal so its drop doesn't race with raw-mode cleanup. Dropping
    // `live_rx` closes the channel; the shared runtime owns the debounce
    // pump worker and shuts down when `main` returns.
    if let Some(handle) = live_watcher.take() {
        handle.stop();
    }
    drop(live_rx.take());

    // Restore terminal
    let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        DisableBracketedPaste,
        LeaveAlternateScreen
    )?;

    // Print pending stdout output if --stdout was used
    if let Some(output) = app.pending_stdout_output {
        print!("{output}");
    }

    // Flush any remaining MCP notifications to their peers before we tear
    // down the runtime. The per-tick drain and the pre-break flush push
    // into `hub.notify_tx`; the background drain task still has to call
    // `peer.send_notification().await` to actually deliver. `shutdown()`
    // closes the channel and awaits the drain task up to 250ms so a
    // `ReviewSubmitted` queued by `:Z` / `--stdout` export actually lands.
    if let Some(hub) = mcp_hub.take() {
        hub.shutdown(Duration::from_millis(250));
    }

    // Shut the shared runtime down without blocking on still-in-flight
    // background tasks (socket listener, mcp-alongside pump). Those threads
    // are owned by the process; we just want the worker threads to exit.
    runtime.shutdown_background();

    Ok(())
}

/// Phase I1b: outcome of entering Sparring Review mode.
///
/// `Created` / `Resumed` carry the sparring branch name. `FlagOnly`
/// means the mode flag was flipped but no sparring branch was
/// checked out, either because the VCS doesn't support the branch
/// operations (`VcsUnsupported`, today hg/jj) or because the branch
/// name couldn't be derived (`DetachedHead`, detached HEAD with no
/// PR). Agent-side behavior still gates on the flag either way.
#[derive(Debug)]
pub enum SparEntryOutcome {
    Created(String),
    Resumed(String),
    FlagOnly(SparFlagOnlyReason),
}

/// Why `enter_spar_mode` dropped into flag-only mode rather than
/// creating a sparring branch. Each variant has a `user_message()`
/// method so the two call sites (startup `--spar` and mid-session
/// `:spar`) render the same prose for the same cause.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SparFlagOnlyReason {
    /// VCS backend refused the sparring branch operation. Carries the
    /// `UnsupportedOperation` message from the backend (e.g. the
    /// default `TrvError::UnsupportedOperation` emitted by hg/jj
    /// stubs) so the user knows which operation was unsupported.
    VcsUnsupported(String),
    /// Couldn't derive a sparring branch name — working from detached
    /// HEAD with no remote PR number. Nothing for the backend to
    /// branch off, so the mode flag flips without a branch change.
    DetachedHead,
}

impl SparFlagOnlyReason {
    /// Human-readable fragment for the "Sparring mode flag-only — …"
    /// status/warning message. Kept on the variant so future reasons
    /// don't require touching every call site.
    #[must_use]
    pub fn user_message(&self) -> String {
        match self {
            Self::VcsUnsupported(msg) => msg.clone(),
            Self::DetachedHead => {
                "could not derive branch name (detached HEAD and no PR number)".to_string()
            }
        }
    }
}

/// Derive the sparring branch name for the current session. For
/// remote PR mode we use the PR number (stable across branch
/// renames); for local review we fall back to the current branch
/// name so users can tell sparring branches apart at a glance.
pub fn spar_branch_name(app: &app::App) -> Option<String> {
    if let Some(remote) = app.remote() {
        return Some(format!("sparring-tests/{}", remote.pr_id.number));
    }
    app.vcs_info
        .branch_name
        .as_deref()
        .map(|b| format!("sparring-tests/{b}"))
}

/// Phase I1b: drive the Sparring Review entry flow — refuse on
/// dirty tree, create-or-resume the sparring branch, check it out.
/// Returns a `SparEntryOutcome` carrying the branch name so callers
/// can surface a helpful status message. Extended in post-v1.3.0
/// cleanup to treat UnsupportedOperation from any of the four
/// sparring VCS methods as FlagOnly, not just `is_working_tree_dirty`.
pub fn enter_spar_mode(app: &mut app::App) -> anyhow::Result<SparEntryOutcome> {
    let Some(branch) = spar_branch_name(app) else {
        return Ok(SparEntryOutcome::FlagOnly(SparFlagOnlyReason::DetachedHead));
    };

    // Probe for VCS support. hg/jj return UnsupportedOperation from
    // any of the four sparring methods; we treat any of those as
    // "flag-only mode" so a partial backend can't leave the reviewer
    // half-sparring without the right affordances. Real git errors
    // still bubble up.
    macro_rules! try_vcs {
        ($call:expr) => {
            match $call {
                Ok(v) => v,
                Err(travelagent_core::error::TrvError::UnsupportedOperation(msg)) => {
                    return Ok(SparEntryOutcome::FlagOnly(
                        SparFlagOnlyReason::VcsUnsupported(msg),
                    ));
                }
                Err(e) => return Err(e.into()),
            }
        };
    }

    let dirty = try_vcs!(app.vcs.is_working_tree_dirty());
    if dirty {
        return Err(anyhow::anyhow!(
            "working tree is dirty; commit or stash before entering sparring mode"
        ));
    }

    let exists = try_vcs!(app.vcs.branch_exists(&branch));
    if !exists {
        try_vcs!(app.vcs.create_branch(&branch));
    }
    try_vcs!(app.vcs.checkout_branch(&branch));

    if exists {
        Ok(SparEntryOutcome::Resumed(branch))
    } else {
        Ok(SparEntryOutcome::Created(branch))
    }
}

/// Proxy stdin/stdout to the MCP socket at `target`. `target` is either an
/// explicit path (absolute, relative, or `~/...`) or a bare PID whose default
/// socket path is derived from `$XDG_STATE_HOME/travelagent/sessions/<pid>.sock`.
///
/// Returns after the socket closes (EOF) or on any I/O error. Exit code maps
/// connect-failure to non-zero; clean EOF returns `Ok(())`. Unix only — the
/// socket transport relies on `std::os::unix` and the `mcp_socket` module
/// (itself `#[cfg(unix)]`); the `--attach` CLI path is gated to match.
#[cfg(unix)]
fn run_attach(target: &str) -> anyhow::Result<()> {
    use std::io::{Read, Write};
    use std::os::unix::net::UnixStream;

    // If the target parses cleanly as a PID, expand it to the default path.
    // Otherwise treat as a filesystem path (with `~/` expansion handled inside
    // mcp_socket::resolve_socket_path via the `Some(raw)` branch).
    let path = if let Ok(pid) = target.parse::<i32>() {
        let Some(base) = mcp_socket::sessions_dir() else {
            eprintln!("Error: could not resolve default sessions dir. Pass a socket path instead.");
            std::process::exit(2);
        };
        base.join(format!("{pid}.sock"))
    } else {
        match mcp_socket::resolve_socket_path(Some(target)) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("Error: invalid socket path: {e}");
                std::process::exit(2);
            }
        }
    };

    let stream = match UnixStream::connect(&path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!(
                "Error: could not connect to MCP socket {}: {e}",
                path.display()
            );
            std::process::exit(2);
        }
    };

    // Dup the stream so the two directions can own independent handles.
    let stream_w = stream.try_clone()?;
    let mut stream_r = stream;

    // stdin -> socket
    let up = std::thread::spawn(move || {
        let mut w = stream_w;
        let mut stdin = io::stdin().lock();
        let mut buf = [0u8; 8192];
        loop {
            match stdin.read(&mut buf) {
                Ok(0) => break,
                Ok(n) => {
                    if w.write_all(&buf[..n]).is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        // Half-close the write side so the server sees EOF.
        let _ = w.shutdown(std::net::Shutdown::Write);
    });

    // socket -> stdout (runs on this thread so we exit after server hangs up)
    let mut stdout = io::stdout().lock();
    let mut buf = [0u8; 8192];
    loop {
        match stream_r.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                if stdout.write_all(&buf[..n]).is_err() {
                    break;
                }
                let _ = stdout.flush();
            }
            Err(_) => break,
        }
    }
    // Stdin pump may still be waiting on a read; detach rather than block.
    drop(up);
    Ok(())
}

/// Suspend the TUI, run the external editor against `buffer`, and restore the
/// TUI afterwards. Returns the edited buffer with a single trailing newline
/// stripped (editors conventionally add one on save, and we don't want that
/// accumulating across repeat edits).
fn run_external_editor<B>(terminal: &mut Terminal<B>, buffer: &str) -> anyhow::Result<String>
where
    B: ratatui::backend::Backend + std::io::Write,
    <B as ratatui::backend::Backend>::Error: Send + Sync + 'static,
{
    // Tear down the TUI so the editor owns the terminal. All calls are
    // best-effort: if any fail we still proceed to spawn the editor and
    // restore afterwards, because leaving the terminal mid-teardown would
    // corrupt the user's session.
    let _ = terminal.clear();
    let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        DisableBracketedPaste,
        LeaveAlternateScreen,
        Show,
    );

    // Run the editor. Whatever happens we MUST rebuild the TUI before
    // returning, so capture the result and restore unconditionally.
    let result = external_editor::edit_text(buffer);

    // Rebuild the TUI exactly how `main` initially set it up. These are
    // also best-effort so the user isn't left stranded if one crossterm
    // call fails — the next frame render will bring everything back.
    let _ = enable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        EnterAlternateScreen,
        EnableBracketedPaste,
        Hide,
    );
    if matches!(supports_keyboard_enhancement(), Ok(true)) {
        let _ = execute!(
            terminal.backend_mut(),
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
    let _ = terminal.clear();

    let mut content = result?;
    if content.ends_with('\n') {
        content.pop();
        if content.ends_with('\r') {
            content.pop();
        }
    }
    Ok(content)
}

/// Suspend the TUI, open `path` (resolved against `repo_root` if relative) in
/// the user's external editor at `line`, and restore the TUI afterwards.
///
/// Editor resolution follows the usual `$VISUAL` → `$EDITOR` → `vi` order
/// (shared with `external_editor::resolve_editor`). The argv uses the vi/
/// nvim/nano-compatible `+<line> <path>` syntax — this is the broadest
/// fallback: it's correct for vi, vim, nvim, nano, emacs, and Kakoune;
/// editors like VS Code that prefer `--goto path:line` will ignore the
/// `+<line>` token and just open the file without jumping to the line.
/// Documenting that tradeoff rather than branching per-editor keeps this
/// single site simple and predictable.
fn run_external_editor_on_file<B>(
    terminal: &mut Terminal<B>,
    repo_root: &std::path::Path,
    path: &std::path::Path,
    line: u32,
) -> anyhow::Result<()>
where
    B: ratatui::backend::Backend + std::io::Write,
    <B as ratatui::backend::Backend>::Error: Send + Sync + 'static,
{
    // Resolve relative paths against the repo root so the editor sees an
    // unambiguous location regardless of the user's current directory.
    let abs_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        repo_root.join(path)
    };

    // Tear down the TUI so the editor owns the terminal. Best-effort —
    // matches `run_external_editor` above.
    let _ = terminal.clear();
    let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        DisableBracketedPaste,
        LeaveAlternateScreen,
        Show,
    );

    let (editor, extra_args) = external_editor::resolve_editor(&|key| std::env::var(key).ok());
    // `+<line> <path>` syntax: supported by vi/vim/nvim/nano/emacs/Kakoune.
    // VS Code and a few others ignore the `+` token and open the file at the
    // top; we accept that tradeoff rather than branching per-editor.
    let spawn_result = std::process::Command::new(&editor)
        .args(&extra_args)
        .arg(format!("+{line}"))
        .arg(&abs_path)
        .status();

    // Rebuild the TUI no matter what — same restore dance as
    // `run_external_editor`.
    let _ = enable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        EnterAlternateScreen,
        EnableBracketedPaste,
        Hide,
    );
    if matches!(supports_keyboard_enhancement(), Ok(true)) {
        let _ = execute!(
            terminal.backend_mut(),
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
    let _ = terminal.clear();

    // Surface spawn/exit errors via the normal status-line path.
    match spawn_result {
        Ok(status) if status.success() => Ok(()),
        Ok(status) => Err(anyhow::anyhow!(
            "editor '{editor}' exited with non-zero status: {status}"
        )),
        Err(e) => Err(anyhow::anyhow!("failed to spawn editor '{editor}': {e}")),
    }
}

/// Handle `--session-gc`: load the global config, apply CLI overrides, run
/// the age / size / count sweep, and print a human-readable summary to
/// stdout. Warnings from config loading go to stderr so agents that parse
/// stdout (e.g. via `trv --session-gc | awk ...`) see a clean report.
fn run_session_gc_command(cli_args: &Cli) -> anyhow::Result<()> {
    use travelagent_core::config::SessionGcConfig;

    let mut cfg = match travelagent_core::config::load_config() {
        Ok(outcome) => {
            for w in &outcome.warnings {
                eprintln!("{w}");
            }
            outcome
                .config
                .map(|c| c.session_gc)
                .unwrap_or_else(SessionGcConfig::default)
        }
        Err(e) => {
            eprintln!("Warning: Failed to load config: {e}");
            SessionGcConfig::default()
        }
    };

    if let Some(v) = cli_args.gc_max_age_days {
        cfg.max_age_days = v;
    }
    if let Some(v) = cli_args.gc_max_size_mb {
        cfg.max_size_mb = v;
    }
    if let Some(v) = cli_args.gc_max_count {
        cfg.max_count = v;
    }

    let report = travelagent_core::persistence::run_session_gc(&cfg, cli_args.gc_dry_run)?;

    let mode = if cli_args.gc_dry_run {
        "session GC (dry run)"
    } else {
        "session GC"
    };
    println!(
        "{mode}: scanned {} file(s); removed {} (age {}, size {}, count {}); remaining {} file(s), {:.2} MB",
        report.scanned,
        report.total_removed(),
        report.removed_age,
        report.removed_size,
        report.removed_count,
        report.remaining_files,
        report.remaining_bytes as f64 / (1024.0 * 1024.0),
    );

    Ok(())
}

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

    #[test]
    fn flag_only_reason_vcs_unsupported_echoes_backend_message() {
        let reason = SparFlagOnlyReason::VcsUnsupported(
            "hg backend does not implement create_branch".to_string(),
        );
        assert_eq!(
            reason.user_message(),
            "hg backend does not implement create_branch"
        );
    }

    #[test]
    fn flag_only_reason_detached_head_has_specific_message() {
        let msg = SparFlagOnlyReason::DetachedHead.user_message();
        // The prose is what users see in the startup-warning banner;
        // pin the gist so rewording stays intentional.
        assert!(msg.contains("detached HEAD"), "{msg}");
        assert!(msg.contains("PR number"), "{msg}");
    }
}