turboreview 0.1.2

A terminal code-review tool for git: review working-tree changes and commits, stage files, leave line comments, and hand off to an AI agent.
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
use std::path::{Path, PathBuf};

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::app::CommentScope;

/// Returns the worktree-scope directory: `<repo_root>/.turboreview`.
pub fn worktree_dir(repo_root: &Path) -> PathBuf {
    repo_root.join(".turboreview")
}

/// Returns the commit-scope directory: `<repo_root>/.turboreview/commits/<sha>`.
pub fn commit_dir(repo_root: &Path, sha: &str) -> PathBuf {
    repo_root.join(".turboreview").join("commits").join(sha)
}

/// The directory holding comments.json / reviewed.json for the given scope.
pub fn scope_dir(repo_root: &Path, scope: &CommentScope) -> PathBuf {
    match scope {
        CommentScope::Worktree => worktree_dir(repo_root),
        CommentScope::Commit(sha) => commit_dir(repo_root, sha),
    }
}

#[derive(Serialize)]
struct LogEntry<'a> {
    path: &'a str,
    line: u32,
    scope: &'a str,
    date: String,
    action: &'a str,
}

/// Persisted configuration. New fields use `#[serde(default)]` so older
/// config.json files (which may lack them) keep loading.
#[derive(Serialize, Deserialize, Default)]
struct Config {
    theme: String, // "dark" | "light"
    #[serde(default)]
    split_diff: bool, // side-by-side diff toggle
}

/// Read the whole config (defaults if missing/unparseable).
fn load_config(repo_root: &Path) -> Config {
    let path = worktree_dir(repo_root).join("config.json");
    let Ok(bytes) = std::fs::read(&path) else {
        return Config::default();
    };
    serde_json::from_slice(&bytes).unwrap_or_default()
}

/// Write the whole config to `<repo_root>/.turboreview/config.json`.
fn save_config(repo_root: &Path, cfg: &Config) -> Result<()> {
    let dir = worktree_dir(repo_root);
    std::fs::create_dir_all(&dir)?;
    std::fs::write(dir.join("config.json"), serde_json::to_vec_pretty(cfg)?)?;
    Ok(())
}

/// Load the persisted theme. Returns `Theme::Dark` if missing/unparseable.
pub fn load_theme(repo_root: &Path) -> crate::theme::Theme {
    match load_config(repo_root).theme.as_str() {
        "light" => crate::theme::Theme::Light,
        _ => crate::theme::Theme::Dark,
    }
}

/// Persist the theme, preserving any other config fields (read-modify-write).
pub fn save_theme(repo_root: &Path, theme: crate::theme::Theme) -> Result<()> {
    let mut cfg = load_config(repo_root);
    cfg.theme = match theme {
        crate::theme::Theme::Light => "light".into(),
        _ => "dark".into(),
    };
    save_config(repo_root, &cfg)
}

/// Load the persisted side-by-side diff preference (false if unset).
pub fn load_split(repo_root: &Path) -> bool {
    load_config(repo_root).split_diff
}

/// Persist the side-by-side diff preference, preserving other config fields.
pub fn save_split(repo_root: &Path, split: bool) -> Result<()> {
    let mut cfg = load_config(repo_root);
    cfg.split_diff = split;
    save_config(repo_root, &cfg)
}

const ARCHIVE_DAYS: i64 = 14;

/// Returns the archive file path: `<repo_root>/.turboreview/archive/comments-archive.jsonl`.
pub fn archive_path(repo_root: &Path) -> PathBuf {
    worktree_dir(repo_root)
        .join("archive")
        .join("comments-archive.jsonl")
}

/// Append archived comments as JSON lines to the archive file. Best-effort; errors returned.
pub fn append_archive(
    repo_root: &Path,
    comments: &[crate::comments::Comment],
) -> anyhow::Result<()> {
    if comments.is_empty() {
        return Ok(());
    }
    let path = archive_path(repo_root);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)?;
    for c in comments {
        let mut line = serde_json::to_string(c)?;
        line.push('\n');
        f.write_all(line.as_bytes())?;
    }
    Ok(())
}

/// Returns the cutoff unix epoch seconds for auto-archiving: `now - ARCHIVE_DAYS * 86400`.
pub fn archive_cutoff_secs(now: i64) -> i64 {
    now - ARCHIVE_DAYS * 86400
}

