commitbee 0.6.0

AI-powered commit message generator using tree-sitter semantic analysis and local LLMs
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
// SPDX-FileCopyrightText: 2026 Sephyi <me@sephy.io>
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial

use commitbee::services::history::{HistoryContext, HistoryService};

// ─── Subject Analysis (Pure Functions) ───────────────────────────────────────

#[test]
fn type_distribution_counts_correctly() {
    let subjects = vec![
        "feat: add feature A".to_string(),
        "feat: add feature B".to_string(),
        "feat: add feature C".to_string(),
        "fix: resolve crash".to_string(),
        "fix: handle edge case".to_string(),
        "refactor: cleanup code".to_string(),
        "docs: update guide".to_string(),
        "chore: update deps".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);

    assert_eq!(ctx.type_distribution[0], ("feat".to_string(), 3));
    assert_eq!(ctx.type_distribution[1], ("fix".to_string(), 2));
    // refactor, docs, chore each appear once
    assert_eq!(ctx.type_distribution.len(), 5);
}

#[test]
fn scope_extraction_from_conventional_commits() {
    let subjects = vec![
        "feat(auth): add login".to_string(),
        "fix(auth): fix token".to_string(),
        "feat(api): add endpoint".to_string(),
        "fix(api): null check".to_string(),
        "fix(api): timeout".to_string(),
        "refactor(db): cleanup".to_string(),
        "chore: update deps".to_string(), // no scope
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);

    // api appears 3 times, auth appears 2 times, db appears 1 time
    assert_eq!(ctx.scope_patterns[0], ("api".to_string(), 3));
    assert_eq!(ctx.scope_patterns[1], ("auth".to_string(), 2));
    assert_eq!(ctx.scope_patterns[2], ("db".to_string(), 1));
}

