arf-console 0.4.4

A cross-platform R console written in Rust
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
//! REPL (Read-Eval-Print Loop) implementation.

mod banner;
mod meta_command;
mod prompt;
mod reprex;
mod shell;
pub(crate) mod state;

use crate::completion::completer::CombinedCompleter;
use crate::completion::menu::{FunctionAwareMenu, StateSyncHistoryMenu};
use crate::completion::shell::ShellCompleter;
use crate::config::{
    AutoSuggestions, Config, ConfigStatus, EditorMode, ModeIndicatorPosition, RSourceStatus,
    history_dir,
};
use crate::editor::hinter::RLanguageHinter;
use crate::editor::mode::new_editor_state_ref;
use crate::editor::prompt::PromptFormatter;
use crate::highlighter::{CombinedHighlighter, MetaCommandHighlighter};
use crate::history::FuzzyHistory;
use anyhow::Result;
use crossterm::{
    ExecutableCommand,
    style::Stylize,
    terminal::{self, ClearType},
};
use nu_ansi_term::{Color, Style};
use reedline::{
    DefaultHinter, Emacs, HistorySessionId, IdeMenu, ListMenu, MenuBuilder, Reedline, ReedlineMenu,
    Signal, SqliteBackedHistory, Vi, default_emacs_keybindings, default_vi_insert_keybindings,
    default_vi_normal_keybindings,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::atomic::{AtomicU16, Ordering};

use crate::editor::keybindings::{
    add_auto_match_keybindings, add_common_keybindings, add_key_map_keybindings,
    add_shell_semicolon_keybinding, wrap_edit_mode_with_conditional_rules,
};
use crate::editor::validator::RValidator;
use banner::format_banner;
use meta_command::{MetaCommandResult, process_meta_command};
use prompt::RPrompt;
use reprex::{clear_input_lines, strip_reprex_output};
use shell::{execute_shell_command, restart_process};
use state::{PromptRuntimeConfig, ReplState};

// Thread-local storage for the REPL state.
// This allows the ReadConsole callback to access the line editor.
thread_local! {
    static REPL_STATE: RefCell<Option<ReplState>> = const { RefCell::new(None) };
}

/// Last known terminal width for detecting resize.
/// Updated by `sync_r_width()` to avoid redundant R calls.
static LAST_TERMINAL_WIDTH: AtomicU16 = AtomicU16::new(0);

/// Minimum width for R's `options(width)`, matching radian's behavior.
const MIN_R_WIDTH: u16 = 20;

/// Maximum width for R's `options(width)`. R enforces a hard maximum of 10000.
const MAX_R_WIDTH: u16 = 10000;

/// Sync R's `options(width)` with the current terminal width.
///
/// Compares the current terminal columns against the last known width.
/// If changed, updates R's width option. Called both at startup and
/// periodically from the idle callback to handle terminal resize.
fn sync_r_width() {
    let prev = LAST_TERMINAL_WIDTH.load(Ordering::Relaxed);

    let (cols, _) = match terminal::size() {
        Ok(size) => size,
        Err(e) => {
            if prev != 0 {
                // Already have a known width; treat as transient failure.
                log::debug!(
                    "Failed to read terminal size (transient); keeping previous width: {:?}",
                    e
                );
                return;
            }
            // No previous width recorded; fall back to a reasonable default.
            log::debug!(
                "Failed to read terminal size; falling back to default width: {:?}",
                e
            );
            (80, 24)
        }
    };

    let clamped = cols.clamp(MIN_R_WIDTH, MAX_R_WIDTH);
    if prev != clamped {
        let code = format!("options(width = {})", clamped);
        match arf_harp::eval_string_with_visibility(&code) {
            Ok(_) => {
                LAST_TERMINAL_WIDTH.store(clamped, Ordering::Relaxed);
            }
            Err(e) => log::debug!("Failed to set R width option: {:?}", e),
        }
    }
}

/// Install the Ctrl+C handler that forwards interrupts to R.
///
/// Without this, Ctrl+C during R evaluation terminates the process: we set
/// R_SignalHandlers = 0, so R installs no SIGINT handler itself and the
/// default action kills the process (on Unix, R_SelectEx only installs a
/// temporary handler while blocked in select(), leaving a fatal window
/// between calls; on Windows, STATUS_CONTROL_C_EXIT).
/// The handler sets R's interrupt flag (R_interrupts_pending / UserBreak),
/// which R checks periodically (R_CheckUserInterrupt, R_SelectEx) and
/// turns into an interrupt condition via onintr() — but only while R is
/// evaluating: while ReadConsole waits for input there is nothing to
/// interrupt, and a flag observed by the event polling done from the
/// input-waiting loops would make onintr() longjmp through their Rust
/// frames, so the handler drops the signal instead.
///
/// On Unix, call this BEFORE R initialization: startup profiles run inside
/// setup_Rmainloop, so installing later leaves a window where Ctrl+C during
/// a slow .Rprofile kills the process. The interrupt flag pointer is
/// resolved early in initialization (before profiles are evaluated); until
/// then the handler is a no-op. If the flag is still unavailable after
/// initialization, call [`restore_default_sigint_handler`] so Ctrl+C is not
/// swallowed forever. On Windows, profiles are sourced manually after
/// initialization, so call this between the two (gated on flag
/// availability).
pub(crate) fn install_r_interrupt_handler() {
    // Unix: register a SIGINT-only sigaction instead of using ctrlc.
    // The workspace builds ctrlc with the "termination" feature (for
    // headless graceful shutdown), so ctrlc::set_handler would also
    // capture SIGTERM/SIGHUP and an interactive session could no
    // longer be terminated by them.
    #[cfg(unix)]
    {
        use nix::sys::signal;

        extern "C" fn handle_sigint(_signum: std::ffi::c_int) {
            // Async-signal-safe: one atomic load, then an atomic load
            // plus a volatile write. Must not panic or allocate.
            if !arf_libr::is_r_awaiting_console_input() {
                arf_libr::set_r_interrupt_pending();
            }
        }

        // SA_RESTART so blocking syscalls interrupted by the signal
        // are transparently restarted (as ctrlc does).
        let action = signal::SigAction::new(
            signal::SigHandler::Handler(handle_sigint),
            signal::SaFlags::SA_RESTART,
            signal::SigSet::empty(),
        );
        // SAFETY: handle_sigint is async-signal-safe (see above).
        if let Err(e) = unsafe { signal::sigaction(signal::Signal::SIGINT, &action) } {
            log::warn!("Could not set Ctrl+C handler: {e}");
        }
    }

    #[cfg(windows)]
    if let Err(e) = ctrlc::set_handler(|| {
        if !arf_libr::is_r_awaiting_console_input() {
            arf_libr::set_r_interrupt_pending();
        }
    }) {
        log::warn!("Could not set Ctrl+C handler: {e}");
    }
}

/// Restore the default SIGINT disposition (terminate the process).
///
/// Used when R's interrupt flag turns out to be unavailable after R
/// initialization: the handler installed by [`install_r_interrupt_handler`]
/// can never forward interrupts then, and would swallow Ctrl+C forever.
#[cfg(unix)]
pub(crate) fn restore_default_sigint_handler() {
    use nix::sys::signal;

    let action = signal::SigAction::new(
        signal::SigHandler::SigDfl,
        signal::SaFlags::empty(),
        signal::SigSet::empty(),
    );
    // SAFETY: restores the default disposition; no handler code involved.
    if let Err(e) = unsafe { signal::sigaction(signal::Signal::SIGINT, &action) } {
        log::warn!("Could not restore default Ctrl+C handler: {e}");
    }
}

/// Prefix for arf messages to distinguish them from R output.
/// Uses R comment syntax so messages don't interfere with R code.
pub(crate) const ARF_PREFIX: &str = "# [arf]";

/// Print an arf message to stdout.
macro_rules! arf_println {
    ($($arg:tt)*) => {
        println!("{} {}", $crate::repl::ARF_PREFIX, format_args!($($arg)*))
    };
}

/// Print an arf message to stderr.
macro_rules! arf_eprintln {
    ($($arg:tt)*) => {
        eprintln!("{} {}", $crate::repl::ARF_PREFIX, format_args!($($arg)*))
    };
}

pub(crate) use arf_eprintln;
pub(crate) use arf_println;

/// The main REPL structure.
pub struct Repl {
    config: Config,
    /// Path to the config file (if specified via --config, or the default XDG path).
    config_path: Option<std::path::PathBuf>,
    /// Status of config file loading (for :info display).
    config_status: ConfigStatus,
    /// How R was resolved at startup (determines if :switch is available).
    r_source_status: RSourceStatus,
    r_initialized: bool,
    prompt_formatter: PromptFormatter,
    /// Session ID for history isolation (shared across R and shell history).
    session_id: Option<HistorySessionId>,
}

impl Repl {
    /// Create a new REPL with the given configuration.
    ///
    /// The `config_path` should be the path to the config file that was used,
    /// or `None` if using defaults (no config file found).
    ///
    /// The `r_source_status` describes how R was resolved at startup,
    /// which determines if features like `:switch` are available.
    pub fn new(
        config: Config,
        config_path: Option<std::path::PathBuf>,
        config_status: ConfigStatus,
        r_source_status: RSourceStatus,
        session_id: Option<HistorySessionId>,
    ) -> Result<Self> {
        // Check if R is initialized
        let r_initialized = arf_libr::r_library().is_ok();

        // Create prompt formatter (caches R version)
        let prompt_formatter = PromptFormatter::new();

        // Set up reprex mode if enabled
        if config.startup.mode.reprex {
            arf_libr::set_reprex_mode(true, &config.mode.reprex.comment);
        }

        Ok(Repl {
            config,
            config_path,
            config_status,
            r_source_status,
            r_initialized,
            prompt_formatter,
            session_id,
        })
    }

    /// Get the history session ID as an i64 (for IPC).
    fn history_session_id_raw(&self) -> Option<i64> {
        self.session_id.map(i64::from)
    }

    /// Get the R history database path based on configuration.
    fn r_history_path(&self) -> Option<std::path::PathBuf> {
        if self.config.history.disabled {
            return None;
        }
        let dir = self.config.history.dir.clone().or_else(history_dir);
        dir.map(|d| d.join("r.db"))
    }

    /// Get the Shell history database path based on configuration.
    fn shell_history_path(&self) -> Option<std::path::PathBuf> {
        if self.config.history.disabled {
            return None;
        }
        let dir = self.config.history.dir.clone().or_else(history_dir);
        dir.map(|d| d.join("shell.db"))
    }

    /// Create an R language hinter based on config settings.
    ///
    /// Returns `Some(hinter)` if auto_suggestions is enabled, `None` otherwise.
    fn create_r_hinter(&self) -> Option<Box<RLanguageHinter>> {
        match self.config.editor.auto_suggestions {
            AutoSuggestions::None => None,
            AutoSuggestions::All => Some(Box::new(
                RLanguageHinter::new().with_style(Style::new().italic().fg(Color::DarkGray)),
            )),
            AutoSuggestions::Cwd => Some(Box::new(
                RLanguageHinter::new()
                    .with_style(Style::new().italic().fg(Color::DarkGray))
                    .with_cwd_aware(true),
            )),
        }
    }

    /// Run the REPL main loop.
    pub fn run(&mut self) -> Result<()> {
        // Show startup banner unless disabled
        if self.config.startup.show_banner {
            let banner = format_banner(&self.config, self.r_initialized);
            // Apply color to the "not initialized" warning if present
            if !self.r_initialized {
                for line in banner.lines() {
                    if line.contains("R is not initialized") {
                        println!(
                            "# {}",
                            "R is not initialized. Commands will not be evaluated.".yellow()
                        );
                    } else {
                        println!("{}", line);
                    }
                }
            } else {
                print!("{}", banner);
            }
        }

        if self.r_initialized {
            // Use R's main loop with ReadConsole callback
            self.run_with_r_mainloop()?;
        } else {
            // Fall back to standalone mode without R
            self.run_standalone()?;
        }

        Ok(())
    }

    /// Run with R's main loop (run_Rmainloop).
    fn run_with_r_mainloop(&self) -> Result<()> {
        // Create line editor with bracketed paste enabled
        // This allows detecting paste operations and prevents auto-match from
        // interfering with pasted text (e.g., pasting "()" won't become "())")
        let line_editor = Reedline::create().use_bracketed_paste(true);

        // Set up SQLite-backed history for R mode
        let (mut line_editor, r_history_ok) =
            setup_history(line_editor, self.r_history_path(), self.session_id);

        // Set up edit mode (Vi or Emacs) with conditional ':' keybinding
        let editor_state = new_editor_state_ref();
        line_editor = match self.config.editor.mode {
            EditorMode::Vi => {
                let mut insert_keybindings = default_vi_insert_keybindings();
                add_common_keybindings(&mut insert_keybindings);
                if self.config.editor.auto_match {
                    add_auto_match_keybindings(&mut insert_keybindings);
                }
                if self.config.experimental.shell_semicolon_shortcut {
                    add_shell_semicolon_keybinding(&mut insert_keybindings);
                }
                add_key_map_keybindings(&mut insert_keybindings, &self.config.editor.key_map);
                let vi = Vi::new(insert_keybindings, default_vi_normal_keybindings());
                line_editor.with_edit_mode(wrap_edit_mode_with_conditional_rules(
                    vi,
                    editor_state.clone(),
                    self.config.editor.auto_match,
                    self.config.experimental.completion_min_chars,
                    self.config.experimental.shell_semicolon_shortcut,
                ))
            }
            EditorMode::Emacs => {
                let mut keybindings = default_emacs_keybindings();
                add_common_keybindings(&mut keybindings);
                if self.config.editor.auto_match {
                    add_auto_match_keybindings(&mut keybindings);
                }
                if self.config.experimental.shell_semicolon_shortcut {
                    add_shell_semicolon_keybinding(&mut keybindings);
                }
                add_key_map_keybindings(&mut keybindings, &self.config.editor.key_map);
                let emacs = Emacs::new(keybindings);
                line_editor.with_edit_mode(wrap_edit_mode_with_conditional_rules(
                    emacs,
                    editor_state.clone(),
                    self.config.editor.auto_match,
                    self.config.experimental.completion_min_chars,
                    self.config.experimental.shell_semicolon_shortcut,
                ))
            }
        };

        // Set up combined completer (R + meta commands) if completion is enabled
        // When rig is not enabled, :switch is excluded from completion
        if self.config.completion.enabled {
            let completer = Box::new(CombinedCompleter::with_settings_full(
                self.config.completion.timeout_ms,
                self.config.completion.debounce_ms,
                self.config.completion.auto_paren_limit,
                self.r_source_status.rig_enabled(),
                self.config.experimental.r_completion.fuzzy,
                self.config
                    .experimental
                    .r_completion
                    .package_functions
                    .clone(),
            ));
            line_editor = line_editor.with_completer(completer);

            // Set up completion menu with height limit for better UX
            // Use FunctionAwareMenu to handle cursor positioning for function completions
            // Pass editor_state to synchronize shadow tracking after completion
            let ide_menu = IdeMenu::default()
                .with_name("completion_menu")
                .with_max_completion_height(self.config.completion.max_height);
            let completion_menu =
                Box::new(FunctionAwareMenu::new(ide_menu).with_editor_state(editor_state.clone()));
            line_editor = line_editor.with_menu(ReedlineMenu::EngineCompleter(completion_menu));
        }

        // Set up history menu for Ctrl+R search (shows multiple candidates)
        // Use only_buffer_difference(false) so selecting replaces buffer instead of appending
        // See: https://github.com/nushell/nushell/issues/7746
        // Dynamic page size based on terminal height (leave space for prompt and input)
        // Capped by config max_height to avoid overwhelming display on tall terminals
        //
        // TODO: reedline's ListMenu.page_size only limits the first page; subsequent pages
        // use full terminal height. This is a bug in reedline's printable_entries() method.
        // See IdeMenu fix in reedline#781 for reference. Once fixed upstream, this will work
        // correctly for all pages.
        let (_, rows) = terminal::size().unwrap_or((80, 24));
        let terminal_based_size = rows.saturating_sub(5) as usize;
        let config_max_height = self.config.history.menu_max_height as usize;
        let history_page_size = terminal_based_size.min(config_max_height).max(3);
        let list_menu = ListMenu::default()
            .with_name("history_menu")
            .with_only_buffer_difference(false)
            .with_page_size(history_page_size);
        let history_menu =
            Box::new(StateSyncHistoryMenu::new(list_menu).with_editor_state(editor_state.clone()));
        line_editor = line_editor.with_menu(ReedlineMenu::HistoryMenu(history_menu));

        // Set up validator for multiline input
        // Pass editor_state so validator can synchronize shadow state with actual buffer
        line_editor = line_editor.with_validator(Box::new(
            RValidator::new().with_editor_state(editor_state.clone()),
        ));

        // Set up syntax highlighter (R code + meta commands)
        // Pass editor_state so highlighter can sync shadow state on every redraw
        let highlighter = CombinedHighlighter::new(
            self.config.colors.clone(),
            self.config.editor.highlight_matching_bracket,
        )
        .with_editor_state(editor_state.clone());
        line_editor = line_editor.with_highlighter(Box::new(highlighter));

        // Set up history-based autosuggestion (fish/nushell style)
        // Uses RLanguageHinter for proper R token handling (e.g., |> as single token)
        if let Some(hinter) = self.create_r_hinter() {
            line_editor = line_editor.with_hinter(hinter);
        }

        // Set up idle callback to process R events during input waiting.
        // This allows graphics windows (plot(), help browser) to remain responsive
        // while the user is typing or the editor is waiting for input.
        // Also syncs R's options(width) with terminal size on resize (if enabled).
        //
        // Safety note: This callback runs inside R's ReadConsole callback, but calling
        // R via R_ToplevelExec from here is the standard embedded-R pattern. R explicitly
        // supports this, and radian uses the same approach (setoption() in its inputhook).
        let auto_width = self.config.r.auto_width;
        line_editor = line_editor
            .with_break_signal(crate::ipc::break_signal())
            .with_poll_interval(std::time::Duration::from_millis(33))
            .with_idle_callback(Box::new(move || {
                arf_libr::process_r_events();
                if auto_width {
                    sync_r_width();
                }
                crate::ipc::poll_ipc_requests();
            }));

        // Create shell line editor with separate history
        let (shell_line_editor, shell_history_ok) = self.create_shell_line_editor();

        // If neither history DB was opened, clear the session ID from IPC metadata
        // so clients are not misled about history isolation being active.
        if !r_history_ok && !shell_history_ok {
            crate::ipc::clear_history_session_id();
        }

        // Create prompt runtime config with unexpanded templates
        // Templates are expanded dynamically in build_main_prompt() to track cwd changes
        let prompt_config = PromptRuntimeConfig::builder(
            self.prompt_formatter.clone(),
            self.config.prompt.format.clone(),
            self.config.prompt.continuation.clone(),
            self.config.prompt.shell_format.clone(),
        )
        .mode_indicator_position(self.config.prompt.mode_indicator)
        .reprex(
            self.config.startup.mode.reprex,
            self.config.mode.reprex.comment.clone(),
        )
        .indicators(self.config.prompt.indicators.clone())
        .autoformat(self.config.startup.mode.autoformat)
        .main_color(self.config.colors.prompt.main)
        .continuation_color(self.config.colors.prompt.continuation)
        .shell_color(self.config.colors.prompt.shell)
        .mode_indicator_color(self.config.colors.prompt.indicator)
        .status(
            self.config.prompt.status.clone(),
            self.config.colors.prompt.status.clone(),
        )
        .duration(
            self.config.experimental.prompt_duration.clone(),
            self.config.colors.prompt.duration,
        )
        .spinner(self.config.experimental.prompt_spinner.clone())
        .vi(
            self.config.prompt.vi.clone(),
            self.config.colors.prompt.vi.clone(),
        )
        .build();

        // Get history paths for :history commands
        let r_history_path = self.r_history_path();
        let shell_history_path = self.shell_history_path();

        // Store state in thread-local
        REPL_STATE.with(|state| {
            *state.borrow_mut() = Some(ReplState {
                line_editor,
                shell_line_editor,
                prompt_config,
                should_exit: false,
                config_path: self.config_path.clone(),
                config_status: self.config_status,
                r_history_path,
                shell_history_path,
                r_source_status: self.r_source_status.clone(),
                forget_config: self.config.experimental.history_forget.clone(),
                sponge_queue: state::SpongeQueue::new(),
                dir_stack: Vec::new(),
                // Only expose session ID if at least one history DB was opened
                history_session_id: if r_history_ok || shell_history_ok {
                    self.history_session_id_raw()
                } else {
                    None
                },
            });
        });

        // Initialize global error handler for rlang/dplyr error detection
        // This sets up globalCallingHandlers() to track error conditions
        // that output to stdout instead of stderr
        let error_handler_code = arf_libr::global_error_handler_code();
        match arf_harp::eval_string_with_visibility(error_handler_code) {
            Ok(_) => {
                log::info!("Global error handler initialized");
                arf_libr::mark_global_error_handler_initialized();
            }
            Err(e) => {
                log::warn!("Failed to initialize global error handler: {:?}", e);
            }
        }

        // Initialize askpass handler (Unix only) to bypass reedline for password input.
        #[cfg(unix)]
        {
            let askpass_handler_code = arf_libr::askpass_handler_code();
            match arf_harp::eval_string_with_visibility(askpass_handler_code) {
                Ok(_) => {
                    log::info!("Askpass handler initialized");
                }
                Err(e) => {
                    log::warn!("Failed to initialize askpass handler: {:?}", e);
                }
            }
        }

        // Sync R's options(width) with the current terminal width.
        // Dynamic resize is handled by the idle callback above.
        if self.config.r.auto_width {
            sync_r_width();
        }

        // Set up the ReadConsole callback
        arf_libr::set_read_console_callback(read_console_callback);

        // Note: the Ctrl+C handler that forwards interrupts to R is installed
        // in main() around R initialization (see install_r_interrupt_handler),
        // so that startup profile evaluation is already covered.

        // Run R's main loop - this doesn't return until EOF
        unsafe {
            arf_libr::run_r_mainloop();
        }

        // Sponge cleanup on exit: purge all remaining failed commands in the queue.
        // Note: R's q() may terminate the process before this cleanup completes,
        // so the most recent failed command might remain in history.
        // The main value of sponge is purging OLD failed commands during the session.
        REPL_STATE.with(|state| {
            if let Some(ref mut repl_state) = *state.borrow_mut()
                && repl_state.forget_config.enabled
                && !repl_state.sponge_queue.is_empty()
            {
                for id_to_delete in repl_state.sponge_queue.drain_failed_ids() {
                    let _ = repl_state.line_editor.history_mut().delete(id_to_delete);
                }
                let _ = repl_state.line_editor.sync_history();
            }
        });

        REPL_STATE.with(|state| {
            *state.borrow_mut() = None;
        });

        println!("\nGoodbye!");
        Ok(())
    }

    /// Run without R (standalone mode).
    fn run_standalone(&self) -> Result<()> {
        // Create line editor with bracketed paste enabled
        let line_editor = Reedline::create().use_bracketed_paste(true);

        // Set up SQLite-backed history for R mode
        let (mut line_editor, history_ok) =
            setup_history(line_editor, self.r_history_path(), self.session_id);

        // If history DB failed to open, clear the session ID from IPC metadata
        if !history_ok {
            crate::ipc::clear_history_session_id();
        }
        let history_session_id = if history_ok {
            self.history_session_id_raw()
        } else {
            None
        };

        // Set up edit mode with conditional ':' keybinding
        let editor_state = new_editor_state_ref();
        line_editor = match self.config.editor.mode {
            EditorMode::Vi => {
                let mut insert_keybindings = default_vi_insert_keybindings();
                add_common_keybindings(&mut insert_keybindings);
                if self.config.editor.auto_match {
                    add_auto_match_keybindings(&mut insert_keybindings);
                }
                if self.config.experimental.shell_semicolon_shortcut {
                    add_shell_semicolon_keybinding(&mut insert_keybindings);
                }
                add_key_map_keybindings(&mut insert_keybindings, &self.config.editor.key_map);
                let vi = Vi::new(insert_keybindings, default_vi_normal_keybindings());
                line_editor.with_edit_mode(wrap_edit_mode_with_conditional_rules(
                    vi,
                    editor_state.clone(),
                    self.config.editor.auto_match,
                    self.config.experimental.completion_min_chars,
                    self.config.experimental.shell_semicolon_shortcut,
                ))
            }
            EditorMode::Emacs => {
                let mut keybindings = default_emacs_keybindings();
                add_common_keybindings(&mut keybindings);
                if self.config.editor.auto_match {
                    add_auto_match_keybindings(&mut keybindings);
                }
                if self.config.experimental.shell_semicolon_shortcut {
                    add_shell_semicolon_keybinding(&mut keybindings);
                }
                add_key_map_keybindings(&mut keybindings, &self.config.editor.key_map);
                let emacs = Emacs::new(keybindings);
                line_editor.with_edit_mode(wrap_edit_mode_with_conditional_rules(
                    emacs,
                    editor_state.clone(),
                    self.config.editor.auto_match,
                    self.config.experimental.completion_min_chars,
                    self.config.experimental.shell_semicolon_shortcut,
                ))
            }
        };

        // Set up history-based autosuggestion (fish/nushell style)
        // Uses RLanguageHinter for proper R token handling (e.g., |> as single token)
        if let Some(hinter) = self.create_r_hinter() {
            line_editor = line_editor.with_hinter(hinter);
        }

        // Mode indicator for special modes (reprex, etc.)
        let mode_position = self.config.prompt.mode_indicator;
        let mode_indicator =
            if self.config.startup.mode.reprex && mode_position != ModeIndicatorPosition::None {
                Some(self.config.prompt.indicators.reprex.clone())
            } else {
                None
            };

        let prompt = RPrompt::new(
            self.prompt_formatter.format(&self.config.prompt.format),
            self.prompt_formatter
                .format(&self.config.prompt.continuation),
        )
        .with_mode_indicator(mode_indicator, mode_position)
        .with_colors(
            self.config.colors.prompt.main,
            self.config.colors.prompt.continuation,
            self.config.colors.prompt.indicator,
        );

        // Minimal prompt config for meta commands (R not available)
        let mut prompt_config =
            PromptRuntimeConfig::builder(self.prompt_formatter.clone(), "R > ", "+   ", "$ ")
                .mode_indicator_position(ModeIndicatorPosition::None)
                .main_color(self.config.colors.prompt.main)
                .continuation_color(self.config.colors.prompt.continuation)
                .shell_color(self.config.colors.prompt.shell)
                .mode_indicator_color(self.config.colors.prompt.indicator)
                .status(
                    self.config.prompt.status.clone(),
                    self.config.colors.prompt.status.clone(),
                )
                .duration(
                    self.config.experimental.prompt_duration.clone(),
                    self.config.colors.prompt.duration,
                )
                .spinner(self.config.experimental.prompt_spinner.clone())
                .vi(
                    self.config.prompt.vi.clone(),
                    self.config.colors.prompt.vi.clone(),
                )
                .build();
        let r_history_path = self.r_history_path();
        let shell_history_path = self.shell_history_path();
        // Separate dir_stack for standalone mode (R not initialized).
        // The R mainloop path stores its own dir_stack in ReplState.
        // These two paths are mutually exclusive, so no sharing is needed.
        let mut dir_stack: Vec<std::path::PathBuf> = Vec::new();

        loop {
            match line_editor.read_line(&prompt) {
                Ok(Signal::Success(line)) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    // Process meta commands even when R is not initialized
                    // This allows :switch, :quit, :shell, etc. to work
                    if let Some(result) = process_meta_command(
                        &line,
                        &mut prompt_config,
                        &r_history_path,
                        &shell_history_path,
                        &self.r_source_status,
                        &mut dir_stack,
                        history_session_id,
                    ) {
                        // Clear duration so the previous R command's time
                        // does not persist in the prompt after a meta command.
                        prompt_config.clear_command_duration();
                        let ctx = SessionInfoContext {
                            prompt_config: &prompt_config,
                            config_path: &self.config_path,
                            config_status: self.config_status,
                            r_history_path: &r_history_path,
                            shell_history_path: &shell_history_path,
                            r_source_status: &self.r_source_status,
                        };
                        match handle_meta_command_result(result, &ctx) {
                            MetaAction::Continue => continue,
                            MetaAction::Exit => {
                                println!("\nGoodbye!");
                                return Ok(());
                            }
                        }
                    }

                    // Not a meta command - show R not initialized message
                    println!("{}", format!("[R not initialized] {}", line).dark_grey());
                }
                Ok(Signal::CtrlC) => {
                    // Clear any visible completion menu before printing ^C
                    let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
                    println!("^C");
                    continue;
                }
                Ok(Signal::CtrlD) => {
                    // Clear any visible menu before printing farewell message
                    let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
                    println!("\nGoodbye!");
                    break;
                }
                Ok(_) => {
                    // ExternalBreak or future variants: ignore in standalone mode
                    continue;
                }
                Err(err) => {
                    eprintln!("Error: {}", err);
                    break;
                }
            }
        }

        Ok(())
    }

    /// Create a shell mode line editor with separate history.
    ///
    /// Shell mode uses a separate SQLite history database from R mode.
    fn create_shell_line_editor(&self) -> (Reedline, bool) {
        // Create shell editor with bracketed paste enabled
        let shell_editor = Reedline::create().use_bracketed_paste(true);

        // Set up SQLite-backed history for Shell mode (separate from R)
        let (mut shell_editor, history_ok) =
            setup_history(shell_editor, self.shell_history_path(), self.session_id);

        // Use same edit mode as R editor
        shell_editor = match self.config.editor.mode {
            EditorMode::Vi => {
                let mut insert_keybindings = default_vi_insert_keybindings();
                add_common_keybindings(&mut insert_keybindings);
                add_key_map_keybindings(&mut insert_keybindings, &self.config.editor.key_map);
                shell_editor.with_edit_mode(Box::new(Vi::new(
                    insert_keybindings,
                    default_vi_normal_keybindings(),
                )))
            }
            EditorMode::Emacs => {
                let mut keybindings = default_emacs_keybindings();
                add_common_keybindings(&mut keybindings);
                add_key_map_keybindings(&mut keybindings, &self.config.editor.key_map);
                shell_editor.with_edit_mode(Box::new(Emacs::new(keybindings)))
            }
        };

        // Set up shell mode completer with path completion if completion is enabled
        if self.config.completion.enabled {
            let completer = Box::new(ShellCompleter::new(
                self.config.experimental.shell_completion.command_names,
            ));
            shell_editor = shell_editor.with_completer(completer);

            // Set up completion menu with height limit for better UX
            let completion_menu = Box::new(
                IdeMenu::default()
                    .with_name("completion_menu")
                    .with_max_completion_height(self.config.completion.max_height),
            );
            shell_editor = shell_editor.with_menu(ReedlineMenu::EngineCompleter(completion_menu));
        }

        // History menu for shell mode (same setup as main R mode).
        // See reedline#781 TODO note above for page size limitation.
        let (_, rows) = terminal::size().unwrap_or((80, 24));
        let terminal_based_size = rows.saturating_sub(5) as usize;
        let config_max_height = self.config.history.menu_max_height as usize;
        let history_page_size = terminal_based_size.min(config_max_height).max(3);
        let history_menu = Box::new(
            ListMenu::default()
                .with_name("history_menu")
                .with_only_buffer_difference(false)
                .with_page_size(history_page_size),
        );
        shell_editor = shell_editor.with_menu(ReedlineMenu::HistoryMenu(history_menu));

        // Set up highlighter for meta command visual feedback
        shell_editor = shell_editor.with_highlighter(Box::new(MetaCommandHighlighter::new(
            self.config.colors.meta.clone(),
        )));

        // Set up history-based autosuggestion (uses shell history)
        // Note: Shell mode doesn't support cwd filtering; treat All and Cwd the same
        if !matches!(self.config.editor.auto_suggestions, AutoSuggestions::None) {
            let hinter =
                DefaultHinter::default().with_style(Style::new().italic().fg(Color::DarkGray));
            shell_editor = shell_editor.with_hinter(Box::new(hinter));
        }

        if !self.config.experimental.shell_abbreviations.is_empty() {
            let abbrs: HashMap<String, String> = self
                .config
                .experimental
                .shell_abbreviations
                .clone()
                .into_iter()
                .collect();
            shell_editor = shell_editor.with_abbreviations(abbrs);
        }

        // Set up idle callback to process R events during input waiting.
        // Even in shell mode, R graphics windows may be open and need event processing.
        shell_editor = shell_editor
            .with_poll_interval(std::time::Duration::from_millis(33))
            .with_idle_callback(Box::new(|| {
                arf_libr::process_r_events();
            }));

        (shell_editor, history_ok)
    }
}

