zshrs 0.11.4

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! SQLite-backed command history for zshrs.
//!
//! **zshrs-original infrastructure with strong C-zsh ancestry.** C
//! zsh keeps history in a flat file (`Src/hist.c::savehistfile()`)
//! and an in-memory linked list of `Histent` entries. zshrs
//! replaces both with a SQLite database for two reasons: (1) FTS5
//! full-text search makes fzf-style fuzzy matching microsecond-
//! latency vs zsh's `O(N)` linear scan, (2) frequency / recency /
//! per-directory tracking can layer on top of the same row without
//! parallel files. The interactive surface (the `fc` builtin,
//! `$HISTFILE` semantics, `setopt SHARE_HISTORY` etc.) preserves
//! the C source's behavior — we just swap the storage backend.
//!
//! Features:
//! - Persistent history across sessions
//! - Frequency and recency tracking
//! - FTS5 full-text search for fzf-style matching
//! - Per-directory history context
//! - Deduplication with timestamp updates

use rusqlite::{params, Connection};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use std::io::Write as _;
use std::io::Read;
use std::io::Write;
use std::io::{Seek, SeekFrom};

/// SQLite-backed history engine.
/// Replaces the in-memory `histent` doubly-linked list +
/// `histfile` flat-file pair from Src/hist.c — same logical
/// history but with FTS5 search, frequency tracking, and
/// per-directory context.
pub struct HistoryEngine {
    conn: Connection,
}

/// One history record.
/// Port of `struct histent` from Src/zsh.h (`text` / `stim` /
/// `ftim` fields) plus zshrs additions (`exit_code`, `cwd`,
/// `frequency`, `duration_ms`) the SQLite schema captures from
/// the `precmd`/`preexec` hooks.
#[derive(Debug, Clone)]
pub struct HistoryEntry {
    pub id: i64,
    pub command: String,
    pub timestamp: i64,
    pub duration_ms: Option<i64>,
    pub exit_code: Option<i32>,
    pub cwd: Option<String>,
    pub frequency: u32,
}

