kaeru 0.1.3

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
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
//! Notes on disk: one JSON file per note in kaeru's state folder, the `.cwd`
//! file that a shell keeps its folder in, the lock that lets only one tab ask
//! about waiting tabs, and the log of the commands that print nothing.

use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};

use crate::engine::config::Config;
use crate::engine::note::Note;
use crate::engine::rules::{self, Facts, SingleWindowClose, TabState, TerminalShape};
use crate::engine::tabs::Seen;
use crate::procs::{self, ProcessTable};

/// The environment variable that moves the state folder, and with it the
/// config file, for tests and for trying kaeru without touching the real
/// notes.
pub const STATE_DIR_VAR: &str = "KAERU_STATE_DIR";

/// How large the log may grow, in bytes, before it starts over.
const LOG_LIMIT: u64 = 256 * 1024;

/// kaeru's state folder, and its config file.
pub struct Store {
    dir: PathBuf,
    config: PathBuf,
}

/// A note, and the file it was read from.
#[derive(Debug, Clone)]
pub struct StoredNote {
    pub path: PathBuf,
    pub note: Note,
}

/// A note, and what it means now.
#[derive(Debug, Clone)]
pub struct Reviewed {
    pub stored: StoredNote,
    pub state: TabState,
}

impl Store {
    /// Returns the state folder: the one in `KAERU_STATE_DIR` when that is
    /// set, or else the OS's usual place for app state. The config file is
    /// in the OS's usual place for app config, or in the state folder when
    /// `KAERU_STATE_DIR` is set.
    ///
    /// # Errors
    ///
    /// Fails when the OS has no such place, or the folder can't be created.
    pub fn open() -> Result<Store> {
        if let Some(dir) = std::env::var_os(STATE_DIR_VAR) {
            return Store::at(PathBuf::from(dir));
        }
        let mut store =
            Store::at(default_dir().context("this system has no folder for app state")?)?;
        if let Some(config) = dirs::config_dir() {
            store.config = config.join("kaeru").join("config.toml");
        }
        Ok(store)
    }

    /// Returns the store in `dir`, with its config file there too, creating
    /// the folders it needs.
    ///
    /// # Errors
    ///
    /// Fails when the folders can't be created.
    pub fn at(dir: PathBuf) -> Result<Store> {
        let notes = dir.join("notes");
        fs::create_dir_all(&notes).with_context(|| format!("can't create {}", notes.display()))?;
        let config = dir.join("config.toml");
        Ok(Store { dir, config })
    }

    /// Returns the user's options from the config file, or the defaults when
    /// there is no file. A file that can't be read is logged, and the
    /// defaults are used.
    pub fn config(&self) -> Config {
        let Ok(text) = fs::read_to_string(&self.config) else {
            return Config::default();
        };
        toml::from_str(&text).unwrap_or_else(|error| {
            self.log(&format!("can't read {}: {error}", self.config.display()));
            Config::default()
        })
    }

    /// Saves the user's options to the config file.
    ///
    /// # Errors
    ///
    /// Fails when the file can't be written.
    pub fn save_config(&self, config: &Config) -> Result<()> {
        if let Some(folder) = self.config.parent() {
            fs::create_dir_all(folder)?;
        }
        fs::write(&self.config, toml::to_string(config)?)
            .with_context(|| format!("can't write {}", self.config.display()))
    }

    /// Returns the note in one file, as it is on disk now.
    ///
    /// # Errors
    ///
    /// Fails when the file is gone or can't be read.
    pub fn read(&self, path: &Path) -> Result<Note> {
        read_note(path)
    }