#[test]
fn lowercase_detection_all_lowercase() {
    let subjects = vec![
        "feat: add search".to_string(),
        "fix: resolve issue".to_string(),
        "refactor: cleanup".to_string(),
        "docs: update readme".to_string(),
        "chore: update deps".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    assert!(
        ctx.uses_lowercase,
        "all lowercase subjects should be detected"
    );
}

#[test]
fn lowercase_detection_mixed_case() {
    let subjects = vec![
        "feat: Add search".to_string(),
        "fix: Resolve issue".to_string(),
        "refactor: cleanup".to_string(),
        "docs: update readme".to_string(),
        "chore: update deps".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    // 3 out of 5 start lowercase (60%), below 80% threshold
    assert!(
        !ctx.uses_lowercase,
        "mixed case (60% lowercase) should not flag as lowercase"
    );
}

#[test]
fn conventional_ratio_all_conventional() {
    let subjects = vec![
        "feat: one".to_string(),
        "fix: two".to_string(),
        "refactor: three".to_string(),
        "docs: four".to_string(),
        "test: five".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    assert!(
        (ctx.conventional_ratio - 1.0).abs() < f32::EPSILON,
        "all conventional commits should have ratio 1.0"
    );
}

#[test]
fn conventional_ratio_none_conventional() {
    let subjects = vec![
        "Update README".to_string(),
        "Fix typo".to_string(),
        "Add feature".to_string(),
        "Remove old code".to_string(),
        "Merge branch".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    assert!(
        ctx.conventional_ratio < f32::EPSILON,
        "no conventional commits should have ratio 0.0"
    );
}

#[test]
fn conventional_ratio_partial() {
    let subjects = vec![
        "feat: add search".to_string(),
        "Update README".to_string(),
        "fix: crash".to_string(),
        "Merge branch".to_string(),
        "refactor: cleanup".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    // 3 out of 5 = 0.6
    assert!(
        (ctx.conventional_ratio - 0.6).abs() < 0.01,
        "3/5 conventional should have ratio 0.6, got {}",
        ctx.conventional_ratio
    );
}

#[test]
fn average_subject_length() {
    let subjects = vec![
        "feat: a".to_string(),     // 7 chars
        "fix: bb".to_string(),     // 7 chars
        "docs: ccc".to_string(),   // 9 chars
        "chore: dddd".to_string(), // 11 chars
        "test: e".to_string(),     // 7 chars
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);
    // Total = 7+7+9+11+7 = 41, avg = 41/5 = 8
    assert_eq!(ctx.avg_subject_length, 8);
}

#[test]
fn empty_subjects_returns_zero_defaults() {
    let ctx = HistoryService::analyze_subjects(&[]);

    assert!(ctx.type_distribution.is_empty());
    assert!(ctx.scope_patterns.is_empty());
    assert_eq!(ctx.avg_subject_length, 0);
    assert!(!ctx.uses_lowercase);
    assert!(ctx.conventional_ratio < f32::EPSILON);
    assert!(ctx.sample_subjects.is_empty());
}

#[test]
fn non_conventional_subjects_still_extract_style() {
    let subjects = vec![
        "Update README with setup instructions".to_string(),
        "Fix database connection timeout".to_string(),
        "Add user profile endpoint".to_string(),
        "Remove deprecated API calls".to_string(),
        "Improve error handling in auth".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);

    // No conventional types, but still has style info
    assert!(ctx.type_distribution.is_empty());
    assert!(ctx.scope_patterns.is_empty());
    assert!(ctx.avg_subject_length > 0);
    // All start uppercase
    assert!(!ctx.uses_lowercase);
}

#[test]
fn sample_subjects_capped_at_five() {
    let subjects: Vec<String> = (0..20)
        .map(|i| format!("feat: feature number {}", i))
        .collect();

    let ctx = HistoryService::analyze_subjects(&subjects);
    assert_eq!(
        ctx.sample_subjects.len(),
        5,
        "sample subjects should be capped at 5"
    );
}

#[test]
fn breaking_change_indicator_parsed() {
    let subjects = vec![
        "feat!: breaking feature".to_string(),
        "refactor(api)!: remove endpoint".to_string(),
        "fix: normal fix".to_string(),
        "feat: normal feat".to_string(),
        "chore: cleanup".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);

    // All 5 are conventional (breaking indicator should be stripped for parsing)
    assert!(
        (ctx.conventional_ratio - 1.0).abs() < f32::EPSILON,
        "commits with ! should still be parsed as conventional"
    );
}

#[test]
fn scope_patterns_sorted_by_frequency() {
    let subjects = vec![
        "feat(z): one".to_string(),
        "feat(a): two".to_string(),
        "feat(a): three".to_string(),
        "feat(a): four".to_string(),
        "feat(m): five".to_string(),
        "feat(m): six".to_string(),
    ];

    let ctx = HistoryService::analyze_subjects(&subjects);

    // a=3, m=2, z=1
    assert_eq!(ctx.scope_patterns[0].0, "a");
    assert_eq!(ctx.scope_patterns[1].0, "m");
    assert_eq!(ctx.scope_patterns[2].0, "z");
}

// ─── Prompt Section Formatting ───────────────────────────────────────────────

#[test]
fn prompt_section_includes_all_components() {
    let ctx = HistoryContext {
        type_distribution: vec![("feat".to_string(), 5), ("fix".to_string(), 3)],
        scope_patterns: vec![("auth".to_string(), 3)],
        avg_subject_length: 40,
        uses_lowercase: true,
        conventional_ratio: 0.9,
        sample_subjects: vec!["feat(auth): add login flow".to_string()],
    };

    let section = ctx.to_prompt_section(50);

    assert!(section.contains("PROJECT STYLE"));
    assert!(section.contains("Type usage:"));
    assert!(section.contains("Common scopes:"));
    assert!(section.contains("Subject style:"));
    assert!(section.contains("Conventional compliance:"));
    assert!(section.contains("Recent examples:"));
}

#[test]
fn prompt_section_no_scopes_omits_scope_line() {
    let ctx = HistoryContext {
        type_distribution: vec![("feat".to_string(), 5)],
        scope_patterns: vec![],
        avg_subject_length: 30,
        uses_lowercase: true,
        conventional_ratio: 1.0,
        sample_subjects: vec![],
    };

    let section = ctx.to_prompt_section(50);

    assert!(!section.contains("Common scopes:"));
}

#[test]
fn prompt_section_no_samples_omits_examples() {
    let ctx = HistoryContext {
        type_distribution: vec![("feat".to_string(), 5)],
        scope_patterns: vec![],
        avg_subject_length: 30,
        uses_lowercase: false,
        conventional_ratio: 1.0,
        sample_subjects: vec![],
    };

    let section = ctx.to_prompt_section(25);

    assert!(section.contains("from last 25 commits"));
    assert!(!section.contains("Recent examples:"));
}

#[test]
fn prompt_section_percentage_calculation() {
    let ctx = HistoryContext {
        type_distribution: vec![
            ("feat".to_string(), 10),
            ("fix".to_string(), 5),
            ("refactor".to_string(), 5),
        ],
        scope_patterns: vec![],
        avg_subject_length: 40,
        uses_lowercase: true,
        conventional_ratio: 0.8,
        sample_subjects: vec![],
    };

    let section = ctx.to_prompt_section(50);

    // feat = 10/20 = 50%, fix = 5/20 = 25%, refactor = 5/20 = 25%
    assert!(section.contains("feat (50%)"));
    assert!(section.contains("fix (25%)"));
    assert!(section.contains("refactor (25%)"));
}

// ─── Git Integration (requires tempdir with git repo) ────────────────────────

#[tokio::test]
async fn analyze_repo_with_enough_commits() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path();

    // Init repo
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(path)
        .output()
        .unwrap();

    // Create 6 commits (above MIN_COMMITS_FOR_ANALYSIS = 5)
    let commit_subjects = [
        "feat(auth): add login endpoint",
        "fix(auth): handle expired tokens",
        "refactor(db): use connection pool",
        "feat(api): add user search",
        "docs: update API guide",
        "chore: update dependencies",
    ];

    for (i, subject) in commit_subjects.iter().enumerate() {
        let file = path.join(format!("file_{}.txt", i));
        std::fs::write(&file, format!("content {}", i)).unwrap();

        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", subject])
            .current_dir(path)
            .output()
            .unwrap();
    }

    let result = HistoryService::analyze(path, 50).await;
    assert!(result.is_some(), "should succeed with 6 commits");

    let ctx = result.unwrap();
    assert!(!ctx.type_distribution.is_empty());
    assert!(!ctx.scope_patterns.is_empty());
    assert!(ctx.uses_lowercase);
    assert!((ctx.conventional_ratio - 1.0).abs() < f32::EPSILON);
}

#[tokio::test]
async fn analyze_repo_with_too_few_commits() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path();

    // Init repo
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(path)
        .output()
        .unwrap();

    // Create only 3 commits (below MIN_COMMITS_FOR_ANALYSIS = 5)
    for i in 0..3 {
        let file = path.join(format!("file_{}.txt", i));
        std::fs::write(&file, format!("content {}", i)).unwrap();

        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", &format!("feat: feature {}", i)])
            .current_dir(path)
            .output()
            .unwrap();
    }

    let result = HistoryService::analyze(path, 50).await;
    assert!(result.is_none(), "should return None with < 5 commits");
}

#[tokio::test]
async fn analyze_empty_repo() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path();

    // Init repo but make no commits
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .unwrap();

    let result = HistoryService::analyze(path, 50).await;
    assert!(result.is_none(), "should return None for empty repo");
}

#[tokio::test]
async fn analyze_non_git_directory() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path();

    // Don't init git
    let result = HistoryService::analyze(path, 50).await;
    assert!(result.is_none(), "should return None for non-git directory");
}

#[tokio::test]
async fn analyze_respects_sample_size() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path();

    std::process::Command::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(path)
        .output()
        .unwrap();

    std::process::Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(path)
        .output()
        .unwrap();

    // Create 10 commits
    for i in 0..10 {
        let file = path.join(format!("file_{}.txt", i));
        std::fs::write(&file, format!("content {}", i)).unwrap();

        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["commit", "-m", &format!("feat: feature {}", i)])
            .current_dir(path)
            .output()
            .unwrap();
    }

    // Request only 5 commits
    let result = HistoryService::analyze(path, 5).await;
    assert!(result.is_some());

    let ctx = result.unwrap();
    // The type distribution total should be exactly 5
    let total: usize = ctx.type_distribution.iter().map(|(_, c)| c).sum();
    assert_eq!(total, 5, "should only analyze 5 commits");
}