worktrunk 0.46.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
//! Persistent cache for SHA-keyed git command results.
//!
//! Caches the results of expensive git operations keyed on pairs of
//! content-addressed SHAs — diffing commit A against commit B is the same
//! today as last week. One variant (working-tree conflict checks) uses a
//! composite key that includes a tree SHA; see
//! [`Repository::has_merge_conflicts_by_tree`]. No TTL, no invalidation
//! logic, only a per-kind LRU size bound to prevent unbounded growth.
//!
//! Layout: `.git/wt/cache/{kind}/{key}.json` where `kind` is one of
//! `merge-tree-conflicts`, `merge-add-probe`, `is-ancestor`,
//! `has-added-changes`, or `diff-stats`. Symmetric kinds sort the SHA pair
//! so `(A, B)` and `(B, A)` hit the same entry; asymmetric kinds preserve
//! ordering. See [`crate::cache`] for read/write/clear mechanics,
//! torn-write semantics, and the user-initiated clear error policy.

use super::Repository;
use super::integration::MergeProbeResult;
use crate::cache;
use crate::git::LineDiff;

/// Maximum cached entries per task kind before the LRU sweep removes the
/// oldest entries. 5000 entries × ~80 bytes ≈ 400 KB per kind — small
/// enough to ignore, large enough to cover years of typical use.
const MAX_ENTRIES_PER_KIND: usize = 5000;

const KIND_MERGE_TREE_CONFLICTS: &str = "merge-tree-conflicts";
const KIND_MERGE_ADD_PROBE: &str = "merge-add-probe";
const KIND_IS_ANCESTOR: &str = "is-ancestor";
const KIND_HAS_ADDED_CHANGES: &str = "has-added-changes";
const KIND_DIFF_STATS: &str = "diff-stats";

/// All cache kind identifiers, used by [`clear_all`].
const ALL_KINDS: &[&str] = &[
    KIND_MERGE_TREE_CONFLICTS,
    KIND_MERGE_ADD_PROBE,
    KIND_IS_ANCESTOR,
    KIND_HAS_ADDED_CHANGES,
    KIND_DIFF_STATS,
];

/// Build a symmetric filename from a SHA pair (order-independent).
fn symmetric_key(sha1: &str, sha2: &str) -> String {
    if sha1 <= sha2 {
        format!("{sha1}-{sha2}.json")
    } else {
        format!("{sha2}-{sha1}.json")
    }
}

/// Build an asymmetric filename from a SHA pair (order preserved).
fn asymmetric_key(first: &str, second: &str) -> String {
    format!("{first}-{second}.json")
}

// merge-tree conflicts (symmetric)

/// Look up a cached `has_merge_conflicts(sha1, sha2)` result.
///
/// The key is order-independent: `(A, B)` and `(B, A)` hit the same entry.
pub(super) fn merge_conflicts(repo: &Repository, sha1: &str, sha2: &str) -> Option<bool> {
    cache::read(repo, KIND_MERGE_TREE_CONFLICTS, &symmetric_key(sha1, sha2))
}

/// Store a `has_merge_conflicts(sha1, sha2)` result, triggering an LRU
/// sweep if the per-kind entry bound is exceeded.
pub(super) fn put_merge_conflicts(repo: &Repository, sha1: &str, sha2: &str, value: bool) {
    cache::write_with_lru(
        repo,
        KIND_MERGE_TREE_CONFLICTS,
        &symmetric_key(sha1, sha2),
        &value,
        MAX_ENTRIES_PER_KIND,
    );
}

// merge-add probe (asymmetric)

/// Look up a cached `merge_integration_probe(branch, target)` result.
///
/// The key is order-dependent: the merge result is compared against
/// `target`'s tree, so swapping arguments changes the semantics.
pub(super) fn merge_add_probe(
    repo: &Repository,
    branch_sha: &str,
    target_sha: &str,
) -> Option<MergeProbeResult> {
    cache::read(
        repo,
        KIND_MERGE_ADD_PROBE,
        &asymmetric_key(branch_sha, target_sha),
    )
}

/// Store a `merge_integration_probe(branch, target)` result, triggering
/// an LRU sweep if the per-kind entry bound is exceeded.
pub(super) fn put_merge_add_probe(
    repo: &Repository,
    branch_sha: &str,
    target_sha: &str,
    value: MergeProbeResult,
) {
    cache::write_with_lru(
        repo,
        KIND_MERGE_ADD_PROBE,
        &asymmetric_key(branch_sha, target_sha),
        &value,
        MAX_ENTRIES_PER_KIND,
    );
}