impl HistoryEngine {
    pub fn new() -> rusqlite::Result<Self> {
        let path = Self::db_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).ok();
        }

        // One-shot migration. Two legacy sources, in priority order:
        //   1. The previous shell-side path at
        //      `$ZSHRS_HOME/zshrs_history` — was a sqlite db, briefly
        //      named without the `.db` suffix. Move it into place.
        //   2. The pre-2026-05-03 location at
        //      `~/Library/Application Support/zshrs/history.db`
        //      (macOS) / `$XDG_DATA_HOME/zshrs/history.db` (Linux).
        //      Copy (don't move) so users who roll back keep the old
        //      file readable.
        // Both fire only when zshrs_history.db does not yet exist —
        // never overwrites populated state. Schema is identical (same
        // writer at every age), so byte-level copy is sufficient.
        if !path.exists() {
            let prev_inplace = Self::root().join("zshrs_history");
            // Only move-rename if the file is actually a sqlite db —
            // protects users who already created a flat-text
            // `zshrs_history` by hand.
            if prev_inplace.exists() && is_sqlite_file(&prev_inplace) {
                match std::fs::rename(&prev_inplace, &path) {
                    Ok(()) => tracing::info!(
                        from = %prev_inplace.display(),
                        to = %path.display(),
                        "history: renamed legacy zshrs_history -> zshrs_history.db"
                    ),
                    Err(e) => tracing::warn!(
                        ?e,
                        "history: rename legacy zshrs_history failed"
                    ),
                }
            }
        }
        if !path.exists() {
            if let Some(legacy) = legacy_db_path() {
                if legacy.exists() {
                    if let Err(e) = std::fs::copy(&legacy, &path) {
                        tracing::warn!(
                            from = %legacy.display(),
                            to = %path.display(),
                            error = %e,
                            "history: migrate from legacy path failed; starting empty"
                        );
                    } else {
                        tracing::info!(
                            from = %legacy.display(),
                            to = %path.display(),
                            "history: migrated from legacy path"
                        );
                    }
                }
            }
        }

        let conn = Connection::open(&path)?;
        let engine = Self { conn };
        engine.init_schema()?;
        let count = engine.count().unwrap_or(0);
        let db_size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
        tracing::info!(
            entries = count,
            db_bytes = db_size,
            path = %path.display(),
            "history: sqlite opened"
        );

        // Rehydrate the flat text mirror from the sqlite index when
        // the text file is missing or stale (size 0 with a populated
        // db — happens after the rename migration above moves the
        // user's old `zshrs_history` to `.db`). Cheap: one-shot
        // chronological dump, no FTS / no joins.
        if let Err(e) = engine.rehydrate_text_if_stale() {
            tracing::warn!(?e, "history: failed to rehydrate text mirror; continuing");
        }
        Ok(engine)
    }

    pub fn in_memory() -> rusqlite::Result<Self> {
        let conn = Connection::open_in_memory()?;
        let engine = Self { conn };
        engine.init_schema()?;
        Ok(engine)
    }

    // Helpers below are inherent associated functions; see free
    // `legacy_db_path()` outside the impl block for the migration source.

    /// `$ZSHRS_HOME/zshrs_history.db` — sqlite index that powers FTS5
    /// search, frequency tracking, dedup. Hidden under `.db` so the
    /// user-facing artifact is the flat-text mirror at
    /// `zshrs_history` (see `text_path`), zsh-compatible so muscle
    /// memory + `cat` / `grep` / external history tools all keep
    /// working.
    ///
    /// The daemon owns its OWN history db at `~/.zshrs/history.db`
    /// (different schema, daemon-only writer); shells append to it via
    /// `history_append` IPC. This shell-side db is the fallback path
    /// used when the daemon is absent.
    fn db_path() -> PathBuf {
        Self::root().join("zshrs_history.db")
    }

    /// `$ZSHRS_HOME/zshrs_history` — flat text mirror, one line per
    /// command in zsh extended-history format:
    ///
    /// ```text
    /// : <unix_ts>:<duration>;<command>
    /// ```
    ///
    /// Newlines inside multi-line commands are escaped as the literal
    /// two-character sequence `\\n` (matches `setopt EXTENDED_HISTORY`
    /// — `zsh/Src/hist.c:gethistent`). Every `add` appends one line;
    /// `update_last` rewrites the trailing line in place when the
    /// duration becomes known. The sqlite index at `zshrs_history.db`
    /// is the query-side mirror of this file — they're kept in lockstep
    /// by the writer, and a divergence-repair pass on open re-reads
    /// the text file if the sqlite is missing or older.
    pub fn text_path() -> PathBuf {
        Self::root().join("zshrs_history")
    }

    fn root() -> PathBuf {
        if let Some(custom) = std::env::var_os("ZSHRS_HOME") {
            PathBuf::from(custom)
        } else {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".zshrs")
        }
    }

    fn init_schema(&self) -> rusqlite::Result<()> {
        self.conn.execute_batch(r#"
            CREATE TABLE IF NOT EXISTS history (
                id INTEGER PRIMARY KEY,
                command TEXT NOT NULL,
                timestamp INTEGER NOT NULL,
                duration_ms INTEGER,
                exit_code INTEGER,
                cwd TEXT,
                frequency INTEGER DEFAULT 1
            );

            CREATE INDEX IF NOT EXISTS idx_history_timestamp ON history(timestamp DESC);
            CREATE INDEX IF NOT EXISTS idx_history_cwd ON history(cwd);
            CREATE UNIQUE INDEX IF NOT EXISTS idx_history_command ON history(command);

            CREATE VIRTUAL TABLE IF NOT EXISTS history_fts USING fts5(
                command,
                content='history',
                content_rowid='id',
                tokenize='trigram'
            );

            CREATE TRIGGER IF NOT EXISTS history_ai AFTER INSERT ON history BEGIN
                INSERT INTO history_fts(rowid, command) VALUES (new.id, new.command);
            END;

            CREATE TRIGGER IF NOT EXISTS history_ad AFTER DELETE ON history BEGIN
                INSERT INTO history_fts(history_fts, rowid, command) VALUES('delete', old.id, old.command);
            END;

            CREATE TRIGGER IF NOT EXISTS history_au AFTER UPDATE ON history BEGIN
                INSERT INTO history_fts(history_fts, rowid, command) VALUES('delete', old.id, old.command);
                INSERT INTO history_fts(rowid, command) VALUES (new.id, new.command);
            END;
        "#)?;
        Ok(())
    }

    fn now() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0)
    }

    /// Add a command to history, updating frequency if it already exists
    pub fn add(&self, command: &str, cwd: Option<&str>) -> rusqlite::Result<i64> {
        let command = command.trim();
        if command.is_empty() || command.starts_with(' ') {
            return Ok(0);
        }

        let now = Self::now();

        // Try to update existing entry
        let updated = self.conn.execute(
            "UPDATE history SET timestamp = ?1, frequency = frequency + 1, cwd = COALESCE(?2, cwd)
             WHERE command = ?3",
            params![now, cwd, command],
        )?;

        if updated > 0 {
            // Return the existing ID
            let id: i64 = self.conn.query_row(
                "SELECT id FROM history WHERE command = ?1",
                params![command],
                |row| row.get(0),
            )?;
            return Ok(id);
        }

        // Insert new entry
        self.conn.execute(
            "INSERT INTO history (command, timestamp, cwd) VALUES (?1, ?2, ?3)",
            params![command, now, cwd],
        )?;

        let id = self.conn.last_insert_rowid();

        // Mirror to the flat zsh-extended-history file. Best-effort —
        // a write failure here doesn't fail the sqlite insert (e.g.
        // disk full mid-write should still let the shell record state
        // in the index). The duration is unknown at this point;
        // `update_last` rewrites the trailing line once it knows.
        if let Err(e) = append_text_line(now, 0, command) {
            tracing::warn!(?e, "history: text mirror append failed");
        }

        Ok(id)
    }

    /// Update the duration and exit code of the last command
    pub fn update_last(&self, id: i64, duration_ms: i64, exit_code: i32) -> rusqlite::Result<()> {
        self.conn.execute(
            "UPDATE history SET duration_ms = ?1, exit_code = ?2 WHERE id = ?3",
            params![duration_ms, exit_code, id],
        )?;

        // Update the trailing line of the text mirror with the now-known
        // duration. Look up the command by id so the rewrite stays
        // consistent even if `add` deduped to an earlier entry.
        if let Ok((ts, command)) = self.conn.query_row(
            "SELECT timestamp, command FROM history WHERE id = ?1",
            params![id],
            |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)),
        ) {
            let duration_secs = (duration_ms / 1000).max(0);
            if let Err(e) = rewrite_last_text_line(ts, duration_secs, &command) {
                tracing::warn!(?e, "history: text mirror update failed");
            }
        }
        Ok(())
    }

    /// If the text mirror is missing or empty but the sqlite db has
    /// entries, dump the db chronologically into the text file. Used
    /// by `new()` after the first-time rename migration so users get
    /// the full backlog in the user-facing text file from day one.
    fn rehydrate_text_if_stale(&self) -> rusqlite::Result<()> {
        let text = Self::text_path();
        let text_size = std::fs::metadata(&text).map(|m| m.len()).unwrap_or(0);
        if text_size > 0 {
            return Ok(());
        }
        let count: i64 = self.conn.query_row("SELECT COUNT(*) FROM history", [], |r| r.get(0))?;
        if count == 0 {
            return Ok(());
        }
        let mut stmt = self.conn.prepare(
            "SELECT timestamp, COALESCE(duration_ms, 0), command \
             FROM history ORDER BY timestamp ASC, id ASC",
        )?;
        let rows = stmt.query_map([], |r| {
            Ok((
                r.get::<_, i64>(0)?,
                r.get::<_, i64>(1)?,
                r.get::<_, String>(2)?,
            ))
        })?;
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true)
            .open(&text)
            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
        let mut w = std::io::BufWriter::new(file);
        let mut written: u64 = 0;
        for row in rows {
            let (ts, dur_ms, cmd) = row?;
            let line = format_text_line(ts, (dur_ms / 1000).max(0), &cmd);
            w.write_all(line.as_bytes())
                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
            written += 1;
        }
        w.flush()
            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
        tracing::info!(
            entries = written,
            path = %text.display(),
            "history: rehydrated text mirror from sqlite index"
        );
        Ok(())
    }

    /// Search history with FTS5 (fuzzy/substring matching)
    pub fn search(&self, query: &str, limit: usize) -> rusqlite::Result<Vec<HistoryEntry>> {
        if query.is_empty() {
            return self.recent(limit);
        }

        // Escape special FTS5 characters and use prefix matching
        let escaped = query.replace('"', "\"\"");
        let fts_query = format!("\"{}\"*", escaped);

        let mut stmt = self.conn.prepare(
            r#"SELECT h.id, h.command, h.timestamp, h.duration_ms, h.exit_code, h.cwd, h.frequency
               FROM history h
               JOIN history_fts f ON h.id = f.rowid
               WHERE history_fts MATCH ?1
               ORDER BY h.frequency DESC, h.timestamp DESC
               LIMIT ?2"#,
        )?;

        let entries = stmt.query_map(params![fts_query, limit as i64], |row| {
            Ok(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            })
        })?;

        entries.collect()
    }

    /// Search history with prefix matching (for up-arrow completion)
    pub fn search_prefix(&self, prefix: &str, limit: usize) -> rusqlite::Result<Vec<HistoryEntry>> {
        if prefix.is_empty() {
            return self.recent(limit);
        }

        let mut stmt = self.conn.prepare(
            r#"SELECT id, command, timestamp, duration_ms, exit_code, cwd, frequency
               FROM history
               WHERE command LIKE ?1 || '%' ESCAPE '\'
               ORDER BY timestamp DESC
               LIMIT ?2"#,
        )?;

        // Escape SQL LIKE special chars
        let escaped = prefix
            .replace('\\', "\\\\")
            .replace('%', "\\%")
            .replace('_', "\\_");

        let entries = stmt.query_map(params![escaped, limit as i64], |row| {
            Ok(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            })
        })?;

        entries.collect()
    }

    /// Get recent history entries
    pub fn recent(&self, limit: usize) -> rusqlite::Result<Vec<HistoryEntry>> {
        let mut stmt = self.conn.prepare(
            r#"SELECT id, command, timestamp, duration_ms, exit_code, cwd, frequency
               FROM history
               ORDER BY timestamp DESC
               LIMIT ?1"#,
        )?;

        let entries = stmt.query_map(params![limit as i64], |row| {
            Ok(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            })
        })?;

        entries.collect()
    }

    /// Get history for a specific directory
    pub fn for_directory(&self, cwd: &str, limit: usize) -> rusqlite::Result<Vec<HistoryEntry>> {
        let mut stmt = self.conn.prepare(
            r#"SELECT id, command, timestamp, duration_ms, exit_code, cwd, frequency
               FROM history
               WHERE cwd = ?1
               ORDER BY frequency DESC, timestamp DESC
               LIMIT ?2"#,
        )?;

        let entries = stmt.query_map(params![cwd, limit as i64], |row| {
            Ok(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            })
        })?;

        entries.collect()
    }

    /// Delete a history entry
    pub fn delete(&self, id: i64) -> rusqlite::Result<()> {
        self.conn
            .execute("DELETE FROM history WHERE id = ?1", params![id])?;
        Ok(())
    }

    /// Clear all history
    pub fn clear(&self) -> rusqlite::Result<()> {
        self.conn.execute("DELETE FROM history", [])?;
        Ok(())
    }

    /// Get total history count
    pub fn count(&self) -> rusqlite::Result<i64> {
        self.conn
            .query_row("SELECT COUNT(*) FROM history", [], |row| row.get(0))
    }

    /// Get entry by index from end (0 = most recent, like !-1)
    pub fn get_by_offset(&self, offset: usize) -> rusqlite::Result<Option<HistoryEntry>> {
        let mut stmt = self.conn.prepare(
            r#"SELECT id, command, timestamp, duration_ms, exit_code, cwd, frequency
               FROM history
               ORDER BY timestamp DESC
               LIMIT 1 OFFSET ?1"#,
        )?;

        let mut rows = stmt.query(params![offset as i64])?;
        if let Some(row) = rows.next()? {
            Ok(Some(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            }))
        } else {
            Ok(None)
        }
    }

    /// Get entry by absolute history number (like !123)
    pub fn get_by_number(&self, num: i64) -> rusqlite::Result<Option<HistoryEntry>> {
        let mut stmt = self.conn.prepare(
            r#"SELECT id, command, timestamp, duration_ms, exit_code, cwd, frequency
               FROM history
               WHERE id = ?1"#,
        )?;

        let mut rows = stmt.query(params![num])?;
        if let Some(row) = rows.next()? {
            Ok(Some(HistoryEntry {
                id: row.get(0)?,
                command: row.get(1)?,
                timestamp: row.get(2)?,
                duration_ms: row.get(3)?,
                exit_code: row.get(4)?,
                cwd: row.get(5)?,
                frequency: row.get(6)?,
            }))
        } else {
            Ok(None)
        }
    }
}

