osp-cli 1.5.1

CLI and REPL for querying and managing OSP infrastructure data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
//! Persistent REPL history with profile-aware visibility and shell-prefix
//! scoping.
//!
//! Records are stored oldest-to-newest. Public listing helpers preserve that
//! order while filtering by the active profile scope, optional shell prefix,
//! and configured exclusion patterns. Shell-scoped views strip the prefix back
//! off so callers see the command as it was typed inside that shell.
//!
//! Pruning and clearing only remove records visible in the chosen scope. The
//! store also records terminal identifiers on entries for provenance, but that
//! metadata is not currently part of view scoping.
//!
//! Public API shape:
//!
//! - [`HistoryConfig::builder`] is the guided construction path and produces a
//!   normalized config snapshot on `build()`
//! - [`SharedHistory`] is the public facade; the raw `reedline` store stays
//!   crate-private

use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::Result;
use reedline::{
    CommandLineSearch, History, HistoryItem, HistoryItemId, HistorySessionId, ReedlineError,
    ReedlineErrorVariants, Result as ReedlineResult, SearchDirection, SearchFilter, SearchQuery,
};
use serde::{Deserialize, Serialize};

use crate::normalize::normalize_optional_identifier;

/// Configuration for REPL history persistence, visibility, and shell scoping.
#[derive(Debug, Clone)]
#[non_exhaustive]
#[must_use]
pub struct HistoryConfig {
    /// Path to the history file, when persistence is enabled.
    pub path: Option<PathBuf>,
    /// Maximum number of retained history entries.
    pub max_entries: usize,
    /// Whether history capture is enabled.
    pub enabled: bool,
    /// Whether duplicate commands should be collapsed.
    pub dedupe: bool,
    /// Whether entries should be partitioned by active profile.
    pub profile_scoped: bool,
    /// Prefix patterns excluded from persistence.
    pub exclude_patterns: Vec<String>,
    /// Active profile identifier used for scoping.
    pub profile: Option<String>,
    /// Active terminal identifier recorded on saved entries.
    pub terminal: Option<String>,
    /// Shared shell-prefix scope used to filter and strip shell-prefixed views.
    pub shell_context: HistoryShellContext,
}

impl Default for HistoryConfig {
    fn default() -> Self {
        Self {
            path: None,
            max_entries: 1_000,
            enabled: true,
            dedupe: true,
            profile_scoped: true,
            exclude_patterns: Vec::new(),
            profile: None,
            terminal: None,
            shell_context: HistoryShellContext::default(),
        }
    }
}

impl HistoryConfig {
    /// Starts guided construction for REPL history configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use osp_cli::repl::HistoryConfig;
    ///
    /// let config = HistoryConfig::builder()
    ///     .with_path(Some(PathBuf::from("/tmp/osp-history.jsonl")))
    ///     .with_max_entries(250)
    ///     .with_profile(Some(" Dev ".to_string()))
    ///     .build();
    ///
    /// assert_eq!(config.max_entries, 250);
    /// assert_eq!(config.profile.as_deref(), Some("dev"));
    /// ```
    pub fn builder() -> HistoryConfigBuilder {
        HistoryConfigBuilder::new()
    }

    /// Normalizes configured identifiers and exclusion patterns.
    pub fn normalized(mut self) -> Self {
        self.exclude_patterns =
            normalize_exclude_patterns(std::mem::take(&mut self.exclude_patterns));
        self.profile = normalize_optional_identifier(self.profile.take());
        self.terminal = normalize_optional_identifier(self.terminal.take());
        self
    }

    fn persist_enabled(&self) -> bool {
        self.enabled && self.path.is_some() && self.max_entries > 0
    }
}

/// Builder for [`HistoryConfig`].
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct HistoryConfigBuilder {
    config: HistoryConfig,
}

impl HistoryConfigBuilder {
    /// Starts a builder with normal REPL-history defaults.
    pub fn new() -> Self {
        Self {
            config: HistoryConfig::default(),
        }
    }

    /// Replaces the optional persistence path.
    ///
    /// If omitted, history persistence stays in-memory only.
    pub fn with_path(mut self, path: Option<PathBuf>) -> Self {
        self.config.path = path;
        self
    }

