beads_rust 0.2.21

Agent-first issue tracker (SQLite + JSONL)
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
//! Storage-level tests for history backup module.
//!
//! Tests edge cases and invariants not covered by the e2e CLI tests:
//! - Disabled config skips backup
//! - Non-existent target skips backup (no crash)
//! - Changed content creates a new backup (non-dedup)
//! - Rotation by age deletes old backups
//! - Mixed file stems rotate independently
//! - list_backups with prefix filter only returns matching files
//! - Confinement: backup only for files inside .beads/
//! - Prune with zero keep deletes everything
//! - Rapid backups with distinct content all preserved
//!
//! Related bead: beads_rust-2xbh

use beads_rust::sync::history::{
    BackupEntry, HistoryConfig, backup_before_export, list_backups, prune_backups,
};
use chrono::{Duration, Utc};
use std::fs::{self, File};
use std::io::Write;
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn setup_beads_dir(temp: &TempDir) -> std::path::PathBuf {
    let beads_dir = temp.path().join(".beads");
    fs::create_dir_all(&beads_dir).unwrap();
    beads_dir
}

fn write_file(path: &std::path::Path, content: &[u8]) {
    File::create(path).unwrap().write_all(content).unwrap();
}

fn history_dir(beads_dir: &std::path::Path) -> std::path::PathBuf {
    beads_dir.join(".br_history")
}

// ===========================================================================
// 1. Disabled config skips backup
// ===========================================================================

#[test]
fn disabled_config_skips_backup() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("issues.jsonl");
    write_file(&target, b"some content");

    let config = HistoryConfig {
        enabled: false,
        max_count: 100,
        max_age_days: 30,
        min_interval_secs: 0,
    };

    backup_before_export(&beads_dir, &config, &target).unwrap();

    // History directory should not even be created
    assert!(
        !history_dir(&beads_dir).exists(),
        "disabled config should not create history directory"
    );
}

// ===========================================================================
// 2. Non-existent target skips backup gracefully
// ===========================================================================

#[test]
fn nonexistent_target_skips_backup() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("does_not_exist.jsonl");

    let config = HistoryConfig::default();

    // Should succeed without error
    backup_before_export(&beads_dir, &config, &target).unwrap();

    // No history directory created
    assert!(!history_dir(&beads_dir).exists());
}

// ===========================================================================
// 3. Changed content creates new backup (non-dedup)
// ===========================================================================

#[test]
fn changed_content_creates_new_backup() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("issues.jsonl");

    // Disable the snapshot throttle: this test validates that *changed* content
    // produces a new (non-deduped) backup, independent of the #313 throttle.
    let config = HistoryConfig {
        min_interval_secs: 0,
        ..HistoryConfig::default()
    };

    // First backup
    write_file(&target, b"version 1");
    backup_before_export(&beads_dir, &config, &target).unwrap();

    // Change content
    write_file(&target, b"version 2");

    // Need a small delay so timestamp differs
    std::thread::sleep(std::time::Duration::from_secs(1));
    backup_before_export(&beads_dir, &config, &target).unwrap();

    let backups = list_backups(&history_dir(&beads_dir), None).unwrap();
    assert_eq!(
        backups.len(),
        2,
        "changed content should create a second backup"
    );
}

// ===========================================================================
// 4. Identical content is deduplicated
// ===========================================================================

#[test]
fn identical_content_is_deduplicated() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("issues.jsonl");
    write_file(&target, b"identical content");

    let config = HistoryConfig::default();

    backup_before_export(&beads_dir, &config, &target).unwrap();
    backup_before_export(&beads_dir, &config, &target).unwrap();
    backup_before_export(&beads_dir, &config, &target).unwrap();

    let backups = list_backups(&history_dir(&beads_dir), None).unwrap();
    assert_eq!(
        backups.len(),
        1,
        "identical content should be deduplicated to one backup"
    );
}

// ===========================================================================
// 5. Rotation by count keeps newest
// ===========================================================================

#[test]
fn rotation_by_count_keeps_newest() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let hdir = history_dir(&beads_dir);
    fs::create_dir_all(&hdir).unwrap();

    let target = beads_dir.join("issues.jsonl");

    let config = HistoryConfig {
        enabled: true,
        max_count: 2,
        max_age_days: 365, // Don't trigger age-based rotation
        min_interval_secs: 0,
    };

    // Create 4 backups with distinct content
    for i in 0..4 {
        write_file(&target, format!("version {i}").as_bytes());
        std::thread::sleep(std::time::Duration::from_secs(1));
        backup_before_export(&beads_dir, &config, &target).unwrap();
    }

    let backups = list_backups(&hdir, None).unwrap();
    assert_eq!(backups.len(), 2, "rotation should keep only 2 newest");

    // Verify the kept backups are the newest ones (largest size = latest versions)
    // Since list_backups returns newest first, first entry should be the most recent
    assert!(backups[0].timestamp > backups[1].timestamp);
}