/// ReadConsole callback function.
/// This is called by R when it needs user input.
///
/// With the Validator in place, reedline handles multiline input internally.
/// The callback receives complete expressions (possibly with embedded newlines)
/// from reedline and passes them to R.
fn read_console_callback(r_prompt: &str) -> Option<String> {
    REPL_STATE.with(|state| {
        // Use try_borrow_mut to detect re-entrant calls.
        // This is a defensive measure in case R unexpectedly calls ReadConsole
        // while we're still processing a previous call. This was originally
        // needed when RValidator called harp::is_expression_complete (which
        // invokes R's parser), but is now less critical since we switched to
        // a tree-sitter-r based validator that doesn't call into R.
        let mut guard = match state.try_borrow_mut() {
            Ok(guard) => guard,
            Err(_) => {
                // Re-entrant call detected - RefCell already borrowed.
                // Return None (EOF) to terminate the nested call.
                // This prevents panic from double borrow.
                return None;
            }
        };
        let state = guard.as_mut()?;

        if state.should_exit {
            return None;
        }

        // Update exit_status for the previous command when a new prompt is shown.
        // This is called when R has finished evaluating and wants new input.
        // Continuation prompts (starting with '+') mean we're still in the same expression.
        // Non-command prompts (menus, etc.) should also not trigger exit status updates.
        // Track prompt state for IPC: true when R is idle at the command
        // prompt, false for continuation/menu/selection prompts so IPC
        // requests are correctly rejected during non-command prompts.
        crate::ipc::set_r_at_prompt(is_r_command_prompt(r_prompt));

        if is_r_command_prompt(r_prompt) && !state.prompt_config.is_shell_enabled() {
            let had_error = if state.line_editor.has_last_command_context() {
                let had_error = arf_libr::command_had_error();
                let exit_status = if had_error { 1i64 } else { 0i64 };

                // Use Cell to capture the history item ID through the immutable closure
                let captured_id: std::cell::Cell<Option<reedline::HistoryItemId>> =
                    std::cell::Cell::new(None);
                let _ = state.line_editor.update_last_command_context(&|mut item| {
                    item.exit_status = Some(exit_status);
                    captured_id.set(item.id);
                    item
                });

                // Sponge feature: track all commands and purge old failed ones.
                // See SpongeQueue for the algorithm details.
                if state.forget_config.enabled {
                    // Determine effective delay: use configured delay normally,
                    // or usize::MAX for on_exit_only (defer all deletions until exit)
                    let effective_delay = if state.forget_config.on_exit_only {
                        usize::MAX
                    } else {
                        state.forget_config.delay
                    };

                    if let Some(id_to_delete) = state.sponge_queue.record_command(
                        had_error,
                        captured_id.get(),
                        effective_delay,
                    ) {
                        let _ = state.line_editor.history_mut().delete(id_to_delete);
                    }
                }
                had_error
            } else {
                false
            };

            // Update prompt status indicator for the next prompt
            state.prompt_config.set_last_command_failed(had_error);

            // Calculate duration for the {duration} prompt placeholder
            state.prompt_config.set_command_duration();

            // Reset error state for the next command
            arf_libr::reset_command_error_state();
        }

        // Check for pending IPC operations before entering the reedline input loop.
        // At this point reedline hasn't started, so there's no editor buffer to
        // conflict with — we can always accept.
        if is_r_command_prompt(r_prompt)
            && !state.prompt_config.is_shell_enabled()
            && let Some(op) = crate::ipc::take_pending_ipc_operation()
        {
            use crate::ipc::{
                PendingIpcKind, accept_user_input, run_silent_eval, setup_visible_eval,
            };
            match op.kind {
                PendingIpcKind::SilentEvaluate { reply } => {
                    // Run silent evaluate directly — no buffer conflict possible.
                    // Unlike visible eval / user_input, silent eval does not return
                    // code to R. It runs synchronously here and then falls through
                    // to the reedline loop below to wait for user input.
                    run_silent_eval(&op.code, reply);
                }
                PendingIpcKind::VisibleEvaluate { reply, timeout } => {
                    setup_visible_eval(reply, timeout);
                    let prompt_str = "agent> ";
                    println!("{}{}", prompt_str.dark_cyan(), op.code);
                    if !op.code.is_empty() {
                        state.prompt_config.set_command_start();
                        state.prompt_config.start_spinner();
                    }
                    crate::ipc::set_r_at_prompt(false);
                    return Some(op.code);
                }
                PendingIpcKind::UserInput { reply } => {
                    accept_user_input(reply);
                    let prompt_str = "agent> ";
                    println!("{}{}", prompt_str.dark_cyan(), op.code);
                    if !op.code.is_empty() {
                        state.prompt_config.set_command_start();
                        state.prompt_config.start_spinner();
                    }
                    crate::ipc::set_r_at_prompt(false);
                    return Some(op.code);
                }
            }
        }

        loop {
            // Build prompt dynamically from config.
            // We detect the type of prompt R is asking for:
            // - Continuation prompts start with '+' (multiline input)
            // - Command prompts typically end with "> " (R's default prompt)
            // - Non-standard prompts (menus, etc.) are passed through directly
            let prompt = if r_prompt.starts_with('+') {
                state.prompt_config.build_cont_prompt()
            } else if is_r_command_prompt(r_prompt) {
                state.prompt_config.build_main_prompt()
            } else {
                // Non-standard prompt from R (menu selection, etc.)
                // Pass through R's actual prompt instead of our configured one
                RPrompt::new(r_prompt.to_string(), r_prompt.to_string())
            };

            // Use shell editor when in shell mode (for separate history)
            let editor = if state.prompt_config.is_shell_enabled() {
                &mut state.shell_line_editor
            } else {
                &mut state.line_editor
            };

            // Process R events once before entering the input loop.
            // The idle callback will continue processing events at ~30fps while waiting for input,
            // keeping graphics windows (plot(), help browser) responsive.
            arf_libr::process_r_events();

            // Track whether we're in a non-standard prompt mode (menu selection, etc.)
            let is_menu_prompt = !is_r_command_prompt(r_prompt) && !r_prompt.starts_with('+');

            match editor.read_line(&prompt) {
                Ok(Signal::Success(line)) => {
                    // For non-standard prompts (menus, etc.), pass input directly to R
                    // without any processing (meta commands, shell mode, reprex, autoformat)
                    if is_menu_prompt {
                        return Some(line);
                    }

                    // Check for meta commands first
                    if let Some(result) = process_meta_command(
                        &line,
                        &mut state.prompt_config,
                        &state.r_history_path,
                        &state.shell_history_path,
                        &state.r_source_status,
                        &mut state.dir_stack,
                        state.history_session_id,
                    ) {
                        // Clear duration so the previous R command's time
                        // does not persist in the prompt after a meta command.
                        state.prompt_config.clear_command_duration();
                        let ctx = SessionInfoContext {
                            prompt_config: &state.prompt_config,
                            config_path: &state.config_path,
                            config_status: state.config_status,
                            r_history_path: &state.r_history_path,
                            shell_history_path: &state.shell_history_path,
                            r_source_status: &state.r_source_status,
                        };
                        match handle_meta_command_result(result, &ctx) {
                            MetaAction::Continue => continue,
                            MetaAction::Exit => {
                                state.should_exit = true;
                                return None;
                            }
                        }
                    }

                    // Shell mode: execute as shell command instead of R
                    if state.prompt_config.is_shell_enabled() {
                        let trimmed = line.trim();
                        if !trimmed.is_empty() {
                            // Check if user wants to exit shell mode.
                            // We compare commands as strings because Shell mode doesn't run
                            // a persistent shell process - each command is executed via
                            // `$SHELL -c "command"`. There's no actual shell session to exit,
                            // so we intercept "exit" and "logout" to return to R mode instead
                            // of running them as no-op shell commands.
                            if trimmed == "exit" || trimmed == "logout" {
                                state.prompt_config.set_shell(false);
                                arf_println!("Returned to R mode.");
                                continue;
                            }
                            // Show a hint for cd/pushd/popd since they have no effect
                            // in a subprocess. The command still runs in the shell.
                            if let Some(hint) = meta_command::dir_command_hint(trimmed) {
                                arf_println!("{}", hint);
                            }
                            execute_shell_command(trimmed);
                        }
                        continue;
                    }

                    // In reprex mode, strip lines starting with "#>" (reprex output comments)
                    // This allows users to paste reprex output directly without duplicate output
                    // Keep original for line count calculation in clear_input_lines
                    let (original_line, line) = if state.prompt_config.is_reprex_enabled() {
                        (line.clone(), strip_reprex_output(&line))
                    } else {
                        (line.clone(), line)
                    };

                    // Format code if autoformat is enabled
                    let code = state.prompt_config.maybe_format_code(&line);

                    // In reprex mode, clear the prompt and input lines
                    // Show the (possibly formatted) code
                    // Use original_line for line count since that's what was displayed on terminal
                    if state.prompt_config.is_reprex_enabled() && !code.is_empty() {
                        clear_input_lines(&original_line, &code);
                    }

                    // Record command start time for the {duration} prompt placeholder
                    // Start the spinner to indicate R is evaluating code
                    // The spinner will be stopped when R produces output or the next prompt appears
                    if !code.is_empty() {
                        state.prompt_config.set_command_start();
                        state.prompt_config.start_spinner();
                    }

                    // Mark R as busy (no longer at prompt) for IPC
                    crate::ipc::set_r_at_prompt(false);

                    // Return the (possibly formatted) code to R
                    return Some(code);
                }
                Ok(Signal::CtrlC) => {
                    // Clear any visible completion menu before printing ^C
                    let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
                    println!("^C");
                    // In shell mode, Ctrl+C returns to R mode
                    if state.prompt_config.is_shell_enabled() {
                        state.prompt_config.set_shell(false);
                        arf_println!("Returned to R mode.");
                        continue;
                    }
                    return Some(String::new());
                }
                Ok(Signal::CtrlD) => {
                    // Clear any visible menu before proceeding
                    let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
                    // In shell mode, Ctrl+D returns to R mode (consistent with Ctrl+C)
                    if state.prompt_config.is_shell_enabled() {
                        state.prompt_config.set_shell(false);
                        arf_println!("Returned to R mode.");
                        continue;
                    }
                    state.should_exit = true;
                    return None;
                }
                Ok(Signal::ExternalBreak(buffer)) => {
                    // IPC operation triggered a break signal.
                    // Check the editor buffer for mutual exclusion with console input.
                    if let Some(op) = crate::ipc::take_pending_ipc_operation() {
                        use crate::ipc::{
                            PendingIpcKind, accept_user_input, reject_operation_user_typing,
                            run_silent_eval, setup_visible_eval,
                        };

                        // If the user has typed something, reject the IPC operation.
                        // We use trim() because reedline may include trailing whitespace
                        // in the buffer; whitespace-only input is treated as empty.
                        if !buffer.trim().is_empty() {
                            reject_operation_user_typing(op, &buffer);
                            continue;
                        }

                        // Helper: clear the current prompt line and show agent prefix
                        let clear_and_show_agent_prompt = |code: &str| {
                            let mut out = io::stdout();
                            let _ = out.execute(crossterm::cursor::MoveToColumn(0));
                            let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
                            println!("{}{}", "agent> ".dark_cyan(), code);
                        };

                        // Silent evaluate: run in-place and return to reedline
                        if let PendingIpcKind::SilentEvaluate { reply } = op.kind {
                            // Show visual indicator, run eval, then return to reedline
                            {
                                let mut out = io::stdout();
                                let _ = out.execute(crossterm::cursor::MoveToColumn(0));
                                let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
                                print!("{}", "[evaluating...]".dark_cyan());
                                let _ = out.flush();
                            }

                            run_silent_eval(&op.code, reply);

                            // Clear the indicator — reedline will repaint the prompt
                            {
                                let mut out = io::stdout();
                                let _ = out.execute(crossterm::cursor::MoveToColumn(0));
                                let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
                            }

                            continue;
                        }

                        // Visible evaluate / user input: accept, inject code into REPL
                        match op.kind {
                            PendingIpcKind::VisibleEvaluate { reply, timeout } => {
                                setup_visible_eval(reply, timeout);
                            }
                            PendingIpcKind::UserInput { reply } => {
                                accept_user_input(reply);
                            }
                            PendingIpcKind::SilentEvaluate { .. } => unreachable!(),
                        }

                        clear_and_show_agent_prompt(&op.code);

                        // ExternalBreak leaves reedline's previous prompt position suspended.
                        // Its saved row range includes the line after a single-line prompt, so
                        // leave the cursor one row beyond that range. Otherwise, when R produces
                        // no output, the next repaint reuses the old prompt origin and clears the
                        // echoed agent line.
                        println!();

                        if !op.code.is_empty() {
                            let entry = reedline::HistoryItem::from_command_line(&op.code);
                            let _ = editor.history_mut().save(entry);
                        }

                        if !op.code.is_empty() {
                            state.prompt_config.set_command_start();
                            state.prompt_config.start_spinner();
                        }

                        crate::ipc::set_r_at_prompt(false);
                        return Some(op.code);
                    }
                    // No pending operation (spurious signal), continue waiting
                    continue;
                }
                Ok(_) => continue,
                Err(err) => {
                    eprintln!("Error: {}", err);
                    state.should_exit = true;
                    return None;
                }
            }
        }
    })
}