// is-ancestor (asymmetric)

/// Look up a cached `is_ancestor(base_sha, head_sha)` result.
///
/// Asymmetric: "is base ancestor of head?" differs from "is head ancestor of base?".
pub(super) fn is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str) -> Option<bool> {
    cache::read(repo, KIND_IS_ANCESTOR, &asymmetric_key(base_sha, head_sha))
}

/// Store an `is_ancestor(base_sha, head_sha)` result.
pub(super) fn put_is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str, value: bool) {
    cache::write_with_lru(
        repo,
        KIND_IS_ANCESTOR,
        &asymmetric_key(base_sha, head_sha),
        &value,
        MAX_ENTRIES_PER_KIND,
    );
}

// has-added-changes (asymmetric)

/// Look up a cached `has_added_changes(branch_sha, target_sha)` result.
///
/// Asymmetric: diff from merge-base to branch is directional.
pub(super) fn has_added_changes(
    repo: &Repository,
    branch_sha: &str,
    target_sha: &str,
) -> Option<bool> {
    cache::read(
        repo,
        KIND_HAS_ADDED_CHANGES,
        &asymmetric_key(branch_sha, target_sha),
    )
}

/// Store a `has_added_changes(branch_sha, target_sha)` result.
pub(super) fn put_has_added_changes(
    repo: &Repository,
    branch_sha: &str,
    target_sha: &str,
    value: bool,
) {
    cache::write_with_lru(
        repo,
        KIND_HAS_ADDED_CHANGES,
        &asymmetric_key(branch_sha, target_sha),
        &value,
        MAX_ENTRIES_PER_KIND,
    );
}

// diff-stats (asymmetric)

/// Look up cached `branch_diff_stats(base_sha, head_sha)` result.
///
/// Asymmetric: diff from merge-base(base,head)..head is directional.
pub(super) fn diff_stats(repo: &Repository, base_sha: &str, head_sha: &str) -> Option<LineDiff> {
    cache::read(repo, KIND_DIFF_STATS, &asymmetric_key(base_sha, head_sha))
}

/// Store a `branch_diff_stats(base_sha, head_sha)` result.
pub(super) fn put_diff_stats(repo: &Repository, base_sha: &str, head_sha: &str, value: LineDiff) {
    cache::write_with_lru(
        repo,
        KIND_DIFF_STATS,
        &asymmetric_key(base_sha, head_sha),
        &value,
        MAX_ENTRIES_PER_KIND,
    );
}

// Maintenance

/// Clear all cached SHA-keyed entries, returning the count removed. Called
/// by `wt config state clear`; see [`cache::clear_json_files`] for the
/// missing-dir / concurrent-removal / error-propagation semantics.
pub fn clear_all(repo: &Repository) -> anyhow::Result<usize> {
    let mut cleared = 0;
    for kind in ALL_KINDS {
        cleared += cache::clear_json_files(&cache::cache_dir(repo, kind))?;
    }
    Ok(cleared)
}