    /// Replaces the retained-entry limit.
    ///
    /// If omitted, the builder keeps the default retained-entry limit.
    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
        self.config.max_entries = max_entries;
        self
    }

    /// Enables or disables history capture.
    ///
    /// If omitted, history capture stays enabled.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// Enables or disables duplicate collapsing.
    ///
    /// If omitted, duplicate collapsing stays enabled.
    pub fn with_dedupe(mut self, dedupe: bool) -> Self {
        self.config.dedupe = dedupe;
        self
    }

    /// Enables or disables profile scoping.
    ///
    /// If omitted, history remains profile-scoped.
    pub fn with_profile_scoped(mut self, profile_scoped: bool) -> Self {
        self.config.profile_scoped = profile_scoped;
        self
    }

    /// Replaces the excluded command patterns.
    ///
    /// If omitted, no exclusion patterns are applied.
    pub fn with_exclude_patterns<I, S>(mut self, exclude_patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.config.exclude_patterns = exclude_patterns.into_iter().map(Into::into).collect();
        self
    }

    /// Replaces the active profile used for scoping.
    ///
    /// If omitted, history entries are not tagged with a profile identifier.
    pub fn with_profile(mut self, profile: Option<String>) -> Self {
        self.config.profile = profile;
        self
    }

    /// Replaces the active terminal label recorded on entries.
    ///
    /// If omitted, saved entries carry no terminal label.
    pub fn with_terminal(mut self, terminal: Option<String>) -> Self {
        self.config.terminal = terminal;
        self
    }

    /// Replaces the shared shell context used for scoped history views.
    ///
    /// If omitted, the builder keeps [`HistoryShellContext::default`].
    pub fn with_shell_context(mut self, shell_context: HistoryShellContext) -> Self {
        self.config.shell_context = shell_context;
        self
    }

    /// Builds a normalized history configuration.
    pub fn build(self) -> HistoryConfig {
        self.config.normalized()
    }
}

/// Shared shell-prefix state used to scope history to nested shell integrations.
#[derive(Clone, Default, Debug)]
pub struct HistoryShellContext {
    inner: Arc<RwLock<Option<String>>>,
}

impl HistoryShellContext {
    /// Creates a shell context with an initial normalized prefix.
    pub fn new(prefix: impl Into<String>) -> Self {
        let context = Self::default();
        context.set_prefix(prefix);
        context
    }

    /// Sets or replaces the normalized shell prefix.
    pub fn set_prefix(&self, prefix: impl Into<String>) {
        if let Ok(mut guard) = self.inner.write() {
            *guard = normalize_shell_prefix(prefix.into());
        }
    }

    /// Clears the current shell prefix.
    pub fn clear(&self) {
        if let Ok(mut guard) = self.inner.write() {
            *guard = None;
        }
    }

    /// Returns the current normalized shell prefix, if one is set.
    pub fn prefix(&self) -> Option<String> {
        self.inner.read().map(|value| value.clone()).unwrap_or(None)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct HistoryRecord {
    id: i64,
    command_line: String,
    #[serde(default)]
    timestamp_ms: Option<i64>,
    #[serde(default)]
    duration_ms: Option<i64>,
    #[serde(default)]
    exit_status: Option<i64>,
    #[serde(default)]
    cwd: Option<String>,
    #[serde(default)]
    hostname: Option<String>,
    #[serde(default)]
    session_id: Option<i64>,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    terminal: Option<String>,
}

/// Visible history entry returned by listing operations after scope filtering.
#[derive(Debug, Clone)]
pub struct HistoryEntry {
    /// Stable identifier within the visible ordered entry list.
    pub id: i64,
    /// Recorded timestamp in milliseconds since the Unix epoch, when available.
    pub timestamp_ms: Option<i64>,
    /// Command line as presented in the selected scope.
    pub command: String,
}

/// Thread-safe facade over the REPL history store.
///
/// Listing helpers return entries in oldest-to-newest order. Mutating helpers
/// such as prune and clear only touch entries visible in the chosen scope.
#[derive(Clone)]
pub struct SharedHistory {
    inner: Arc<Mutex<OspHistoryStore>>,
}

impl SharedHistory {
    /// Creates a shared history store from the provided configuration.
    ///
    /// Persisted history loading is best-effort: unreadable files and malformed
    /// lines are ignored during initialization.
    pub fn new(config: HistoryConfig) -> Self {
        Self {
            inner: Arc::new(Mutex::new(OspHistoryStore::new(config))),
        }
    }

    /// Returns whether history capture is enabled for the current config.
    pub fn enabled(&self) -> bool {
        self.inner
            .lock()
            .map(|store| store.history_enabled())
            .unwrap_or(false)
    }

    /// Returns visible commands in oldest-to-newest order using the active
    /// shell scope.
    pub fn recent_commands(&self) -> Vec<String> {
        self.inner
            .lock()
            .map(|store| store.recent_commands())
            .unwrap_or_default()
    }

    /// Returns visible commands in oldest-to-newest order for the provided
    /// shell prefix.
    ///
    /// Matching profile scope and exclusion patterns still apply. When a shell
    /// prefix is provided, the returned commands have that prefix stripped.
    pub fn recent_commands_for(&self, shell_prefix: Option<&str>) -> Vec<String> {
        self.inner
            .lock()
            .map(|store| store.recent_commands_for(shell_prefix))
            .unwrap_or_default()
    }

    /// Returns visible history entries in oldest-to-newest order using the
    /// active shell scope.
    pub fn list_entries(&self) -> Vec<HistoryEntry> {
        self.inner
            .lock()
            .map(|store| store.list_entries())
            .unwrap_or_default()
    }

    /// Returns visible history entries in oldest-to-newest order for the
    /// provided shell prefix.
    pub fn list_entries_for(&self, shell_prefix: Option<&str>) -> Vec<HistoryEntry> {
        self.inner
            .lock()
            .map(|store| store.list_entries_for(shell_prefix))
            .unwrap_or_default()
    }

    /// Removes the oldest visible entries, keeping at most `keep` entries in
    /// the active scope.
    ///
    /// Returns the number of removed entries.
    ///
    /// # Errors
    ///
    /// Returns an error when the history lock is poisoned or when persisting
    /// the updated history file fails.
    pub fn prune(&self, keep: usize) -> Result<usize> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| anyhow::anyhow!("history lock poisoned"))?;
        guard.prune(keep)
    }