    /// Returns every note, oldest process first. A file that can't be read
    /// is skipped and logged.
    pub fn notes(&self) -> Vec<StoredNote> {
        let Ok(entries) = fs::read_dir(self.notes_dir()) else {
            return Vec::new();
        };
        let mut notes: Vec<StoredNote> = entries
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .filter(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "json")
            })
            .filter_map(|path| match read_note(&path) {
                Ok(note) => Some(StoredNote { path, note }),
                Err(error) => {
                    self.log(&format!("skipped {}: {error:#}", path.display()));
                    None
                }
            })
            .collect();
        notes.sort_by_key(|stored| stored.note.process().started_ms);
        notes
    }

    /// Returns the path that a note is saved at.
    pub fn path_of(&self, note: &Note) -> PathBuf {
        self.notes_dir().join(file_name(note))
    }

    /// Writes a note, replacing an earlier one for the same process. The note
    /// goes to a temporary file that is then renamed, to avoid half-written
    /// notes after a crash.
    ///
    /// # Errors
    ///
    /// Fails when the file can't be written.
    pub fn save(&self, note: &Note) -> Result<PathBuf> {
        let path = self.path_of(note);
        let temp = path.with_extension(format!("json.{}.tmp", std::process::id()));
        fs::write(&temp, serde_json::to_vec_pretty(note)?)
            .with_context(|| format!("can't write {}", temp.display()))?;
        if let Err(error) = fs::rename(&temp, &path) {
            let _ = fs::remove_file(&temp);
            return Err(error).with_context(|| format!("can't write {}", path.display()));
        }
        Ok(path)
    }

    /// Deletes a note, and the `.cwd` file of a shell note.
    pub fn remove(&self, stored: &StoredNote) {
        let _ = fs::remove_file(&stored.path);
        let _ = fs::remove_file(cwd_file(&stored.path));
    }

    /// Returns the state folder.
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Deletes everything kaeru keeps: the notes, the lock, the log and the
    /// config file, and then the state folder if nothing else is in it. Only
    /// kaeru's own files are deleted, even when `KAERU_STATE_DIR` points to a
    /// folder that holds other files too.
    ///
    /// # Errors
    ///
    /// Fails when the notes folder can't be deleted.
    pub fn delete_all(&self) -> Result<()> {
        let notes = self.notes_dir();
        if notes.exists() {
            fs::remove_dir_all(&notes)
                .with_context(|| format!("can't delete {}", notes.display()))?;
        }
        for file in [self.dir.join("lock"), self.log_path(), self.config.clone()] {
            let _ = fs::remove_file(file);
        }
        let _ = fs::remove_dir(&self.dir);
        if let Some(folder) = self.config.parent() {
            let _ = fs::remove_dir(folder);
        }
        Ok(())
    }

    /// Takes the lock that lets only one tab ask about waiting tabs, or
    /// returns `None` when another process holds it. The lock is released
    /// when the returned file is dropped, or when the process ends.
    ///
    /// # Errors
    ///
    /// Fails when the lock file can't be opened.
    pub fn try_lock(&self) -> Result<Option<File>> {
        let path = self.dir.join("lock");
        let file = OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .with_context(|| format!("can't open {}", path.display()))?;
        match file.try_lock() {
            Ok(()) => Ok(Some(file)),
            Err(TryLockError::WouldBlock) => Ok(None),
            Err(TryLockError::Error(error)) => {
                Err(error).with_context(|| format!("can't lock {}", path.display()))
            }
        }
    }

    /// Returns the path of the log.
    pub fn log_path(&self) -> PathBuf {
        self.dir.join("kaeru.log")
    }

    /// Appends a line to the log. The commands that a shell or an agent runs
    /// print nothing, so their problems go here, for `kaeru doctor` to
    /// show. The log starts over when it grows past 256 KB.
    pub fn log(&self, message: &str) {
        let path = self.log_path();
        if fs::metadata(&path).is_ok_and(|metadata| metadata.len() > LOG_LIMIT) {
            let _ = fs::remove_file(&path);
        }
        let seconds = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| since.as_secs());
        if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) {
            let _ = writeln!(file, "{seconds} [{}] {message}", std::process::id());
        }
    }

    /// Returns the folder that the notes are in.
    fn notes_dir(&self) -> PathBuf {
        self.dir.join("notes")
    }
}

/// Returns a note's file name: its kind, process id and start time, which
/// together are unique.
pub fn file_name(note: &Note) -> String {
    let kind = match note {
        Note::Shell(_) => "shell",
        Note::Agent(_) => "agent",
    };
    let process = note.process();
    format!("{kind}-{}-{}.json", process.pid, process.started_ms)
}