/// Append one line to `<repo_root>/.turboreview/comment-log.jsonl`.
/// Best-effort; errors are returned but the caller is expected to ignore them.
pub fn append_comment_log(
    repo_root: &Path,
    path: &Path,
    line: u32,
    scope: &str,
    action: &str,
) -> Result<()> {
    let dir = repo_root.join(".turboreview");
    std::fs::create_dir_all(&dir)?;
    let path_str = path.to_string_lossy();
    let entry = LogEntry {
        path: &path_str,
        line,
        scope,
        date: crate::git::format_datetime(now_secs()),
        action,
    };
    let mut line_json = serde_json::to_string(&entry)?;
    line_json.push('\n');
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(dir.join("comment-log.jsonl"))?;
    f.write_all(line_json.as_bytes())?;
    Ok(())
}

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

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

    // ─── Config: theme + split_diff round-trip, no clobber ───────────────────

    #[test]
    fn split_round_trips() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        assert!(!load_split(root)); // default
        save_split(root, true).unwrap();
        assert!(load_split(root));
        save_split(root, false).unwrap();
        assert!(!load_split(root));
    }

    #[test]
    fn saving_theme_preserves_split() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        save_split(root, true).unwrap();
        save_theme(root, crate::theme::Theme::Light).unwrap();
        // Theme write must not wipe the split flag.
        assert!(load_split(root));
        assert_eq!(load_theme(root), crate::theme::Theme::Light);
    }

    #[test]
    fn saving_split_preserves_theme() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        save_theme(root, crate::theme::Theme::Light).unwrap();
        save_split(root, true).unwrap();
        assert_eq!(load_theme(root), crate::theme::Theme::Light);
        assert!(load_split(root));
    }

    #[test]
    fn old_theme_only_config_still_loads() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let cfgdir = worktree_dir(root);
        std::fs::create_dir_all(&cfgdir).unwrap();
        // A pre-split config.json with only the theme field.
        std::fs::write(cfgdir.join("config.json"), br#"{"theme":"light"}"#).unwrap();
        assert_eq!(load_theme(root), crate::theme::Theme::Light);
        assert!(!load_split(root)); // missing field defaults to false
    }

    // ─── TDD: archive_path, append_archive, archive_cutoff_secs ──────────────

    #[test]
    fn archive_path_is_under_dot_turboreview_archive() {
        let root = PathBuf::from("/my/repo");
        let p = archive_path(&root);
        assert_eq!(
            p,
            PathBuf::from("/my/repo/.turboreview/archive/comments-archive.jsonl")
        );
    }

    #[test]
    fn append_archive_writes_one_json_line_per_comment() {
        use crate::comments::{Comment, CommentStatus};
        let dir = tempdir().unwrap();
        let root = dir.path();

        let comments = vec![
            Comment {
                file: std::path::PathBuf::from("a.rs"),
                line: 1,
                hunk: "@@".to_string(),
                text: "note one".to_string(),
                line_text: "fn a()".to_string(),
                context_before: vec![],
                context_after: vec![],
                orig_line: 1,
                stale: false,
                status: CommentStatus::Resolved,
                response: None,
                updated: 1000,
            },
            Comment {
                file: std::path::PathBuf::from("b.rs"),
                line: 5,
                hunk: "@@".to_string(),
                text: "note two".to_string(),
                line_text: "fn b()".to_string(),
                context_before: vec![],
                context_after: vec![],
                orig_line: 5,
                stale: false,
                status: CommentStatus::Resolved,
                response: None,
                updated: 2000,
            },
        ];

        append_archive(root, &comments).unwrap();

        let archive = archive_path(root);
        assert!(archive.exists(), "archive file must exist");
        let contents = std::fs::read_to_string(&archive).unwrap();
        let lines: Vec<&str> = contents.lines().collect();
        assert_eq!(lines.len(), 2, "must write one line per comment");

        // Each line must be valid JSON and contain the comment text
        let v1: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(v1["text"], "note one");
        let v2: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(v2["text"], "note two");
    }

    #[test]
    fn append_archive_is_append_only() {
        use crate::comments::{Comment, CommentStatus};
        let dir = tempdir().unwrap();
        let root = dir.path();

        let c1 = Comment {
            file: std::path::PathBuf::from("a.rs"),
            line: 1,
            hunk: "@@".to_string(),
            text: "first".to_string(),
            line_text: "".to_string(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 1,
            stale: false,
            status: CommentStatus::Resolved,
            response: None,
            updated: 100,
        };
        let c2 = Comment {
            file: std::path::PathBuf::from("b.rs"),
            line: 2,
            hunk: "@@".to_string(),
            text: "second".to_string(),
            line_text: "".to_string(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 2,
            stale: false,
            status: CommentStatus::Resolved,
            response: None,
            updated: 200,
        };

        append_archive(root, &[c1]).unwrap();
        append_archive(root, &[c2]).unwrap();

        let contents = std::fs::read_to_string(archive_path(root)).unwrap();
        let lines: Vec<&str> = contents.lines().collect();
        assert_eq!(lines.len(), 2, "second call must append, not overwrite");
        let v1: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(v1["text"], "first");
        let v2: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(v2["text"], "second");
    }

    #[test]
    fn append_archive_errors_when_path_unwritable() {
        use crate::comments::{Comment, CommentStatus};
        let dir = tempdir().unwrap();
        // Create a FILE where the .turboreview dir should be, so create_dir_all fails.
        std::fs::write(dir.path().join(".turboreview"), b"x").unwrap();
        let c = Comment {
            file: std::path::PathBuf::from("a.rs"),
            line: 1,
            hunk: "@@".to_string(),
            text: "test".to_string(),
            line_text: "fn a()".to_string(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 1,
            stale: false,
            status: CommentStatus::Resolved,
            response: None,
            updated: 1000,
        };
        let res = append_archive(dir.path(), &[c]);
        assert!(
            res.is_err(),
            "append_archive must error when the dir can't be created"
        );
    }

    #[test]
    fn append_archive_empty_slice_does_nothing() {
        use crate::comments::Comment;
        let dir = tempdir().unwrap();
        let root = dir.path();
        append_archive(root, &[] as &[Comment]).unwrap();
        assert!(
            !archive_path(root).exists(),
            "empty slice must not create archive file"
        );
    }

    #[test]
    fn archive_cutoff_secs_is_14_days_before_now() {
        let now = 1_000_000_i64;
        let cutoff = archive_cutoff_secs(now);
        assert_eq!(cutoff, now - 14 * 86400);
    }

    #[test]
    fn worktree_dir_is_dot_turboreview() {
        let root = PathBuf::from("/my/repo");
        assert_eq!(worktree_dir(&root), PathBuf::from("/my/repo/.turboreview"));
    }

    #[test]
    fn commit_dir_is_commits_slash_sha() {
        let root = PathBuf::from("/my/repo");
        assert_eq!(
            commit_dir(&root, "abc123"),
            PathBuf::from("/my/repo/.turboreview/commits/abc123")
        );
    }

    #[test]
    fn save_then_load_theme_round_trips_light() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        save_theme(root, crate::theme::Theme::Light).unwrap();
        let loaded = load_theme(root);
        assert_eq!(loaded, crate::theme::Theme::Light);
    }

    #[test]
    fn save_then_load_theme_round_trips_dark() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        save_theme(root, crate::theme::Theme::Dark).unwrap();
        let loaded = load_theme(root);
        assert_eq!(loaded, crate::theme::Theme::Dark);
    }

    #[test]
    fn load_theme_missing_file_returns_dark() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        // No config.json created — should default to Dark
        let loaded = load_theme(root);
        assert_eq!(loaded, crate::theme::Theme::Dark);
    }

    #[test]
    fn append_comment_log_writes_two_valid_json_lines() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        append_comment_log(root, Path::new("src/main.rs"), 42, "worktree", "set").unwrap();
        append_comment_log(
            root,
            Path::new("src/lib.rs"),
            10,
            "commit:deadbeef",
            "remove",
        )
        .unwrap();

        let log_path = root.join(".turboreview/comment-log.jsonl");
        assert!(log_path.exists(), "log file should exist");

        let contents = std::fs::read_to_string(&log_path).unwrap();
        let lines: Vec<&str> = contents.lines().collect();
        assert_eq!(lines.len(), 2, "should have 2 lines");

        // Parse each line as JSON and verify fields
        let entry1: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(entry1["path"], "src/main.rs");
        assert_eq!(entry1["line"], 42);
        assert_eq!(entry1["scope"], "worktree");
        assert_eq!(entry1["action"], "set");
        let date_str = entry1["date"].as_str().expect("date should be a string");
        // date now holds YYYY-MM-DD HH:MM:SS (19 chars)
        assert_eq!(
            date_str.len(),
            19,
            "date field must be YYYY-MM-DD HH:MM:SS (19 chars): {}",
            date_str
        );
        assert!(
            date_str.contains(' '),
            "date field must contain a space separating date and time"
        );
        assert_eq!(
            date_str.chars().filter(|&c| c == ':').count(),
            2,
            "date field must have two colons for HH:MM:SS"
        );

        let entry2: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(entry2["path"], "src/lib.rs");
        assert_eq!(entry2["line"], 10);
        assert_eq!(entry2["scope"], "commit:deadbeef");
        assert_eq!(entry2["action"], "remove");
    }
}