/// Pre-2026-05-03 history db location. Returned only when the legacy
/// file actually exists — used by `HistoryEngine::new` to migrate
/// once into `$ZSHRS_HOME/zshrs_history.db`. Returns None if
/// `dirs::data_dir` can't resolve (no $HOME / no platform data dir).
fn legacy_db_path() -> Option<PathBuf> {
    Some(dirs::data_dir()?.join("zshrs").join("history.db"))
}

/// Detect whether `path` is a sqlite database by sniffing the magic
/// header (first 16 bytes start with `SQLite format 3\0`). Used by
/// the rename-migration to avoid clobbering a user's hand-written
/// flat text file. Errors / short files / unknown content all return
/// false (safe default — leave unknown content alone).
fn is_sqlite_file(path: &std::path::Path) -> bool {
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return false,
    };
    let mut header = [0u8; 16];
    if f.read_exact(&mut header).is_err() {
        return false;
    }
    &header == b"SQLite format 3\0"
}

/// Format one zsh-extended-history line:
///
/// ```text
/// : <unix_ts>:<duration>;<command>\n
/// ```
///
/// Multi-line commands escape literal `\n` to the two-character
/// sequence `\\n` so each entry stays on a single line; the unescape
/// is the inverse done at read time. Matches what zsh writes when
/// `EXTENDED_HISTORY` is set (zsh/Src/hist.c:savehistfile).
fn format_text_line(ts: i64, duration_secs: i64, command: &str) -> String {
    let escaped = command.replace('\\', "\\\\").replace('\n', "\\\n");
    format!(": {}:{};{}\n", ts, duration_secs, escaped)
}