/// Returns the path of the `.cwd` file that belongs to a note file.
pub fn cwd_file(note_path: &Path) -> PathBuf {
    note_path.with_extension("cwd")
}

/// Returns a folder as Windows writes it when it is a Windows path with
/// forward slashes, as Git Bash's `pwd -W` prints it, such as `C:/code`.
/// Other paths come back as they are.
fn windows_path(path: &str) -> String {
    let bytes = path.as_bytes();
    let drive = bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && &bytes[1..3] == b":/";
    if drive {
        path.replace('/', "\\")
    } else {
        path.to_string()
    }
}

/// Returns what kaeru last saw of a note's tab: the folder its shell wrote to
/// the `.cwd` file, or else the folder the note records, and when the shell
/// last showed its prompt, which is when the `.cwd` file last changed,
/// because the snippet touches it at every prompt.
pub fn last_seen(stored: &StoredNote) -> Seen {
    let recorded = match &stored.note {
        Note::Shell(note) => &note.cwd,
        Note::Agent(note) => &note.cwd,
    };
    let file = cwd_file(&stored.path);
    let cwd = fs::read_to_string(&file)
        .ok()
        .map(|text| windows_path(text.trim()))
        .filter(|text| !text.is_empty())
        .unwrap_or_else(|| recorded.clone());
    let prompt_ms = fs::metadata(&file)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
        .and_then(|since| u64::try_from(since.as_millis()).ok());
    Seen { cwd, prompt_ms }
}

/// Returns what every note means now, and deletes the notes of closed tabs,
/// as docs/architecture.md describes under Housekeeping.
pub fn review(
    store: &Store,
    table: &dyn ProcessTable,
    session: &str,
    single_window_close: SingleWindowClose,
) -> Vec<Reviewed> {
    let mut kept = Vec::new();
    for stored in store.notes() {
        let terminal = stored.note.terminal();
        let facts = Facts {
            program: procs::liveness(table, stored.note.process()),
            terminal: terminal.map(|terminal| procs::liveness(table, &terminal.process)),
            shape: terminal.map_or(TerminalShape::SingleWindow, |terminal| terminal.shape),
            same_session: stored.note.session() == session,
            single_window_close,
        };
        let state = rules::decide(&facts);
        if state == TabState::Closed {
            store.remove(&stored);
        } else {
            kept.push(Reviewed { stored, state });
        }
    }
    kept
}

/// Reads one note file.
fn read_note(path: &Path) -> Result<Note> {
    Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
}