    /// Removes the oldest visible entries for a specific shell scope, keeping
    /// at most `keep`.
    ///
    /// Returns the number of removed entries.
    ///
    /// # Errors
    ///
    /// Returns an error when the history lock is poisoned or when persisting
    /// the updated history file fails.
    pub fn prune_for(&self, keep: usize, shell_prefix: Option<&str>) -> Result<usize> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| anyhow::anyhow!("history lock poisoned"))?;
        guard.prune_for(keep, shell_prefix)
    }

    /// Clears all entries visible in the current scope.
    ///
    /// Returns the number of removed entries.
    ///
    /// # Errors
    ///
    /// Returns an error when the history lock is poisoned or when persisting
    /// the updated history file fails.
    pub fn clear_scoped(&self) -> Result<usize> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| anyhow::anyhow!("history lock poisoned"))?;
        guard.clear_scoped()
    }

    /// Clears all entries visible to the provided shell prefix.
    ///
    /// Returns the number of removed entries.
    ///
    /// # Errors
    ///
    /// Returns an error when the history lock is poisoned or when persisting
    /// the updated history file fails.
    pub fn clear_for(&self, shell_prefix: Option<&str>) -> Result<usize> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| anyhow::anyhow!("history lock poisoned"))?;
        guard.clear_for(shell_prefix)
    }

    /// Saves one command line through the underlying `reedline::History`
    /// implementation.
    ///
    /// # Errors
    ///
    /// Returns an error when the history lock is poisoned or when the
    /// underlying history backend rejects or fails to persist the item.
    pub fn save_command_line(&self, command_line: &str) -> Result<()> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| anyhow::anyhow!("history lock poisoned"))?;
        let item = HistoryItem::from_command_line(command_line);
        History::save(&mut *guard, item).map(|_| ())?;
        Ok(())
    }
}

/// `reedline::History` implementation backed by newline-delimited JSON records.
///
/// The store keeps insertion order, applies visibility rules when presenting
/// commands back to callers, and writes the full persisted record stream back
/// out atomically after mutations.
pub(crate) struct OspHistoryStore {
    config: HistoryConfig,
    records: Vec<HistoryRecord>,
}

impl OspHistoryStore {
    /// Creates a history store and eagerly loads persisted records when
    /// persistence is enabled.
    pub fn new(config: HistoryConfig) -> Self {
        let config = config.normalized();
        let mut records = Vec::new();
        if config.persist_enabled()
            && let Some(path) = &config.path
        {
            records = load_records(path);
        }
        let mut store = Self { config, records };
        store.trim_to_capacity();
        store
    }

    /// Returns whether history operations are active for this store.
    ///
    /// This is false when history is disabled or when the configured capacity is
    /// zero.
    pub fn history_enabled(&self) -> bool {
        self.config.enabled && self.config.max_entries > 0
    }

    /// Returns visible commands in oldest-to-newest order using the active
    /// shell scope.
    pub fn recent_commands(&self) -> Vec<String> {
        self.recent_commands_for(self.shell_prefix().as_deref())
    }

    /// Returns visible commands in oldest-to-newest order for the provided
    /// shell prefix.
    ///
    /// Profile scoping and exclusion patterns still apply.
    pub fn recent_commands_for(&self, shell_prefix: Option<&str>) -> Vec<String> {
        self.visible_record_indices_for(shell_prefix)
            .into_iter()
            .map(|record_index| self.records[record_index].command_line.clone())
            .collect()
    }

