worktrunk 0.40.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
//! LLM summary generation for the interactive selector.
//!
//! Thin adapter over `crate::summary` that adds TUI-specific rendering
//! and integrates with the selector's preview cache.

use dashmap::DashMap;
use worktrunk::git::Repository;

use super::super::list::model::ListItem;
use super::items::PreviewCacheKey;
use super::preview::PreviewMode;

/// Render LLM summary for terminal display using the project's markdown theme.
///
/// Promotes the first line to an H4 header (renders bold) so the commit-message
/// subject line stands out, then renders everything through the standard
/// markdown renderer used by `--help` pages.
///
/// Pre-styled text (containing ANSI escapes) is passed through with word
/// wrapping only — no H4 promotion.
pub(super) fn render_summary(text: &str, width: usize) -> String {
    // Already styled (e.g. dim "no changes" message) — just wrap
    if text.contains('\x1b') {
        return crate::md_help::render_markdown_in_help_with_width(text, Some(width));
    }

    // Promote subject line to H4 (bold) for visual hierarchy
    let markdown = if let Some((subject, body)) = text.split_once('\n') {
        format!("#### {subject}\n{body}")
    } else {
        format!("#### {text}")
    };

    crate::md_help::render_markdown_in_help_with_width(&markdown, Some(width))
}