// ===========================================================================
// 6. Rotation by age deletes old backups
// ===========================================================================

#[test]
fn rotation_by_age_deletes_old() {
    let temp = TempDir::new().unwrap();
    let hdir = temp.path().to_path_buf();

    let now = Utc::now();

    // Create backups: one recent (1 hour ago), one old (40 days ago)
    let recent_ts = (now - Duration::hours(1)).format("%Y%m%d_%H%M%S");
    let old_ts = (now - Duration::days(40)).format("%Y%m%d_%H%M%S");

    write_file(&hdir.join(format!("issues.{recent_ts}.jsonl")), b"recent");
    write_file(&hdir.join(format!("issues.{old_ts}.jsonl")), b"old");

    // Prune: keep 100, older than 30 days
    let deleted = prune_backups(&hdir, 100, Some(30)).unwrap();
    assert_eq!(deleted, 1, "should delete 1 old backup");

    let remaining = list_backups(&hdir, None).unwrap();
    assert_eq!(remaining.len(), 1);
    assert!(
        remaining[0]
            .path
            .to_string_lossy()
            .contains(&recent_ts.to_string()),
        "recent backup should remain"
    );
}

// ===========================================================================
// 7. Mixed file stems rotate independently
// ===========================================================================

#[test]
fn mixed_stems_rotate_independently() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let hdir = history_dir(&beads_dir);
    fs::create_dir_all(&hdir).unwrap();

    let config = HistoryConfig {
        enabled: true,
        max_count: 1,
        max_age_days: 365,
        min_interval_secs: 0,
    };

    // Create backups for "issues" stem
    let issues_target = beads_dir.join("issues.jsonl");
    write_file(&issues_target, b"issues v1");
    backup_before_export(&beads_dir, &config, &issues_target).unwrap();

    std::thread::sleep(std::time::Duration::from_secs(1));
    write_file(&issues_target, b"issues v2");
    backup_before_export(&beads_dir, &config, &issues_target).unwrap();

    // Create backups for "archive" stem
    let archive_target = beads_dir.join("archive.jsonl");
    write_file(&archive_target, b"archive v1");
    backup_before_export(&beads_dir, &config, &archive_target).unwrap();

    std::thread::sleep(std::time::Duration::from_secs(1));
    write_file(&archive_target, b"archive v2");
    backup_before_export(&beads_dir, &config, &archive_target).unwrap();

    // Each stem should have max_count=1 backups
    let issues_backups = list_backups(&hdir, Some("issues.")).unwrap();
    let archive_backups = list_backups(&hdir, Some("archive.")).unwrap();

    assert_eq!(
        issues_backups.len(),
        1,
        "issues should have exactly 1 backup after rotation"
    );
    assert_eq!(
        archive_backups.len(),
        1,
        "archive should have exactly 1 backup after rotation"
    );

    // Total backups = 2 (one per stem)
    let all_backups = list_backups(&hdir, None).unwrap();
    assert_eq!(all_backups.len(), 2);
}

// ===========================================================================
// 8. list_backups with prefix filter
// ===========================================================================

#[test]
fn list_backups_prefix_filter() {
    let temp = TempDir::new().unwrap();
    let hdir = temp.path();

    let now = Utc::now();
    let ts = now.format("%Y%m%d_%H%M%S");

    write_file(&hdir.join(format!("issues.{ts}.jsonl")), b"a");
    write_file(&hdir.join(format!("archive.{ts}.jsonl")), b"b");
    write_file(&hdir.join(format!("tasks.{ts}.jsonl")), b"c");

    // No filter: all 3
    assert_eq!(list_backups(hdir, None).unwrap().len(), 3);

    // Filter by "issues."
    let filtered = list_backups(hdir, Some("issues.")).unwrap();
    assert_eq!(filtered.len(), 1);
    assert!(filtered[0].path.to_string_lossy().contains("issues."));

    // Filter by "archive."
    let filtered = list_backups(hdir, Some("archive.")).unwrap();
    assert_eq!(filtered.len(), 1);

    // Filter with non-matching prefix
    let filtered = list_backups(hdir, Some("nonexistent.")).unwrap();
    assert_eq!(filtered.len(), 0);
}

// ===========================================================================
// 9. list_backups on nonexistent directory returns empty
// ===========================================================================

#[test]
fn list_backups_nonexistent_dir_returns_empty() {
    let temp = TempDir::new().unwrap();
    let fake_dir = temp.path().join("does_not_exist");

    let backups = list_backups(&fake_dir, None).unwrap();
    assert!(backups.is_empty());
}