    /// Returns visible history entries in oldest-to-newest order using the
    /// active shell scope.
    pub fn list_entries(&self) -> Vec<HistoryEntry> {
        self.list_entries_for(self.shell_prefix().as_deref())
    }

    /// Returns visible history entries in oldest-to-newest order for the
    /// provided shell prefix.
    pub fn list_entries_for(&self, shell_prefix: Option<&str>) -> Vec<HistoryEntry> {
        if !self.history_enabled() {
            return Vec::new();
        }
        let shell_prefix = normalize_scope_prefix(shell_prefix);
        self.visible_record_indices_for(shell_prefix.as_deref())
            .into_iter()
            .enumerate()
            .map(|(idx, record_index)| HistoryEntry {
                id: idx as i64 + 1,
                timestamp_ms: self.records[record_index].timestamp_ms,
                command: self.view_command_line(
                    &self.records[record_index].command_line,
                    shell_prefix.as_deref(),
                ),
            })
            .collect()
    }

    /// Removes the oldest visible entries, keeping at most `keep` in the active
    /// scope.
    ///
    /// Returns the number of removed entries.
    pub fn prune(&mut self, keep: usize) -> Result<usize> {
        let shell_prefix = self.shell_prefix();
        self.prune_for(keep, shell_prefix.as_deref())
    }

    /// Removes the oldest visible entries for a specific shell scope, keeping
    /// at most `keep`.
    ///
    /// Returns the number of removed entries.
    pub fn prune_for(&mut self, keep: usize, shell_prefix: Option<&str>) -> Result<usize> {
        if !self.history_enabled() {
            return Ok(0);
        }
        let eligible = self.visible_record_indices_for(shell_prefix);

        if keep == 0 {
            return self.remove_records(&eligible);
        }

        if eligible.len() <= keep {
            return Ok(0);
        }

        let remove_count = eligible.len() - keep;
        let to_remove = eligible.into_iter().take(remove_count).collect::<Vec<_>>();
        self.remove_records(&to_remove)
    }

    /// Clears all entries visible in the current scope.
    ///
    /// This is equivalent to `prune(0)`.
    ///
    /// Returns the number of removed entries.
    pub fn clear_scoped(&mut self) -> Result<usize> {
        self.prune(0)
    }

    /// Clears all entries visible to the provided shell prefix.
    ///
    /// This is equivalent to `prune_for(0, shell_prefix)`.
    ///
    /// Returns the number of removed entries.
    pub fn clear_for(&mut self, shell_prefix: Option<&str>) -> Result<usize> {
        self.prune_for(0, shell_prefix)
    }

    fn profile_allows(&self, record: &HistoryRecord) -> bool {
        if !self.config.profile_scoped {
            return true;
        }
        match (self.config.profile.as_deref(), record.profile.as_deref()) {
            (Some(active), Some(profile)) => active == profile,
            (Some(_), None) => false,
            _ => true,
        }
    }

    fn shell_prefix(&self) -> Option<String> {
        self.config.shell_context.prefix()
    }

    fn shell_allows(&self, record: &HistoryRecord, shell_prefix: Option<&str>) -> bool {
        command_matches_shell_prefix(&record.command_line, shell_prefix)
    }

    fn view_command_line(&self, command: &str, shell_prefix: Option<&str>) -> String {
        strip_shell_prefix(command, shell_prefix)
    }

    fn record_view_if_allowed(
        &self,
        record: &HistoryRecord,
        shell_prefix: Option<&str>,
        require_shell: bool,
    ) -> Option<String> {
        if !self.profile_allows(record) {
            return None;
        }
        if require_shell && !self.shell_allows(record, shell_prefix) {
            return None;
        }
        let view_command = self.view_command_line(&record.command_line, shell_prefix);
        if self.is_command_excluded(&view_command) {
            return None;
        }
        Some(view_command)
    }

    fn visible_record_indices_for(&self, shell_prefix: Option<&str>) -> Vec<usize> {
        let shell_prefix = normalize_scope_prefix(shell_prefix);
        let mut out = Vec::new();
        for (record_index, record) in self.records.iter().enumerate() {
            if self
                .record_view_if_allowed(record, shell_prefix.as_deref(), true)
                .is_none()
            {
                continue;
            }
            out.push(record_index);
        }
        out
    }

    fn is_command_excluded(&self, command: &str) -> bool {
        is_excluded_command(command, &self.config.exclude_patterns)
    }