/// Append one line to `$ZSHRS_HOME/zshrs_history`.
fn append_text_line(ts: i64, duration_secs: i64, command: &str) -> std::io::Result<()> {
    let path = HistoryEngine::text_path();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let line = format_text_line(ts, duration_secs, command);
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)?;
    f.write_all(line.as_bytes())
}

/// Rewrite the trailing entry of the text file in place — used by
/// `update_last` once the duration is known. Strategy: read the file
/// to the last newline-delimited record, replace it with a freshly
/// formatted line. For multi-MB history files we only buffer the
/// trailing record's tail bytes (`max_tail` cap) — anything older
/// stays untouched on disk.
fn rewrite_last_text_line(ts: i64, duration_secs: i64, command: &str) -> std::io::Result<()> {
    let path = HistoryEngine::text_path();
    let mut f = std::fs::OpenOptions::new().read(true).write(true).open(&path)?;
    let len = f.metadata()?.len();
    // 64 KiB is enough for any realistic single-command record (zsh
    // commands top out at ~1-4 KiB). Beyond that, give up and append
    // a corrected line rather than risk truncating the file.
    let max_tail = 65_536u64.min(len);
    let read_from = len - max_tail;
    f.seek(SeekFrom::Start(read_from))?;
    let mut tail = Vec::with_capacity(max_tail as usize);
    f.read_to_end(&mut tail)?;
    // Find the offset (within `tail`) where the last record begins.
    // A record begins at the byte AFTER the second-to-last newline,
    // or at offset 0 if there is none.
    let mut last_record_start = 0usize;
    let mut nl_count = 0;
    for (i, b) in tail.iter().enumerate().rev() {
        if *b == b'\n' {
            nl_count += 1;
            if nl_count == 2 {
                last_record_start = i + 1;
                break;
            }
        }
    }
    let new_record = format_text_line(ts, duration_secs, command);
    let new_abs = read_from + last_record_start as u64;
    f.seek(SeekFrom::Start(new_abs))?;
    f.write_all(new_record.as_bytes())?;
    let new_len = new_abs + new_record.len() as u64;
    if new_len < len {
        f.set_len(new_len)?;
    }
    Ok(())
}