/// Generate a summary for one item and insert it into the preview cache.
///
/// `generate_summary_core` acquires `LLM_SEMAPHORE` internally, so the
/// no-changes and cache-hit fast paths return without contending.
pub(super) fn generate_and_cache_summary(
    item: &ListItem,
    llm_command: &str,
    preview_cache: &DashMap<PreviewCacheKey, String>,
    repo: &Repository,
) {
    let branch = item.branch_name();
    let worktree_path = item.worktree_data().map(|d| d.path.as_path());
    let summary =
        crate::summary::generate_summary(branch, item.head(), worktree_path, llm_command, repo);
    preview_cache.insert((branch.to_string(), PreviewMode::Summary), summary);
}

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;

    use super::*;
    use crate::commands::list::model::{ItemKind, WorktreeData};
    use std::fs;
    use worktrunk::testing::TestRepo;

    /// Create a minimal temp git repo (for cache-only tests that don't need branches).
    fn temp_repo() -> (TestRepo, Repository) {
        let t = TestRepo::new();
        t.repo
            .run_command(&["commit", "--allow-empty", "-m", "init"])
            .unwrap();
        let repo = Repository::at(t.path()).unwrap();
        (t, repo)
    }

    /// Create a temp repo with main branch, default-branch config, and a real commit.
    fn temp_repo_configured() -> (TestRepo, Repository, String) {
        let t = TestRepo::new();
        t.repo
            .run_command(&["config", "worktrunk.default-branch", "main"])
            .unwrap();
        fs::write(t.path().join("README.md"), "# Project\n").unwrap();
        t.repo.run_command(&["add", "README.md"]).unwrap();
        t.repo
            .run_command(&["commit", "-m", "initial commit"])
            .unwrap();
        let head = t
            .repo
            .run_command(&["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();
        let repo = Repository::at(t.path()).unwrap();
        (t, repo, head)
    }

    /// Create a temp repo with main + feature branch that has real changes.
    fn temp_repo_with_feature() -> (TestRepo, Repository, String) {
        let (t, repo, _) = temp_repo_configured();

        repo.run_command(&["checkout", "-b", "feature"]).unwrap();
        fs::write(t.path().join("new.txt"), "new content\n").unwrap();
        repo.run_command(&["add", "new.txt"]).unwrap();
        repo.run_command(&["commit", "-m", "add new file"]).unwrap();

        let head = repo
            .run_command(&["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();
        let repo = Repository::at(t.path()).unwrap();
        (t, repo, head)
    }

    fn feature_item(head: &str, path: &std::path::Path) -> ListItem {
        let mut item = ListItem::new_branch(head.to_string(), "feature".to_string());
        item.kind = ItemKind::Worktree(Box::new(WorktreeData {
            path: path.to_path_buf(),
            ..Default::default()
        }));
        item
    }

    #[test]
    fn test_cache_roundtrip() {
        use crate::summary::{CachedSummary, read_cache, write_cache};
        let (_t, repo) = temp_repo();
        let branch = "feature/test-branch";
        let cached = CachedSummary {
            summary: "Add tests\n\nThis adds unit tests for cache.".to_string(),
            diff_hash: 12345,
            branch: branch.to_string(),
        };

        assert!(read_cache(&repo, branch).is_none());

        write_cache(&repo, branch, &cached);
        let loaded = read_cache(&repo, branch).unwrap();
        assert_eq!(loaded.summary, cached.summary);
        assert_eq!(loaded.diff_hash, cached.diff_hash);
        assert_eq!(loaded.branch, cached.branch);
    }

    #[test]
    fn test_write_cache_handles_unwritable_path() {
        use crate::summary::{CachedSummary, read_cache, write_cache};
        let (_t, repo) = temp_repo();
        // Block cache directory creation by placing a file where the directory should be
        let wt_dir = repo.wt_dir();
        fs::create_dir_all(&wt_dir).unwrap();
        let cache_parent = wt_dir.join("cache");
        fs::write(&cache_parent, "blocker").unwrap();

        let cached = CachedSummary {
            summary: "test".to_string(),
            diff_hash: 1,
            branch: "main".to_string(),
        };
        // Should not panic — just logs and returns
        write_cache(&repo, "main", &cached);
        assert!(read_cache(&repo, "main").is_none());

        // Cleanup: remove the blocker file so TempDir cleanup works
        fs::remove_file(&cache_parent).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn test_write_cache_handles_write_failure() {
        use crate::summary::{CachedSummary, cache_dir, read_cache, write_cache};
        use std::os::unix::fs::PermissionsExt;

        let (_t, repo) = temp_repo();
        let cache_path = cache_dir(&repo);
        fs::create_dir_all(&cache_path).unwrap();
        // Make directory read-only so file writes fail
        fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o444)).unwrap();

        let cached = CachedSummary {
            summary: "test".to_string(),
            diff_hash: 1,
            branch: "main".to_string(),
        };
        // Should not panic — just logs and returns
        write_cache(&repo, "main", &cached);
        assert!(read_cache(&repo, "main").is_none());

        // Restore permissions so TempDir cleanup works
        fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn test_cache_invalidation_by_hash() {
        use crate::summary::{CachedSummary, read_cache, write_cache};
        let (_t, repo) = temp_repo();
        let branch = "main";
        let cached = CachedSummary {
            summary: "Old summary".to_string(),
            diff_hash: 111,
            branch: branch.to_string(),
        };
        write_cache(&repo, branch, &cached);

        let loaded = read_cache(&repo, branch).unwrap();
        assert_ne!(loaded.diff_hash, 222);
    }

    #[test]
    fn test_cache_file_uses_sanitized_branch() {
        use crate::summary::cache_file;
        let (_t, repo) = temp_repo();
        let path = cache_file(&repo, "feature/my-branch");
        let filename = path.file_name().unwrap().to_str().unwrap();
        assert!(filename.starts_with("feature-my-branch-"));
        assert!(filename.ends_with(".json"));
    }

    #[test]
    fn test_cache_dir_under_git() {
        use crate::summary::cache_dir;
        let (_t, repo) = temp_repo();
        let dir = cache_dir(&repo);
        assert!(dir.to_str().unwrap().contains("wt"));
        assert!(dir.to_str().unwrap().contains("summaries"));
    }

    #[test]
    fn test_hash_diff_deterministic() {
        use crate::summary::hash_diff;
        let hash1 = hash_diff("some diff content");
        let hash2 = hash_diff("some diff content");
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_hash_diff_different_inputs() {
        use crate::summary::hash_diff;
        let hash1 = hash_diff("diff A");
        let hash2 = hash_diff("diff B");
        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_render_prompt() {
        use crate::summary::render_prompt;

        // With diff content and stat
        let prompt = render_prompt("diff content", "1 file changed").unwrap();
        assert_snapshot!(prompt, @r#"
        <task>Write a summary of this branch's changes as a commit message.</task>

        <format>
        - Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
        - Blank line, then a body paragraph or bullet list explaining the key changes
        - Output only the message — no quotes, code blocks, or labels
        </format>

        <diffstat>
        1 file changed
        </diffstat>

        <diff>
        diff content
        </diff>
        "#);

        // Empty inputs still include format instructions
        let empty_prompt = render_prompt("", "").unwrap();
        assert_snapshot!(empty_prompt, @r#"
        <task>Write a summary of this branch's changes as a commit message.</task>

        <format>
        - Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
        - Blank line, then a body paragraph or bullet list explaining the key changes
        - Output only the message — no quotes, code blocks, or labels
        </format>

        <diffstat>

        </diffstat>

        <diff>

        </diff>
        "#);
    }

    #[test]
    fn test_render_summary() {
        // Multi-line: subject promoted to bold H4, body preserved
        assert_snapshot!(
            render_summary("Add new feature\n\nSome body text here.", 80),
            @"
        Add new feature

        Some body text here.
        "
        );

        // Single line: also promoted to bold H4
        assert_snapshot!(render_summary("Add new feature", 80), @"Add new feature");

        // Bullet list body preserved
        assert_snapshot!(
            render_summary("Subject\n\n- First bullet\n- Second bullet", 80),
            @"
        Subject

        - First bullet
        - Second bullet
        "
        );

        // Pre-styled text (ANSI escapes) skips H4 promotion
        assert_snapshot!(
            render_summary("\x1b[2mNo changes to summarize.\x1b[0m", 80),
            @"No changes to summarize."
        );
    }

    #[test]
    fn test_render_summary_wraps_body() {
        let text = format!("Subject\n\n{}", "word ".repeat(30));
        let rendered = render_summary(&text, 40);
        assert!(rendered.lines().count() > 3);
    }

    #[test]
    fn test_compute_combined_diff_with_branch_changes() {
        use crate::summary::compute_combined_diff;
        let (t, repo, head) = temp_repo_with_feature();

        let result = compute_combined_diff("feature", &head, Some(t.path()), &repo);
        assert!(result.is_some());
        let combined = result.unwrap();
        assert!(combined.diff.contains("new.txt"));
        assert!(combined.stat.contains("new.txt"));
    }

    #[test]
    fn test_compute_combined_diff_default_branch_no_changes() {
        use crate::summary::compute_combined_diff;
        let (t, repo, head) = temp_repo_configured();

        let result = compute_combined_diff("main", &head, Some(t.path()), &repo);
        assert!(result.is_none());
    }

    #[test]
    fn test_compute_combined_diff_with_uncommitted_changes() {
        use crate::summary::compute_combined_diff;
        let (t, repo, head) = temp_repo_with_feature();
        // Add uncommitted changes
        fs::write(t.path().join("uncommitted.txt"), "wip\n").unwrap();
        repo.run_command(&["add", "uncommitted.txt"]).unwrap();

        let result = compute_combined_diff("feature", &head, Some(t.path()), &repo);
        assert!(result.is_some());
        let combined = result.unwrap();
        // Should contain both the branch diff and the working tree diff
        assert!(combined.diff.contains("new.txt"));
        assert!(combined.diff.contains("uncommitted.txt"));
    }

    #[test]
    fn test_compute_combined_diff_branch_only_no_worktree() {
        use crate::summary::compute_combined_diff;
        let (_t, repo, head) = temp_repo_with_feature();
        // Branch-only item (no worktree data) — only branch diff included
        let result = compute_combined_diff("feature", &head, None, &repo);
        assert!(result.is_some());
        let combined = result.unwrap();
        assert!(combined.diff.contains("new.txt"));
    }

    #[test]
    fn test_compute_combined_diff_no_default_branch_with_worktree_changes() {
        use crate::summary::compute_combined_diff;
        // Repo without default-branch config and exotic branch names that
        // infer_default_branch_locally() won't detect (it checks "main",
        // "master", "develop", "trunk"). This ensures default_branch() returns
        // None, exercising the code path where branch diff is skipped.
        let t = TestRepo::new();
        t.commit("initial commit");
        // Rename to exotic branch name so infer_default_branch_locally() returns None
        t.run_git(&["branch", "-m", "main", "init-branch"]);
        t.run_git(&["checkout", "-b", "feature"]);
        t.run_git(&["commit", "--allow-empty", "-m", "feature commit"]);

        // Add uncommitted changes
        fs::write(t.path().join("wip.txt"), "work in progress\n").unwrap();
        t.repo.run_command(&["add", "wip.txt"]).unwrap();

        let head = t
            .repo
            .run_command(&["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();
        let repo = Repository::at(t.path()).unwrap();

        // Verify default_branch() actually returns None with these branch names
        assert!(
            repo.default_branch().is_none(),
            "expected no default branch with exotic branch names"
        );

        let result = compute_combined_diff("feature", &head, Some(t.path()), &repo);
        assert!(
            result.is_some(),
            "should include working tree diff even without default branch"
        );
        let combined = result.unwrap();
        assert!(combined.diff.contains("wip.txt"));
    }

    #[test]
    fn test_generate_summary_calls_llm() {
        let (t, repo, head) = temp_repo_with_feature();

        let summary = crate::summary::generate_summary(
            "feature",
            &head,
            Some(t.path()),
            "cat >/dev/null && echo 'Add new file'",
            &repo,
        );
        assert_eq!(summary, "Add new file");
    }

    #[test]
    fn test_generate_summary_caches_result() {
        let (t, repo, head) = temp_repo_with_feature();

        let summary1 = crate::summary::generate_summary(
            "feature",
            &head,
            Some(t.path()),
            "cat >/dev/null && echo 'Add new file'",
            &repo,
        );
        assert_eq!(summary1, "Add new file");

        // Second call with different command should return cached value
        let summary2 = crate::summary::generate_summary(
            "feature",
            &head,
            Some(t.path()),
            "cat >/dev/null && echo 'Different output'",
            &repo,
        );
        assert_eq!(summary2, "Add new file");
    }

    #[test]
    fn test_generate_summary_no_changes() {
        let (t, repo, head) = temp_repo_configured();

        let summary = crate::summary::generate_summary(
            "main",
            &head,
            Some(t.path()),
            "echo 'should not run'",
            &repo,
        );
        assert_snapshot!(summary, @"â—‹ main has no changes to summarize");
    }

    #[test]
    fn test_generate_summary_llm_error() {
        let (t, repo, head) = temp_repo_with_feature();

        let summary = crate::summary::generate_summary(
            "feature",
            &head,
            Some(t.path()),
            "cat >/dev/null && echo 'fail' >&2 && exit 1",
            &repo,
        );
        assert!(summary.starts_with("Error:"));
    }

    #[test]
    fn test_generate_and_cache_summary_populates_cache() {
        let (t, repo, head) = temp_repo_with_feature();
        let item = feature_item(&head, t.path());
        let cache: DashMap<PreviewCacheKey, String> = DashMap::new();

        generate_and_cache_summary(
            &item,
            "cat >/dev/null && echo 'Add new file'",
            &cache,
            &repo,
        );

        let key = ("feature".to_string(), PreviewMode::Summary);
        assert!(cache.contains_key(&key));
        assert_eq!(cache.get(&key).unwrap().value(), "Add new file");
    }
}