    fn next_id(&self) -> i64 {
        self.records.len() as i64
    }

    fn trim_to_capacity(&mut self) {
        if self.config.max_entries == 0 {
            self.records.clear();
            return;
        }
        if self.records.len() > self.config.max_entries {
            let start = self.records.len() - self.config.max_entries;
            self.records = self.records.split_off(start);
        }
        for (idx, record) in self.records.iter_mut().enumerate() {
            record.id = idx as i64;
        }
    }

    fn append_record(&mut self, mut record: HistoryRecord) -> HistoryItemId {
        record.id = self.next_id();
        self.records.push(record);
        self.trim_to_capacity();
        HistoryItemId::new(self.records.len() as i64 - 1)
    }

    fn remove_records(&mut self, indices: &[usize]) -> Result<usize> {
        if indices.is_empty() {
            return Ok(0);
        }
        let mut drop_flags = vec![false; self.records.len()];
        for idx in indices {
            if *idx < drop_flags.len() {
                drop_flags[*idx] = true;
            }
        }
        let mut cursor = 0usize;
        let removed = drop_flags.iter().filter(|flag| **flag).count();
        self.records.retain(|_| {
            let keep = !drop_flags.get(cursor).copied().unwrap_or(false);
            cursor += 1;
            keep
        });
        self.trim_to_capacity();
        if let Err(err) = self.write_all() {
            return Err(err.into());
        }
        Ok(removed)
    }

    fn write_all(&self) -> std::io::Result<()> {
        if !self.config.persist_enabled() {
            return Ok(());
        }
        let Some(path) = &self.config.path else {
            return Ok(());
        };
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut payload = Vec::new();
        for record in &self.records {
            serde_json::to_writer(&mut payload, record).map_err(std::io::Error::other)?;
            payload.push(b'\n');
        }
        crate::config::write_text_atomic(path, &payload, false)
    }

    fn should_skip_command(&self, command: &str) -> bool {
        is_excluded_command(command, &self.config.exclude_patterns)
    }

    fn command_list_for_expansion(&self) -> Vec<String> {
        self.recent_commands()
    }

    fn expand_if_needed(&self, command: &str, shell_prefix: Option<&str>) -> Option<String> {
        if !command.starts_with('!') {
            return Some(command.to_string());
        }
        let history = self.command_list_for_expansion();
        expand_history(command, &history, shell_prefix, false)
    }

    fn record_matches_filter(
        &self,
        record: &HistoryRecord,
        filter: &SearchFilter,
        shell_prefix: Option<&str>,
    ) -> bool {
        let Some(view_command) = self.record_view_if_allowed(record, shell_prefix, true) else {
            return false;
        };
        if let Some(search) = &filter.command_line {
            let matches = match search {
                CommandLineSearch::Prefix(prefix) => view_command.starts_with(prefix),
                CommandLineSearch::Substring(substr) => view_command.contains(substr),
                CommandLineSearch::Exact(exact) => view_command == *exact,
            };
            if !matches {
                return false;
            }
        }
        if let Some(hostname) = &filter.hostname
            && record.hostname.as_deref() != Some(hostname.as_str())
        {
            return false;
        }
        if let Some(cwd) = &filter.cwd_exact
            && record.cwd.as_deref() != Some(cwd.as_str())
        {
            return false;
        }
        if let Some(prefix) = &filter.cwd_prefix {
            match record.cwd.as_deref() {
                Some(value) if value.starts_with(prefix) => {}
                _ => return false,
            }
        }
        if let Some(exit_successful) = filter.exit_successful {
            let is_success = record.exit_status == Some(0);
            if exit_successful != is_success {
                return false;
            }
        }
        if let Some(session) = filter.session
            && record.session_id != Some(i64::from(session))
        {
            return false;
        }
        true
    }

    fn record_from_item(&self, item: &HistoryItem, command_line: String) -> HistoryRecord {
        HistoryRecord {
            id: -1,
            command_line,
            timestamp_ms: item.start_timestamp.map(|ts| ts.timestamp_millis()),
            duration_ms: item.duration.map(|value| value.as_millis() as i64),
            exit_status: item.exit_status,
            cwd: item.cwd.clone(),
            hostname: item.hostname.clone(),
            session_id: item.session_id.map(i64::from),
            profile: self.config.profile.clone(),
            terminal: self.config.terminal.clone(),
        }
    }