/// RAII guard that sets IPC alternate mode on creation and restores the previous state on drop.
///
/// Pagers that enter crossterm's alternate screen must be wrapped with this guard
/// so that IPC requests are rejected immediately instead of hanging.
/// The drop guard also restores the state on panic unwind (where the panic strategy permits it).
struct IpcAlternateGuard {
    was_alternate: bool,
}

impl IpcAlternateGuard {
    fn new() -> Self {
        let was_alternate = crate::ipc::is_in_alternate_mode();
        crate::ipc::set_in_alternate_mode(true);
        Self { was_alternate }
    }
}

impl Drop for IpcAlternateGuard {
    fn drop(&mut self) {
        crate::ipc::set_in_alternate_mode(self.was_alternate);
    }
}

/// Run a closure with IPC alternate mode enabled, restoring the previous state afterward.
fn with_ipc_alternate_guard<R>(f: impl FnOnce() -> R) -> R {
    let _guard = IpcAlternateGuard::new();
    f()
}

/// Run the help browser pager, wrapping with IPC alternate mode.
fn run_pager_help_browser(query: &str) {
    let help_result = with_ipc_alternate_guard(|| crate::pager::run_help_browser(query));
    if let Err(e) = help_result {
        arf_println!("Error in help browser: {}", e);
    }
}