/// Adapter exposing `HistoryEngine` to the line editor.
/// zshrs-original — bridges the SQLite engine into the line-editor
/// crate. C zsh's equivalent is the per-key history-search /
/// up-arrow plumbing in Src/Zle/zle_hist.c that walks the
/// `histent` linked list directly.
pub struct ReedlineHistory {
    engine: HistoryEngine,
    session_history: Vec<String>,
    cursor: usize,
}

impl ReedlineHistory {
    pub fn new() -> rusqlite::Result<Self> {
        Ok(Self {
            engine: HistoryEngine::new()?,
            session_history: Vec::new(),
            cursor: 0,
        })
    }

    pub fn add(&mut self, command: &str) -> rusqlite::Result<i64> {
        self.session_history.push(command.to_string());
        self.cursor = self.session_history.len();
        let cwd = std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string());
        self.engine.add(command, cwd.as_deref())
    }

    pub fn search(&self, query: &str) -> Vec<String> {
        self.engine
            .search(query, 50)
            .unwrap_or_default()
            .into_iter()
            .map(|e| e.command)
            .collect()
    }

    pub fn previous(&mut self, prefix: &str) -> Option<String> {
        if self.cursor == 0 {
            return None;
        }

        // Search backwards in session history first
        for i in (0..self.cursor).rev() {
            if self.session_history[i].starts_with(prefix) {
                self.cursor = i;
                return Some(self.session_history[i].clone());
            }
        }

        // Fall back to database
        self.engine
            .search_prefix(prefix, 1)
            .ok()
            .and_then(|v| v.into_iter().next())
            .map(|e| e.command)
    }

    pub fn next(&mut self, prefix: &str) -> Option<String> {
        if self.cursor >= self.session_history.len() {
            return None;
        }

        for i in (self.cursor + 1)..self.session_history.len() {
            if self.session_history[i].starts_with(prefix) {
                self.cursor = i;
                return Some(self.session_history[i].clone());
            }
        }

        self.cursor = self.session_history.len();
        None
    }

    pub fn reset_cursor(&mut self) {
        self.cursor = self.session_history.len();
    }
}

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

    #[test]
    fn test_add_and_search() {
        let engine = HistoryEngine::in_memory().unwrap();

        engine.add("ls -la", Some("/home/user")).unwrap();
        engine.add("cd /tmp", Some("/home/user")).unwrap();
        engine.add("echo hello", Some("/tmp")).unwrap();

        // Use prefix search for short queries (trigram FTS5 needs 3+ chars)
        let results = engine.search_prefix("ls", 10).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].command, "ls -la");
    }

    #[test]
    fn test_frequency_tracking() {
        let engine = HistoryEngine::in_memory().unwrap();

        engine.add("git status", None).unwrap();
        engine.add("git status", None).unwrap();
        engine.add("git status", None).unwrap();

        let results = engine.recent(10).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].frequency, 3);
    }

    #[test]
    fn test_prefix_search() {
        let engine = HistoryEngine::in_memory().unwrap();

        engine.add("git status", None).unwrap();
        engine.add("git commit -m 'test'", None).unwrap();
        engine.add("grep foo bar", None).unwrap();

        let results = engine.search_prefix("git", 10).unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_directory_history() {
        let engine = HistoryEngine::in_memory().unwrap();

        engine.add("make build", Some("/project")).unwrap();
        engine.add("cargo test", Some("/project")).unwrap();
        engine.add("ls", Some("/tmp")).unwrap();

        let results = engine.for_directory("/project", 10).unwrap();
        assert_eq!(results.len(), 2);
    }
}