    fn history_item_from_record(
        &self,
        record: &HistoryRecord,
        shell_prefix: Option<&str>,
    ) -> HistoryItem {
        let command_line = self.view_command_line(&record.command_line, shell_prefix);
        HistoryItem {
            id: Some(HistoryItemId::new(record.id)),
            start_timestamp: None,
            command_line,
            session_id: None,
            hostname: record.hostname.clone(),
            cwd: record.cwd.clone(),
            duration: record
                .duration_ms
                .map(|value| Duration::from_millis(value as u64)),
            exit_status: record.exit_status,
            more_info: None,
        }
    }

    fn reedline_error(message: &'static str) -> ReedlineError {
        ReedlineError(ReedlineErrorVariants::OtherHistoryError(message))
    }

    fn record_matches_query(
        &self,
        record: &HistoryRecord,
        filter: &SearchFilter,
        start_time_ms: Option<i64>,
        end_time_ms: Option<i64>,
        shell_prefix: Option<&str>,
        skip_command_line: Option<&str>,
    ) -> bool {
        if !self.record_matches_filter(record, filter, shell_prefix) {
            return false;
        }
        if let Some(skip) = skip_command_line {
            let view_command = self.view_command_line(&record.command_line, shell_prefix);
            if view_command == skip {
                return false;
            }
        }
        if let Some(start) = start_time_ms {
            match record.timestamp_ms {
                Some(value) if value >= start => {}
                _ => return false,
            }
        }
        if let Some(end) = end_time_ms {
            match record.timestamp_ms {
                Some(value) if value <= end => {}
                _ => return false,
            }
        }
        true
    }
}

impl History for OspHistoryStore {
    fn save(&mut self, h: HistoryItem) -> ReedlineResult<HistoryItem> {
        if !self.config.enabled || self.config.max_entries == 0 {
            return Ok(h);
        }

        let raw = h.command_line.trim();
        if raw.is_empty() {
            return Ok(h);
        }

        let shell_prefix = self.shell_prefix();
        let Some(expanded) = self.expand_if_needed(raw, shell_prefix.as_deref()) else {
            return Ok(h);
        };
        if self.should_skip_command(&expanded) {
            return Ok(h);
        }
        let expanded_full = apply_shell_prefix(&expanded, shell_prefix.as_deref());

        if self.config.dedupe {
            let last_match = self.records.iter().rev().find(|record| {
                self.profile_allows(record) && self.shell_allows(record, shell_prefix.as_deref())
            });
            if let Some(last) = last_match
                && last.command_line == expanded_full
            {
                return Ok(h);
            }
        }

        let mut record = self.record_from_item(&h, expanded_full);
        if record.timestamp_ms.is_none() {
            record.timestamp_ms = Some(now_ms());
        }
        let id = self.append_record(record);

        if let Err(err) = self.write_all() {
            return Err(ReedlineError(ReedlineErrorVariants::IOError(err)));
        }

        Ok(HistoryItem {
            id: Some(id),
            command_line: self.records[id.0 as usize].command_line.clone(),
            ..h
        })
    }

    fn load(&self, id: HistoryItemId) -> ReedlineResult<HistoryItem> {
        let idx = id.0 as usize;
        let shell_prefix = self.shell_prefix();
        let record = self
            .records
            .get(idx)
            .ok_or_else(|| Self::reedline_error("history item not found"))?;
        Ok(self.history_item_from_record(record, shell_prefix.as_deref()))
    }

    fn count(&self, query: SearchQuery) -> ReedlineResult<i64> {
        Ok(self.search(query)?.len() as i64)
    }

    fn search(&self, query: SearchQuery) -> ReedlineResult<Vec<HistoryItem>> {
        let (min_id, max_id) = {
            let start = query.start_id.map(|value| value.0);
            let end = query.end_id.map(|value| value.0);
            if let SearchDirection::Backward = query.direction {
                (end, start)
            } else {
                (start, end)
            }
        };
        let min_id = min_id.map(|value| value + 1).unwrap_or(0);
        let max_id = max_id
            .map(|value| value - 1)
            .unwrap_or(self.records.len().saturating_sub(1) as i64);

        if self.records.is_empty() || max_id < 0 || min_id > max_id {
            return Ok(Vec::new());
        }

        let intrinsic_limit = max_id - min_id + 1;
        let limit = query
            .limit
            .map(|value| std::cmp::min(intrinsic_limit, value) as usize)
            .unwrap_or(intrinsic_limit as usize);

        let start_time_ms = query.start_time.map(|ts| ts.timestamp_millis());
        let end_time_ms = query.end_time.map(|ts| ts.timestamp_millis());
        let shell_prefix = self.shell_prefix();

        let mut results = Vec::new();
        let iter = self
            .records
            .iter()
            .enumerate()
            .skip(min_id as usize)
            .take(intrinsic_limit as usize);
        let skip_command_line = query
            .start_id
            .and_then(|id| self.records.get(id.0 as usize))
            .map(|record| self.view_command_line(&record.command_line, shell_prefix.as_deref()));

        if let SearchDirection::Backward = query.direction {
            for (idx, record) in iter.rev() {
                if results.len() >= limit {
                    break;
                }
                if !self.record_matches_query(
                    record,
                    &query.filter,
                    start_time_ms,
                    end_time_ms,
                    shell_prefix.as_deref(),
                    skip_command_line.as_deref(),
                ) {
                    continue;
                }
                let mut item = self.history_item_from_record(record, shell_prefix.as_deref());
                item.id = Some(HistoryItemId::new(idx as i64));
                results.push(item);
            }
        } else {
            for (idx, record) in iter {
                if results.len() >= limit {
                    break;
                }
                if !self.record_matches_query(
                    record,
                    &query.filter,
                    start_time_ms,
                    end_time_ms,
                    shell_prefix.as_deref(),
                    skip_command_line.as_deref(),
                ) {
                    continue;
                }
                let mut item = self.history_item_from_record(record, shell_prefix.as_deref());
                item.id = Some(HistoryItemId::new(idx as i64));
                results.push(item);
            }
        }

        Ok(results)
    }