/// Run the history browser pager, wrapping with IPC alternate mode.
fn run_pager_history_browser(path: &std::path::Path, mode: crate::pager::HistoryDbMode) {
    let browser_result = with_ipc_alternate_guard(|| crate::pager::run_history_browser(path, mode));

    match browser_result {
        Ok(crate::pager::HistoryBrowserResult::Copied(cmd)) => {
            let display = crate::pager::text_utils::truncate_to_width(&cmd, 60);
            arf_println!("Copied: {}", display);
        }
        Ok(crate::pager::HistoryBrowserResult::Cancelled) => {}
        Err(e) => {
            arf_println!("Error: {}", e);
        }
    }
}

/// Result of handling a meta command in the REPL loop.
enum MetaAction {
    /// Continue the REPL loop (show next prompt).
    Continue,
    /// The user requested exit.
    Exit,
}

/// Context for displaying session info in the pager.
struct SessionInfoContext<'a> {
    prompt_config: &'a PromptRuntimeConfig,
    config_path: &'a Option<std::path::PathBuf>,
    config_status: ConfigStatus,
    r_history_path: &'a Option<std::path::PathBuf>,
    shell_history_path: &'a Option<std::path::PathBuf>,
    r_source_status: &'a RSourceStatus,
}

/// Handle a `MetaCommandResult`, executing pager side effects as needed.
///
/// Returns `MetaAction::Exit` if the user wants to quit, otherwise `MetaAction::Continue`.
/// This is the single place where all `MetaCommandResult` variants are dispatched,
/// shared by both `Repl::run` (pre-R-init loop) and `read_console_callback` (main REPL).
fn handle_meta_command_result(
    result: MetaCommandResult,
    ctx: &SessionInfoContext<'_>,
) -> MetaAction {
    match result {
        MetaCommandResult::Handled | MetaCommandResult::ShellExecuted => MetaAction::Continue,
        MetaCommandResult::Exit => MetaAction::Exit,
        MetaCommandResult::Unknown(cmd) => {
            arf_println!(
                "Unknown command: {}. Type :commands for available commands.",
                cmd
            );
            MetaAction::Continue
        }
        MetaCommandResult::Restart(version) => {
            restart_process(version.as_deref());
            MetaAction::Continue
        }
        MetaCommandResult::ShowHelpBrowser(query) => {
            run_pager_help_browser(&query);
            MetaAction::Continue
        }
        MetaCommandResult::ShowSessionInfo => {
            with_ipc_alternate_guard(|| {
                crate::pager::display_session_info(
                    ctx.prompt_config,
                    ctx.config_path,
                    ctx.config_status,
                    ctx.r_history_path,
                    ctx.shell_history_path,
                    ctx.r_source_status,
                );
            });
            MetaAction::Continue
        }
        MetaCommandResult::ShowChangelog => {
            with_ipc_alternate_guard(crate::pager::display_changelog);
            MetaAction::Continue
        }
        MetaCommandResult::ShowHistoryBrowser { path, mode } => {
            run_pager_history_browser(&path, mode);
            MetaAction::Continue
        }
        MetaCommandResult::ShowHistorySchema => {
            if let Err(e) =
                with_ipc_alternate_guard(crate::pager::history_schema::show_schema_pager)
            {
                arf_println!("Error: {}", e);
            }
            MetaAction::Continue
        }
    }
}