/// Count all cached SHA-keyed entries across every kind.
///
/// Called by `wt config state get` to surface the same state that
/// `clear_all` would sweep, preserving get ↔ clear parity.
pub fn count_all(repo: &Repository) -> usize {
    ALL_KINDS
        .iter()
        .map(|kind| cache::count_json_files(&cache::cache_dir(repo, kind)))
        .sum()
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;
    use crate::testing::TestRepo;

    // Key formatting

    #[test]
    fn test_symmetric_key_sorts_pair() {
        assert_eq!(symmetric_key("aaaa", "bbbb"), "aaaa-bbbb.json");
        assert_eq!(symmetric_key("bbbb", "aaaa"), "aaaa-bbbb.json");
        assert_eq!(
            symmetric_key("deadbeef", "deadbeef"),
            "deadbeef-deadbeef.json"
        );
    }

    #[test]
    fn test_asymmetric_key_preserves_order() {
        assert_eq!(asymmetric_key("aaaa", "bbbb"), "aaaa-bbbb.json");
        assert_eq!(asymmetric_key("bbbb", "aaaa"), "bbbb-aaaa.json");
    }

    // Round-trip file I/O

    #[test]
    fn test_merge_conflicts_roundtrip() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        assert_eq!(merge_conflicts(&repo, "aaaa", "bbbb"), None);

        put_merge_conflicts(&repo, "aaaa", "bbbb", true);
        assert_eq!(merge_conflicts(&repo, "aaaa", "bbbb"), Some(true));

        // Symmetric: swapped args hit the same entry
        assert_eq!(merge_conflicts(&repo, "bbbb", "aaaa"), Some(true));

        // Overwrite with a new value
        put_merge_conflicts(&repo, "aaaa", "bbbb", false);
        assert_eq!(merge_conflicts(&repo, "aaaa", "bbbb"), Some(false));
    }

    #[test]
    fn test_merge_add_probe_roundtrip() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        assert_eq!(merge_add_probe(&repo, "aaaa", "bbbb"), None);

        let value = MergeProbeResult {
            would_merge_add: true,
            is_patch_id_match: false,
        };
        put_merge_add_probe(&repo, "aaaa", "bbbb", value);
        assert_eq!(merge_add_probe(&repo, "aaaa", "bbbb"), Some(value));

        // Asymmetric: swapped args miss
        assert_eq!(merge_add_probe(&repo, "bbbb", "aaaa"), None);
    }

    #[test]
    fn test_kinds_are_isolated() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        put_merge_conflicts(&repo, "aaaa", "bbbb", true);
        // Same SHA pair in a different kind is a separate entry
        assert_eq!(merge_add_probe(&repo, "aaaa", "bbbb"), None);
    }

    #[test]
    fn test_corrupt_entry_returns_none() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        put_merge_conflicts(&repo, "aaaa", "bbbb", true);

        let path =
            cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS).join(symmetric_key("aaaa", "bbbb"));
        fs::write(&path, "not valid json {{{").unwrap();

        assert_eq!(merge_conflicts(&repo, "aaaa", "bbbb"), None);
    }

    // Cache consultation by has_merge_conflicts

    #[test]
    fn test_has_merge_conflicts_reads_cache() {
        let test = TestRepo::with_initial_commit();

        // Create a feature branch with a clean merge (no conflicts)
        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("new.txt"), "content\n").unwrap();
        test.run_git(&["add", "new.txt"]);
        test.run_git(&["commit", "-m", "Add file"]);
        test.run_git(&["checkout", "main"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // First call: real computation — clean merge → false
        assert!(!repo.has_merge_conflicts("main", "feature").unwrap());

        // Tamper with the cache file to return the wrong answer
        let dir = cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1, "exactly one cache entry expected");
        fs::write(entries[0].path(), "true").unwrap();

        // Second call: reads the tampered value from cache
        // Note: we need a fresh Repository so the in-memory RepoCache doesn't
        // interfere (resolved_refs, merge_base, etc. are all keyed by ref name
        // and would bypass the cache for the same invocation — but
        // rev_parse_commit is cached per command, and on a fresh Repo the SHAs
        // will resolve identically to the first run).
        let repo2 = Repository::at(test.root_path()).unwrap();
        assert!(repo2.has_merge_conflicts("main", "feature").unwrap());
    }

    #[test]
    fn test_has_merge_conflicts_by_tree_uses_composite_cache_key() {
        let test = TestRepo::with_initial_commit();

        // Create a feature branch with a staged change
        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("dirty.txt"), "uncommitted\n").unwrap();
        test.run_git(&["add", "dirty.txt"]);

        let branch_head = test.git_output(&["rev-parse", "HEAD"]);
        let tree_sha = test.git_output(&["write-tree"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // Call with composite keying — computes and caches
        let result = repo
            .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)
            .unwrap();

        // Verify the cache entry uses the composite key
        let dir = cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1, "exactly one cache entry expected");

        let filename = entries[0].file_name().to_string_lossy().into_owned();
        assert!(
            filename.contains(&tree_sha),
            "cache filename should contain tree SHA ({tree_sha}), got: {filename}"
        );

        // Tamper with the cache and verify a fresh repo reads the tampered value
        let tampered = !result;
        fs::write(entries[0].path(), serde_json::to_string(&tampered).unwrap()).unwrap();

        let repo2 = Repository::at(test.root_path()).unwrap();
        let cached = repo2
            .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)
            .unwrap();
        assert_eq!(cached, tampered, "should read tampered value from cache");
    }

    #[test]
    fn test_has_merge_conflicts_by_tree_invalidates_on_branch_head_change() {
        let test = TestRepo::with_initial_commit();

        // Set up a common ancestor with shared.txt
        fs::write(test.root_path().join("shared.txt"), "initial\n").unwrap();
        test.run_git(&["add", "shared.txt"]);
        test.run_git(&["commit", "-m", "base: add shared.txt"]);

        // Create feature branch from this point, then diverge both branches
        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("shared.txt"), "feature content\n").unwrap();
        test.run_git(&["add", "shared.txt"]);
        test.run_git(&["commit", "-m", "feature: modify shared.txt"]);

        test.run_git(&["checkout", "main"]);
        fs::write(test.root_path().join("shared.txt"), "main content\n").unwrap();
        test.run_git(&["add", "shared.txt"]);
        test.run_git(&["commit", "-m", "main: modify shared.txt"]);

        // Back to feature, stage an extra file
        test.run_git(&["checkout", "feature"]);
        fs::write(test.root_path().join("extra.txt"), "extra\n").unwrap();
        test.run_git(&["add", "extra.txt"]);

        let head_before = test.git_output(&["rev-parse", "HEAD"]);
        let tree1 = test.git_output(&["write-tree"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // Before rebase: feature conflicts with main (both modified shared.txt)
        let result_before = repo
            .has_merge_conflicts_by_tree("main", &head_before, &tree1)
            .unwrap();
        assert!(result_before, "should conflict before rebase");

        // Unstage, rebase, then re-stage (rebase requires a clean index)
        test.run_git(&["reset", "HEAD", "extra.txt"]);
        fs::remove_file(test.root_path().join("extra.txt")).unwrap();
        test.run_git(&["rebase", "main", "--strategy-option=theirs"]);

        // Re-stage the same extra file
        fs::write(test.root_path().join("extra.txt"), "extra\n").unwrap();
        test.run_git(&["add", "extra.txt"]);

        let head_after = test.git_output(&["rev-parse", "HEAD"]);
        let tree2 = test.git_output(&["write-tree"]);

        assert_ne!(
            head_before, head_after,
            "branch HEAD should change after rebase"
        );

        let repo2 = Repository::at(test.root_path()).unwrap();
        let result_after = repo2
            .has_merge_conflicts_by_tree("main", &head_after, &tree2)
            .unwrap();

        // After rebase onto main, feature is based on main — no conflicts
        assert!(
            !result_after,
            "should not conflict after rebase (different branch HEAD = different cache key)"
        );
    }

    #[test]
    fn test_merge_integration_probe_reads_cache() {
        let test = TestRepo::with_initial_commit();

        // Create a feature branch that's already merged (fast-forward)
        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("new.txt"), "content\n").unwrap();
        test.run_git(&["add", "new.txt"]);
        test.run_git(&["commit", "-m", "Feature"]);
        test.run_git(&["checkout", "main"]);
        test.run_git(&["merge", "feature"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // First call: feature is fully integrated → would_merge_add=false
        let real = repo.merge_integration_probe("feature", "main").unwrap();
        assert!(!real.would_merge_add);

        // Tamper with the cache to flip the answer
        let dir = cache::cache_dir(&repo, KIND_MERGE_ADD_PROBE);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1, "exactly one cache entry expected");
        let tampered = MergeProbeResult {
            would_merge_add: true,
            is_patch_id_match: true,
        };
        fs::write(entries[0].path(), serde_json::to_string(&tampered).unwrap()).unwrap();

        // Fresh repo reads the tampered cache
        let repo2 = Repository::at(test.root_path()).unwrap();
        let cached = repo2.merge_integration_probe("feature", "main").unwrap();
        assert!(cached.would_merge_add);
        assert!(cached.is_patch_id_match);
    }

    // Round-trip: is-ancestor, has-added-changes, diff-stats

    #[test]
    fn test_is_ancestor_roundtrip() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        assert_eq!(is_ancestor(&repo, "aaaa", "bbbb"), None);

        put_is_ancestor(&repo, "aaaa", "bbbb", true);
        assert_eq!(is_ancestor(&repo, "aaaa", "bbbb"), Some(true));

        // Asymmetric: swapped args miss
        assert_eq!(is_ancestor(&repo, "bbbb", "aaaa"), None);
    }

    #[test]
    fn test_has_added_changes_roundtrip() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        assert_eq!(has_added_changes(&repo, "aaaa", "bbbb"), None);

        put_has_added_changes(&repo, "aaaa", "bbbb", false);
        assert_eq!(has_added_changes(&repo, "aaaa", "bbbb"), Some(false));

        // Asymmetric: swapped args miss
        assert_eq!(has_added_changes(&repo, "bbbb", "aaaa"), None);
    }

    #[test]
    fn test_diff_stats_roundtrip() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        assert_eq!(diff_stats(&repo, "aaaa", "bbbb"), None);

        let value = LineDiff {
            added: 42,
            deleted: 7,
        };
        put_diff_stats(&repo, "aaaa", "bbbb", value);
        assert_eq!(diff_stats(&repo, "aaaa", "bbbb"), Some(value));

        // Asymmetric: swapped args miss
        assert_eq!(diff_stats(&repo, "bbbb", "aaaa"), None);
    }

    // Cache consultation: is_ancestor, has_added_changes, branch_diff_stats

    #[test]
    fn test_is_ancestor_reads_cache() {
        let test = TestRepo::with_initial_commit();

        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("new.txt"), "content\n").unwrap();
        test.run_git(&["add", "new.txt"]);
        test.run_git(&["commit", "-m", "Feature"]);
        test.run_git(&["checkout", "main"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // feature is NOT an ancestor of main (main didn't merge feature)
        assert!(!repo.is_ancestor("feature", "main").unwrap());

        // Tamper with cache to flip the answer
        let dir = cache::cache_dir(&repo, KIND_IS_ANCESTOR);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1);
        fs::write(entries[0].path(), "true").unwrap();

        let repo2 = Repository::at(test.root_path()).unwrap();
        assert!(repo2.is_ancestor("feature", "main").unwrap());
    }

    #[test]
    fn test_has_added_changes_reads_cache() {
        let test = TestRepo::with_initial_commit();

        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("new.txt"), "content\n").unwrap();
        test.run_git(&["add", "new.txt"]);
        test.run_git(&["commit", "-m", "Feature"]);
        test.run_git(&["checkout", "main"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // feature has added changes compared to main
        assert!(repo.has_added_changes("feature", "main").unwrap());

        // Tamper with cache to flip the answer
        let dir = cache::cache_dir(&repo, KIND_HAS_ADDED_CHANGES);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1);
        fs::write(entries[0].path(), "false").unwrap();

        let repo2 = Repository::at(test.root_path()).unwrap();
        assert!(!repo2.has_added_changes("feature", "main").unwrap());
    }

    #[test]
    fn test_branch_diff_stats_reads_cache() {
        let test = TestRepo::with_initial_commit();

        test.run_git(&["checkout", "-b", "feature"]);
        fs::write(test.root_path().join("new.txt"), "content\n").unwrap();
        test.run_git(&["add", "new.txt"]);
        test.run_git(&["commit", "-m", "Feature"]);
        test.run_git(&["checkout", "main"]);

        let repo = Repository::at(test.root_path()).unwrap();

        // Real computation
        let real = repo.branch_diff_stats("main", "feature").unwrap();
        assert_eq!(real.added, 1);
        assert_eq!(real.deleted, 0);

        // Tamper with cache to return different stats
        let dir = cache::cache_dir(&repo, KIND_DIFF_STATS);
        let entries: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))
            .collect();
        assert_eq!(entries.len(), 1);
        let tampered = LineDiff {
            added: 999,
            deleted: 888,
        };
        fs::write(entries[0].path(), serde_json::to_string(&tampered).unwrap()).unwrap();

        let repo2 = Repository::at(test.root_path()).unwrap();
        let cached = repo2.branch_diff_stats("main", "feature").unwrap();
        assert_eq!(cached.added, 999);
        assert_eq!(cached.deleted, 888);
    }

    #[test]
    fn test_clear_all_covers_all_kinds() {
        let test = TestRepo::with_initial_commit();
        let repo = Repository::at(test.root_path()).unwrap();

        // Populate one entry in each kind
        put_merge_conflicts(&repo, "a", "b", true);
        put_merge_add_probe(
            &repo,
            "a",
            "b",
            MergeProbeResult {
                would_merge_add: true,
                is_patch_id_match: false,
            },
        );
        put_is_ancestor(&repo, "a", "b", true);
        put_has_added_changes(&repo, "a", "b", true);
        put_diff_stats(
            &repo,
            "a",
            "b",
            LineDiff {
                added: 1,
                deleted: 0,
            },
        );

        let cleared = clear_all(&repo).unwrap();
        assert_eq!(cleared, 5, "should clear one entry per kind");

        // All kinds should be empty
        assert_eq!(merge_conflicts(&repo, "a", "b"), None);
        assert_eq!(merge_add_probe(&repo, "a", "b"), None);
        assert_eq!(is_ancestor(&repo, "a", "b"), None);
        assert_eq!(has_added_changes(&repo, "a", "b"), None);
        assert_eq!(diff_stats(&repo, "a", "b"), None);
    }
}