    fn update(
        &mut self,
        _id: HistoryItemId,
        _updater: &dyn Fn(HistoryItem) -> HistoryItem,
    ) -> ReedlineResult<()> {
        Err(ReedlineError(
            ReedlineErrorVariants::HistoryFeatureUnsupported {
                history: "OspHistoryStore",
                feature: "updating entries",
            },
        ))
    }

    fn clear(&mut self) -> ReedlineResult<()> {
        self.records.clear();
        if let Some(path) = &self.config.path {
            let _ = std::fs::remove_file(path);
        }
        Ok(())
    }

    fn delete(&mut self, _h: HistoryItemId) -> ReedlineResult<()> {
        Err(ReedlineError(
            ReedlineErrorVariants::HistoryFeatureUnsupported {
                history: "OspHistoryStore",
                feature: "removing entries",
            },
        ))
    }

    fn sync(&mut self) -> std::io::Result<()> {
        self.write_all()
    }

    fn session(&self) -> Option<HistorySessionId> {
        None
    }
}

impl History for SharedHistory {
    fn save(&mut self, h: HistoryItem) -> ReedlineResult<HistoryItem> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::save(&mut *guard, h)
    }

    fn load(&self, id: HistoryItemId) -> ReedlineResult<HistoryItem> {
        let guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::load(&*guard, id)
    }

    fn count(&self, query: SearchQuery) -> ReedlineResult<i64> {
        let guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::count(&*guard, query)
    }

    fn search(&self, query: SearchQuery) -> ReedlineResult<Vec<HistoryItem>> {
        let guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::search(&*guard, query)
    }

    fn update(
        &mut self,
        id: HistoryItemId,
        updater: &dyn Fn(HistoryItem) -> HistoryItem,
    ) -> ReedlineResult<()> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::update(&mut *guard, id, updater)
    }

    fn clear(&mut self) -> ReedlineResult<()> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::clear(&mut *guard)
    }

    fn delete(&mut self, h: HistoryItemId) -> ReedlineResult<()> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| OspHistoryStore::reedline_error("history lock poisoned"))?;
        History::delete(&mut *guard, h)
    }

    fn sync(&mut self) -> std::io::Result<()> {
        let mut guard = self
            .inner
            .lock()
            .map_err(|_| std::io::Error::other("history lock poisoned"))?;
        History::sync(&mut *guard)
    }

    fn session(&self) -> Option<HistorySessionId> {
        let guard = self.inner.lock().ok()?;
        History::session(&*guard)
    }
}

fn load_records(path: &Path) -> Vec<HistoryRecord> {
    if !path.exists() {
        return Vec::new();
    }
    let file = match File::open(path) {
        Ok(file) => file,
        Err(_) => return Vec::new(),
    };
    let reader = BufReader::new(file);
    let mut records = Vec::new();
    for line in reader.lines().map_while(Result::ok) {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let record: HistoryRecord = match serde_json::from_str(trimmed) {
            Ok(record) => record,
            Err(_) => continue,
        };
        if record.command_line.trim().is_empty() {
            continue;
        }
        records.push(record);
    }
    records
}

fn normalize_exclude_patterns(patterns: Vec<String>) -> Vec<String> {
    patterns
        .into_iter()
        .map(|pattern| pattern.trim().to_string())
        .filter(|pattern| !pattern.is_empty())
        .collect()
}