/// Check if the prompt is R's standard command prompt (top-level).
///
/// Uses R's call stack depth (sys.nframe()) to determine if we're at the top-level
/// or if user code is requesting input (e.g., via readline() or menu()).
///
/// This approach is more robust than heuristics like checking prompt endings,
/// because it detects the actual R evaluation context.
///
/// Returns true if:
/// - We're at the top-level (n_frame == 0) AND not a continuation prompt
///
/// Returns false if:
/// - This is a continuation prompt (starts with '+')
/// - User code is requesting input (n_frame > 0), e.g., readline(), menu()
///
/// Reference: This approach is used by ark (Positron's R kernel).
fn is_r_command_prompt(prompt: &str) -> bool {
    // Continuation prompts (starting with '+') are NOT command prompts
    if prompt.starts_with('+') {
        return false;
    }

    // Use R's call stack depth to detect if we're at top-level
    // n_frame == 0 means top-level prompt
    // n_frame > 0 means user code is requesting input (readline, menu, etc.)
    match arf_harp::r_n_frame() {
        Ok(n_frame) => n_frame == 0,
        Err(_) => {
            // If we can't get n_frame, fall back to heuristic
            // R's default prompt ends with "> ", menu prompts end with ": "
            prompt.ends_with("> ")
        }
    }
}