/// Returns the OS's usual folder for kaeru's state.
fn default_dir() -> Option<PathBuf> {
    #[cfg(target_os = "linux")]
    let base = dirs::state_dir();
    #[cfg(not(target_os = "linux"))]
    let base = dirs::data_local_dir();
    base.map(|dir| dir.join("kaeru"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::note::{ProcessRef, ShellNote, TerminalRef};

    #[test]
    fn a_folder_from_git_bash_becomes_a_windows_path() {
        assert_eq!(windows_path("C:/Users/demo/code"), r"C:\Users\demo\code");
        assert_eq!(windows_path("d:/"), r"d:\");
        assert_eq!(windows_path(r"C:\Users\demo"), r"C:\Users\demo");
        assert_eq!(windows_path("/home/demo/code"), "/home/demo/code");
    }
    use crate::procs::fake::FakeTable;

    fn temp_store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        (dir, store)
    }

    fn shell(pid: u32, started_ms: u64, terminal: Option<(u32, u64)>) -> Note {
        Note::Shell(ShellNote {
            process: ProcessRef { pid, started_ms },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo\code\api-server".into(),
            terminal: terminal.map(|(pid, started_ms)| TerminalRef {
                adapter: "windows-terminal".into(),
                process: ProcessRef { pid, started_ms },
                shape: TerminalShape::Tabs,
                tab_id: None,
                profile: None,
                exe: None,
            }),
            session: "win-1".into(),
            offered: false,
        })
    }

    #[test]
    fn a_saved_note_reads_back() {
        let (_dir, store) = temp_store();
        let note = shell(10, 1_000, None);
        let path = store.save(&note).unwrap();
        assert!(path.ends_with("shell-10-1000.json"));
        let notes = store.notes();
        assert_eq!(notes.len(), 1);
        assert_eq!(notes[0].note, note);
    }

    #[test]
    fn saving_the_same_process_again_replaces_its_note() {
        let (_dir, store) = temp_store();
        store.save(&shell(10, 1_000, None)).unwrap();
        store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
        let notes = store.notes();
        assert_eq!(notes.len(), 1);
        assert!(notes[0].note.terminal().is_some());
    }

    #[test]
    fn removing_a_note_also_removes_its_cwd_file() {
        let (_dir, store) = temp_store();
        let path = store.save(&shell(10, 1_000, None)).unwrap();
        fs::write(cwd_file(&path), "D:\\work").unwrap();
        store.remove(&store.notes()[0]);
        assert!(!path.exists());
        assert!(!cwd_file(&path).exists());
    }

    #[test]
    fn an_unreadable_note_is_skipped_and_logged() {
        let (dir, store) = temp_store();
        fs::write(dir.path().join("notes").join("shell-1-1.json"), "not json").unwrap();
        assert!(store.notes().is_empty());
        let log = fs::read_to_string(store.log_path()).unwrap();
        assert!(log.contains("skipped"));
    }

    #[test]
    fn the_last_folder_comes_from_the_cwd_file() {
        let (_dir, store) = temp_store();
        let path = store.save(&shell(10, 1_000, None)).unwrap();
        let stored = store.notes().remove(0);
        assert_eq!(last_seen(&stored).cwd, r"C:\Users\demo\code\api-server");
        fs::write(cwd_file(&path), "D:\\work\\프로젝트\r\n").unwrap();
        assert_eq!(last_seen(&stored).cwd, "D:\\work\\프로젝트");
    }

    #[test]
    fn only_one_holder_gets_the_lock() {
        let (_dir, store) = temp_store();
        let first = store.try_lock().unwrap();
        assert!(first.is_some());
        assert!(store.try_lock().unwrap().is_none());
        drop(first);
        assert!(store.try_lock().unwrap().is_some());
    }

    #[test]
    fn review_deletes_closed_tabs_and_keeps_the_rest() {
        let (_dir, store) = temp_store();
        let open = store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
        let closed = store.save(&shell(20, 2_000, Some((1, 500)))).unwrap();
        let waiting = store.save(&shell(30, 3_000, Some((2, 600)))).unwrap();
        let table = FakeTable::new(&[
            (10, Some(1), "powershell.exe", Some(1_000)),
            (1, None, "WindowsTerminal.exe", Some(500)),
        ]);
        let reviewed = review(&store, &table, "win-1", SingleWindowClose::Forget);
        let states: Vec<(&Path, TabState)> = reviewed
            .iter()
            .map(|reviewed| (reviewed.stored.path.as_path(), reviewed.state))
            .collect();
        assert_eq!(
            states,
            [
                (open.as_path(), TabState::Open),
                (waiting.as_path(), TabState::Waiting)
            ]
        );
        assert!(!closed.exists());
    }

    #[test]
    fn options_are_saved_and_read_back() {
        let (_dir, store) = temp_store();
        assert_eq!(store.config(), Config::default(), "no file yet");
        let config = Config {
            offer_shells: false,
            ..Config::default()
        };
        store.save_config(&config).unwrap();
        assert_eq!(store.config(), config);
    }

    #[test]
    fn a_broken_config_file_gives_the_defaults_and_is_logged() {
        let (dir, store) = temp_store();
        fs::write(dir.path().join("config.toml"), "offer-shells = maybe").unwrap();
        assert_eq!(store.config(), Config::default());
        let log = fs::read_to_string(store.log_path()).unwrap();
        assert!(log.contains("config.toml"));
    }
}