fn normalize_shell_prefix(value: String) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }
    let mut out = trimmed.to_string();
    if !out.ends_with(' ') {
        out.push(' ');
    }
    Some(out)
}

fn normalize_scope_prefix(shell_prefix: Option<&str>) -> Option<String> {
    shell_prefix.and_then(|value| normalize_shell_prefix(value.to_string()))
}

fn command_matches_shell_prefix(command: &str, shell_prefix: Option<&str>) -> bool {
    match shell_prefix {
        Some(prefix) => command.starts_with(prefix),
        None => true,
    }
}

pub(crate) fn apply_shell_prefix(command: &str, shell_prefix: Option<&str>) -> String {
    let trimmed = command.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    match shell_prefix {
        Some(prefix) => {
            let prefix_trimmed = prefix.trim_end();
            if trimmed == prefix_trimmed || trimmed.starts_with(prefix) {
                return trimmed.to_string();
            }
            let mut out = String::with_capacity(prefix.len() + trimmed.len());
            out.push_str(prefix);
            out.push_str(trimmed);
            out
        }
        _ => trimmed.to_string(),
    }
}

fn strip_shell_prefix(command: &str, shell_prefix: Option<&str>) -> String {
    let trimmed = command.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    match shell_prefix {
        Some(prefix) => trimmed
            .strip_prefix(prefix)
            .map(|rest| rest.trim_start().to_string())
            .unwrap_or_else(|| trimmed.to_string()),
        None => trimmed.to_string(),
    }
}

fn now_ms() -> i64 {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| Duration::from_secs(0));
    now.as_millis() as i64
}

/// Expands shell-style history references against the provided command list.
///
/// Supports `!!`, `!-N`, `!N`, and prefix search forms such as `!osp`.
pub(crate) fn expand_history(
    input: &str,
    history: &[String],
    shell_prefix: Option<&str>,
    strip_prefix: bool,
) -> Option<String> {
    if !input.starts_with('!') {
        return Some(input.to_string());
    }

    let entries: Vec<(&str, String)> = history
        .iter()
        .filter(|cmd| command_matches_shell_prefix(cmd, shell_prefix))
        .map(|cmd| {
            let view = strip_shell_prefix(cmd, shell_prefix);
            (cmd.as_str(), view)
        })
        .collect();

    if entries.is_empty() {
        return None;
    }

    let select = |full: &str, view: &str, strip: bool| -> String {
        if strip {
            view.to_string()
        } else {
            full.to_string()
        }
    };

    if input == "!!" {
        let (full, view) = entries.last()?;
        return Some(select(full, view, strip_prefix));
    }

    if let Some(rest) = input.strip_prefix("!-") {
        let idx = rest.parse::<usize>().ok()?;
        if idx == 0 || idx > entries.len() {
            return None;
        }
        let (full, view) = entries.get(entries.len() - idx)?;
        return Some(select(full, view, strip_prefix));
    }

    let rest = input.strip_prefix('!')?;
    if let Ok(abs_id) = rest.parse::<usize>() {
        if abs_id == 0 || abs_id > entries.len() {
            return None;
        }
        let (full, view) = entries.get(abs_id - 1)?;
        return Some(select(full, view, strip_prefix));
    }

    for (full, view) in entries.iter().rev() {
        if view.starts_with(rest) {
            return Some(select(full, view, strip_prefix));
        }
    }

    None
}

fn is_excluded_command(command: &str, exclude_patterns: &[String]) -> bool {
    let trimmed = command.trim();
    if trimmed.is_empty() {
        return true;
    }
    if trimmed.starts_with('!') {
        return true;
    }
    if trimmed.contains("--help") {
        return true;
    }
    exclude_patterns
        .iter()
        .any(|pattern| matches_pattern(pattern, trimmed))
}

fn matches_pattern(pattern: &str, command: &str) -> bool {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return false;
    }
    if pattern == "*" {
        return true;
    }
    if !pattern.contains('*') {
        return pattern == command;
    }

    let parts: Vec<&str> = pattern.split('*').collect();
    let mut cursor = 0usize;

    let mut first = true;
    for part in &parts {
        if part.is_empty() {
            continue;
        }
        if first && !pattern.starts_with('*') {
            if !command[cursor..].starts_with(part) {
                return false;
            }
            cursor += part.len();
        } else if let Some(pos) = command[cursor..].find(part) {
            cursor += pos + part.len();
        } else {
            return false;
        }
        first = false;
    }

    if !pattern.ends_with('*')
        && let Some(last) = parts.iter().rev().find(|part| !part.is_empty())
        && !command.ends_with(last)
    {
        return false;
    }

    true
}

#[cfg(test)]
mod tests;