/// Set up history for a line editor with a specific database path.
///
/// Returns `(editor, true)` if history was successfully configured, or
/// `(editor, false)` if history path was `None` or the database failed to open.
/// The history is wrapped with FuzzyHistory to provide fuzzy search capabilities.
fn setup_history(
    line_editor: Reedline,
    history_path: Option<std::path::PathBuf>,
    session_id: Option<HistorySessionId>,
) -> (Reedline, bool) {
    let Some(path) = history_path else {
        return (line_editor, false);
    };
    match SqliteBackedHistory::with_file(path.clone(), session_id, Some(chrono::Utc::now())) {
        Ok(history) => {
            let fuzzy_history = FuzzyHistory::new(history);
            let editor = line_editor
                .with_history_session_id(session_id)
                .with_history(Box::new(fuzzy_history));
            (editor, true)
        }
        Err(e) => {
            log::warn!("Failed to open history database {}: {}", path.display(), e);
            (line_editor, false)
        }
    }
}

#[cfg(test)]
mod sponge_tests {
    use super::state::SpongeQueue;
    use reedline::HistoryItemId;

    /// Helper to create a HistoryItemId for testing.
    fn make_id(id: i64) -> HistoryItemId {
        HistoryItemId::new(id)
    }

    /// Helper to run a sequence of commands through SpongeQueue and collect deleted IDs.
    fn run_commands(commands: &[(bool, i64)], delay: usize) -> Vec<HistoryItemId> {
        let mut queue = SpongeQueue::new();
        let mut deleted = Vec::new();

        for &(is_failure, id) in commands {
            let history_id = Some(make_id(id));
            if let Some(id_to_delete) = queue.record_command(is_failure, history_id, delay) {
                deleted.push(id_to_delete);
            }
        }

        deleted
    }