// ===========================================================================
// 10. list_backups skips invalid filenames
// ===========================================================================

#[test]
fn list_backups_skips_invalid_filenames() {
    let temp = TempDir::new().unwrap();
    let hdir = temp.path();

    let now = Utc::now();
    let ts = now.format("%Y%m%d_%H%M%S");

    // Valid backup
    write_file(&hdir.join(format!("issues.{ts}.jsonl")), b"valid");

    // Invalid filenames
    write_file(&hdir.join("issues.not_a_timestamp.jsonl"), b"invalid");
    write_file(&hdir.join("random_file.txt"), b"ignored");
    write_file(&hdir.join("issues.jsonl"), b"no timestamp");

    let backups = list_backups(hdir, None).unwrap();
    assert_eq!(
        backups.len(),
        1,
        "should only list validly-timestamped backup files"
    );
}

// ===========================================================================
// 11. Prune with zero keep deletes all
// ===========================================================================

#[test]
fn prune_zero_keep_deletes_all() {
    let temp = TempDir::new().unwrap();
    let hdir = temp.path();

    let now = Utc::now();
    for i in 0..5 {
        let ts = (now - Duration::hours(i)).format("%Y%m%d_%H%M%S");
        write_file(&hdir.join(format!("issues.{ts}.jsonl")), b"data");
    }

    assert_eq!(list_backups(hdir, None).unwrap().len(), 5);

    let deleted = prune_backups(hdir, 0, None).unwrap();
    assert_eq!(deleted, 5);
    assert!(list_backups(hdir, None).unwrap().is_empty());
}

// ===========================================================================
// 12. Prune on empty directory is a no-op
// ===========================================================================

#[test]
fn prune_empty_dir_is_noop() {
    let temp = TempDir::new().unwrap();
    let deleted = prune_backups(temp.path(), 10, None).unwrap();
    assert_eq!(deleted, 0);
}

// ===========================================================================
// 13. BackupEntry fields are populated correctly
// ===========================================================================

#[test]
fn backup_entry_fields_populated() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("issues.jsonl");
    write_file(&target, b"hello world");

    let config = HistoryConfig::default();
    backup_before_export(&beads_dir, &config, &target).unwrap();

    let backups = list_backups(&history_dir(&beads_dir), None).unwrap();
    assert_eq!(backups.len(), 1);

    let entry: &BackupEntry = &backups[0];
    assert!(entry.path.exists(), "backup file should exist");
    assert!(entry.size > 0, "backup should have non-zero size");
    assert_eq!(entry.size, 11, "size should match 'hello world'");

    // Timestamp should be recent (within last 60 seconds)
    let age = Utc::now() - entry.timestamp;
    assert!(
        age.num_seconds() < 60,
        "backup timestamp should be recent, got age: {age}"
    );
}

// ===========================================================================
// 14. Backup preserves content exactly
// ===========================================================================

#[test]
fn backup_preserves_content_exactly() {
    let temp = TempDir::new().unwrap();
    let beads_dir = setup_beads_dir(&temp);
    let target = beads_dir.join("issues.jsonl");

    let content =
        b"{\"id\":\"test-1\",\"title\":\"Hello\"}\n{\"id\":\"test-2\",\"title\":\"World\"}\n";
    write_file(&target, content);

    let config = HistoryConfig::default();
    backup_before_export(&beads_dir, &config, &target).unwrap();

    let backups = list_backups(&history_dir(&beads_dir), None).unwrap();
    let backup_content = fs::read(&backups[0].path).unwrap();
    assert_eq!(
        backup_content, content,
        "backup content should be byte-identical to source"
    );
}

// ===========================================================================
// 15. Backups sorted newest first
// ===========================================================================

#[test]
fn backups_sorted_newest_first() {
    let temp = TempDir::new().unwrap();
    let hdir = temp.path();

    let now = Utc::now();
    // Create backups with explicit timestamps in reverse order
    let old_ts = (now - Duration::hours(3)).format("%Y%m%d_%H%M%S");
    let mid_ts = (now - Duration::hours(2)).format("%Y%m%d_%H%M%S");
    let new_ts = (now - Duration::hours(1)).format("%Y%m%d_%H%M%S");

    // Write in scrambled order
    write_file(&hdir.join(format!("issues.{mid_ts}.jsonl")), b"mid");
    write_file(&hdir.join(format!("issues.{old_ts}.jsonl")), b"old");
    write_file(&hdir.join(format!("issues.{new_ts}.jsonl")), b"new");

    let backups = list_backups(hdir, None).unwrap();
    assert_eq!(backups.len(), 3);

    // Should be sorted newest → oldest
    assert!(backups[0].timestamp > backups[1].timestamp);
    assert!(backups[1].timestamp > backups[2].timestamp);
}