    #[test]
    fn test_sponge_delay_keeps_recent_failures() {
        // With delay=2, failed commands should remain accessible for 2 more commands
        // Command sequence: fail(1), success, success -> fail(1) should be deleted
        let commands = vec![
            (true, 1),  // Failed command with ID 1
            (false, 2), // Success
            (false, 3), // Success -> now queue has 3 entries, purge oldest
        ];

        let deleted = run_commands(&commands, 2);
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], make_id(1));
    }

    #[test]
    fn test_sponge_delay_zero_deletes_immediately() {
        // With delay=0, failed commands are deleted immediately
        let commands = vec![
            (true, 1), // Failed -> immediately deleted (queue > 0)
        ];

        let deleted = run_commands(&commands, 0);
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], make_id(1));
    }

    #[test]
    fn test_sponge_success_does_not_delete() {
        // Successful commands never cause deletions directly
        let commands = vec![
            (false, 1), // Success
            (false, 2), // Success
            (false, 3), // Success -> purges None entries
        ];

        let deleted = run_commands(&commands, 2);
        assert!(deleted.is_empty(), "No failures to delete");
    }

    #[test]
    fn test_sponge_multiple_failures_fifo() {
        // Multiple failures should be deleted in FIFO order
        // delay=2: keep 2 entries, delete older ones
        let commands = vec![
            (true, 1),  // fail(1) -> queue: [Some(1)]
            (true, 2),  // fail(2) -> queue: [Some(2), Some(1)]
            (true, 3),  // fail(3) -> queue: [Some(3), Some(2), Some(1)] -> delete 1
            (false, 4), // success -> queue: [None, Some(3), Some(2)] -> delete 2
        ];

        let deleted = run_commands(&commands, 2);
        assert_eq!(deleted.len(), 2);
        assert_eq!(deleted[0], make_id(1)); // First to be deleted
        assert_eq!(deleted[1], make_id(2)); // Second to be deleted
    }

    #[test]
    fn test_sponge_interleaved_success_failure() {
        // Interleaved success/failure pattern
        // delay=3
        let commands = vec![
            (true, 1),  // fail -> [Some(1)]
            (false, 2), // ok   -> [None, Some(1)]
            (true, 3),  // fail -> [Some(3), None, Some(1)]
            (false, 4), // ok   -> [None, Some(3), None, Some(1)] -> delete 1
            (false, 5), // ok   -> [None, None, Some(3), None] -> delete None (no-op)
        ];

        let deleted = run_commands(&commands, 3);
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], make_id(1));
    }

    #[test]
    fn test_sponge_large_delay_no_deletion() {
        // With a large delay, nothing gets deleted during the session
        let commands = vec![(true, 1), (true, 2), (true, 3), (false, 4), (false, 5)];

        let deleted = run_commands(&commands, 100);
        assert!(deleted.is_empty(), "Delay is larger than command count");
    }

    #[test]
    fn test_sponge_delay_one_keeps_one_command() {
        // delay=1 means keep only the most recent command in queue
        let commands = vec![
            (true, 1),  // fail -> [Some(1)]
            (false, 2), // ok   -> [None, Some(1)] -> delete 1
            (true, 3),  // fail -> [Some(3), None] -> delete None (no-op)
            (true, 4),  // fail -> [Some(4), Some(3)] -> delete 3
        ];

        let deleted = run_commands(&commands, 1);
        assert_eq!(deleted.len(), 2);
        assert_eq!(deleted[0], make_id(1));
        assert_eq!(deleted[1], make_id(3));
    }

    #[test]
    fn test_sponge_realistic_scenario() {
        // Realistic scenario: user typos a command, then fixes it
        // With delay=2, they can use up-arrow to see the failed command for 2 commands
        let commands = vec![
            (true, 100),  // typo: "gti status" -> [Some(100)]
            (false, 101), // fix: "git status" -> [None, Some(100)]
            (false, 102), // continue: "git add ." -> [None, None, Some(100)] -> delete 100
        ];

        let deleted = run_commands(&commands, 2);
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], make_id(100));
    }

    #[test]
    fn test_sponge_drain_failed_ids() {
        // Test drain_failed_ids for exit cleanup
        let mut queue = SpongeQueue::new();

        // Add some commands with a large delay (no immediate deletion)
        queue.record_command(true, Some(make_id(1)), 100);
        queue.record_command(false, Some(make_id(2)), 100);
        queue.record_command(true, Some(make_id(3)), 100);
        queue.record_command(false, Some(make_id(4)), 100);

        // Drain should return only the failed command IDs
        let drained: Vec<_> = queue.drain_failed_ids().collect();
        assert_eq!(drained.len(), 2);
        // drain_failed_ids returns in FIFO order (oldest first)
        assert_eq!(drained[0], make_id(1));
        assert_eq!(drained[1], make_id(3));

        // Queue should be empty after drain
        assert!(queue.is_empty());
    }
}